flash555588_ai-model-workbench/main.js
2026-07-12 23:28:52 +08:00

24620 lines
4 MiB

"use strict";var O0=Object.defineProperty;var zte=Object.getOwnPropertyDescriptor;var Wte=Object.getOwnPropertyNames;var Hte=Object.prototype.hasOwnProperty;var y=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(i){throw t=[i],i}};var Be=(n,e)=>{for(var t in e)O0(n,t,{get:e[t],enumerable:!0})},Xte=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Wte(e))!Hte.call(n,r)&&r!==t&&O0(n,r,{get:()=>e[r],enumerable:!(i=zte(e,r))||i.enumerable});return n};var Yte=n=>Xte(O0({},"__esModule",{value:!0}),n);function qd(n,e,t){return`${n}::${e}::${t}`}function V3(n,e){return!!(n.cacheVersion===2&&n.converterId&&n.converterCacheKey&&n.sourcePath&&n.sourceExt&&n.targetExt==="glb"&&n.outputPath&&n.outputExt==="glb"&&Number.isFinite(n.createdAt)&&e-n.createdAt<=2592e6)}function U3(n,e=Date.now()){let t=new Map;for(let i of n){if(!V3(i,e))continue;let r=qd(i.sourcePath,i.sourceExt,i.targetExt),s=t.get(r);(!s||i.createdAt>s.createdAt)&&t.set(r,i)}return[...t.values()].sort((i,r)=>r.createdAt-i.createdAt).slice(0,200)}function Kte(n,e){if(n.length>200)return null;let t=new Set,i=Number.POSITIVE_INFINITY;for(let r of n){if(!V3(r,e))return null;let s=qd(r.sourcePath,r.sourceExt,r.targetExt);if(t.has(s)||r.createdAt>i)return null;t.add(s),i=r.createdAt}return n}function jte(n,e){return!!n&&!!e&&n.cacheVersion===e.cacheVersion&&n.converterId===e.converterId&&n.converterCacheKey===e.converterCacheKey&&n.sourcePath===e.sourcePath&&n.sourceExt===e.sourceExt&&n.targetExt===e.targetExt&&n.outputPath===e.outputPath&&n.outputExt===e.outputExt&&n.createdAt===e.createdAt&&n.warnings.join(`
`)===e.warnings.join(`
`)}function G3(n=[],e){var c;function t(){return U3([...a.values()])}function i(f){a.clear();for(let d of f)a.set(qd(d.sourcePath,d.sourceExt,d.targetExt),d)}let r=Date.now(),s=(c=Kte(n,r))!=null?c:U3(n,r),a=new Map(s.map(f=>[qd(f.sourcePath,f.sourceExt,f.targetExt),f]));function o(){let f=t();i(f),e==null||e(f)}return(n.length!==s.length||s.some((f,d)=>!jte(f,n[d])))&&(e==null||e([...s])),{get(f,d,u){return a.get(qd(f,d,u))},set(f){a.set(qd(f.sourcePath,f.sourceExt,f.targetExt),f),o()},delete(f,d,u){let h=a.delete(qd(f,d,u));return h&&o(),h},clear(){a.size!==0&&(a.clear(),o())},entries(){return t()}}}var N0=y(()=>{"use strict"});function ma(n){return n.trim().toLowerCase().replace(/^\./,"")}function Kg(n){return Zte.get(ma(n))}function _o(n){let e=Kg(n);return!!(e!=null&&e.enabled)}function jg(n){return["splat","spz","sog"].includes(ma(n))}function sc(){return k3.filter(n=>n.enabled).map(n=>n.ext)}var k3,Zte,Wa=y(()=>{"use strict";k3=[{ext:"glb",family:"mesh",strategy:"direct",directLoader:"babylon",enabled:!0},{ext:"gltf",family:"mesh",strategy:"direct",directLoader:"babylon",enabled:!0},{ext:"stl",family:"mesh",strategy:"direct",directLoader:"custom-stl",enabled:!0},{ext:"obj",family:"mesh",strategy:"direct",directLoader:"babylon",converterId:"obj2gltf",outputFormat:"glb",enabled:!0},{ext:"ply",family:"mesh",strategy:"direct",directLoader:"custom-ply",enabled:!0},{ext:"fbx",family:"mesh",strategy:"convert",converterId:"fbx2gltf",outputFormat:"glb",enabled:!0},{ext:"step",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"stp",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"iges",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"igs",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"brep",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"sldprt",family:"cad",strategy:"convert",converterId:"sldprt",outputFormat:"glb",enabled:!0},{ext:"3mf",family:"mesh",strategy:"convert",converterId:"assimp",outputFormat:"glb",enabled:!0},{ext:"dae",family:"mesh",strategy:"convert",converterId:"assimp",outputFormat:"glb",enabled:!0}],Zte=new Map(k3.map(n=>[n.ext,n]))});var Pbe,_f,w0=y(()=>{"use strict";Wa();Pbe=new Set(sc()),_f={analysisMode:"local",serviceBaseUrl:"",copySourceModelToVault:!1,sourceModelFolder:"Assets/3D",auxiliaryFileFolder:"",reportFolder:"Analysis/3D Reports",partFolder:"Parts/3D Components",previewFolder:"Media/3D Previews",maxFileSizeMb:50,autoGenerateKnowledgeNotes:!0,annotationPreviewMode:"plain-text",annotationDisplayMode:"surface",previewRendererRollout:"babylon-safe",useThreeRenderer:!1,useThreeForConvertedDirectView:!0,experimentalThreeWorkbench:!1,sendRawModelToRemote:!1,sendPreviewImagesToRemote:!1,sendGeometrySummaryToRemote:!1,defaultKnowledgeTaxonomy:"default-v1",defaultCanvasHeight:400,autoRotateDefault:!1,autoRotateSpeed:.5,renderQuality:"high",renderScale:1.5,snapshotFolder:"Media/3D Previews",snapshotNaming:"model-name",enabledConverterIds:[],freecadCommand:"",obj2gltfCommand:"",fbx2gltfCommand:"",assimpCommand:"",freecadcmdCommand:"",preferObj2gltfForObj:!1,preferFbx2gltfForFbx:!1,logLevel:"warn",locale:"en"}});function z3(n){let e={...n},t=new Set;return{getState:()=>e,setState(i){e={...e,...i};let r=[...t];for(let s of r)s()},subscribe(i){return t.add(i),()=>{t.delete(i)}}}}var W3=y(()=>{"use strict"});function fS(n){if(!Number.isFinite(n))return n;let e=Number(n.toPrecision(6));return Object.is(e,-0)?0:e}function Nh(n){return[fS(n[0]),fS(n[1]),fS(n[2])]}function H3(n){return Object.is(fS(n),n)}var dS=y(()=>{"use strict"});function X3(n){return n.trim()}function qte(n){let e=X3(n);return/^Registered from model group with /.test(e)||/^Registered from model component metadata with /.test(e)||/^Merged from [\d,]+ generic tiny meshes? to avoid over-splitting renderer fragments\.$/.test(e)||/^Component ID: .+\.$/.test(e)||/^Occurrence ID: .+\.$/.test(e)||/^Part number: .+\.$/.test(e)||/^Component path: .+\.$/.test(e)||/^Format lineage: .+\.$/.test(e)||/^[\d,]+ triangles? and [\d,]+ vertex(?:es|s)\.$/.test(e)||/^Bounding size [-+0-9.eE]+ x [-+0-9.eE]+ x [-+0-9.eE]+\.$/.test(e)||/^Uses material ".+"\.$/.test(e)}function Qte(n){return n.map(X3).filter(e=>e.length>0)}function Y3(n){let e=Qte(n.observations);return n.reviewed||n.notePath?e.slice(0,16):e.filter(t=>!qte(t)).slice(0,16)}function F0(n){let e=Y3(n);return e.length===n.observations.length&&e.every((t,i)=>t===n.observations[i])}function wh(n){return{...n,meshRefs:n.meshRefs.slice(0,16),materialRefs:n.materialRefs.slice(0,32),observations:Y3(n),registeredMatches:void 0}}var uS=y(()=>{"use strict"});function Q3(n){let e=z3($te),t=null,i=0,r=0,s=null;function a(){t&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,c().catch(u=>console.error("[AI3D] Auto-save failed:",u))},500)}function o(){i+=1,a()}function l(){let u=e.getState();return{stateSchemaVersion:K3,settings:u.settings,convertedAssetRecords:u.convertedAssetRecords,modelAssetProfiles:u.modelAssetProfiles,agentDraft:u.agentDraft,agentPlan:u.agentPlan,lastKnowledgeGeneration:u.lastKnowledgeGeneration}}function c(u=!1){return u&&r>=i&&(i+=1),s||(s=f()),s}async function f(){try{for(;r<i;){let u=i,h=l();await n.saveData(h),r=Math.max(r,u)}}finally{s=null}r<i&&await c()}let d=!1;return{store:e,get localeLoadedFromSaved(){return d},setCurrentModel(u,h){e.setState({currentModelPath:u,modelPreview:h,selectedPart:null})},clearModelPreview(){e.setState({modelPreview:null,selectedPart:null})},updateModelProfile(u,h){var p;let m=e.getState().modelAssetProfiles,g=(p=m[u])!=null?p:V0();e.setState({modelAssetProfiles:{...m,[u]:{...g,...h(g),updatedAt:new Date().toISOString()}}}),o()},setConvertedAssetRecords(u){u!==e.getState().convertedAssetRecords&&(e.setState({convertedAssetRecords:u}),o())},updateSettings(u){let h=e.getState().settings;Object.entries(u).some(([m,g])=>h[m]!==g)&&(e.setState({settings:{...h,...u}}),o())},setLastKnowledgeGeneration(u){u!==e.getState().lastKnowledgeGeneration&&(e.setState({lastKnowledgeGeneration:u}),o())},async load(){var p,_,v,E,S;let u=await n.loadData();if(!u)return;d=!!((p=u.settings)!=null&&p.locale);let h=u.stateSchemaVersion===K3,{profiles:m,changed:g}=eie(u.modelAssetProfiles,{trustPersistedSchema:h});e.setState({settings:{..._f,...(_=u.settings)!=null?_:{}},convertedAssetRecords:(v=u.convertedAssetRecords)!=null?v:[],modelAssetProfiles:m,agentDraft:(E=u.agentDraft)!=null?E:"",agentPlan:(S=u.agentPlan)!=null?S:null,lastKnowledgeGeneration:lie(u.lastKnowledgeGeneration)}),(g||!h)&&(i+=1,t&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,c().catch(T=>console.error("[AI3D] Normalized state save failed:",T))},Jte))},async save(){t&&(window.clearTimeout(t),t=null),await c(!0)},dispose(){t&&(window.clearTimeout(t),t=null),c().catch(u=>console.error("[AI3D] Final save on dispose failed:",u))}}}function eie(n,e={}){if(!n||typeof n!="object")return{profiles:{},changed:!1};let t={},i=!1;for(let[r,s]of Object.entries(n)){if(!s||typeof s!="object")continue;if(e.trustPersistedSchema&&tie(s)){t[r]=s;continue}let a=new Date().toISOString(),o=oie(s.registeredParts,r);i=i||o.changed,t[r]={tags:Array.isArray(s.tags)?s.tags:[],notes:typeof s.notes=="string"?s.notes:"",annotations:Array.isArray(s.annotations)?s.annotations:[],registeredParts:o.parts,analysisVersion:typeof s.analysisVersion=="string"?s.analysisVersion:void 0,reportNotePath:typeof s.reportNotePath=="string"?s.reportNotePath:void 0,analysisSidecarPath:typeof s.analysisSidecarPath=="string"?s.analysisSidecarPath:void 0,previewImagePaths:Array.isArray(s.previewImagePaths)?s.previewImagePaths.filter(l=>typeof l=="string"):void 0,knowledgeIndexPath:typeof s.knowledgeIndexPath=="string"?s.knowledgeIndexPath:void 0,createdAt:typeof s.createdAt=="string"?s.createdAt:a,updatedAt:typeof s.updatedAt=="string"?s.updatedAt:a}}return{profiles:t,changed:i}}function tie(n){return Array.isArray(n.tags)&&typeof n.notes=="string"&&Array.isArray(n.annotations)&&(n.registeredParts===void 0||Array.isArray(n.registeredParts)&&n.registeredParts.length<=hS)&&vo(n.analysisVersion)&&vo(n.reportNotePath)&&vo(n.analysisSidecarPath)&&vo(n.knowledgeIndexPath)&&(n.previewImagePaths===void 0||Array.isArray(n.previewImagePaths))&&typeof n.createdAt=="string"&&typeof n.updatedAt=="string"}function Zg(n,e=Number.POSITIVE_INFINITY){let t=Array.isArray(n)?n.filter(i=>typeof i=="string"&&i.trim().length>0):[];return Number.isFinite(e)?t.slice(0,e):t}function qg(n,e=Number.POSITIVE_INFINITY){return Array.isArray(n)&&(!Number.isFinite(e)||n.length<=e)&&n.every(t=>typeof t=="string"&&t.trim().length>0)}function j3(n){if(!Array.isArray(n)||n.length<3)return;let e=n.slice(0,3).map(t=>Number(t));return e.every(Number.isFinite)?Nh(e):void 0}function mS(n){return Array.isArray(n)&&n.length===3&&n.every(e=>Number.isFinite(e)&&H3(Number(e)))}function $3(n){return n==="group"||n==="mesh"||n==="component"||n==="detail-cluster"?n:void 0}function iie(n){return n===void 0||$3(n)===n}function U0(n){return n==="glb"||n==="gltf"||n==="stl"||n==="obj"||n==="splat"||n==="ply"||n==="fbx"||n==="step"||n==="stp"||n==="iges"||n==="igs"||n==="brep"||n==="sldprt"||n==="3mf"||n==="dae"?n:void 0}function Z3(n){return n===void 0||U0(n)===n}function J3(n){return n==="direct"||n==="convert"?n:void 0}function rie(n){return n===void 0||J3(n)===n}function vo(n){return n===void 0||typeof n=="string"}function B0(n){return n===void 0||Number.isInteger(n)&&Number(n)>=0}function nie(n){if(!n||typeof n!="object")return!1;let e=n;return"registeredMatches"in e?!1:typeof e.partId=="string"&&e.partId.length>0&&typeof e.assetId=="string"&&e.assetId.length>0&&typeof e.name=="string"&&e.name.length>0&&vo(e.parentPartId)&&iie(e.source)&&vo(e.componentId)&&vo(e.occurrenceId)&&vo(e.partNumber)&&vo(e.componentPath)&&vo(e.category)&&qg(e.meshRefs,16)&&B0(e.childCount)&&qg(e.materialRefs,32)&&(e.bbox===void 0||mS(e.bbox))&&(e.center===void 0||mS(e.center))&&B0(e.triangleCount)&&B0(e.vertexCount)&&(typeof e.materialName=="string"||e.materialName===null)&&Z3(e.sourceFormat)&&Z3(e.effectiveFormat)&&rie(e.loadStrategy)&&Number.isFinite(e.confidence)&&Number(e.confidence)>=0&&Number(e.confidence)<=1&&qg(e.observations,16)&&F0(e)&&qg(e.inferredFunctions)&&qg(e.knowledgeTags)&&vo(e.notePath)&&typeof e.reviewed=="boolean"}function sie(n){if(n.length===0)return;if(n.length>hS)return null;let e=new Set;for(let t of n){if(!nie(t))return null;let i=`${t.assetId}:${t.partId}`;if(e.has(i))return null;e.add(i)}return n}function q3(n){return n.reviewed||n.notePath?0:n.source==="component"?1:n.source==="group"?2:n.source==="detail-cluster"?3:4}function aie(n){return n.length<=hS?n:[...n].sort((e,t)=>{var s,a;let i=q3(e)-q3(t);if(i!==0)return i;let r=t.confidence-e.confidence;return r!==0?r:((s=t.childCount)!=null?s:0)-((a=e.childCount)!=null?a:0)}).slice(0,hS)}function oie(n,e){if(!Array.isArray(n))return{parts:void 0,changed:!1};let t=sie(n);if(t!==null)return{parts:t,changed:!1};let i=[],r=new Set,s=!1;for(let o of n){if(!o||typeof o!="object")continue;let l=o;"registeredMatches"in l&&(s=!0),(Array.isArray(l.meshRefs)&&l.meshRefs.length>16||Array.isArray(l.materialRefs)&&l.materialRefs.length>32||Array.isArray(l.observations)&&l.observations.length>16||l.bbox!==void 0&&!mS(l.bbox)||l.center!==void 0&&!mS(l.center))&&(s=!0);let c=typeof l.partId=="string"?l.partId:"",f=typeof l.name=="string"?l.name:"";if(!c||!f)continue;let d=typeof l.assetId=="string"&&l.assetId?l.assetId:e,u=`${d}:${c}`;if(r.has(u))continue;r.add(u);let h={partId:c,assetId:d,parentPartId:typeof l.parentPartId=="string"?l.parentPartId:void 0,name:f,source:$3(l.source),componentId:typeof l.componentId=="string"?l.componentId:void 0,occurrenceId:typeof l.occurrenceId=="string"?l.occurrenceId:void 0,partNumber:typeof l.partNumber=="string"?l.partNumber:void 0,componentPath:typeof l.componentPath=="string"?l.componentPath:void 0,category:typeof l.category=="string"?l.category:void 0,meshRefs:Zg(l.meshRefs,16),childCount:Number.isFinite(l.childCount)?Math.max(0,Math.floor(Number(l.childCount))):void 0,materialRefs:Zg(l.materialRefs,32),bbox:j3(l.bbox),center:j3(l.center),triangleCount:Number.isFinite(l.triangleCount)?Math.max(0,Math.floor(Number(l.triangleCount))):void 0,vertexCount:Number.isFinite(l.vertexCount)?Math.max(0,Math.floor(Number(l.vertexCount))):void 0,materialName:typeof l.materialName=="string"?l.materialName:null,sourceFormat:U0(l.sourceFormat),effectiveFormat:U0(l.effectiveFormat),loadStrategy:J3(l.loadStrategy),confidence:Number.isFinite(l.confidence)?Math.max(0,Math.min(1,Number(l.confidence))):.5,observations:Zg(l.observations,16),inferredFunctions:Zg(l.inferredFunctions),knowledgeTags:Zg(l.knowledgeTags),notePath:typeof l.notePath=="string"?l.notePath:void 0,registeredMatches:void 0,reviewed:l.reviewed===!0},m=wh(h);F0(h)||(s=!0),i.push(m)}let a=aie(i);return(i.length!==n.length||a.length!==i.length)&&(s=!0),{parts:a.length>0?a:void 0,changed:s}}function lie(n){if(!n||typeof n!="object")return null;let e=typeof n.modelPath=="string"?n.modelPath:"";return e?{modelPath:e,reportNotePath:typeof n.reportNotePath=="string"?n.reportNotePath:void 0,analysisSidecarPath:typeof n.analysisSidecarPath=="string"?n.analysisSidecarPath:void 0,knowledgeIndexPath:typeof n.knowledgeIndexPath=="string"?n.knowledgeIndexPath:void 0,partNoteCount:Number.isFinite(n.partNoteCount)?Math.max(0,Math.floor(n.partNoteCount)):0,previewImageCount:Number.isFinite(n.previewImageCount)?Math.max(0,Math.floor(n.previewImageCount)):0,generatedAt:typeof n.generatedAt=="string"?n.generatedAt:new Date().toISOString(),status:n.status==="failed"||n.status==="pending"?n.status:"success",warningCount:Number.isFinite(n.warningCount)?Math.max(0,Math.floor(n.warningCount)):0}:null}function V0(){let n=new Date().toISOString();return{tags:[],notes:"",annotations:[],registeredParts:void 0,createdAt:n,updatedAt:n}}var $te,hS,Jte,K3,G0=y(()=>{"use strict";w0();W3();dS();uS();$te={settings:{..._f},currentModelPath:null,convertedAssetRecords:[],modelAssetProfiles:{},agentDraft:"",agentPlan:null,modelPreview:null,selectedPart:null,lastKnowledgeGeneration:null},hS=256,Jte=50,K3=1});var k0,eB=y(()=>{"use strict";k0={"settings.title":"AI 3D Model Workbench","settings.folders":"Folders","settings.behavior":"Behavior","settings.converters":"Converters","settings.converterMenu":"Model converters","settings.converterMenu.desc":"Closed by default. Open this section only when you want to manually enable an optional local conversion route.","settings.environmentInspector":"Environment inspector","settings.environmentInspector.desc":"Closed by default. Open this section when you need to configure command paths or run environment checks.","settings.paths":"Converter paths","settings.diagnostics":"Converter command diagnostics","settings.performance":"Performance & display","settings.mobileSupport":"Mobile support","settings.knowledgeGeneration":"Knowledge generation","settings.sourceModelFolder":"Source model folder","settings.sourceModelFolder.desc":"Vault folder where source model files are stored.","settings.auxiliaryFileFolder":"Auxiliary file folder","settings.auxiliaryFileFolder.desc":"Vault folder for generated side files such as converted GLB assets. Leave empty to keep them under the Obsidian config folder.","settings.auxiliaryFileFolder.placeholder":"Leave empty for the hidden config folder","settings.reportFolder":"Report folder","settings.reportFolder.desc":"Vault folder where generated knowledge notes are saved.","settings.partFolder":"Part notes folder","settings.partFolder.desc":"Vault folder where generated part note drafts are saved.","settings.snapshotFolder":"Snapshot folder","settings.snapshotFolder.desc":"Vault folder where exported snapshots are saved.","settings.autoGenerateKnowledgeNotes":"Auto-generate knowledge notes","settings.autoGenerateKnowledgeNotes.desc":"Reserved for a future automation flow. For now, generate notes manually from the command palette.","settings.annotationPreviewMode":"Annotation preview mode","settings.annotationPreviewMode.desc":"Choose how bound note previews render in annotation popovers and the editor.","settings.annotationPreviewMode.plainText":"Plain text","settings.annotationPreviewMode.markdown":"Markdown","settings.annotationDisplayMode":"Annotation display mode","settings.annotationDisplayMode.desc":"Choose how bookmark pins appear over the model.","settings.annotationDisplayMode.snippet":"Full snippet","settings.annotationDisplayMode.surface":"Single surface","settings.annotationDisplayMode.dot":"Single dot","settings.previewRendererRollout":"Preview compatibility mode","settings.previewRendererRollout.desc":"Controls how widely the Three.js preview path is used for single-model previews (GLB, GLTF, STL, PLY, OBJ). Switch back to Compatibility mode if pin projection, occlusion, edit pins, snapshots, or toolbar behavior regress. 3dgrid is not affected by this setting.","settings.previewRendererRollout.babylonSafe":"Compatibility mode (Default)","settings.previewRendererRollout.readonly":"Reading surfaces only","settings.previewRendererRollout.direct":"Reading + file view","settings.useThreeRenderer":"Use Three.js renderer","settings.useThreeRenderer.desc":"Toggle between Three.js (faster, lighter) and Babylon.js (full compatibility) for single-model previews. Three.js supports GLB/GLTF/STL/PLY/OBJ. 3dgrid always uses Babylon.js.","settings.useThreeForConvertedDirectView":"Converted GLB Three fast path","settings.useThreeForConvertedDirectView.desc":"When opening STEP, FBX, 3MF, DAE, and other converted files, load the generated GLB with Three.js first and silently fall back to Babylon.js if it fails. Turn this off to make converted files follow the normal compatibility mode.","settings.experimentalThreeWorkbench":"Experimental Three workbench","settings.experimentalThreeWorkbench.desc":"Try the Three.js workbench path for direct GLB/GLTF files only. If loading fails, the file view falls back to Babylon.js automatically.","settings.autoRotateDefault":"Auto-rotate by default","settings.autoRotateDefault.desc":"Start model previews with auto-rotation enabled.","settings.snapshotNaming":"Snapshot naming","settings.snapshotNaming.desc":"How exported snapshot files are named.","settings.snapshotNaming.modelName":"Model name + timestamp","settings.snapshotNaming.timestamp":"Timestamp only","settings.logLevel":"Log level","settings.logLevel.desc":"Controls plugin runtime log verbosity in the developer console.","settings.language":"Language","settings.language.desc":"Choose how AI Model Workbench writes its settings, preview controls, diagnostics, and knowledge-workflow labels. The switch is immediate and stays local to this vault.","settings.language.englishName":"English","settings.language.chineseName":"Simplified Chinese","settings.analysisMode":"AI drafting mode","settings.analysisMode.desc":"Controls whether knowledge-note generation stays local or also requests a sanitized remote draft. Raw model upload is blocked by the current client.","settings.analysisMode.local":"Local evidence only","settings.analysisMode.hybrid":"Local evidence + remote draft","settings.analysisMode.remote":"Remote draft from evidence","settings.serviceBaseUrl":"Draft service URL","settings.serviceBaseUrl.desc":"Optional base URL for a service that accepts POST /draft-note. Leave empty to keep all drafting local.","settings.sendGeometrySummaryToRemote":"Send geometry summary","settings.sendGeometrySummaryToRemote.desc":"Allow sanitized mesh counts, bounds, part candidates, annotation coordinates, and nearest-part links to be included in remote draft input.","settings.sendPreviewImagesToRemote":"Send preview image references","settings.sendPreviewImagesToRemote.desc":"Allow generated preview image paths to be listed in the remote draft input. Image bytes are not uploaded by this client.","settings.sendRawModelToRemote":"Send raw model file","settings.sendRawModelToRemote.desc":"Reserved for future explicit upload support. If enabled manually, remote draft requests are blocked instead of uploading the model.","settings.enableCad":"Enable cad conversion for step, iges, and brep files","settings.enableCad.desc":"Enable cad conversion for step, iges, and brep formats. Requires cadquery and trimesh in your python environment.","settings.enableObj2gltf":"Enable obj2gltf converter (experimental)","settings.enableObj2gltf.desc":"Keep obj direct loading as the default. Enable this only if you want an optional local normalization route through obj2gltf.","settings.preferObj2gltf":"Prefer obj2gltf for obj","settings.preferObj2gltf.desc":"Recommended default is off. Turn this on only when you want normalized output files or direct obj loading is not good enough.","settings.enableFbx2gltf":"Enable FBX2glTF converter","settings.enableFbx2gltf.desc":"Enable conversion for fbx files via FBX2glTF. Requires the FBX2glTF binary installed locally.","settings.enableMesh":"Enable mesh conversion for 3mf and dae files","settings.enableMesh.desc":"Enable conversion for 3mf and dae formats via python trimesh. Requires trimesh, numpy, networkx, and pycollada in your python environment.","settings.enableSldprt":"Enable sldprt conversion for SolidWorks files","settings.enableSldprt.desc":"Enable conversion for SolidWorks sldprt files via FreeCAD. Requires FreeCAD installed locally.","settings.mobileSupport.desc":"On iOS, iPadOS, and Android, direct formats like GLB, GLTF, STL, OBJ, and PLY are supported. Local converter settings and diagnostics remain desktop-only.","settings.pythonCmd":"Path to the python command for cad conversion","settings.pythonCmd.desc":"Optional path to the python command used for cad conversion. Windows usually uses py. macOS and Linux usually use python3. Overrides auto-discovery when set.","settings.freecadCmd":"Path to the FreeCAD command for sldprt conversion","settings.freecadCmd.desc":"Optional path to the FreeCAD command used for SolidWorks file conversion. Windows usually uses FreeCADCmd.exe, macOS usually uses FreeCADCmd, and Linux usually uses freecadcmd. Overrides auto-discovery when set.","settings.obj2gltfCmd":"Path to the obj2gltf command","settings.obj2gltfCmd.desc":"Optional path to the obj2gltf command. Windows usually uses obj2gltf.cmd, and macOS and Linux usually use obj2gltf. Overrides auto-discovery when set.","settings.fbx2gltfCmd":"FBX2glTF command path","settings.fbx2gltfCmd.desc":"Optional path to the FBX2glTF command. Windows usually uses FBX2glTF.exe, and macOS and Linux usually use FBX2glTF. Overrides auto-discovery when set.","settings.assimpCmd":"Path to the python command for 3mf and dae conversion","settings.assimpCmd.desc":"Optional path to the python command used for 3mf and dae conversion. Windows usually uses py. macOS and Linux usually use python3. Overrides auto-discovery when set.","settings.diagnostics.desc":"Shows the exact executable path the plugin would use right now and runs lightweight self-checks for Python environments and converter CLIs.","settings.diagnostics.idle":"Diagnostics are off by default. Click Check now to run them manually.","settings.diagnostics.checkNow":"Check now","settings.diagnostics.checking":"Checking...","settings.diagnostics.refreshed":"Converter command diagnostics refreshed.","settings.diagnostics.checkingAvailability":"Checking converter command availability...","settings.diagnostics.available":"available","settings.diagnostics.notFound":"not found","settings.diagnostics.sourceLabel":"Source","settings.diagnostics.commandLabel":"Command","settings.diagnostics.resolvedPathLabel":"Resolved path","settings.diagnostics.selfCheckLabel":"Self-check","settings.diagnostics.selfCheckOk":"passed","settings.diagnostics.selfCheckFailed":"failed","settings.diagnostics.cadPythonCheck":"Python CAD bridge (cadquery, trimesh, OCP STEP/glTF)","settings.diagnostics.meshPythonCheck":"Python packages (trimesh, numpy, networkx, collada)","settings.diagnostics.freecadCmdCheck":"FreeCADCmd launch probe","settings.diagnostics.obj2gltfCheck":"obj2gltf launch probe","settings.diagnostics.fbx2gltfCheck":"FBX2glTF launch probe","settings.canvasHeight":"Default canvas height","settings.canvasHeight.desc":"Default height (px) for inline model previews. Range: 200\u2013800.","settings.autoRotateSpeed":"Auto-rotate speed","settings.autoRotateSpeed.desc":"Rotation speed when auto-rotate is enabled. Range: 0.1\u20132.0.","settings.renderQuality":"Render quality","settings.renderQuality.desc":"Higher quality uses more GPU resources. Affects anti-aliasing and resolution.","settings.renderScale":"Render scale","settings.renderScale.desc":"Canvas resolution multiplier. 1.0 = native, 0.5 = half, 2.0 = double (supersampling). Range: 0.25\u20132.0.","modelLoad.warningTitle":"Model preview unavailable","modelLoad.warningMessage":"{ext} files need the {converterName} converter enabled in plugin settings before they can load.","modelLoad.warningHint":"Enable the matching converter in plugin settings, then reload this file.","modelLoad.mobileWarningMessage":"{ext} files need local conversion tools that are unavailable on iOS, iPadOS, and Android.","modelLoad.mobileWarningHint":"Open this file on desktop, or convert it to GLB, GLTF, OBJ, STL, or PLY first.","modelLoad.errorTitle":"Couldn't display this model","modelLoad.errorMessage":"Failed to load: {reason}","modelLoad.errorHint":"Check the file format or open the developer console for details.","directView.deferredLoadTitle":"Model preview paused","directView.deferredLoadMessage":"This large or conversion-backed model is paused before loading to keep the vault responsive.","directView.deferredLoadButton":"Load model","headingPin.showSingle":"Show linked pin","headingPin.showMultiple":"Show linked pins","headingPin.linkedTo":"Pin linked to: {models}","helper.resetViewLabel":"Reset view","helper.resetViewDone":"Reset","helper.copyModelInfoLabel":"Copy model info as Markdown","helper.copySelectedPartInfoLabel":"Copy selected part info","helper.noSelectedPart":"Select a part first","helper.copied":"Copied!","helper.failed":"Failed","helper.toggleWireframeLabel":"Toggle wireframe","helper.wireframeOn":"Wireframe","helper.wireframeOff":"Solid","helper.toggleAxesLabel":"Toggle orientation axes","helper.axesOn":"Axes on","helper.axesOff":"Axes off","helper.toggleBoundingBoxLabel":"Toggle bounding box","helper.boundingBoxOn":"Bounding box on","helper.boundingBoxOff":"Bounding box off","helper.toggleFocusSelectionLabel":"Focus selected part","helper.focusSelectionOn":"Focus mode on","helper.focusSelectionOff":"Focus mode off","helper.toggleDisassemblyLabel":"Toggle disassembly mode","helper.disassemblyOn":"Disassembly on","helper.disassemblyOff":"Disassembly off","helper.toggleSliceLabel":"Slice model","helper.sliceButtonText":"Slice","helper.sliceOn":"Slice on","helper.sliceOff":"Slice off","helper.sliceTitle":"Slice","helper.sliceOffsetLabel":"Position:","helper.sliceNormalLabel":"Normal:","helper.sliceTiltLabel":"World tilt:","helper.sliceRotationLabel":"Rotation:","helper.sliceModeLabel":"Control:","helper.sliceModeMove":"Move up/down","helper.sliceModeRotate":"Rotate board","helper.sliceMoveReady":"Drag the center arrow; drag elsewhere to orbit","helper.sliceRotateReady":"Drag a colored ring; drag elsewhere to orbit","helper.sliceMoving":"Moving cutting board","helper.sliceRotating":"Rotating cutting board","helper.sliceGizmoReady":"Drag the arrow or an axis ring; drag elsewhere to orbit","helper.interactionModeAnnotation":"Annotation mode","helper.interactionModeFocus":"Focus mode","helper.interactionModeDisassembly":"Disassembly mode","helper.interactionModeMeasurement":"Measurement mode","helper.interactionModeSlice":"Slice mode","helper.sliceReady":"Plane ready","helper.sliceDragging":"Dragging plane","helper.sliceAxisLabel":"Plane:","helper.sliceAxisValue":"{axis} section plane","helper.slicePlaneX":"YZ","helper.slicePlaneY":"XZ","helper.slicePlaneZ":"XY","helper.slicePositionLabel":"Center:","helper.sliceThicknessLabel":"Window:","helper.slicePresetLabel":"Preset:","helper.slicePresetFine":"Fine","helper.slicePresetThin":"Thin","helper.slicePresetWide":"Wide","helper.slicePresetFull":"Full","helper.sliceNudgeBack":"Move slice backward","helper.sliceNudgeForward":"Move slice forward","helper.sliceNarrower":"Narrow slice window","helper.sliceWider":"Widen slice window","helper.sliceReset":"Reset to world-horizontal center","helper.sliceSummary":"{axis} / {position} / {thickness}","helper.changeResolutionLabel":"Change render scale","helper.resolutionValue":"Render scale: {value}","helper.cameraZoomLabel":"Camera zoom","helper.cameraZoomValue":"Zoom: {value}","helper.toggleAnimationLabel":"Play or pause animation","helper.playing":"Playing","helper.paused":"Paused","helper.toggleMeasurementLabel":"Measure model; focus a part first to limit scope; Alt/Option-click for free pick","helper.measurementOn":"Measurement on","helper.measurementOff":"Measurement off","helper.clearMeasurementsLabel":"Clear measurements","helper.measurementsCleared":"Cleared","helper.copyMeasurementsLabel":"Copy measurements","helper.noMeasurements":"No measurements","helper.measurementsCopied":"Measurements copied","helper.measurementStripTitle":"Measure","helper.measurementStripActive":"Active","helper.measurementSelectTarget":"Select target","helper.measurementPickStart":"Pick start","helper.measurementPickEnd":"Pick end","helper.measurementSnapVertex":"Snap: vertex","helper.measurementSnapEdge":"Snap: edge","helper.measurementSnapFree":"Free pick","helper.measurementTargetLabel":"Target: {target}","helper.measurementTargetMissing":"Click object","helper.measurementTargetModel":"Entire model","helper.measurementReviewing":"Reviewing","helper.measurementStripSaved":"{count} saved","helper.measurementStripEmpty":"No distance","helper.measurementStripMeta":"{count} measurements / {unit}","helper.measurementRecordsTitle":"Records","helper.measurementNoRecords":"No saved measurements","helper.measurementCalibrationTitle":"Reference scale","helper.measurementModelSizeTitle":"Model calibration","helper.measurementUnitLabel":"Unit:","helper.calibrateLabel":"Model scale","helper.calibrateTitle":"Model scale","helper.calibrateReference":"Latest ruler:","helper.calibrateReferenceEmpty":"Measure a distance first","helper.calibrateReferencePlaceholder":"Real length","helper.calibrateReferenceApply":"Scale model","helper.calibrateCurrent":"Model size:","helper.calibrateReal":"Known size:","helper.calibrateLock":"Uniform","helper.calibrateApply":"Apply","helper.calibrateReset":"Reset","helper.calibrated":"Model scale applied","helper.calibrateNeedsValue":"Enter a positive target size","helper.calibrateResetDone":"Model scale reset","helper.calibrateOpen":"Model scale opened","helper.calibrateClose":"Model scale closed","helper.removePreviewLabel":"Remove preview","helper.copySnapshotLabel":"Copy snapshot","helper.saveSnapshotLabel":"Save snapshot to vault","helper.saved":"Saved!","helper.downloadSnapshotLabel":"Download snapshot","helper.downloaded":"Downloaded!","helper.toggleAnnotationLabel":"Toggle annotation mode","helper.toggleAnnotationsVisibilityLabel":"Show or hide annotations","helper.annotateOn":"Annotation mode on","helper.annotateOff":"Annotation mode off","helper.annotationsVisible":"Annotations shown","helper.annotationsHidden":"Annotations hidden","helper.enableInteractionLabel":"Enable touch interaction","helper.disableInteractionLabel":"Return to scroll mode","helper.interactionOn":"Model interaction on","helper.interactionOff":"Scroll mode on","helper.showMoreActionsLabel":"Show more actions","helper.hideMoreActionsLabel":"Hide extra actions","helper.moreActionsShown":"More actions shown","helper.moreActionsHidden":"Extra actions hidden","helper.interactAction":"Interact","helper.scrollAction":"Scroll","previewCanvas.inlineLabel":"3D model preview: {model}","previewCanvas.gridLabel":"3D model grid preview","previewCanvas.liveLabel":"Embedded 3D model preview: {model}","previewCanvas.directLabel":"3D file preview: {model}","workbench.emptyTitle":"No model","workbench.emptyText":'Use the "import 3D model" command to load a GLB, GLTF, STL, OBJ, or PLY file.',"workbench.modelTitle":"Model","workbench.studioTitle":"AI Model Workbench","workbench.studioTagline":"Inspect, annotate, and turn 3D assets into linked notes.","workbench.navLabel":"Workbench sections","workbench.navGallery":"Gallery","workbench.navLibrary":"Library","workbench.navNotebooks":"Notebooks","workbench.navSettings":"Settings","workbench.sourcesTitle":"Model sources","workbench.layersTitle":"Review layers","workbench.viewModeTitle":"View mode","workbench.modeMesh":"Mesh view","workbench.modeFocus":"Focus selection","workbench.modeMeshShort":"Mesh","workbench.modeFocusShort":"Focus","workbench.previewViewsTitle":"Preview views","workbench.connectionsTitle":"Knowledge connections","workbench.currentModelLabel":"Current model","workbench.noReportYet":"No report note yet","workbench.noIndexYet":"No knowledge index yet. Generate a knowledge note first.","workbench.noModelLoaded":"No model loaded","workbench.disassemblyTitle":"Disassembly","workbench.explodeLabel":"Explode","workbench.summaryTitle":"Summary","workbench.meshesLabel":"Meshes","workbench.splatsLabel":"Splats","workbench.trianglesLabel":"Triangles","workbench.verticesLabel":"Vertices","workbench.materialsLabel":"Materials","workbench.boundingSizeLabel":"Bounds","workbench.centerLabel":"Center","workbench.selectedPartTitle":"Selected Part","workbench.partMeshLabel":"Mesh","workbench.noSelectedPart":"Click a model part to inspect it here.","workbench.tagsTitle":"Tags","workbench.noTagsYet":"No tags yet","workbench.addTagPlaceholder":"Add tag...","workbench.addTagAction":"Add","workbench.annotationsTitle":"Annotations","workbench.exitAnnotate":"Exit annotate","workbench.annotate":"Annotate","workbench.annotateHintActive":"Click the model to add a label \xB7 press Esc to exit","workbench.annotateHintActiveMobile":"Tap the model to add a label. Switch back to Scroll when you want to move through the note again.","workbench.pinCount":"{count} pin(s)","workbench.editAction":"Edit","workbench.deleteAction":"Delete","workbench.resetViewAction":"Reset view","workbench.insertInfoAction":"Insert info","workbench.insertGalleryAction":"Insert Gallery","workbench.insertCompareAction":"Insert Compare","workbench.playAction":"Play","workbench.pauseAction":"Pause","workbench.saveProfileAction":"Save profile","workbench.generateNoteAction":"Generate note","workbench.openNoteAction":"Open note","workbench.openIndexAction":"Open index","workbench.recordTitle":"Specimen card","workbench.recordSubtitle":"Current asset profile","workbench.notesTitle":"Analysis notes","workbench.whereTitle":"Where it connects","workbench.noteReady":"Linked note ready","workbench.indexReady":"Knowledge index ready","workbench.notePending":"Linked note pending","workbench.analysisLabel":"Analysis","workbench.settingsUnavailable":"Open this plugin from Obsidian settings to change workbench options.","workbench.profileSaved":"Profile saved","workbench.viewReset":"View reset","workbench.infoInserted":"Model info inserted","workbench.infoCopied":"Model info copied","workbench.templateInserted":"Template inserted","workbench.templateCopied":"Template copied","workbench.mobileHint":"Mobile tip: tap Interact to move the model, then switch back to Scroll to keep reading the note.","workbench.mobileHintInteractive":"Interaction mode is on. Switch back to Scroll when you want to move through the note again.","directView.mobileHint":"Mobile tip: use the toolbar Interact button to switch between model interaction and note scrolling.","directWorkbench.modelLoadInterrupted":"Model load was interrupted by a newer request.","directWorkbench.backendLabel":"Backend","directWorkbench.routeLabel":"Route","directWorkbench.performanceLabel":"Performance","directWorkbench.partCandidatesLabel":"Part candidates","directWorkbench.knowledgeTitle":"Knowledge","directWorkbench.registeredTitle":"Registered part matches","directWorkbench.registeredLoading":"Checking...","directWorkbench.registeredCount":"{count} match(es)","directWorkbench.registeredEmpty":"No cross-model part match yet","directWorkbench.registeredUnavailable":"Part evidence unavailable","directWorkbench.registeredOpen":"Open","directWorkbench.registeredOpenNote":"Note","directWorkbench.registeredOpenModel":"Model","directWorkbench.registeredSourceModel":"From {model}","directWorkbench.registeredTargetPartNote":"Opens matched part note","directWorkbench.registeredTargetSourceModel":"Opens source model","directWorkbench.registeredTargetUnavailable":"No linked target","workbench.fileNotFound":"File not found: {path}","annotation.selectColor":"Select color {color}","annotation.sectionEmpty":"Section is empty.","modal.selectModel":"Select a 3D model...","main.commandImportModel":"Import a 3D model","main.commandGenerateNote":"Generate knowledge note","main.commandOpenKnowledgeIndex":"Open knowledge index","main.commandClearConversionCache":"Clear conversion cache","main.commandCheckConverters":"Check converters","main.commandCopyDiagnostics":"Copy diagnostics report","main.converterDiagnosticsMobileUnavailable":"Converter diagnostics are only available on desktop. On iOS, iPadOS, and Android, direct formats can still load.","main.diagnosticsCopied":"AI Model Workbench diagnostics copied to clipboard.","main.diagnosticsCopyFailed":"Couldn't copy diagnostics. A sanitized diagnostics note was created instead.","codeBlock.noModelPathOrConfig":"No model path or config specified.","codeBlock.jsonParseError":"JSON parse error: {error}","codeBlock.jsonParseLine":" (line {line})","codeBlock.noModelsInConfig":"No models specified in config.","codeBlock.unsupportedFormat":"Unsupported format: {ext}. Supported: {formats}","codeBlock.splatDisabled":"SPLAT preview is disabled in packaged builds. Local-only .splat support is planned first; .spz/.sog need locally bundled decoders before reevaluation.","codeBlock.noConfigSpecified":"No config specified.","codeBlock.noModelsSpecified":"No models specified.","codeBlock.mobileHint":"Mobile tip: use Interact to manipulate the model, then switch back to Scroll to keep moving through the note.","codeBlock.renderingGrid":"Rendering grid...","codeBlock.composeRequiresSections":'"compose" preset requires a "sections" array.',"codeBlock.composeNoValidSections":"Compose: no valid sections.","codeBlock.unknownPreset":'Unknown preset: "{preset}". Available: compare, showcase, explode, timeline, compose',"codeBlock.presetRequiresModels":'Preset "{preset}" requires {min}-{max} models, got {count}.',"codeBlock.gridFailed":"Grid failed: {reason}","livePreview.mobileHint":"Mobile tip: switch between Interact and Scroll depending on whether you want to move the model or keep reading.","loading.default":"Loading...","loading.preparingModel":"Preparing model...","loading.loadingModel":"Loading model..."}});var tB,iB=y(()=>{"use strict";tB={"settings.title":"AI 3D \u6A21\u578B\u5DE5\u4F5C\u53F0","settings.folders":"\u6587\u4EF6\u5939","settings.behavior":"\u884C\u4E3A","settings.converters":"\u8F6C\u6362\u5668","settings.converterMenu":"\u6A21\u578B\u8F6C\u6362\u5668","settings.converterMenu.desc":"\u9ED8\u8BA4\u6536\u8D77\u3002\u4EC5\u5728\u4F60\u9700\u8981\u624B\u52A8\u542F\u7528\u67D0\u6761\u672C\u5730\u8F6C\u6362\u8DEF\u7EBF\u65F6\u518D\u5C55\u5F00\u3002","settings.environmentInspector":"\u73AF\u5883\u68C0\u67E5\u5668","settings.environmentInspector.desc":"\u9ED8\u8BA4\u6536\u8D77\u3002\u4EC5\u5728\u9700\u8981\u914D\u7F6E\u547D\u4EE4\u8DEF\u5F84\u6216\u624B\u52A8\u6267\u884C\u73AF\u5883\u68C0\u67E5\u65F6\u518D\u5C55\u5F00\u3002","settings.paths":"\u8F6C\u6362\u5668\u8DEF\u5F84","settings.diagnostics":"\u8F6C\u6362\u5668\u547D\u4EE4\u8BCA\u65AD","settings.performance":"\u6027\u80FD\u4E0E\u663E\u793A","settings.mobileSupport":"\u79FB\u52A8\u7AEF\u652F\u6301","settings.knowledgeGeneration":"\u77E5\u8BC6\u751F\u6210","settings.sourceModelFolder":"\u6E90\u6A21\u578B\u6587\u4EF6\u5939","settings.sourceModelFolder.desc":"\u5B58\u653E\u6E90 3D \u6A21\u578B\u7684\u5E93\u6587\u4EF6\u5939\u3002","settings.auxiliaryFileFolder":"\u8F85\u52A9\u6587\u4EF6\u5939","settings.auxiliaryFileFolder.desc":"\u7528\u4E8E\u5B58\u653E\u8F6C\u6362\u540E\u7684 GLB \u7B49\u63D2\u4EF6\u751F\u6210\u7684\u526F\u6587\u4EF6\u3002\u7559\u7A7A\u65F6\u7EE7\u7EED\u653E\u5728 Obsidian \u914D\u7F6E\u76EE\u5F55\u4E0B\u3002","settings.auxiliaryFileFolder.placeholder":"\u7559\u7A7A\u4F7F\u7528\u9690\u85CF\u914D\u7F6E\u76EE\u5F55","settings.reportFolder":"\u62A5\u544A\u6587\u4EF6\u5939","settings.reportFolder.desc":"\u4FDD\u5B58\u751F\u6210\u7684\u77E5\u8BC6\u7B14\u8BB0\u7684\u5E93\u6587\u4EF6\u5939\u3002","settings.partFolder":"\u90E8\u4EF6\u7B14\u8BB0\u6587\u4EF6\u5939","settings.partFolder.desc":"\u4FDD\u5B58\u751F\u6210\u7684\u90E8\u4EF6\u7B14\u8BB0\u8349\u7A3F\u7684\u5E93\u6587\u4EF6\u5939\u3002","settings.snapshotFolder":"\u5FEB\u7167\u6587\u4EF6\u5939","settings.snapshotFolder.desc":"\u4FDD\u5B58\u5BFC\u51FA\u5FEB\u7167\u7684\u5E93\u6587\u4EF6\u5939\u3002","settings.autoGenerateKnowledgeNotes":"\u81EA\u52A8\u751F\u6210\u77E5\u8BC6\u7B14\u8BB0","settings.autoGenerateKnowledgeNotes.desc":"\u9884\u7559\u7ED9\u540E\u7EED\u81EA\u52A8\u5316\u6D41\u7A0B\u3002\u5F53\u524D\u8BF7\u901A\u8FC7\u547D\u4EE4\u6216\u5DE5\u4F5C\u53F0\u6309\u94AE\u624B\u52A8\u751F\u6210\u77E5\u8BC6\u7B14\u8BB0\u3002","settings.annotationPreviewMode":"\u6807\u6CE8\u9884\u89C8\u6A21\u5F0F","settings.annotationPreviewMode.desc":"\u9009\u62E9\u6807\u6CE8\u7ED1\u5B9A\u7B14\u8BB0\u5728\u60AC\u6D6E\u9884\u89C8\u548C\u7F16\u8F91\u5668\u4E2D\u7684\u663E\u793A\u65B9\u5F0F\u3002","settings.annotationPreviewMode.plainText":"\u7EAF\u6587\u672C","settings.annotationPreviewMode.markdown":"Markdown","settings.annotationDisplayMode":"\u6807\u6CE8\u663E\u793A\u6A21\u5F0F","settings.annotationDisplayMode.desc":"\u9009\u62E9\u6A21\u578B\u4E0A\u4E66\u7B7E\u6807\u6CE8\u7684\u663E\u793A\u65B9\u5F0F\u3002","settings.annotationDisplayMode.snippet":"\u5B8C\u6574\u7247\u6BB5","settings.annotationDisplayMode.surface":"\u5355\u4E2A\u6807\u7B7E\u9762","settings.annotationDisplayMode.dot":"\u5355\u4E2A\u5706\u70B9","settings.previewRendererRollout":"\u9884\u89C8\u517C\u5BB9\u6A21\u5F0F","settings.previewRendererRollout.desc":"\u63A7\u5236\u5355\u6A21\u578B\u9884\u89C8\uFF08GLB\u3001GLTF\u3001STL\u3001PLY\u3001OBJ\uFF09\u4E2D Three.js \u6E32\u67D3\u8DEF\u5F84\u7684\u542F\u7528\u8303\u56F4\u3002\u53EA\u8981\u51FA\u73B0 pin \u6295\u5F71\u3001\u906E\u6321\u3001\u7F16\u8F91\u6001 pin\u3001\u5FEB\u7167\u6216\u5DE5\u5177\u680F\u884C\u4E3A\u56DE\u9000\uFF0C\u5C31\u5207\u56DE\u201C\u517C\u5BB9\u4F18\u5148\u201D\u3002workbench \u548C 3dgrid \u4E0D\u53D7\u8FD9\u4E2A\u8BBE\u7F6E\u5F71\u54CD\u3002","settings.previewRendererRollout.babylonSafe":"\u517C\u5BB9\u4F18\u5148\uFF08\u9ED8\u8BA4\uFF09","settings.previewRendererRollout.readonly":"\u4EC5\u9605\u8BFB\u573A\u666F","settings.previewRendererRollout.direct":"\u9605\u8BFB + \u6587\u4EF6\u89C6\u56FE","settings.useThreeRenderer":"\u4F7F\u7528 Three.js \u6E32\u67D3\u5668","settings.useThreeRenderer.desc":"\u5728 Three.js\uFF08\u66F4\u5FEB\u3001\u66F4\u8F7B\u91CF\uFF09\u548C Babylon.js\uFF08\u5B8C\u5168\u517C\u5BB9\uFF09\u4E4B\u95F4\u5207\u6362\u5355\u6A21\u578B\u9884\u89C8\u6E32\u67D3\u5668\u3002Three.js \u652F\u6301 GLB/GLTF/STL/PLY/OBJ\u3002\u5DE5\u4F5C\u53F0\u548C 3dgrid \u59CB\u7EC8\u4F7F\u7528 Babylon.js\u3002","settings.useThreeForConvertedDirectView":"\u8F6C\u6362 GLB \u7684 Three \u5FEB\u901F\u8DEF\u5F84","settings.useThreeForConvertedDirectView.desc":"\u6253\u5F00 STEP\u3001FBX\u30013MF\u3001DAE \u7B49\u9700\u8981\u8F6C\u6362\u7684\u6587\u4EF6\u65F6\uFF0C\u5148\u7528 Three.js \u52A0\u8F7D\u751F\u6210\u7684 GLB\uFF0C\u5931\u8D25\u540E\u81EA\u52A8\u56DE\u9000\u5230 Babylon.js\u3002\u5173\u95ED\u540E\u8F6C\u6362\u6587\u4EF6\u4F1A\u9075\u5FAA\u666E\u901A\u517C\u5BB9\u6A21\u5F0F\u3002","settings.experimentalThreeWorkbench":"\u5B9E\u9A8C\u6027 Three \u5DE5\u4F5C\u53F0","settings.experimentalThreeWorkbench.desc":"\u4EC5\u5BF9\u76F4\u8BFB GLB/GLTF \u6587\u4EF6\u5C1D\u8BD5\u4F7F\u7528 Three.js \u5DE5\u4F5C\u53F0\u8DEF\u5F84\u3002\u52A0\u8F7D\u5931\u8D25\u65F6\uFF0C\u6587\u4EF6\u89C6\u56FE\u4F1A\u81EA\u52A8\u56DE\u9000\u5230 Babylon.js\u3002","settings.autoRotateDefault":"\u9ED8\u8BA4\u81EA\u52A8\u65CB\u8F6C","settings.autoRotateDefault.desc":"\u542F\u52A8 3D \u9884\u89C8\u65F6\u9ED8\u8BA4\u5F00\u542F\u81EA\u52A8\u65CB\u8F6C\u3002","settings.snapshotNaming":"\u5FEB\u7167\u547D\u540D","settings.snapshotNaming.desc":"\u5BFC\u51FA\u5FEB\u7167\u6587\u4EF6\u7684\u547D\u540D\u65B9\u5F0F\u3002","settings.snapshotNaming.modelName":"\u6A21\u578B\u540D + \u65F6\u95F4\u6233","settings.snapshotNaming.timestamp":"\u4EC5\u65F6\u95F4\u6233","settings.logLevel":"\u65E5\u5FD7\u7EA7\u522B","settings.logLevel.desc":"\u63A7\u5236\u63D2\u4EF6\u5728\u5F00\u53D1\u8005\u63A7\u5236\u53F0\u4E2D\u7684\u65E5\u5FD7\u8BE6\u7EC6\u7A0B\u5EA6\u3002","settings.language":"\u8BED\u8A00","settings.language.desc":"\u9009\u62E9 AI Model Workbench \u5728\u8BBE\u7F6E\u3001\u9884\u89C8\u63A7\u4EF6\u3001\u8BCA\u65AD\u4FE1\u606F\u548C\u77E5\u8BC6\u6D41\u7A0B\u6807\u7B7E\u4E2D\u7684\u8868\u8FBE\u65B9\u5F0F\u3002\u5207\u6362\u4F1A\u7ACB\u5373\u751F\u6548\uFF0C\u5E76\u4E14\u53EA\u4FDD\u5B58\u5728\u5F53\u524D\u4ED3\u5E93\u3002","settings.language.englishName":"English","settings.language.chineseName":"\u7B80\u4F53\u4E2D\u6587","settings.analysisMode":"AI \u8349\u7A3F\u6A21\u5F0F","settings.analysisMode.desc":"\u63A7\u5236\u77E5\u8BC6\u7B14\u8BB0\u751F\u6210\u4FDD\u6301\u672C\u5730\uFF0C\u8FD8\u662F\u989D\u5916\u8BF7\u6C42\u7ECF\u8FC7\u88C1\u526A\u7684\u8FDC\u7A0B\u8349\u7A3F\u3002\u5F53\u524D\u5BA2\u6237\u7AEF\u4F1A\u963B\u6B62\u539F\u59CB\u6A21\u578B\u4E0A\u4F20\u3002","settings.analysisMode.local":"\u4EC5\u672C\u5730\u8BC1\u636E","settings.analysisMode.hybrid":"\u672C\u5730\u8BC1\u636E + \u8FDC\u7A0B\u8349\u7A3F","settings.analysisMode.remote":"\u57FA\u4E8E\u8BC1\u636E\u7684\u8FDC\u7A0B\u8349\u7A3F","settings.serviceBaseUrl":"\u8349\u7A3F\u670D\u52A1 URL","settings.serviceBaseUrl.desc":"\u53EF\u9009\u7684\u8349\u7A3F\u670D\u52A1\u57FA\u7840\u5730\u5740\uFF0C\u670D\u52A1\u9700\u63A5\u6536 POST /draft-note\u3002\u7559\u7A7A\u65F6\u6240\u6709\u8349\u7A3F\u8F93\u5165\u90FD\u4FDD\u7559\u5728\u672C\u5730\u3002","settings.sendGeometrySummaryToRemote":"\u53D1\u9001\u51E0\u4F55\u6458\u8981","settings.sendGeometrySummaryToRemote.desc":"\u5141\u8BB8\u628A\u7ECF\u8FC7\u88C1\u526A\u7684\u7F51\u683C\u6570\u91CF\u3001\u5305\u56F4\u76D2\u3001\u90E8\u4EF6\u5019\u9009\u3001\u6807\u6CE8\u5750\u6807\u548C\u6700\u8FD1\u90E8\u4EF6\u5173\u8054\u52A0\u5165\u8FDC\u7A0B\u8349\u7A3F\u8F93\u5165\u3002","settings.sendPreviewImagesToRemote":"\u53D1\u9001\u9884\u89C8\u56FE\u5F15\u7528","settings.sendPreviewImagesToRemote.desc":"\u5141\u8BB8\u5728\u8FDC\u7A0B\u8349\u7A3F\u8F93\u5165\u4E2D\u5217\u51FA\u751F\u6210\u7684\u9884\u89C8\u56FE\u8DEF\u5F84\u3002\u5F53\u524D\u5BA2\u6237\u7AEF\u4E0D\u4F1A\u4E0A\u4F20\u56FE\u7247\u5B57\u8282\u3002","settings.sendRawModelToRemote":"\u53D1\u9001\u539F\u59CB\u6A21\u578B\u6587\u4EF6","settings.sendRawModelToRemote.desc":"\u9884\u7559\u7ED9\u672A\u6765\u663E\u5F0F\u4E0A\u4F20\u652F\u6301\u3002\u82E5\u624B\u52A8\u5F00\u542F\uFF0C\u8FDC\u7A0B\u8349\u7A3F\u8BF7\u6C42\u4F1A\u88AB\u963B\u6B62\uFF0C\u4E0D\u4F1A\u4E0A\u4F20\u6A21\u578B\u3002","settings.enableCad":"\u542F\u7528 CAD \u8F6C\u6362\u5668 (STEP/IGES/BREP)","settings.enableCad.desc":"\u542F\u7528 STEP/IGES/BREP \u683C\u5F0F\u7684 CAD \u8F6C\u6362\u8DEF\u7EBF\uFF0C\u901A\u8FC7 Python CadQuery (OpenCASCADE)\u3002\u9700\u8981\uFF1Apip install cadquery trimesh","settings.enableObj2gltf":"\u542F\u7528 obj2gltf \u8F6C\u6362\u5668\uFF08\u5B9E\u9A8C\u6027\uFF09","settings.enableObj2gltf.desc":"\u9ED8\u8BA4\u4F7F\u7528 OBJ \u76F4\u63A5\u52A0\u8F7D\u3002\u4EC5\u5728\u9700\u8981\u672C\u5730\u6807\u51C6\u5316 GLB \u8F93\u51FA\u65F6\u542F\u7528\u3002","settings.preferObj2gltf":"OBJ \u4F18\u5148\u4F7F\u7528 obj2gltf","settings.preferObj2gltf.desc":"\u9ED8\u8BA4\u5173\u95ED\u3002\u4EC5\u5728\u9700\u8981\u6807\u51C6\u5316 GLB \u8F93\u51FA\u6216\u76F4\u63A5 OBJ \u52A0\u8F7D\u6548\u679C\u4E0D\u4F73\u65F6\u5F00\u542F\u3002","settings.enableFbx2gltf":"\u542F\u7528 FBX2glTF \u8F6C\u6362\u5668","settings.enableFbx2gltf.desc":"\u542F\u7528 FBX \u6587\u4EF6\u901A\u8FC7 FBX2glTF \u8F6C\u6362\u3002\u9700\u8981\u672C\u5730\u5B89\u88C5 FBX2glTF \u4E8C\u8FDB\u5236\u6587\u4EF6\u3002","settings.enableMesh":"\u542F\u7528\u7F51\u683C\u8F6C\u6362\u5668 (3MF/DAE)","settings.enableMesh.desc":"\u542F\u7528 3MF \u548C DAE (Collada) \u683C\u5F0F\u7684\u8F6C\u6362\u8DEF\u7EBF\uFF0C\u901A\u8FC7 Python trimesh\u3002\u9700\u8981\u5B89\u88C5 Python \u548C trimesh (pip install trimesh numpy networkx pycollada)\u3002","settings.enableSldprt":"\u542F\u7528 SLDPRT \u8F6C\u6362\u5668 (SolidWorks)","settings.enableSldprt.desc":"\u542F\u7528 SolidWorks .sldprt \u6587\u4EF6\u901A\u8FC7 FreeCAD \u8F6C\u6362\u3002\u9700\u8981\u5B89\u88C5 FreeCAD (https://www.freecad.org/downloads.php)\u3002","settings.mobileSupport.desc":"\u5728 iOS\u3001iPadOS \u548C Android \u4E0A\uFF0CGLB\u3001GLTF\u3001STL\u3001OBJ\u3001PLY \u8FD9\u7C7B\u76F4\u8BFB\u683C\u5F0F\u53EF\u7528\u3002\u672C\u5730\u8F6C\u6362\u5668\u8BBE\u7F6E\u548C\u547D\u4EE4\u8BCA\u65AD\u4ECD\u4EC5\u652F\u6301\u684C\u9762\u7AEF\u3002","settings.pythonCmd":"Python \u547D\u4EE4\u8DEF\u5F84\uFF08CAD \u7528\uFF09","settings.pythonCmd.desc":"\u53EF\u9009\u7684 Python \u547D\u4EE4\u8DEF\u5F84\uFF0C\u7528\u4E8E CAD \u8F6C\u6362\u3002Windows \u901A\u5E38\u7528 py\uFF0CmacOS \u548C Linux \u901A\u5E38\u7528 python3\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_FREECAD_CMD\u3002","settings.freecadCmd":"FreeCAD \u547D\u4EE4\u8DEF\u5F84\uFF08SLDPRT \u7528\uFF09","settings.freecadCmd.desc":"\u53EF\u9009\u7684 FreeCAD \u547D\u4EE4\u8DEF\u5F84\uFF0C\u7528\u4E8E SolidWorks \u6587\u4EF6\u8F6C\u6362\u3002Windows \u901A\u5E38\u7528 FreeCADCmd.exe\uFF0CmacOS \u901A\u5E38\u7528 FreeCADCmd\uFF0CLinux \u901A\u5E38\u7528 freecadcmd\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_FREECADCMD\u3002","settings.obj2gltfCmd":"obj2gltf \u547D\u4EE4\u8DEF\u5F84","settings.obj2gltfCmd.desc":"\u53EF\u9009\u7684 obj2gltf \u547D\u4EE4\u8DEF\u5F84\u3002Windows \u901A\u5E38\u7528 obj2gltf.cmd\uFF0CmacOS \u548C Linux \u901A\u5E38\u7528 obj2gltf\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_OBJ2GLTF_CMD\u3002","settings.fbx2gltfCmd":"FBX2glTF \u547D\u4EE4\u8DEF\u5F84","settings.fbx2gltfCmd.desc":"\u53EF\u9009\u7684 FBX2glTF \u547D\u4EE4\u8DEF\u5F84\u3002Windows \u901A\u5E38\u7528 FBX2glTF.exe\uFF0CmacOS \u548C Linux \u901A\u5E38\u7528 FBX2glTF\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_FBX2GLTF_CMD\u3002","settings.assimpCmd":"Python \u547D\u4EE4\u8DEF\u5F84\uFF083MF/DAE \u7528\uFF09","settings.assimpCmd.desc":"\u53EF\u9009\u7684 Python \u547D\u4EE4\u8DEF\u5F84\uFF0C\u7528\u4E8E 3MF \u548C DAE \u8F6C\u6362\u3002Windows \u901A\u5E38\u7528 py\uFF0CmacOS \u548C Linux \u901A\u5E38\u7528 python3\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_ASSIMP_CMD\u3002","settings.diagnostics.desc":"\u663E\u793A\u63D2\u4EF6\u5F53\u524D\u5B9E\u9645\u4F7F\u7528\u7684\u53EF\u6267\u884C\u6587\u4EF6\u8DEF\u5F84\uFF0C\u5E76\u4E3A Python \u73AF\u5883\u548C\u8F6C\u6362\u5668\u547D\u4EE4\u6267\u884C\u8F7B\u91CF\u81EA\u68C0\u3002","settings.diagnostics.idle":"\u73AF\u5883\u68C0\u67E5\u9ED8\u8BA4\u5173\u95ED\u3002\u70B9\u51FB\u201C\u7ACB\u5373\u68C0\u67E5\u201D\u540E\u624D\u4F1A\u6267\u884C\u3002","settings.diagnostics.checkNow":"\u7ACB\u5373\u68C0\u67E5","settings.diagnostics.checking":"\u68C0\u67E5\u4E2D...","settings.diagnostics.refreshed":"AI 3D \u8F6C\u6362\u5668\u547D\u4EE4\u8BCA\u65AD\u5DF2\u5237\u65B0\u3002","settings.diagnostics.checkingAvailability":"\u6B63\u5728\u68C0\u67E5\u8F6C\u6362\u5668\u547D\u4EE4\u53EF\u7528\u6027...","settings.diagnostics.available":"\u53EF\u7528","settings.diagnostics.notFound":"\u672A\u627E\u5230","settings.diagnostics.sourceLabel":"\u6765\u6E90","settings.diagnostics.commandLabel":"\u547D\u4EE4","settings.diagnostics.resolvedPathLabel":"\u89E3\u6790\u8DEF\u5F84","settings.diagnostics.selfCheckLabel":"\u81EA\u68C0","settings.diagnostics.selfCheckOk":"\u901A\u8FC7","settings.diagnostics.selfCheckFailed":"\u5931\u8D25","settings.diagnostics.cadPythonCheck":"Python \u5305\uFF08cadquery\u3001trimesh\uFF09","settings.diagnostics.meshPythonCheck":"Python \u5305\uFF08trimesh\u3001numpy\u3001networkx\u3001collada\uFF09","settings.diagnostics.freecadCmdCheck":"FreeCADCmd \u542F\u52A8\u63A2\u6D4B","settings.diagnostics.obj2gltfCheck":"obj2gltf \u542F\u52A8\u63A2\u6D4B","settings.diagnostics.fbx2gltfCheck":"FBX2glTF \u542F\u52A8\u63A2\u6D4B","settings.canvasHeight":"\u9ED8\u8BA4\u753B\u5E03\u9AD8\u5EA6","settings.canvasHeight.desc":"\u5185\u8054 3D \u9884\u89C8\u7684\u9ED8\u8BA4\u9AD8\u5EA6\uFF08\u50CF\u7D20\uFF09\u3002\u8303\u56F4\uFF1A200\u2013800\u3002","settings.autoRotateSpeed":"\u81EA\u52A8\u65CB\u8F6C\u901F\u5EA6","settings.autoRotateSpeed.desc":"\u542F\u7528\u81EA\u52A8\u65CB\u8F6C\u65F6\u7684\u65CB\u8F6C\u901F\u5EA6\u3002\u8303\u56F4\uFF1A0.1\u20132.0\u3002","settings.renderQuality":"\u6E32\u67D3\u8D28\u91CF","settings.renderQuality.desc":"\u66F4\u9AD8\u8D28\u91CF\u4F7F\u7528\u66F4\u591A GPU \u8D44\u6E90\u3002\u5F71\u54CD\u6297\u952F\u9F7F\u548C\u5206\u8FA8\u7387\u3002","settings.renderScale":"\u6E32\u67D3\u7F29\u653E","settings.renderScale.desc":"\u753B\u5E03\u5206\u8FA8\u7387\u500D\u6570\u30021.0 = \u539F\u59CB\uFF0C0.5 = \u4E00\u534A\uFF0C2.0 = \u53CC\u500D\uFF08\u8D85\u91C7\u6837\uFF09\u3002\u8303\u56F4\uFF1A0.25\u20132.0\u3002","modelLoad.warningTitle":"\u6682\u65F6\u65E0\u6CD5\u9884\u89C8\u6A21\u578B","modelLoad.warningMessage":"{ext} \u6587\u4EF6\u9700\u8981\u5148\u5728\u63D2\u4EF6\u8BBE\u7F6E\u4E2D\u542F\u7528 {converterName} \u8F6C\u6362\u5668\uFF0C\u624D\u80FD\u52A0\u8F7D\u3002","modelLoad.warningHint":"\u8BF7\u5148\u5728\u63D2\u4EF6\u8BBE\u7F6E\u4E2D\u542F\u7528\u5BF9\u5E94\u8F6C\u6362\u5668\uFF0C\u7136\u540E\u91CD\u65B0\u52A0\u8F7D\u5F53\u524D\u6587\u4EF6\u3002","modelLoad.mobileWarningMessage":"{ext} \u6587\u4EF6\u9700\u8981\u672C\u5730\u8F6C\u6362\u5DE5\u5177\uFF0C\u4F46\u8FD9\u4E9B\u5DE5\u5177\u5728 iOS\u3001iPadOS \u548C Android \u4E0A\u4E0D\u53EF\u7528\u3002","modelLoad.mobileWarningHint":"\u8BF7\u5728\u684C\u9762\u7AEF\u6253\u5F00\u6B64\u6587\u4EF6\uFF0C\u6216\u5148\u5C06\u5B83\u8F6C\u6362\u4E3A GLB\u3001GLTF\u3001OBJ\u3001STL \u6216 PLY\u3002","modelLoad.errorTitle":"\u65E0\u6CD5\u663E\u793A\u8FD9\u4E2A\u6A21\u578B","modelLoad.errorMessage":"\u52A0\u8F7D\u5931\u8D25\uFF1A{reason}","modelLoad.errorHint":"\u8BF7\u68C0\u67E5\u6587\u4EF6\u683C\u5F0F\uFF0C\u6216\u6253\u5F00\u5F00\u53D1\u8005\u63A7\u5236\u53F0\u67E5\u770B\u8BE6\u7EC6\u4FE1\u606F\u3002","directView.deferredLoadTitle":"\u6A21\u578B\u9884\u89C8\u5DF2\u6682\u505C","directView.deferredLoadMessage":"\u8FD9\u4E2A\u5927\u578B\u6216\u9700\u8981\u8F6C\u6362\u7684\u6A21\u578B\u4F1A\u5148\u6682\u505C\u52A0\u8F7D\uFF0C\u4EE5\u4FDD\u6301\u4ED3\u5E93\u54CD\u5E94\u3002","directView.deferredLoadButton":"\u52A0\u8F7D\u6A21\u578B","headingPin.showSingle":"\u663E\u793A\u5173\u8054\u6807\u6CE8","headingPin.showMultiple":"\u663E\u793A\u5173\u8054\u6807\u6CE8","headingPin.linkedTo":"\u5173\u8054\u5230\uFF1A{models}","helper.resetViewLabel":"\u91CD\u7F6E\u89C6\u56FE","helper.resetViewDone":"\u5DF2\u91CD\u7F6E","helper.copyModelInfoLabel":"\u590D\u5236\u6A21\u578B\u4FE1\u606F\u4E3A Markdown","helper.copySelectedPartInfoLabel":"\u590D\u5236\u9009\u4E2D\u90E8\u4EF6\u4FE1\u606F","helper.noSelectedPart":"\u8BF7\u5148\u70B9\u51FB\u4E00\u4E2A\u90E8\u4EF6","helper.copied":"\u5DF2\u590D\u5236","helper.failed":"\u5931\u8D25","helper.toggleWireframeLabel":"\u5207\u6362\u7EBF\u6846\u663E\u793A","helper.wireframeOn":"\u7EBF\u6846","helper.wireframeOff":"\u5B9E\u4F53","helper.toggleAxesLabel":"\u5207\u6362\u65B9\u5411\u5750\u6807\u8F74","helper.axesOn":"\u5750\u6807\u8F74\u5DF2\u5F00\u542F","helper.axesOff":"\u5750\u6807\u8F74\u5DF2\u5173\u95ED","helper.toggleBoundingBoxLabel":"\u5207\u6362\u5305\u56F4\u76D2","helper.boundingBoxOn":"\u5305\u56F4\u76D2\u5DF2\u5F00\u542F","helper.boundingBoxOff":"\u5305\u56F4\u76D2\u5DF2\u5173\u95ED","helper.toggleFocusSelectionLabel":"\u805A\u7126\u9009\u4E2D\u90E8\u4EF6","helper.focusSelectionOn":"\u805A\u7126\u6A21\u5F0F\u5DF2\u5F00\u542F","helper.focusSelectionOff":"\u805A\u7126\u6A21\u5F0F\u5DF2\u5173\u95ED","helper.toggleDisassemblyLabel":"\u5207\u6362\u5206\u89E3\u6A21\u5F0F","helper.disassemblyOn":"\u5206\u89E3\u6A21\u5F0F\u5DF2\u5F00\u542F","helper.disassemblyOff":"\u5206\u89E3\u6A21\u5F0F\u5DF2\u5173\u95ED","helper.toggleSliceLabel":"\u5207\u7247\u6A21\u578B","helper.sliceButtonText":"\u5207\u7247","helper.sliceOn":"\u5207\u7247\u5DF2\u5F00\u542F","helper.sliceOff":"\u5207\u7247\u5DF2\u5173\u95ED","helper.sliceTitle":"\u5207\u7247","helper.sliceOffsetLabel":"\u4F4D\u7F6E\uFF1A","helper.sliceNormalLabel":"\u6CD5\u7EBF\uFF1A","helper.sliceTiltLabel":"\u4E16\u754C\u503E\u89D2\uFF1A","helper.sliceRotationLabel":"\u65CB\u8F6C\uFF1A","helper.sliceModeLabel":"\u63A7\u5236\uFF1A","helper.sliceModeMove":"\u4E0A\u4E0B\u79FB\u52A8","helper.sliceModeRotate":"\u65CB\u8F6C\u677F\u5B50","helper.sliceMoveReady":"\u62D6\u52A8\u4E2D\u5FC3\u7BAD\u5934\u79FB\u52A8\uFF0C\u5176\u4ED6\u533A\u57DF\u65CB\u8F6C\u89C6\u89D2","helper.sliceRotateReady":"\u62D6\u52A8\u5F69\u8272\u65CB\u8F6C\u73AF\uFF0C\u5176\u4ED6\u533A\u57DF\u65CB\u8F6C\u89C6\u89D2","helper.sliceMoving":"\u6B63\u5728\u79FB\u52A8\u5207\u7247\u677F","helper.sliceRotating":"\u6B63\u5728\u65CB\u8F6C\u5207\u7247\u677F","helper.sliceGizmoReady":"\u62D6\u52A8\u7BAD\u5934\u6216\u8F74\u5411\u5706\u73AF\uFF0C\u5176\u4ED6\u533A\u57DF\u65CB\u8F6C\u89C6\u89D2","helper.interactionModeAnnotation":"\u6807\u6CE8\u6A21\u5F0F","helper.interactionModeFocus":"\u805A\u7126\u6A21\u5F0F","helper.interactionModeDisassembly":"\u62C6\u89E3\u6A21\u5F0F","helper.interactionModeMeasurement":"\u6D4B\u91CF\u6A21\u5F0F","helper.interactionModeSlice":"\u5207\u7247\u6A21\u5F0F","helper.sliceReady":"\u5207\u9762\u5C31\u7EEA","helper.sliceDragging":"\u6B63\u5728\u62D6\u52A8\u5207\u9762","helper.sliceAxisLabel":"\u622A\u9762\uFF1A","helper.sliceAxisValue":"{axis} \u622A\u9762","helper.slicePlaneX":"YZ","helper.slicePlaneY":"XZ","helper.slicePlaneZ":"XY","helper.slicePositionLabel":"\u4E2D\u5FC3\uFF1A","helper.sliceThicknessLabel":"\u7A97\u53E3\uFF1A","helper.slicePresetLabel":"\u9884\u8BBE\uFF1A","helper.slicePresetFine":"\u7CBE\u7EC6","helper.slicePresetThin":"\u8584\u7247","helper.slicePresetWide":"\u5BBD\u7A97","helper.slicePresetFull":"\u5168\u539A","helper.sliceNudgeBack":"\u540E\u79FB\u5207\u7247","helper.sliceNudgeForward":"\u524D\u79FB\u5207\u7247","helper.sliceNarrower":"\u7F29\u5C0F\u5207\u7247\u7A97\u53E3","helper.sliceWider":"\u6269\u5927\u5207\u7247\u7A97\u53E3","helper.sliceReset":"\u91CD\u7F6E\u4E3A\u4E16\u754C\u6C34\u5E73\u4E2D\u5FC3","helper.sliceSummary":"{axis} / {position} / {thickness}","helper.changeResolutionLabel":"\u5207\u6362\u6E32\u67D3\u7F29\u653E","helper.resolutionValue":"\u6E32\u67D3\u7F29\u653E\uFF1A{value}","helper.cameraZoomLabel":"\u76F8\u673A\u7F29\u653E","helper.cameraZoomValue":"\u7F29\u653E\uFF1A{value}","helper.toggleAnimationLabel":"\u64AD\u653E\u6216\u6682\u505C\u52A8\u753B","helper.playing":"\u64AD\u653E\u4E2D","helper.paused":"\u5DF2\u6682\u505C","helper.toggleMeasurementLabel":"\u6D4B\u91CF\u6574\u4E2A\u6A21\u578B\uFF1B\u5148\u805A\u7126\u96F6\u4EF6\u53EF\u9650\u5236\u8303\u56F4\uFF1B\u6309 Alt/Option \u81EA\u7531\u53D6\u70B9","helper.measurementOn":"\u6D4B\u91CF\u5DF2\u5F00\u542F","helper.measurementOff":"\u6D4B\u91CF\u5DF2\u5173\u95ED","helper.clearMeasurementsLabel":"\u6E05\u9664\u6D4B\u91CF","helper.measurementsCleared":"\u5DF2\u6E05\u9664","helper.copyMeasurementsLabel":"\u590D\u5236\u6D4B\u91CF","helper.noMeasurements":"\u6682\u65E0\u6D4B\u91CF","helper.measurementsCopied":"\u6D4B\u91CF\u5DF2\u590D\u5236","helper.measurementStripTitle":"\u6D4B\u91CF","helper.measurementStripActive":"\u8FDB\u884C\u4E2D","helper.measurementSelectTarget":"\u9009\u62E9\u76EE\u6807","helper.measurementPickStart":"\u9009\u62E9\u8D77\u70B9","helper.measurementPickEnd":"\u9009\u62E9\u7EC8\u70B9","helper.measurementSnapVertex":"\u5438\u9644\uFF1A\u9876\u70B9","helper.measurementSnapEdge":"\u5438\u9644\uFF1A\u8FB9","helper.measurementSnapFree":"\u81EA\u7531\u53D6\u70B9","helper.measurementTargetLabel":"\u76EE\u6807\uFF1A{target}","helper.measurementTargetMissing":"\u70B9\u51FB\u5BF9\u8C61","helper.measurementTargetModel":"\u6574\u4E2A\u6A21\u578B","helper.measurementReviewing":"\u67E5\u770B\u6D4B\u91CF","helper.measurementStripSaved":"{count} \u6761","helper.measurementStripEmpty":"\u672A\u8BB0\u5F55","helper.measurementStripMeta":"{count} \u6761 / {unit}","helper.measurementRecordsTitle":"\u8BB0\u5F55","helper.measurementNoRecords":"\u6682\u65E0\u4FDD\u5B58\u7684\u6D4B\u91CF","helper.measurementCalibrationTitle":"\u53C2\u8003\u7F29\u653E","helper.measurementModelSizeTitle":"\u6A21\u578B\u6821\u51C6","helper.measurementUnitLabel":"\u5355\u4F4D\uFF1A","helper.calibrateLabel":"\u6A21\u578B\u7F29\u653E","helper.calibrateTitle":"\u6A21\u578B\u7F29\u653E","helper.calibrateReference":"\u6700\u65B0\u5C3A\u5B50\uFF1A","helper.calibrateReferenceEmpty":"\u8BF7\u5148\u6D4B\u91CF\u4E00\u6BB5\u8DDD\u79BB","helper.calibrateReferencePlaceholder":"\u771F\u5B9E\u957F\u5EA6","helper.calibrateReferenceApply":"\u7F29\u653E\u6A21\u578B","helper.calibrateCurrent":"\u6A21\u578B\u5C3A\u5BF8\uFF1A","helper.calibrateReal":"\u5DF2\u77E5\u5C3A\u5BF8\uFF1A","helper.calibrateLock":"\u7B49\u6BD4","helper.calibrateApply":"\u5E94\u7528","helper.calibrateReset":"\u91CD\u7F6E","helper.calibrated":"\u6A21\u578B\u7F29\u653E\u5DF2\u5E94\u7528","helper.calibrateNeedsValue":"\u8BF7\u8F93\u5165\u6B63\u6570\u76EE\u6807\u5C3A\u5BF8","helper.calibrateResetDone":"\u6A21\u578B\u7F29\u653E\u5DF2\u91CD\u7F6E","helper.calibrateOpen":"\u6A21\u578B\u7F29\u653E\u5DF2\u5C55\u5F00","helper.calibrateClose":"\u6A21\u578B\u7F29\u653E\u5DF2\u6536\u8D77","helper.removePreviewLabel":"\u79FB\u9664\u9884\u89C8","helper.copySnapshotLabel":"\u590D\u5236\u5FEB\u7167","helper.saveSnapshotLabel":"\u4FDD\u5B58\u5FEB\u7167\u5230\u4ED3\u5E93","helper.saved":"\u5DF2\u4FDD\u5B58","helper.downloadSnapshotLabel":"\u4E0B\u8F7D\u5FEB\u7167","helper.downloaded":"\u5DF2\u4E0B\u8F7D","helper.toggleAnnotationLabel":"\u5207\u6362\u6807\u6CE8\u6A21\u5F0F","helper.toggleAnnotationsVisibilityLabel":"\u663E\u793A\u6216\u9690\u85CF\u6807\u6CE8","helper.annotateOn":"\u6807\u6CE8\u6A21\u5F0F\u5DF2\u5F00\u542F","helper.annotateOff":"\u6807\u6CE8\u6A21\u5F0F\u5DF2\u5173\u95ED","helper.annotationsVisible":"\u6807\u6CE8\u5DF2\u663E\u793A","helper.annotationsHidden":"\u6807\u6CE8\u5DF2\u9690\u85CF","helper.enableInteractionLabel":"\u542F\u7528\u89E6\u63A7\u4EA4\u4E92","helper.disableInteractionLabel":"\u5207\u56DE\u6EDA\u52A8\u6A21\u5F0F","helper.interactionOn":"\u6A21\u578B\u4EA4\u4E92\u5DF2\u5F00\u542F","helper.interactionOff":"\u6EDA\u52A8\u6A21\u5F0F\u5DF2\u5F00\u542F","helper.showMoreActionsLabel":"\u663E\u793A\u66F4\u591A\u64CD\u4F5C","helper.hideMoreActionsLabel":"\u6536\u8D77\u989D\u5916\u64CD\u4F5C","helper.moreActionsShown":"\u5DF2\u5C55\u5F00\u66F4\u591A\u64CD\u4F5C","helper.moreActionsHidden":"\u5DF2\u6536\u8D77\u989D\u5916\u64CD\u4F5C","helper.interactAction":"\u4EA4\u4E92","helper.scrollAction":"\u6EDA\u52A8","previewCanvas.inlineLabel":"3D model preview: {model}","previewCanvas.gridLabel":"3D model grid preview","previewCanvas.liveLabel":"Embedded 3D model preview: {model}","previewCanvas.directLabel":"3D file preview: {model}","workbench.emptyTitle":"\u6682\u65E0\u6A21\u578B","workbench.emptyText":"\u4F7F\u7528\u201C\u5BFC\u5165 3D \u6A21\u578B\u201D\u547D\u4EE4\u52A0\u8F7D GLB\u3001GLTF\u3001STL\u3001OBJ \u6216 PLY \u6587\u4EF6\u3002","workbench.modelTitle":"3D \u6A21\u578B","workbench.studioTitle":"AI \u6A21\u578B\u5DE5\u4F5C\u53F0","workbench.studioTagline":"\u68C0\u67E5\u3001\u6807\u6CE8\uFF0C\u5E76\u628A 3D \u8D44\u4EA7\u6574\u7406\u6210\u53CC\u94FE\u7B14\u8BB0\u3002","workbench.navLabel":"\u5DE5\u4F5C\u53F0\u5206\u533A","workbench.navGallery":"\u753B\u5ECA","workbench.navLibrary":"\u8D44\u6599\u5E93","workbench.navNotebooks":"\u7B14\u8BB0\u672C","workbench.navSettings":"\u8BBE\u7F6E","workbench.sourcesTitle":"\u6A21\u578B\u6765\u6E90","workbench.layersTitle":"\u5BA1\u9605\u5C42","workbench.viewModeTitle":"\u89C6\u56FE\u6A21\u5F0F","workbench.modeMesh":"\u7F51\u683C\u89C6\u56FE","workbench.modeFocus":"\u805A\u7126\u9009\u533A","workbench.modeMeshShort":"\u7F51\u683C","workbench.modeFocusShort":"\u805A\u7126","workbench.previewViewsTitle":"\u9884\u89C8\u89C6\u56FE","workbench.connectionsTitle":"\u77E5\u8BC6\u8FDE\u63A5","workbench.currentModelLabel":"\u5F53\u524D\u6A21\u578B","workbench.noReportYet":"\u8FD8\u6CA1\u6709\u62A5\u544A\u7B14\u8BB0","workbench.noIndexYet":"\u8FD8\u6CA1\u6709\u77E5\u8BC6\u7D22\u5F15\u3002\u8BF7\u5148\u751F\u6210\u77E5\u8BC6\u7B14\u8BB0\u3002","workbench.noModelLoaded":"\u5C1A\u672A\u52A0\u8F7D\u6A21\u578B","workbench.disassemblyTitle":"\u5206\u89E3","workbench.explodeLabel":"\u7206\u70B8","workbench.summaryTitle":"\u6458\u8981","workbench.meshesLabel":"\u7F51\u683C","workbench.splatsLabel":"\u70B9\u4E91","workbench.trianglesLabel":"\u4E09\u89D2\u5F62","workbench.verticesLabel":"\u9876\u70B9","workbench.materialsLabel":"\u6750\u8D28","workbench.boundingSizeLabel":"\u5305\u56F4\u76D2","workbench.centerLabel":"\u4E2D\u5FC3","workbench.selectedPartTitle":"\u5F53\u524D\u9009\u4E2D\u90E8\u4EF6","workbench.partMeshLabel":"\u7F51\u683C","workbench.noSelectedPart":"\u70B9\u51FB\u6A21\u578B\u4E2D\u7684\u90E8\u4EF6\u540E\u4F1A\u663E\u793A\u8BE6\u7EC6\u4FE1\u606F\u3002","workbench.tagsTitle":"\u6807\u7B7E","workbench.noTagsYet":"\u8FD8\u6CA1\u6709\u6807\u7B7E","workbench.addTagPlaceholder":"\u6DFB\u52A0\u6807\u7B7E...","workbench.addTagAction":"\u6DFB\u52A0","workbench.annotationsTitle":"\u6807\u6CE8","workbench.exitAnnotate":"\u9000\u51FA\u6807\u6CE8","workbench.annotate":"\u6807\u6CE8","workbench.annotateHintActive":"\u70B9\u51FB\u6A21\u578B\u6DFB\u52A0\u6807\u7B7E \xB7 \u6309 Esc \u9000\u51FA","workbench.annotateHintActiveMobile":"\u70B9\u6309\u6A21\u578B\u6DFB\u52A0\u6807\u7B7E\u3002\u9700\u8981\u7EE7\u7EED\u9605\u8BFB\u65F6\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","workbench.pinCount":"{count} \u4E2A\u6807\u6CE8","workbench.editAction":"\u7F16\u8F91","workbench.deleteAction":"\u5220\u9664","workbench.resetViewAction":"\u91CD\u7F6E\u89C6\u56FE","workbench.insertInfoAction":"\u63D2\u5165\u4FE1\u606F","workbench.insertGalleryAction":"\u63D2\u5165 Gallery","workbench.insertCompareAction":"\u63D2\u5165\u5BF9\u6BD4","workbench.playAction":"\u64AD\u653E","workbench.pauseAction":"\u6682\u505C","workbench.saveProfileAction":"\u4FDD\u5B58\u914D\u7F6E","workbench.generateNoteAction":"\u751F\u6210\u7B14\u8BB0","workbench.openNoteAction":"\u6253\u5F00\u7B14\u8BB0","workbench.openIndexAction":"\u6253\u5F00\u7D22\u5F15","workbench.recordTitle":"\u6807\u672C\u5361","workbench.recordSubtitle":"\u5F53\u524D\u8D44\u4EA7\u6863\u6848","workbench.notesTitle":"\u5206\u6790\u672D\u8BB0","workbench.whereTitle":"\u5173\u8054\u4F4D\u7F6E","workbench.noteReady":"\u5173\u8054\u7B14\u8BB0\u5DF2\u5C31\u7EEA","workbench.indexReady":"\u77E5\u8BC6\u7D22\u5F15\u5DF2\u5C31\u7EEA","workbench.notePending":"\u5173\u8054\u7B14\u8BB0\u5F85\u751F\u6210","workbench.analysisLabel":"\u5206\u6790","workbench.settingsUnavailable":"\u8BF7\u4ECE Obsidian \u8BBE\u7F6E\u4E2D\u6253\u5F00\u672C\u63D2\u4EF6\u6765\u8C03\u6574\u5DE5\u4F5C\u53F0\u9009\u9879\u3002","workbench.profileSaved":"\u914D\u7F6E\u5DF2\u4FDD\u5B58","workbench.viewReset":"\u89C6\u56FE\u5DF2\u91CD\u7F6E","workbench.infoInserted":"\u6A21\u578B\u4FE1\u606F\u5DF2\u63D2\u5165","workbench.infoCopied":"\u6A21\u578B\u4FE1\u606F\u5DF2\u590D\u5236","workbench.templateInserted":"\u6A21\u677F\u5DF2\u63D2\u5165","workbench.templateCopied":"\u6A21\u677F\u5DF2\u590D\u5236","workbench.mobileHint":"\u79FB\u52A8\u7AEF\u63D0\u793A\uFF1A\u9700\u8981\u64CD\u4F5C\u6A21\u578B\u65F6\u70B9\u201C\u4EA4\u4E92\u201D\uFF0C\u7EE7\u7EED\u9605\u8BFB\u7B14\u8BB0\u65F6\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","workbench.mobileHintInteractive":"\u5F53\u524D\u4E3A\u4EA4\u4E92\u6A21\u5F0F\u3002\u9700\u8981\u7EE7\u7EED\u6EDA\u52A8\u7B14\u8BB0\u65F6\uFF0C\u8BF7\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","directView.mobileHint":"\u79FB\u52A8\u7AEF\u63D0\u793A\uFF1A\u4F7F\u7528\u4E0B\u65B9\u5DE5\u5177\u680F\u91CC\u7684\u201C\u4EA4\u4E92\u201D\u6309\u94AE\uFF0C\u5728\u6A21\u578B\u64CD\u4F5C\u548C\u7B14\u8BB0\u6EDA\u52A8\u4E4B\u95F4\u5207\u6362\u3002","directWorkbench.modelLoadInterrupted":"\u6A21\u578B\u52A0\u8F7D\u88AB\u65B0\u8BF7\u6C42\u4E2D\u65AD\u3002","directWorkbench.backendLabel":"\u540E\u7AEF","directWorkbench.routeLabel":"\u8DEF\u7531","directWorkbench.performanceLabel":"\u6027\u80FD","directWorkbench.partCandidatesLabel":"\u5019\u9009\u96F6\u4EF6","directWorkbench.knowledgeTitle":"\u77E5\u8BC6","directWorkbench.registeredTitle":"\u5DF2\u6CE8\u518C\u96F6\u4EF6\u5339\u914D","directWorkbench.registeredLoading":"\u68C0\u67E5\u4E2D...","directWorkbench.registeredCount":"{count} \u4E2A\u5339\u914D","directWorkbench.registeredEmpty":"\u6682\u65E0\u8DE8\u6A21\u578B\u96F6\u4EF6\u5339\u914D","directWorkbench.registeredUnavailable":"\u6682\u65E0\u96F6\u4EF6\u8BC1\u636E","directWorkbench.registeredOpen":"\u6253\u5F00","directWorkbench.registeredOpenNote":"\u7B14\u8BB0","directWorkbench.registeredOpenModel":"\u6A21\u578B","directWorkbench.registeredSourceModel":"\u6765\u81EA {model}","directWorkbench.registeredTargetPartNote":"\u6253\u5F00\u5339\u914D\u96F6\u4EF6\u7B14\u8BB0","directWorkbench.registeredTargetSourceModel":"\u6253\u5F00\u6765\u6E90\u6A21\u578B","directWorkbench.registeredTargetUnavailable":"\u6682\u65E0\u53EF\u6253\u5F00\u76EE\u6807","workbench.fileNotFound":"\u672A\u627E\u5230\u6587\u4EF6\uFF1A{path}","annotation.selectColor":"\u9009\u62E9\u989C\u8272 {color}","annotation.sectionEmpty":"\u8BE5\u6BB5\u5185\u5BB9\u4E3A\u7A7A\u3002","modal.selectModel":"\u9009\u62E9\u4E00\u4E2A 3D \u6A21\u578B...","main.commandImportModel":"\u5BFC\u5165 3D \u6A21\u578B","main.commandGenerateNote":"\u751F\u6210\u77E5\u8BC6\u7B14\u8BB0","main.commandOpenKnowledgeIndex":"\u6253\u5F00\u77E5\u8BC6\u7D22\u5F15","main.commandClearConversionCache":"\u6E05\u9664\u8F6C\u6362\u7F13\u5B58","main.commandCheckConverters":"\u68C0\u67E5\u8F6C\u6362\u5668","main.commandCopyDiagnostics":"\u590D\u5236\u8BCA\u65AD\u62A5\u544A","main.converterDiagnosticsMobileUnavailable":"\u8F6C\u6362\u5668\u8BCA\u65AD\u4EC5\u652F\u6301\u684C\u9762\u7AEF\u3002\u5728 iOS\u3001iPadOS \u548C Android \u4E0A\uFF0C\u76F4\u8BFB\u683C\u5F0F\u4ECD\u53EF\u52A0\u8F7D\u3002","main.diagnosticsCopied":"AI Model Workbench \u8BCA\u65AD\u62A5\u544A\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\u3002","main.diagnosticsCopyFailed":"\u65E0\u6CD5\u590D\u5236\u8BCA\u65AD\u62A5\u544A\uFF0C\u5DF2\u6539\u4E3A\u521B\u5EFA\u4E00\u4EFD\u8131\u654F\u8BCA\u65AD\u7B14\u8BB0\u3002","codeBlock.noModelPathOrConfig":"\u672A\u6307\u5B9A\u6A21\u578B\u8DEF\u5F84\u6216\u914D\u7F6E\u3002","codeBlock.jsonParseError":"JSON \u89E3\u6790\u9519\u8BEF\uFF1A{error}","codeBlock.jsonParseLine":"\uFF08\u7B2C {line} \u884C\uFF09","codeBlock.noModelsInConfig":"\u914D\u7F6E\u4E2D\u672A\u6307\u5B9A\u6A21\u578B\u3002","codeBlock.unsupportedFormat":"\u4E0D\u652F\u6301\u7684\u683C\u5F0F\uFF1A{ext}\u3002\u652F\u6301\uFF1A{formats}","codeBlock.splatDisabled":"\u5F53\u524D\u6253\u5305\u7248\u672C\u6682\u672A\u542F\u7528 SPLAT \u9884\u89C8\u3002\u540E\u7EED\u4F1A\u4F18\u5148\u6062\u590D\u672C\u5730-only .splat\uFF1B.spz/.sog \u9700\u8981\u672C\u5730\u6253\u5305\u89E3\u7801\u5668\u540E\u518D\u8BC4\u4F30\u3002","codeBlock.noConfigSpecified":"\u672A\u6307\u5B9A\u914D\u7F6E\u3002","codeBlock.noModelsSpecified":"\u672A\u6307\u5B9A\u6A21\u578B\u3002","codeBlock.mobileHint":"\u79FB\u52A8\u7AEF\u63D0\u793A\uFF1A\u9700\u8981\u64CD\u4F5C\u6A21\u578B\u65F6\u70B9\u201C\u4EA4\u4E92\u201D\uFF0C\u7EE7\u7EED\u9605\u8BFB\u7B14\u8BB0\u65F6\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","codeBlock.renderingGrid":"\u6B63\u5728\u6E32\u67D3\u7F51\u683C...","codeBlock.composeRequiresSections":"\u201Ccompose\u201D \u9884\u8BBE\u9700\u8981\u63D0\u4F9B \u201Csections\u201D \u6570\u7EC4\u3002","codeBlock.composeNoValidSections":"Compose\uFF1A\u6CA1\u6709\u6709\u6548\u7684\u5206\u6BB5\u3002","codeBlock.unknownPreset":"\u672A\u77E5\u9884\u8BBE\uFF1A\u201C{preset}\u201D\u3002\u53EF\u7528\uFF1Acompare\u3001showcase\u3001explode\u3001timeline\u3001compose","codeBlock.presetRequiresModels":"\u9884\u8BBE \u201C{preset}\u201D \u9700\u8981 {min}-{max} \u4E2A\u6A21\u578B\uFF0C\u5F53\u524D\u4E3A {count} \u4E2A\u3002","codeBlock.gridFailed":"\u7F51\u683C\u6E32\u67D3\u5931\u8D25\uFF1A{reason}","livePreview.mobileHint":"\u79FB\u52A8\u7AEF\u63D0\u793A\uFF1A\u9700\u8981\u62D6\u52A8\u6A21\u578B\u65F6\u5207\u5230\u201C\u4EA4\u4E92\u201D\uFF0C\u7EE7\u7EED\u9605\u8BFB\u65F6\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","loading.default":"\u52A0\u8F7D\u4E2D...","loading.preparingModel":"\u6B63\u5728\u51C6\u5907\u6A21\u578B...","loading.loadingModel":"\u6B63\u5728\u52A0\u8F7D\u6A21\u578B..."}});function Fh(n){rB=n;for(let e of z0)e()}function H(n){var e,t,i;return(i=(t=(e=cie[rB])==null?void 0:e[n])!=null?t:k0[n])!=null?i:n}function nB(n){return z0.add(n),()=>{z0.delete(n)}}function fie(n,e){return n.replace(/\{(\w+)\}/g,(t,i)=>{var r;return(r=e[i])!=null?r:""})}function Wi(n,e){return fie(H(n),e)}var cie,rB,z0,xn=y(()=>{"use strict";eB();iB();cie={en:k0,"zh-CN":tB},rB="en",z0=new Set});var Qd,pS=y(()=>{"use strict";Qd="ai3d-direct-view"});function $d(n){var t,i;n.classList.add(sB),(t=n.closest(".workspace-leaf"))==null||t.classList.add(aB);let e=(i=n.closest(".workspace-leaf-content"))!=null?i:n.parentElement;e==null||e.classList.add(oB)}function gS(n){var t,i;n.classList.remove(sB),(t=n.closest(".workspace-leaf"))==null||t.classList.remove(aB);let e=(i=n.closest(".workspace-leaf-content"))!=null?i:n.parentElement;e==null||e.classList.remove(oB)}var sB,aB,oB,W0=y(()=>{"use strict";sB="ai3d-direct-view",aB="ai3d-direct-view-leaf",oB="ai3d-direct-view-leaf-content"});var cB={};Be(cB,{listPreferredConversionExts:()=>vf});function vf(n){let e=[];return n.preferObj2gltfForObj&&e.push("obj"),n.preferFbx2gltfForFbx&&e.push("fbx"),e}var e_=y(()=>{"use strict"});function mie(n){return n!=null?n:dB}function Bh(n){var c;let e=n.ext.trim().toLowerCase(),t=(c=n.annotationMode)!=null?c:"none",i=!!n.allowEditModeOnThree,r=!!n.allowWorkbenchFeaturesOnThree,s=!!n.requireWorkbenchFeatures,a=mie(n.rendererRollout);if(!(n.useThreeRenderer!==!1))return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:"useThreeRenderer=false"};if(fB.has(e)&&(!s||r)){if(s&&!hie.has(e))return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:`workbench experimental Three supports GLB/GLTF only, ext=${e}`};if(t==="edit"&&a!=="three-direct-glb")return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:`annotationMode=edit, rendererRollout=${a}`};if(a==="babylon-safe")return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:`rendererRollout=${a}`};if(t==="edit"&&!i)return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:"annotationMode=edit, allowEditModeOnThree=false"};let f=s?`${e} workbench preview`:t==="edit"?`${e} direct view edit preview`:t==="readonly"?`${e} preview with readonly annotations`:`simple ${e} preview`;return{backend:"three",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:f}}let l=[];return fB.has(e)||l.push(`ext=${e}`),t!=="none"&&l.push(`annotationMode=${t}`),t==="edit"&&!i&&l.push("allowEditModeOnThree=false"),s&&l.push("requireWorkbenchFeatures=true"),a!==dB&&l.push(`rendererRollout=${a}`),{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:l.join(", ")||"fallback route"}}function uB(){return{backend:"babylon",reason:"grid previews remain on the Babylon grid renderer"}}var dB,fB,hie,_S=y(()=>{"use strict";dB="babylon-safe",fB=new Set(["glb","gltf","stl","ply","obj"]),hie=new Set(["glb","gltf"])});function pie(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}function gie(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}function sm(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function N2(){let n=sm("canvas");return n.style.display="block",n}function g_(...n){let e="THREE."+n.shift();am?am("log",e,...n):console.log(e,...n)}function w2(n){let e=n[0];if(typeof e=="string"&&e.startsWith("TSL:")){let t=n[1];t&&t.isStackTrace?n[0]+=" "+t.getLocation():n[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return n}function Nt(...n){n=w2(n);let e="THREE."+n.shift();if(am)am("warn",e,...n);else{let t=n[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...n)}}function Ht(...n){n=w2(n);let e="THREE."+n.shift();if(am)am("error",e,...n);else{let t=n[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...n)}}function sT(...n){let e=n.join(" ");e in hB||(hB[e]=!0,Nt(...n))}function F2(n,e,t){return new Promise(function(i,r){function s(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:r();break;case n.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:i()}}setTimeout(s,t)})}function Ro(){let n=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(Xn[n&255]+Xn[n>>8&255]+Xn[n>>16&255]+Xn[n>>24&255]+"-"+Xn[e&255]+Xn[e>>8&255]+"-"+Xn[e>>16&15|64]+Xn[e>>24&255]+"-"+Xn[t&63|128]+Xn[t>>8&255]+"-"+Xn[t>>16&255]+Xn[t>>24&255]+Xn[i&255]+Xn[i>>8&255]+Xn[i>>16&255]+Xn[i>>24&255]).toLowerCase()}function Ai(n,e,t){return Math.max(e,Math.min(t,n))}function jI(n,e){return(n%e+e)%e}function _ie(n,e,t,i,r){return i+(n-e)*(r-i)/(t-e)}function vie(n,e,t){return n!==e?(t-n)/(e-n):0}function h_(n,e,t){return(1-t)*n+t*e}function Eie(n,e,t,i){return h_(n,e,1-Math.exp(-t*i))}function Sie(n,e=1){return e-Math.abs(jI(n,e*2)-e)}function Tie(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function Aie(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function xie(n,e){return n+Math.floor(Math.random()*(e-n+1))}function Rie(n,e){return n+Math.random()*(e-n)}function bie(n){return n*(.5-Math.random())}function Mie(n){n!==void 0&&(mB=n);let e=mB+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function yie(n){return n*u_}function Iie(n){return n*fu}function Cie(n){return(n&n-1)===0&&n!==0}function Pie(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function Lie(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function Die(n,e,t,i,r){let s=Math.cos,a=Math.sin,o=s(t/2),l=a(t/2),c=s((e+i)/2),f=a((e+i)/2),d=s((e-i)/2),u=a((e-i)/2),h=s((i-e)/2),m=a((i-e)/2);switch(r){case"XYX":n.set(o*f,l*d,l*u,o*c);break;case"YZY":n.set(l*u,o*f,l*d,o*c);break;case"ZXZ":n.set(l*d,l*u,o*f,o*c);break;case"XZX":n.set(o*f,l*m,l*h,o*c);break;case"YXY":n.set(l*h,o*f,l*m,o*c);break;case"ZYZ":n.set(l*m,l*h,o*f,o*c);break;default:Nt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}function Ao(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function or(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}function Oie(){let n={enabled:!0,workingColorSpace:gs,spaces:{},convert:function(r,s,a){return this.enabled===!1||s===a||!s||!a||(this.spaces[s].transfer===nr&&(r.r=hc(r.r),r.g=hc(r.g),r.b=hc(r.b)),this.spaces[s].primaries!==this.spaces[a].primaries&&(r.applyMatrix3(this.spaces[s].toXYZ),r.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===nr&&(r.r=im(r.r),r.g=im(r.g),r.b=im(r.b))),r},workingToColorSpace:function(r,s){return this.convert(r,this.workingColorSpace,s)},colorSpaceToWorking:function(r,s){return this.convert(r,s,this.workingColorSpace)},getPrimaries:function(r){return this.spaces[r].primaries},getTransfer:function(r){return r===vc?p_:this.spaces[r].transfer},getToneMappingMode:function(r){return this.spaces[r].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(r,s=this.workingColorSpace){return r.fromArray(this.spaces[s].luminanceCoefficients)},define:function(r){Object.assign(this.spaces,r)},_getMatrix:function(r,s,a){return r.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(r){return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(r=this.workingColorSpace){return this.spaces[r].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(r,s){return sT("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(r,s)},toWorkingColorSpace:function(r,s){return sT("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(r,s)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[gs]:{primaries:e,whitePoint:i,transfer:p_,toXYZ:gB,fromXYZ:_B,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Fi},outputColorSpaceConfig:{drawingBufferColorSpace:Fi}},[Fi]:{primaries:e,whitePoint:i,transfer:nr,toXYZ:gB,fromXYZ:_B,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Fi}}}),n}function hc(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function im(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}function Y0(n){return typeof HTMLImageElement!="undefined"&&n instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&n instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&n instanceof ImageBitmap?aT.getDataURL(n):n.data?{data:Array.from(n.data),width:n.width,height:n.height,type:n.data.constructor.name}:(Nt("Texture: Unable to serialize Texture."),{})}function Z0(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}function rI(n,e,t,i,r){for(let s=0,a=n.length-3;s<=a;s+=3){eu.fromArray(n,s);let o=r.x*Math.abs(eu.x)+r.y*Math.abs(eu.y)+r.z*Math.abs(eu.z),l=e.dot(eu),c=t.dot(eu),f=i.dot(eu);if(Math.max(-Math.max(l,c,f),Math.min(l,c,f))>o)return!1}return!0}function yS(n,e,t,i,r,s){Qh.subVectors(n,t).addScalar(.5).multiply(i),r!==void 0?(a_.x=s*Qh.x-r*Qh.y,a_.y=r*Qh.x+s*Qh.y):a_.copy(Qh),n.copy(e),n.x+=a_.x,n.y+=a_.y,n.applyMatrix4(V2)}function Kie(n,e,t,i,r,s,a,o){let l;if(e.side===On?l=i.intersectTriangle(a,s,r,!0,o):l=i.intersectTriangle(r,s,a,e.side===va,o),l===null)return null;wS.copy(o),wS.applyMatrix4(n.matrixWorld);let c=t.ray.origin.distanceTo(wS);return c<t.near||c>t.far?null:{distance:c,point:wS.clone(),object:n}}function FS(n,e,t,i,r,s,a,o,l,c){n.getVertexPosition(o,LS),n.getVertexPosition(l,DS),n.getVertexPosition(c,OS);let f=Kie(n,e,t,i,LS,DS,OS,PB);if(f){let d=new ie;uc.getBarycoord(PB,LS,DS,OS,d),r&&(f.uv=uc.getInterpolatedAttribute(r,o,l,c,d,new Ct)),s&&(f.uv1=uc.getInterpolatedAttribute(s,o,l,c,d,new Ct)),a&&(f.normal=uc.getInterpolatedAttribute(a,o,l,c,d,new ie),f.normal.dot(i.direction)>0&&f.normal.multiplyScalar(-1));let u={a:o,b:l,c,normal:new ie,materialIndex:0};uc.getNormal(LS,DS,OS,u.normal),f.face=u,f.barycoord=d}return f}function kS(n,e,t,i,r,s,a){let o=n.geometry.attributes.position;if(cT.fromBufferAttribute(o,r),fT.fromBufferAttribute(o,s),t.distanceSqToSegment(cT,fT,mI,VB)>i)return;mI.applyMatrix4(n.matrixWorld);let c=e.ray.origin.distanceTo(mI);if(!(c<e.near||c>e.far))return{distance:c,point:VB.clone().applyMatrix4(n.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:n}}function WB(n,e,t,i,r,s,a){let o=SI.distanceSqToPoint(n);if(o<t){let l=new ie;SI.closestPointToPoint(n,l),l.applyMatrix4(i);let c=r.ray.origin.distanceTo(l);if(c<r.near||c>r.far)return;s.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}function Tu(n){let e={};for(let t in n){e[t]={};for(let i in n[t]){let r=n[t][i];if(HB(r))r.isRenderTargetTexture?(Nt("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][i]=null):e[t][i]=r.clone();else if(Array.isArray(r))if(HB(r[0])){let s=[];for(let a=0,o=r.length;a<o;a++)s[a]=r[a].clone();e[t][i]=s}else e[t][i]=r.slice();else e[t][i]=r}}return e}function jn(n){let e={};for(let t=0;t<n.length;t++){let i=Tu(n[t]);for(let r in i)e[r]=i[r]}return e}function HB(n){return n&&(n.isColor||n.isMatrix3||n.isMatrix4||n.isVector2||n.isVector3||n.isVector4||n.isTexture||n.isQuaternion)}function ere(n){let e=[];for(let t=0;t<n.length;t++)e.push(n[t].clone());return e}function ZI(n){let e=n.getRenderTarget();return e===null?n.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:mi.workingColorSpace}function HS(n,e){return!n||n.constructor===e?n:typeof e.BYTES_PER_ELEMENT=="number"?new e(n):Array.prototype.slice.call(n)}function rre(n){function e(r,s){return n[r]-n[s]}let t=n.length,i=new Array(t);for(let r=0;r!==t;++r)i[r]=r;return i.sort(e),i}function XB(n,e,t){let i=n.length,r=new n.constructor(i);for(let s=0,a=0;a!==i;++s){let o=t[s]*e;for(let l=0;l!==e;++l)r[a++]=n[o+l]}return r}function k2(n,e,t,i){let r=1,s=n[0];for(;s!==void 0&&s[i]===void 0;)s=n[r++];if(s===void 0)return;let a=s[i];if(a!==void 0)if(Array.isArray(a))do a=s[i],a!==void 0&&(e.push(s.time),t.push(...a)),s=n[r++];while(s!==void 0);else if(a.toArray!==void 0)do a=s[i],a!==void 0&&(e.push(s.time),a.toArray(t,t.length)),s=n[r++];while(s!==void 0);else do a=s[i],a!==void 0&&(e.push(s.time),t.push(a)),s=n[r++];while(s!==void 0)}function nre(n){switch(n.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return gl;case"vector":case"vector2":case"vector3":case"vector4":return vl;case"color":return P_;case"quaternion":return _l;case"bool":case"boolean":return pc;case"string":return gc}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+n)}function sre(n){if(n.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");let e=nre(n.type);if(n.times===void 0){let t=[],i=[];k2(n.keys,t,i,"value"),n.times=t,n.values=i}return e.parse!==void 0?e.parse(n):new e(n.name,n.times,n.values,n.interpolation)}function YB(n){try{let e=n.slice(n.indexOf(":")+1);return new URL(e).protocol==="blob:"}catch(e){return!1}}function $B(n,e){return n.distance-e.distance}function MI(n,e,t,i){let r=!0;if(n.layers.test(e.layers)&&n.raycast(e,t)===!1&&(r=!1),r===!0&&i===!0){let s=n.children;for(let a=0,o=s.length;a<o;a++)MI(s[a],e,t,!0)}}function $I(n,e,t,i){let r=pre(i);switch(t){case HI:return n*e;case DT:return n*e/r.components*r.byteLength;case OT:return n*e/r.components*r.byteLength;case wf:return n*e*2/r.components*r.byteLength;case NT:return n*e*2/r.components*r.byteLength;case XI:return n*e*3/r.components*r.byteLength;case Aa:return n*e*4/r.components*r.byteLength;case wT:return n*e*4/r.components*r.byteLength;case G_:case k_:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case z_:case W_:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case BT:case VT:return Math.max(n,16)*Math.max(e,8)/4;case FT:case UT:return Math.max(n,8)*Math.max(e,8)/2;case GT:case kT:case WT:case HT:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case zT:case H_:case XT:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case YT:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case KT:return Math.floor((n+4)/5)*Math.floor((e+3)/4)*16;case jT:return Math.floor((n+4)/5)*Math.floor((e+4)/5)*16;case ZT:return Math.floor((n+5)/6)*Math.floor((e+4)/5)*16;case qT:return Math.floor((n+5)/6)*Math.floor((e+5)/6)*16;case QT:return Math.floor((n+7)/8)*Math.floor((e+4)/5)*16;case $T:return Math.floor((n+7)/8)*Math.floor((e+5)/6)*16;case JT:return Math.floor((n+7)/8)*Math.floor((e+7)/8)*16;case eA:return Math.floor((n+9)/10)*Math.floor((e+4)/5)*16;case tA:return Math.floor((n+9)/10)*Math.floor((e+5)/6)*16;case iA:return Math.floor((n+9)/10)*Math.floor((e+7)/8)*16;case rA:return Math.floor((n+9)/10)*Math.floor((e+9)/10)*16;case nA:return Math.floor((n+11)/12)*Math.floor((e+9)/10)*16;case sA:return Math.floor((n+11)/12)*Math.floor((e+11)/12)*16;case aA:case oA:case lA:return Math.ceil(n/4)*Math.ceil(e/4)*16;case cA:case fA:return Math.ceil(n/4)*Math.ceil(e/4)*8;case X_:case dA:return Math.ceil(n/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function pre(n){switch(n){case Ks:case GI:return{byteLength:1,components:1};case Am:case kI:case Al:return{byteLength:2,components:1};case PT:case LT:return{byteLength:2,components:4};case Co:case CT:case Ta:return{byteLength:4,components:1};case zI:case WI:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${n}.`)}var Lf,Df,JB,II,e2,B_,bT,Sm,va,On,Xs,Tl,au,CI,PI,LI,t2,bf,i2,r2,n2,s2,a2,o2,l2,c2,ZS,qS,f2,d2,u2,h2,m2,p2,g2,_2,v2,QS,$S,JS,ou,eT,tT,iT,rT,U_,E2,S2,Ys,DI,OI,NI,wI,FI,BI,UI,_I,T2,VI,Of,Eu,MT,yT,V_,ul,Xa,rm,kr,IT,Su,zr,Tm,Io,Ks,GI,kI,Am,CT,Co,Ta,Al,PT,LT,xm,zI,WI,HI,XI,Aa,hl,Nf,DT,OT,wf,NT,wT,G_,k_,z_,W_,FT,BT,UT,VT,GT,kT,zT,WT,HT,H_,XT,YT,KT,jT,ZT,qT,QT,$T,JT,eA,tA,iA,rA,nA,sA,aA,oA,lA,cA,fA,X_,dA,A2,x2,R2,lu,cu,jS,vI,nu,su,m_,uA,b2,YI,Y_,Rm,M2,bm,y2,vc,Fi,gs,p_,nr,ru,EI,I2,C2,P2,hA,L2,D2,mA,O2,nT,KI,xo,nm,hB,am,B2,Ya,Xn,mB,u_,fu,K_,JI,Ct,un,eC,ie,H0,pB,tC,li,X0,gB,_B,mi,Uh,aT,Nie,om,wie,K0,Lr,iC,dr,oT,Ea,__,lT,RT,pi,Vh,Eo,Fie,Bie,Ef,vS,pa,vB,EB,bo,lm,Uie,SB,Gh,ac,ES,t_,Vie,Gie,TB,AB,xB,RB,kie,kh,j0,sr,_a,zie,cm,U2,Sf,SS,mt,Yn,du,So,oc,q0,lc,zh,Wh,bB,Q0,$0,J0,eI,tI,iI,uc,Wr,cc,To,TS,Hh,Xh,Yh,Tf,Af,Jd,i_,AS,xS,eu,Jr,RS,Wie,Tr,v_,E_,gi,Hie,r_,nI,Vs,Xie,Ha,sI,Kh,ga,n_,Rn,Bi,uu,ms,Mf,Yie,Hr,fm,jh,s_,Zh,qh,Qh,a_,V2,bS,o_,MS,MB,aI,yB,S_,fc,oI,IS,xf,lI,CS,cI,ml,Kn,IB,tu,PS,CB,LS,DS,OS,fI,NS,PB,wS,ci,l_,LB,DB,jie,OB,BS,dI,NB,uI,T_,dm,um,wB,Zie,A_,yf,$h,FB,US,BB,qie,c_,f_,hu,hI,Qie,$ie,ps,iu,Jie,VS,hm,Ln,cT,fT,UB,d_,GS,mI,VB,mu,GB,kB,_s,x_,Gs,zB,SI,zS,WS,ks,R_,b_,mc,dT,M_,If,pu,mm,y_,G2,tre,ire,Sa,uT,Dn,zs,gu,I_,hT,mT,pl,pT,C_,gT,_T,Ws,pc,P_,gl,vT,_l,gc,vl,_u,dl,pm,pA,bn,dc,TI,Hs,Jh,ET,vu,Cf,gm,pI,KB,jB,L_,XS,YS,fl,D_,Rf,ZB,qB,Sr,AI,_c,xI,Mo,vs,RI,El,_m,yo,gI,O_,em,tm,ST,TT,AT,qI,are,QI,ore,lre,cre,fre,dre,ure,hre,bI,fr,xT,mre,N_,QB,Pf,vm,rC,yI,w_,KS,Sl,Em,F_,nC=y(()=>{Lf={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},Df={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},JB=0,II=1,e2=2,B_=1,bT=2,Sm=3,va=0,On=1,Xs=2,Tl=0,au=1,CI=2,PI=3,LI=4,t2=5,bf=100,i2=101,r2=102,n2=103,s2=104,a2=200,o2=201,l2=202,c2=203,ZS=204,qS=205,f2=206,d2=207,u2=208,h2=209,m2=210,p2=211,g2=212,_2=213,v2=214,QS=0,$S=1,JS=2,ou=3,eT=4,tT=5,iT=6,rT=7,U_=0,E2=1,S2=2,Ys=0,DI=1,OI=2,NI=3,wI=4,FI=5,BI=6,UI=7,_I="attached",T2="detached",VI=300,Of=301,Eu=302,MT=303,yT=304,V_=306,ul=1e3,Xa=1001,rm=1002,kr=1003,IT=1004,Su=1005,zr=1006,Tm=1007,Io=1008,Ks=1009,GI=1010,kI=1011,Am=1012,CT=1013,Co=1014,Ta=1015,Al=1016,PT=1017,LT=1018,xm=1020,zI=35902,WI=35899,HI=1021,XI=1022,Aa=1023,hl=1026,Nf=1027,DT=1028,OT=1029,wf=1030,NT=1031,wT=1033,G_=33776,k_=33777,z_=33778,W_=33779,FT=35840,BT=35841,UT=35842,VT=35843,GT=36196,kT=37492,zT=37496,WT=37488,HT=37489,H_=37490,XT=37491,YT=37808,KT=37809,jT=37810,ZT=37811,qT=37812,QT=37813,$T=37814,JT=37815,eA=37816,tA=37817,iA=37818,rA=37819,nA=37820,sA=37821,aA=36492,oA=36494,lA=36495,cA=36283,fA=36284,X_=36285,dA=36286,A2=2200,x2=2201,R2=2202,lu=2300,cu=2301,jS=2302,vI=2303,nu=2400,su=2401,m_=2402,uA=2500,b2=2501,YI=0,Y_=1,Rm=2,M2=3200,bm=0,y2=1,vc="",Fi="srgb",gs="srgb-linear",p_="linear",nr="srgb",ru=7680,EI=519,I2=512,C2=513,P2=514,hA=515,L2=516,D2=517,mA=518,O2=519,nT=35044,KI="300 es",xo=2e3,nm=2001;hB={},am=null;B2={[QS]:$S,[JS]:iT,[eT]:rT,[ou]:tT,[$S]:QS,[iT]:JS,[rT]:eT,[tT]:ou},Ya=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){let i=this._listeners;return i===void 0?!1:i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){let i=this._listeners;if(i===void 0)return;let r=i[e];if(r!==void 0){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let i=t[e.type];if(i!==void 0){e.target=this;let r=i.slice(0);for(let s=0,a=r.length;s<a;s++)r[s].call(this,e);e.target=null}}},Xn=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],mB=1234567,u_=Math.PI/180,fu=180/Math.PI;K_={DEG2RAD:u_,RAD2DEG:fu,generateUUID:Ro,clamp:Ai,euclideanModulo:jI,mapLinear:_ie,inverseLerp:vie,lerp:h_,damp:Eie,pingpong:Sie,smoothstep:Tie,smootherstep:Aie,randInt:xie,randFloat:Rie,randFloatSpread:bie,seededRandom:Mie,degToRad:yie,radToDeg:Iie,isPowerOfTwo:Cie,ceilPowerOfTwo:Pie,floorPowerOfTwo:Lie,setQuaternionFromProperEuler:Die,normalize:or,denormalize:Ao},JI=class JI{constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,i=this.y,r=e.elements;return this.x=r[0]*t+r[3]*i+r[6],this.y=r[1]*t+r[4]*i+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Ai(this.x,e.x,t.x),this.y=Ai(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Ai(this.x,e,t),this.y=Ai(this.y,e,t),this}clampLength(e,t){let i=this.length();return this.divideScalar(i||1).multiplyScalar(Ai(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let i=this.dot(e)/t;return Math.acos(Ai(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let i=Math.cos(t),r=Math.sin(t),s=this.x-e.x,a=this.y-e.y;return this.x=s*i-a*r+e.x,this.y=s*r+a*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};JI.prototype.isVector2=!0;Ct=JI,un=class{constructor(e=0,t=0,i=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=r}static slerpFlat(e,t,i,r,s,a,o){let l=i[r+0],c=i[r+1],f=i[r+2],d=i[r+3],u=s[a+0],h=s[a+1],m=s[a+2],g=s[a+3];if(d!==g||l!==u||c!==h||f!==m){let p=l*u+c*h+f*m+d*g;p<0&&(u=-u,h=-h,m=-m,g=-g,p=-p);let _=1-o;if(p<.9995){let v=Math.acos(p),E=Math.sin(v);_=Math.sin(_*v)/E,o=Math.sin(o*v)/E,l=l*_+u*o,c=c*_+h*o,f=f*_+m*o,d=d*_+g*o}else{l=l*_+u*o,c=c*_+h*o,f=f*_+m*o,d=d*_+g*o;let v=1/Math.sqrt(l*l+c*c+f*f+d*d);l*=v,c*=v,f*=v,d*=v}}e[t]=l,e[t+1]=c,e[t+2]=f,e[t+3]=d}static multiplyQuaternionsFlat(e,t,i,r,s,a){let o=i[r],l=i[r+1],c=i[r+2],f=i[r+3],d=s[a],u=s[a+1],h=s[a+2],m=s[a+3];return e[t]=o*m+f*d+l*h-c*u,e[t+1]=l*m+f*u+c*d-o*h,e[t+2]=c*m+f*h+o*u-l*d,e[t+3]=f*m-o*d-l*u-c*h,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let i=e._x,r=e._y,s=e._z,a=e._order,o=Math.cos,l=Math.sin,c=o(i/2),f=o(r/2),d=o(s/2),u=l(i/2),h=l(r/2),m=l(s/2);switch(a){case"XYZ":this._x=u*f*d+c*h*m,this._y=c*h*d-u*f*m,this._z=c*f*m+u*h*d,this._w=c*f*d-u*h*m;break;case"YXZ":this._x=u*f*d+c*h*m,this._y=c*h*d-u*f*m,this._z=c*f*m-u*h*d,this._w=c*f*d+u*h*m;break;case"ZXY":this._x=u*f*d-c*h*m,this._y=c*h*d+u*f*m,this._z=c*f*m+u*h*d,this._w=c*f*d-u*h*m;break;case"ZYX":this._x=u*f*d-c*h*m,this._y=c*h*d+u*f*m,this._z=c*f*m-u*h*d,this._w=c*f*d+u*h*m;break;case"YZX":this._x=u*f*d+c*h*m,this._y=c*h*d+u*f*m,this._z=c*f*m-u*h*d,this._w=c*f*d-u*h*m;break;case"XZY":this._x=u*f*d-c*h*m,this._y=c*h*d-u*f*m,this._z=c*f*m+u*h*d,this._w=c*f*d+u*h*m;break;default:Nt("Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let i=t/2,r=Math.sin(i);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,i=t[0],r=t[4],s=t[8],a=t[1],o=t[5],l=t[9],c=t[2],f=t[6],d=t[10],u=i+o+d;if(u>0){let h=.5/Math.sqrt(u+1);this._w=.25/h,this._x=(f-l)*h,this._y=(s-c)*h,this._z=(a-r)*h}else if(i>o&&i>d){let h=2*Math.sqrt(1+i-o-d);this._w=(f-l)/h,this._x=.25*h,this._y=(r+a)/h,this._z=(s+c)/h}else if(o>d){let h=2*Math.sqrt(1+o-i-d);this._w=(s-c)/h,this._x=(r+a)/h,this._y=.25*h,this._z=(l+f)/h}else{let h=2*Math.sqrt(1+d-i-o);this._w=(a-r)/h,this._x=(s+c)/h,this._y=(l+f)/h,this._z=.25*h}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ai(this.dot(e),-1,1)))}rotateTowards(e,t){let i=this.angleTo(e);if(i===0)return this;let r=Math.min(1,t/i);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let i=e._x,r=e._y,s=e._z,a=e._w,o=t._x,l=t._y,c=t._z,f=t._w;return this._x=i*f+a*o+r*c-s*l,this._y=r*f+a*l+s*o-i*c,this._z=s*f+a*c+i*l-r*o,this._w=a*f-i*o-r*l-s*c,this._onChangeCallback(),this}slerp(e,t){let i=e._x,r=e._y,s=e._z,a=e._w,o=this.dot(e);o<0&&(i=-i,r=-r,s=-s,a=-a,o=-o);let l=1-t;if(o<.9995){let c=Math.acos(o),f=Math.sin(c);l=Math.sin(l*c)/f,t=Math.sin(t*c)/f,this._x=this._x*l+i*t,this._y=this._y*l+r*t,this._z=this._z*l+s*t,this._w=this._w*l+a*t,this._onChangeCallback()}else this._x=this._x*l+i*t,this._y=this._y*l+r*t,this._z=this._z*l+s*t,this._w=this._w*l+a*t,this.normalize();return this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),r=Math.sqrt(1-i),s=Math.sqrt(i);return this.set(r*Math.sin(e),r*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},eC=class eC{constructor(e=0,t=0,i=0){this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(pB.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(pB.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,i=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6]*r,this.y=s[1]*t+s[4]*i+s[7]*r,this.z=s[2]*t+s[5]*i+s[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,i=this.y,r=this.z,s=e.elements,a=1/(s[3]*t+s[7]*i+s[11]*r+s[15]);return this.x=(s[0]*t+s[4]*i+s[8]*r+s[12])*a,this.y=(s[1]*t+s[5]*i+s[9]*r+s[13])*a,this.z=(s[2]*t+s[6]*i+s[10]*r+s[14])*a,this}applyQuaternion(e){let t=this.x,i=this.y,r=this.z,s=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*r-o*i),f=2*(o*t-s*r),d=2*(s*i-a*t);return this.x=t+l*c+a*d-o*f,this.y=i+l*f+o*c-s*d,this.z=r+l*d+s*f-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,i=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[4]*i+s[8]*r,this.y=s[1]*t+s[5]*i+s[9]*r,this.z=s[2]*t+s[6]*i+s[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Ai(this.x,e.x,t.x),this.y=Ai(this.y,e.y,t.y),this.z=Ai(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Ai(this.x,e,t),this.y=Ai(this.y,e,t),this.z=Ai(this.z,e,t),this}clampLength(e,t){let i=this.length();return this.divideScalar(i||1).multiplyScalar(Ai(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let i=e.x,r=e.y,s=e.z,a=t.x,o=t.y,l=t.z;return this.x=r*l-s*o,this.y=s*a-i*l,this.z=i*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return H0.copy(this).projectOnVector(e),this.sub(H0)}reflect(e){return this.sub(H0.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let i=this.dot(e)/t;return Math.acos(Ai(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,i=this.y-e.y,r=this.z-e.z;return t*t+i*i+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){let r=Math.sin(t)*e;return this.x=r*Math.sin(i),this.y=Math.cos(t)*e,this.z=r*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};eC.prototype.isVector3=!0;ie=eC,H0=new ie,pB=new un,tC=class tC{constructor(e,t,i,r,s,a,o,l,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,r,s,a,o,l,c)}set(e,t,i,r,s,a,o,l,c){let f=this.elements;return f[0]=e,f[1]=r,f[2]=o,f[3]=t,f[4]=s,f[5]=l,f[6]=i,f[7]=a,f[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let i=e.elements,r=t.elements,s=this.elements,a=i[0],o=i[3],l=i[6],c=i[1],f=i[4],d=i[7],u=i[2],h=i[5],m=i[8],g=r[0],p=r[3],_=r[6],v=r[1],E=r[4],S=r[7],T=r[2],A=r[5],R=r[8];return s[0]=a*g+o*v+l*T,s[3]=a*p+o*E+l*A,s[6]=a*_+o*S+l*R,s[1]=c*g+f*v+d*T,s[4]=c*p+f*E+d*A,s[7]=c*_+f*S+d*R,s[2]=u*g+h*v+m*T,s[5]=u*p+h*E+m*A,s[8]=u*_+h*S+m*R,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],i=e[1],r=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],f=e[8];return t*a*f-t*o*c-i*s*f+i*o*l+r*s*c-r*a*l}invert(){let e=this.elements,t=e[0],i=e[1],r=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],f=e[8],d=f*a-o*c,u=o*l-f*s,h=c*s-a*l,m=t*d+i*u+r*h;if(m===0)return this.set(0,0,0,0,0,0,0,0,0);let g=1/m;return e[0]=d*g,e[1]=(r*c-f*i)*g,e[2]=(o*i-r*a)*g,e[3]=u*g,e[4]=(f*t-r*l)*g,e[5]=(r*s-o*t)*g,e[6]=h*g,e[7]=(i*l-c*t)*g,e[8]=(a*t-i*s)*g,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,r,s,a,o){let l=Math.cos(s),c=Math.sin(s);return this.set(i*l,i*c,-i*(l*a+c*o)+a+e,-r*c,r*l,-r*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(X0.makeScale(e,t)),this}rotate(e){return this.premultiply(X0.makeRotation(-e)),this}translate(e,t){return this.premultiply(X0.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,i=e.elements;for(let r=0;r<9;r++)if(t[r]!==i[r])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){let i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}};tC.prototype.isMatrix3=!0;li=tC,X0=new li,gB=new li().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),_B=new li().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);mi=Oie();aT=class{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement=="undefined")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{Uh===void 0&&(Uh=sm("canvas")),Uh.width=e.width,Uh.height=e.height;let r=Uh.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),i=Uh}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&e instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap){let t=sm("canvas");t.width=e.width,t.height=e.height;let i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);let r=i.getImageData(0,0,e.width,e.height),s=r.data;for(let a=0;a<s.length;a++)s[a]=hc(s[a]/255)*255;return i.putImageData(r,0,0),t}else if(e.data){let t=e.data.slice(0);for(let i=0;i<t.length;i++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[i]=Math.floor(hc(t[i]/255)*255):t[i]=hc(t[i]);return{data:t,width:e.width,height:e.height}}else return Nt("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}},Nie=0,om=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Nie++}),this.uuid=Ro(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement!="undefined"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame!="undefined"&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let i={uuid:this.uuid,url:""},r=this.data;if(r!==null){let s;if(Array.isArray(r)){s=[];for(let a=0,o=r.length;a<o;a++)r[a].isDataTexture?s.push(Y0(r[a].image)):s.push(Y0(r[a]))}else s=Y0(r);i.url=s}return t||(e.images[this.uuid]=i),i}};wie=0,K0=new ie,Lr=class n extends Ya{constructor(e=n.DEFAULT_IMAGE,t=n.DEFAULT_MAPPING,i=Xa,r=Xa,s=zr,a=Io,o=Aa,l=Ks,c=n.DEFAULT_ANISOTROPY,f=vc){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:wie++}),this.uuid=Ro(),this.name="",this.source=new om(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=i,this.wrapT=r,this.magFilter=s,this.minFilter=a,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=l,this.offset=new Ct(0,0),this.repeat=new Ct(1,1),this.center=new Ct(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new li,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=f,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(K0).x}get height(){return this.source.getSize(K0).y}get depth(){return this.source.getSize(K0).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let i=e[t];if(i===void 0){Nt(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){Nt(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&i&&r.isVector2&&i.isVector2||r&&i&&r.isVector3&&i.isVector3||r&&i&&r.isMatrix3&&i.isMatrix3?r.copy(i):this[t]=i}}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==VI)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case ul:e.x=e.x-Math.floor(e.x);break;case Xa:e.x=e.x<0?0:1;break;case rm:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case ul:e.y=e.y-Math.floor(e.y);break;case Xa:e.y=e.y<0?0:1;break;case rm:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};Lr.DEFAULT_IMAGE=null;Lr.DEFAULT_MAPPING=VI;Lr.DEFAULT_ANISOTROPY=1;iC=class iC{constructor(e=0,t=0,i=0,r=1){this.x=e,this.y=t,this.z=i,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,i=this.y,r=this.z,s=this.w,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*r+a[12]*s,this.y=a[1]*t+a[5]*i+a[9]*r+a[13]*s,this.z=a[2]*t+a[6]*i+a[10]*r+a[14]*s,this.w=a[3]*t+a[7]*i+a[11]*r+a[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,r,s,l=e.elements,c=l[0],f=l[4],d=l[8],u=l[1],h=l[5],m=l[9],g=l[2],p=l[6],_=l[10];if(Math.abs(f-u)<.01&&Math.abs(d-g)<.01&&Math.abs(m-p)<.01){if(Math.abs(f+u)<.1&&Math.abs(d+g)<.1&&Math.abs(m+p)<.1&&Math.abs(c+h+_-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;let E=(c+1)/2,S=(h+1)/2,T=(_+1)/2,A=(f+u)/4,R=(d+g)/4,M=(m+p)/4;return E>S&&E>T?E<.01?(i=0,r=.707106781,s=.707106781):(i=Math.sqrt(E),r=A/i,s=R/i):S>T?S<.01?(i=.707106781,r=0,s=.707106781):(r=Math.sqrt(S),i=A/r,s=M/r):T<.01?(i=.707106781,r=.707106781,s=0):(s=Math.sqrt(T),i=R/s,r=M/s),this.set(i,r,s,t),this}let v=Math.sqrt((p-m)*(p-m)+(d-g)*(d-g)+(u-f)*(u-f));return Math.abs(v)<.001&&(v=1),this.x=(p-m)/v,this.y=(d-g)/v,this.z=(u-f)/v,this.w=Math.acos((c+h+_-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Ai(this.x,e.x,t.x),this.y=Ai(this.y,e.y,t.y),this.z=Ai(this.z,e.z,t.z),this.w=Ai(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Ai(this.x,e,t),this.y=Ai(this.y,e,t),this.z=Ai(this.z,e,t),this.w=Ai(this.w,e,t),this}clampLength(e,t){let i=this.length();return this.divideScalar(i||1).multiplyScalar(Ai(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}};iC.prototype.isVector4=!0;dr=iC,oT=class extends Ya{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:zr,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new dr(0,0,e,t),this.scissorTest=!1,this.viewport=new dr(0,0,e,t),this.textures=[];let r={width:e,height:t,depth:i.depth},s=new Lr(r),a=i.count;for(let o=0;o<a;o++)this.textures[o]=s.clone(),this.textures[o].isRenderTargetTexture=!0,this.textures[o].renderTarget=this;this._setTextureOptions(i),this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.resolveDepthBuffer=i.resolveDepthBuffer,this.resolveStencilBuffer=i.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=i.depthTexture,this.samples=i.samples,this.multiview=i.multiview}_setTextureOptions(e={}){let t={minFilter:zr,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let i=0;i<this.textures.length;i++)this.textures[i].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,i=1){if(this.width!==e||this.height!==t||this.depth!==i){this.width=e,this.height=t,this.depth=i;for(let r=0,s=this.textures.length;r<s;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=i,this.textures[r].isData3DTexture!==!0&&(this.textures[r].isArrayTexture=this.textures[r].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,i=e.textures.length;t<i;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let r=Object.assign({},e.textures[t].image);this.textures[t].source=new om(r)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this.multiview=e.multiview,this}dispose(){this.dispatchEvent({type:"dispose"})}},Ea=class extends oT{constructor(e=1,t=1,i={}){super(e,t,i),this.isWebGLRenderTarget=!0}},__=class extends Lr{constructor(e=null,t=1,i=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:i,depth:r},this.magFilter=kr,this.minFilter=kr,this.wrapR=Xa,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},lT=class extends Lr{constructor(e=null,t=1,i=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:i,depth:r},this.magFilter=kr,this.minFilter=kr,this.wrapR=Xa,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},RT=class RT{constructor(e,t,i,r,s,a,o,l,c,f,d,u,h,m,g,p){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,r,s,a,o,l,c,f,d,u,h,m,g,p)}set(e,t,i,r,s,a,o,l,c,f,d,u,h,m,g,p){let _=this.elements;return _[0]=e,_[4]=t,_[8]=i,_[12]=r,_[1]=s,_[5]=a,_[9]=o,_[13]=l,_[2]=c,_[6]=f,_[10]=d,_[14]=u,_[3]=h,_[7]=m,_[11]=g,_[15]=p,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new RT().fromArray(this.elements)}copy(e){let t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){let t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return this.determinant()===0?(e.set(1,0,0),t.set(0,1,0),i.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this)}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){if(e.determinant()===0)return this.identity();let t=this.elements,i=e.elements,r=1/Vh.setFromMatrixColumn(e,0).length(),s=1/Vh.setFromMatrixColumn(e,1).length(),a=1/Vh.setFromMatrixColumn(e,2).length();return t[0]=i[0]*r,t[1]=i[1]*r,t[2]=i[2]*r,t[3]=0,t[4]=i[4]*s,t[5]=i[5]*s,t[6]=i[6]*s,t[7]=0,t[8]=i[8]*a,t[9]=i[9]*a,t[10]=i[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,i=e.x,r=e.y,s=e.z,a=Math.cos(i),o=Math.sin(i),l=Math.cos(r),c=Math.sin(r),f=Math.cos(s),d=Math.sin(s);if(e.order==="XYZ"){let u=a*f,h=a*d,m=o*f,g=o*d;t[0]=l*f,t[4]=-l*d,t[8]=c,t[1]=h+m*c,t[5]=u-g*c,t[9]=-o*l,t[2]=g-u*c,t[6]=m+h*c,t[10]=a*l}else if(e.order==="YXZ"){let u=l*f,h=l*d,m=c*f,g=c*d;t[0]=u+g*o,t[4]=m*o-h,t[8]=a*c,t[1]=a*d,t[5]=a*f,t[9]=-o,t[2]=h*o-m,t[6]=g+u*o,t[10]=a*l}else if(e.order==="ZXY"){let u=l*f,h=l*d,m=c*f,g=c*d;t[0]=u-g*o,t[4]=-a*d,t[8]=m+h*o,t[1]=h+m*o,t[5]=a*f,t[9]=g-u*o,t[2]=-a*c,t[6]=o,t[10]=a*l}else if(e.order==="ZYX"){let u=a*f,h=a*d,m=o*f,g=o*d;t[0]=l*f,t[4]=m*c-h,t[8]=u*c+g,t[1]=l*d,t[5]=g*c+u,t[9]=h*c-m,t[2]=-c,t[6]=o*l,t[10]=a*l}else if(e.order==="YZX"){let u=a*l,h=a*c,m=o*l,g=o*c;t[0]=l*f,t[4]=g-u*d,t[8]=m*d+h,t[1]=d,t[5]=a*f,t[9]=-o*f,t[2]=-c*f,t[6]=h*d+m,t[10]=u-g*d}else if(e.order==="XZY"){let u=a*l,h=a*c,m=o*l,g=o*c;t[0]=l*f,t[4]=-d,t[8]=c*f,t[1]=u*d+g,t[5]=a*f,t[9]=h*d-m,t[2]=m*d-h,t[6]=o*f,t[10]=g*d+u}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Fie,e,Bie)}lookAt(e,t,i){let r=this.elements;return pa.subVectors(e,t),pa.lengthSq()===0&&(pa.z=1),pa.normalize(),Ef.crossVectors(i,pa),Ef.lengthSq()===0&&(Math.abs(i.z)===1?pa.x+=1e-4:pa.z+=1e-4,pa.normalize(),Ef.crossVectors(i,pa)),Ef.normalize(),vS.crossVectors(pa,Ef),r[0]=Ef.x,r[4]=vS.x,r[8]=pa.x,r[1]=Ef.y,r[5]=vS.y,r[9]=pa.y,r[2]=Ef.z,r[6]=vS.z,r[10]=pa.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let i=e.elements,r=t.elements,s=this.elements,a=i[0],o=i[4],l=i[8],c=i[12],f=i[1],d=i[5],u=i[9],h=i[13],m=i[2],g=i[6],p=i[10],_=i[14],v=i[3],E=i[7],S=i[11],T=i[15],A=r[0],R=r[4],M=r[8],I=r[12],C=r[1],L=r[5],w=r[9],G=r[13],O=r[2],N=r[6],B=r[10],V=r[14],q=r[3],K=r[7],J=r[11],Y=r[15];return s[0]=a*A+o*C+l*O+c*q,s[4]=a*R+o*L+l*N+c*K,s[8]=a*M+o*w+l*B+c*J,s[12]=a*I+o*G+l*V+c*Y,s[1]=f*A+d*C+u*O+h*q,s[5]=f*R+d*L+u*N+h*K,s[9]=f*M+d*w+u*B+h*J,s[13]=f*I+d*G+u*V+h*Y,s[2]=m*A+g*C+p*O+_*q,s[6]=m*R+g*L+p*N+_*K,s[10]=m*M+g*w+p*B+_*J,s[14]=m*I+g*G+p*V+_*Y,s[3]=v*A+E*C+S*O+T*q,s[7]=v*R+E*L+S*N+T*K,s[11]=v*M+E*w+S*B+T*J,s[15]=v*I+E*G+S*V+T*Y,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],i=e[4],r=e[8],s=e[12],a=e[1],o=e[5],l=e[9],c=e[13],f=e[2],d=e[6],u=e[10],h=e[14],m=e[3],g=e[7],p=e[11],_=e[15],v=l*h-c*u,E=o*h-c*d,S=o*u-l*d,T=a*h-c*f,A=a*u-l*f,R=a*d-o*f;return t*(g*v-p*E+_*S)-i*(m*v-p*T+_*A)+r*(m*E-g*T+_*R)-s*(m*S-g*A+p*R)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=i),this}invert(){let e=this.elements,t=e[0],i=e[1],r=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],f=e[8],d=e[9],u=e[10],h=e[11],m=e[12],g=e[13],p=e[14],_=e[15],v=t*o-i*a,E=t*l-r*a,S=t*c-s*a,T=i*l-r*o,A=i*c-s*o,R=r*c-s*l,M=f*g-d*m,I=f*p-u*m,C=f*_-h*m,L=d*p-u*g,w=d*_-h*g,G=u*_-h*p,O=v*G-E*w+S*L+T*C-A*I+R*M;if(O===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let N=1/O;return e[0]=(o*G-l*w+c*L)*N,e[1]=(r*w-i*G-s*L)*N,e[2]=(g*R-p*A+_*T)*N,e[3]=(u*A-d*R-h*T)*N,e[4]=(l*C-a*G-c*I)*N,e[5]=(t*G-r*C+s*I)*N,e[6]=(p*S-m*R-_*E)*N,e[7]=(f*R-u*S+h*E)*N,e[8]=(a*w-o*C+c*M)*N,e[9]=(i*C-t*w-s*M)*N,e[10]=(m*A-g*S+_*v)*N,e[11]=(d*S-f*A-h*v)*N,e[12]=(o*I-a*L-l*M)*N,e[13]=(t*L-i*I+r*M)*N,e[14]=(g*E-m*T-p*v)*N,e[15]=(f*T-d*E+u*v)*N,this}scale(e){let t=this.elements,i=e.x,r=e.y,s=e.z;return t[0]*=i,t[4]*=r,t[8]*=s,t[1]*=i,t[5]*=r,t[9]*=s,t[2]*=i,t[6]*=r,t[10]*=s,t[3]*=i,t[7]*=r,t[11]*=s,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,r))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let i=Math.cos(t),r=Math.sin(t),s=1-i,a=e.x,o=e.y,l=e.z,c=s*a,f=s*o;return this.set(c*a+i,c*o-r*l,c*l+r*o,0,c*o+r*l,f*o+i,f*l-r*a,0,c*l-r*o,f*l+r*a,s*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,r,s,a){return this.set(1,i,s,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,i){let r=this.elements,s=t._x,a=t._y,o=t._z,l=t._w,c=s+s,f=a+a,d=o+o,u=s*c,h=s*f,m=s*d,g=a*f,p=a*d,_=o*d,v=l*c,E=l*f,S=l*d,T=i.x,A=i.y,R=i.z;return r[0]=(1-(g+_))*T,r[1]=(h+S)*T,r[2]=(m-E)*T,r[3]=0,r[4]=(h-S)*A,r[5]=(1-(u+_))*A,r[6]=(p+v)*A,r[7]=0,r[8]=(m+E)*R,r[9]=(p-v)*R,r[10]=(1-(u+g))*R,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,i){let r=this.elements;e.x=r[12],e.y=r[13],e.z=r[14];let s=this.determinant();if(s===0)return i.set(1,1,1),t.identity(),this;let a=Vh.set(r[0],r[1],r[2]).length(),o=Vh.set(r[4],r[5],r[6]).length(),l=Vh.set(r[8],r[9],r[10]).length();s<0&&(a=-a),Eo.copy(this);let c=1/a,f=1/o,d=1/l;return Eo.elements[0]*=c,Eo.elements[1]*=c,Eo.elements[2]*=c,Eo.elements[4]*=f,Eo.elements[5]*=f,Eo.elements[6]*=f,Eo.elements[8]*=d,Eo.elements[9]*=d,Eo.elements[10]*=d,t.setFromRotationMatrix(Eo),i.x=a,i.y=o,i.z=l,this}makePerspective(e,t,i,r,s,a,o=xo,l=!1){let c=this.elements,f=2*s/(t-e),d=2*s/(i-r),u=(t+e)/(t-e),h=(i+r)/(i-r),m,g;if(l)m=s/(a-s),g=a*s/(a-s);else if(o===xo)m=-(a+s)/(a-s),g=-2*a*s/(a-s);else if(o===nm)m=-a/(a-s),g=-a*s/(a-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=f,c[4]=0,c[8]=u,c[12]=0,c[1]=0,c[5]=d,c[9]=h,c[13]=0,c[2]=0,c[6]=0,c[10]=m,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,i,r,s,a,o=xo,l=!1){let c=this.elements,f=2/(t-e),d=2/(i-r),u=-(t+e)/(t-e),h=-(i+r)/(i-r),m,g;if(l)m=1/(a-s),g=a/(a-s);else if(o===xo)m=-2/(a-s),g=-(a+s)/(a-s);else if(o===nm)m=-1/(a-s),g=-s/(a-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=f,c[4]=0,c[8]=0,c[12]=u,c[1]=0,c[5]=d,c[9]=0,c[13]=h,c[2]=0,c[6]=0,c[10]=m,c[14]=g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,i=e.elements;for(let r=0;r<16;r++)if(t[r]!==i[r])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){let i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}};RT.prototype.isMatrix4=!0;pi=RT,Vh=new ie,Eo=new pi,Fie=new ie(0,0,0),Bie=new ie(1,1,1),Ef=new ie,vS=new ie,pa=new ie,vB=new pi,EB=new un,bo=class n{constructor(e=0,t=0,i=0,r=n.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=r}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,r=this._order){return this._x=e,this._y=t,this._z=i,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){let r=e.elements,s=r[0],a=r[4],o=r[8],l=r[1],c=r[5],f=r[9],d=r[2],u=r[6],h=r[10];switch(t){case"XYZ":this._y=Math.asin(Ai(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-f,h),this._z=Math.atan2(-a,s)):(this._x=Math.atan2(u,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Ai(f,-1,1)),Math.abs(f)<.9999999?(this._y=Math.atan2(o,h),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,s),this._z=0);break;case"ZXY":this._x=Math.asin(Ai(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-d,h),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,s));break;case"ZYX":this._y=Math.asin(-Ai(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(u,h),this._z=Math.atan2(l,s)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(Ai(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-f,c),this._y=Math.atan2(-d,s)):(this._x=0,this._y=Math.atan2(o,h));break;case"XZY":this._z=Math.asin(-Ai(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(u,c),this._y=Math.atan2(o,s)):(this._x=Math.atan2(-f,h),this._y=0);break;default:Nt("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return vB.makeRotationFromQuaternion(e),this.setFromRotationMatrix(vB,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return EB.setFromEuler(this),this.setFromQuaternion(EB,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};bo.DEFAULT_ORDER="XYZ";lm=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}},Uie=0,SB=new ie,Gh=new un,ac=new pi,ES=new ie,t_=new ie,Vie=new ie,Gie=new un,TB=new ie(1,0,0),AB=new ie(0,1,0),xB=new ie(0,0,1),RB={type:"added"},kie={type:"removed"},kh={type:"childadded",child:null},j0={type:"childremoved",child:null},sr=class n extends Ya{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Uie++}),this.uuid=Ro(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=n.DEFAULT_UP.clone();let e=new ie,t=new bo,i=new un,r=new ie(1,1,1);function s(){i.setFromEuler(t,!1)}function a(){t.setFromQuaternion(i,void 0,!1)}t._onChange(s),i._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:r},modelViewMatrix:{value:new pi},normalMatrix:{value:new li}}),this.matrix=new pi,this.matrixWorld=new pi,this.matrixAutoUpdate=n.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=n.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new lm,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Gh.setFromAxisAngle(e,t),this.quaternion.multiply(Gh),this}rotateOnWorldAxis(e,t){return Gh.setFromAxisAngle(e,t),this.quaternion.premultiply(Gh),this}rotateX(e){return this.rotateOnAxis(TB,e)}rotateY(e){return this.rotateOnAxis(AB,e)}rotateZ(e){return this.rotateOnAxis(xB,e)}translateOnAxis(e,t){return SB.copy(e).applyQuaternion(this.quaternion),this.position.add(SB.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(TB,e)}translateY(e){return this.translateOnAxis(AB,e)}translateZ(e){return this.translateOnAxis(xB,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(ac.copy(this.matrixWorld).invert())}lookAt(e,t,i){e.isVector3?ES.copy(e):ES.set(e,t,i);let r=this.parent;this.updateWorldMatrix(!0,!1),t_.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?ac.lookAt(t_,ES,this.up):ac.lookAt(ES,t_,this.up),this.quaternion.setFromRotationMatrix(ac),r&&(ac.extractRotation(r.matrixWorld),Gh.setFromRotationMatrix(ac),this.quaternion.premultiply(Gh.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(Ht("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(RB),kh.child=e,this.dispatchEvent(kh),kh.child=null):Ht("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(kie),j0.child=e,this.dispatchEvent(j0),j0.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),ac.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),ac.multiply(e.parent.matrixWorld)),e.applyMatrix4(ac),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(RB),kh.child=e,this.dispatchEvent(kh),kh.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let i=0,r=this.children.length;i<r;i++){let a=this.children[i].getObjectByProperty(e,t);if(a!==void 0)return a}}getObjectsByProperty(e,t,i=[]){this[e]===t&&i.push(this);let r=this.children;for(let s=0,a=r.length;s<a;s++)r[s].getObjectsByProperty(e,t,i);return i}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(t_,e,Vie),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(t_,Gie,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);let t=this.children;for(let i=0,r=t.length;i<r;i++)t[i].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let i=0,r=t.length;i<r;i++)t[i].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let e=this.pivot;if(e!==null){let t=e.x,i=e.y,r=e.z,s=this.matrix.elements;s[12]+=t-s[0]*t-s[4]*i-s[8]*r,s[13]+=i-s[1]*t-s[5]*i-s[9]*r,s[14]+=r-s[2]*t-s[6]*i-s[10]*r}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let i=0,r=t.length;i<r;i++)t[i].updateMatrixWorld(e)}updateWorldMatrix(e,t){let i=this.parent;if(e===!0&&i!==null&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){let r=this.children;for(let s=0,a=r.length;s<a;s++)r[s].updateWorldMatrix(!1,!0)}}toJSON(e){let t=e===void 0||typeof e=="string",i={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});let r={};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.castShadow===!0&&(r.castShadow=!0),this.receiveShadow===!0&&(r.receiveShadow=!0),this.visible===!1&&(r.visible=!1),this.frustumCulled===!1&&(r.frustumCulled=!1),this.renderOrder!==0&&(r.renderOrder=this.renderOrder),this.static!==!1&&(r.static=this.static),Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type="InstancedMesh",r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type="BatchedMesh",r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(o=>({...o})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function s(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=s(e.geometries,this.geometry);let o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){let l=o.shapes;if(Array.isArray(l))for(let c=0,f=l.length;c<f;c++){let d=l[c];s(e.shapes,d)}else s(e.shapes,l)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let o=[];for(let l=0,c=this.material.length;l<c;l++)o.push(s(e.materials,this.material[l]));r.material=o}else r.material=s(e.materials,this.material);if(this.children.length>0){r.children=[];for(let o=0;o<this.children.length;o++)r.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let o=0;o<this.animations.length;o++){let l=this.animations[o];r.animations.push(s(e.animations,l))}}if(t){let o=a(e.geometries),l=a(e.materials),c=a(e.textures),f=a(e.images),d=a(e.shapes),u=a(e.skeletons),h=a(e.animations),m=a(e.nodes);o.length>0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),f.length>0&&(i.images=f),d.length>0&&(i.shapes=d),u.length>0&&(i.skeletons=u),h.length>0&&(i.animations=h),m.length>0&&(i.nodes=m)}return i.object=r,i;function a(o){let l=[];for(let c in o){let f=o[c];delete f.metadata,l.push(f)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot!==null?e.pivot.clone():null,this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i<e.children.length;i++){let r=e.children[i];this.add(r.clone())}return this}};sr.DEFAULT_UP=new ie(0,1,0);sr.DEFAULT_MATRIX_AUTO_UPDATE=!0;sr.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;_a=class extends sr{constructor(){super(),this.isGroup=!0,this.type="Group"}},zie={type:"move"},cm=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new _a,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new _a,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new ie,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new ie),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new _a,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new ie,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new ie,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let i of e.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,i){let r=null,s=null,a=null,o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){a=!0;for(let g of e.hand.values()){let p=t.getJointPose(g,i),_=this._getHandJoint(c,g);p!==null&&(_.matrix.fromArray(p.transform.matrix),_.matrix.decompose(_.position,_.rotation,_.scale),_.matrixWorldNeedsUpdate=!0,_.jointRadius=p.radius),_.visible=p!==null}let f=c.joints["index-finger-tip"],d=c.joints["thumb-tip"],u=f.position.distanceTo(d.position),h=.02,m=.005;c.inputState.pinching&&u>h+m?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&u<=h-m&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,i),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,i),r===null&&s!==null&&(r=s),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(zie)))}return o!==null&&(o.visible=r!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let i=new _a;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}},U2={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Sf={h:0,s:0,l:0},SS={h:0,s:0,l:0};mt=class{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){let r=e;r&&r.isColor?this.copy(r):typeof r=="number"?this.setHex(r):typeof r=="string"&&this.setStyle(r)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Fi){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,mi.colorSpaceToWorking(this,t),this}setRGB(e,t,i,r=mi.workingColorSpace){return this.r=e,this.g=t,this.b=i,mi.colorSpaceToWorking(this,r),this}setHSL(e,t,i,r=mi.workingColorSpace){if(e=jI(e,1),t=Ai(t,0,1),i=Ai(i,0,1),t===0)this.r=this.g=this.b=i;else{let s=i<=.5?i*(1+t):i+t-i*t,a=2*i-s;this.r=Z0(a,s,e+1/3),this.g=Z0(a,s,e),this.b=Z0(a,s,e-1/3)}return mi.colorSpaceToWorking(this,r),this}setStyle(e,t=Fi){function i(s){s!==void 0&&parseFloat(s)<1&&Nt("Color: Alpha component of "+e+" will be ignored.")}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let s,a=r[1],o=r[2];switch(a){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:Nt("Color: Unknown color model "+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let s=r[1],a=s.length;if(a===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(s,16),t);Nt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Fi){let i=U2[e.toLowerCase()];return i!==void 0?this.setHex(i,t):Nt("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=hc(e.r),this.g=hc(e.g),this.b=hc(e.b),this}copyLinearToSRGB(e){return this.r=im(e.r),this.g=im(e.g),this.b=im(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Fi){return mi.workingToColorSpace(Yn.copy(this),e),Math.round(Ai(Yn.r*255,0,255))*65536+Math.round(Ai(Yn.g*255,0,255))*256+Math.round(Ai(Yn.b*255,0,255))}getHexString(e=Fi){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=mi.workingColorSpace){mi.workingToColorSpace(Yn.copy(this),t);let i=Yn.r,r=Yn.g,s=Yn.b,a=Math.max(i,r,s),o=Math.min(i,r,s),l,c,f=(o+a)/2;if(o===a)l=0,c=0;else{let d=a-o;switch(c=f<=.5?d/(a+o):d/(2-a-o),a){case i:l=(r-s)/d+(r<s?6:0);break;case r:l=(s-i)/d+2;break;case s:l=(i-r)/d+4;break}l/=6}return e.h=l,e.s=c,e.l=f,e}getRGB(e,t=mi.workingColorSpace){return mi.workingToColorSpace(Yn.copy(this),t),e.r=Yn.r,e.g=Yn.g,e.b=Yn.b,e}getStyle(e=Fi){mi.workingToColorSpace(Yn.copy(this),e);let t=Yn.r,i=Yn.g,r=Yn.b;return e!==Fi?`color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${r.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(i*255)},${Math.round(r*255)})`}offsetHSL(e,t,i){return this.getHSL(Sf),this.setHSL(Sf.h+e,Sf.s+t,Sf.l+i)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,i){return this.r=e.r+(t.r-e.r)*i,this.g=e.g+(t.g-e.g)*i,this.b=e.b+(t.b-e.b)*i,this}lerpHSL(e,t){this.getHSL(Sf),e.getHSL(SS);let i=h_(Sf.h,SS.h,t),r=h_(Sf.s,SS.s,t),s=h_(Sf.l,SS.l,t);return this.setHSL(i,r,s),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,i=this.g,r=this.b,s=e.elements;return this.r=s[0]*t+s[3]*i+s[6]*r,this.g=s[1]*t+s[4]*i+s[7]*r,this.b=s[2]*t+s[5]*i+s[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},Yn=new mt;mt.NAMES=U2;du=class extends sr{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new bo,this.environmentIntensity=1,this.environmentRotation=new bo,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__!="undefined"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},So=new ie,oc=new ie,q0=new ie,lc=new ie,zh=new ie,Wh=new ie,bB=new ie,Q0=new ie,$0=new ie,J0=new ie,eI=new dr,tI=new dr,iI=new dr,uc=class n{constructor(e=new ie,t=new ie,i=new ie){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,r){r.subVectors(i,t),So.subVectors(e,t),r.cross(So);let s=r.lengthSq();return s>0?r.multiplyScalar(1/Math.sqrt(s)):r.set(0,0,0)}static getBarycoord(e,t,i,r,s){So.subVectors(r,t),oc.subVectors(i,t),q0.subVectors(e,t);let a=So.dot(So),o=So.dot(oc),l=So.dot(q0),c=oc.dot(oc),f=oc.dot(q0),d=a*c-o*o;if(d===0)return s.set(0,0,0),null;let u=1/d,h=(c*l-o*f)*u,m=(a*f-o*l)*u;return s.set(1-h-m,m,h)}static containsPoint(e,t,i,r){return this.getBarycoord(e,t,i,r,lc)===null?!1:lc.x>=0&&lc.y>=0&&lc.x+lc.y<=1}static getInterpolation(e,t,i,r,s,a,o,l){return this.getBarycoord(e,t,i,r,lc)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,lc.x),l.addScaledVector(a,lc.y),l.addScaledVector(o,lc.z),l)}static getInterpolatedAttribute(e,t,i,r,s,a){return eI.setScalar(0),tI.setScalar(0),iI.setScalar(0),eI.fromBufferAttribute(e,t),tI.fromBufferAttribute(e,i),iI.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(eI,s.x),a.addScaledVector(tI,s.y),a.addScaledVector(iI,s.z),a}static isFrontFacing(e,t,i,r){return So.subVectors(i,t),oc.subVectors(e,t),So.cross(oc).dot(r)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,r){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,i,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return So.subVectors(this.c,this.b),oc.subVectors(this.a,this.b),So.cross(oc).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return n.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return n.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,r,s){return n.getInterpolation(e,this.a,this.b,this.c,t,i,r,s)}containsPoint(e){return n.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return n.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let i=this.a,r=this.b,s=this.c,a,o;zh.subVectors(r,i),Wh.subVectors(s,i),Q0.subVectors(e,i);let l=zh.dot(Q0),c=Wh.dot(Q0);if(l<=0&&c<=0)return t.copy(i);$0.subVectors(e,r);let f=zh.dot($0),d=Wh.dot($0);if(f>=0&&d<=f)return t.copy(r);let u=l*d-f*c;if(u<=0&&l>=0&&f<=0)return a=l/(l-f),t.copy(i).addScaledVector(zh,a);J0.subVectors(e,s);let h=zh.dot(J0),m=Wh.dot(J0);if(m>=0&&h<=m)return t.copy(s);let g=h*c-l*m;if(g<=0&&c>=0&&m<=0)return o=c/(c-m),t.copy(i).addScaledVector(Wh,o);let p=f*m-h*d;if(p<=0&&d-f>=0&&h-m>=0)return bB.subVectors(s,r),o=(d-f)/(d-f+(h-m)),t.copy(r).addScaledVector(bB,o);let _=1/(p+g+u);return a=g*_,o=u*_,t.copy(i).addScaledVector(zh,a).addScaledVector(Wh,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Wr=class{constructor(e=new ie(1/0,1/0,1/0),t=new ie(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t+=3)this.expandByPoint(To.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,i=e.count;t<i;t++)this.expandByPoint(To.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let i=To.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(i),this.max.copy(e).add(i),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let i=e.geometry;if(i!==void 0){let s=i.getAttribute("position");if(t===!0&&s!==void 0&&e.isInstancedMesh!==!0)for(let a=0,o=s.count;a<o;a++)e.isMesh===!0?e.getVertexPosition(a,To):To.fromBufferAttribute(s,a),To.applyMatrix4(e.matrixWorld),this.expandByPoint(To);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),TS.copy(e.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),TS.copy(i.boundingBox)),TS.applyMatrix4(e.matrixWorld),this.union(TS)}let r=e.children;for(let s=0,a=r.length;s<a;s++)this.expandByObject(r[s],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,To),To.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(i_),AS.subVectors(this.max,i_),Hh.subVectors(e.a,i_),Xh.subVectors(e.b,i_),Yh.subVectors(e.c,i_),Tf.subVectors(Xh,Hh),Af.subVectors(Yh,Xh),Jd.subVectors(Hh,Yh);let t=[0,-Tf.z,Tf.y,0,-Af.z,Af.y,0,-Jd.z,Jd.y,Tf.z,0,-Tf.x,Af.z,0,-Af.x,Jd.z,0,-Jd.x,-Tf.y,Tf.x,0,-Af.y,Af.x,0,-Jd.y,Jd.x,0];return!rI(t,Hh,Xh,Yh,AS)||(t=[1,0,0,0,1,0,0,0,1],!rI(t,Hh,Xh,Yh,AS))?!1:(xS.crossVectors(Tf,Af),t=[xS.x,xS.y,xS.z],rI(t,Hh,Xh,Yh,AS))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,To).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(To).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(cc[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),cc[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),cc[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),cc[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),cc[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),cc[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),cc[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),cc[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(cc),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},cc=[new ie,new ie,new ie,new ie,new ie,new ie,new ie,new ie],To=new ie,TS=new Wr,Hh=new ie,Xh=new ie,Yh=new ie,Tf=new ie,Af=new ie,Jd=new ie,i_=new ie,AS=new ie,xS=new ie,eu=new ie;Jr=new ie,RS=new Ct,Wie=0,Tr=class extends Ya{constructor(e,t,i=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Wie++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=nT,this.updateRanges=[],this.gpuType=Ta,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let r=0,s=this.itemSize;r<s;r++)this.array[e+r]=t.array[i+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,i=this.count;t<i;t++)RS.fromBufferAttribute(this,t),RS.applyMatrix3(e),this.setXY(t,RS.x,RS.y);else if(this.itemSize===3)for(let t=0,i=this.count;t<i;t++)Jr.fromBufferAttribute(this,t),Jr.applyMatrix3(e),this.setXYZ(t,Jr.x,Jr.y,Jr.z);return this}applyMatrix4(e){for(let t=0,i=this.count;t<i;t++)Jr.fromBufferAttribute(this,t),Jr.applyMatrix4(e),this.setXYZ(t,Jr.x,Jr.y,Jr.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)Jr.fromBufferAttribute(this,t),Jr.applyNormalMatrix(e),this.setXYZ(t,Jr.x,Jr.y,Jr.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)Jr.fromBufferAttribute(this,t),Jr.transformDirection(e),this.setXYZ(t,Jr.x,Jr.y,Jr.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let i=this.array[e*this.itemSize+t];return this.normalized&&(i=Ao(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=or(i,this.array)),this.array[e*this.itemSize+t]=i,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Ao(t,this.array)),t}setX(e,t){return this.normalized&&(t=or(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Ao(t,this.array)),t}setY(e,t){return this.normalized&&(t=or(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Ao(t,this.array)),t}setZ(e,t){return this.normalized&&(t=or(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Ao(t,this.array)),t}setW(e,t){return this.normalized&&(t=or(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=or(t,this.array),i=or(i,this.array)),this.array[e+0]=t,this.array[e+1]=i,this}setXYZ(e,t,i,r){return e*=this.itemSize,this.normalized&&(t=or(t,this.array),i=or(i,this.array),r=or(r,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=r,this}setXYZW(e,t,i,r,s){return e*=this.itemSize,this.normalized&&(t=or(t,this.array),i=or(i,this.array),r=or(r,this.array),s=or(s,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=r,this.array[e+3]=s,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==nT&&(e.usage=this.usage),e}dispose(){this.dispatchEvent({type:"dispose"})}},v_=class extends Tr{constructor(e,t,i){super(new Uint16Array(e),t,i)}},E_=class extends Tr{constructor(e,t,i){super(new Uint32Array(e),t,i)}},gi=class extends Tr{constructor(e,t,i){super(new Float32Array(e),t,i)}},Hie=new Wr,r_=new ie,nI=new ie,Vs=class{constructor(e=new ie,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let i=this.center;t!==void 0?i.copy(t):Hie.setFromPoints(e).getCenter(i);let r=0;for(let s=0,a=e.length;s<a;s++)r=Math.max(r,i.distanceToSquared(e[s]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let i=this.center.distanceToSquared(e);return t.copy(e),i>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;r_.subVectors(e,this.center);let t=r_.lengthSq();if(t>this.radius*this.radius){let i=Math.sqrt(t),r=(i-this.radius)*.5;this.center.addScaledVector(r_,r/i),this.radius+=r}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(nI.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(r_.copy(e.center).add(nI)),this.expandByPoint(r_.copy(e.center).sub(nI))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},Xie=0,Ha=new pi,sI=new sr,Kh=new ie,ga=new Wr,n_=new Wr,Rn=new ie,Bi=class n extends Ya{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Xie++}),this.uuid=Ro(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(pie(e)?E_:v_)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,i=0){this.groups.push({start:e,count:t,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let i=this.attributes.normal;if(i!==void 0){let s=new li().getNormalMatrix(e);i.applyNormalMatrix(s),i.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Ha.makeRotationFromQuaternion(e),this.applyMatrix4(Ha),this}rotateX(e){return Ha.makeRotationX(e),this.applyMatrix4(Ha),this}rotateY(e){return Ha.makeRotationY(e),this.applyMatrix4(Ha),this}rotateZ(e){return Ha.makeRotationZ(e),this.applyMatrix4(Ha),this}translate(e,t,i){return Ha.makeTranslation(e,t,i),this.applyMatrix4(Ha),this}scale(e,t,i){return Ha.makeScale(e,t,i),this.applyMatrix4(Ha),this}lookAt(e){return sI.lookAt(e),sI.updateMatrix(),this.applyMatrix4(sI.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Kh).negate(),this.translate(Kh.x,Kh.y,Kh.z),this}setFromPoints(e){let t=this.getAttribute("position");if(t===void 0){let i=[];for(let r=0,s=e.length;r<s;r++){let a=e[r];i.push(a.x,a.y,a.z||0)}this.setAttribute("position",new gi(i,3))}else{let i=Math.min(e.length,t.count);for(let r=0;r<i;r++){let s=e[r];t.setXYZ(r,s.x,s.y,s.z||0)}e.length>t.count&&Nt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Wr);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ht("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new ie(-1/0,-1/0,-1/0),new ie(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,r=t.length;i<r;i++){let s=t[i];ga.setFromBufferAttribute(s),this.morphTargetsRelative?(Rn.addVectors(this.boundingBox.min,ga.min),this.boundingBox.expandByPoint(Rn),Rn.addVectors(this.boundingBox.max,ga.max),this.boundingBox.expandByPoint(Rn)):(this.boundingBox.expandByPoint(ga.min),this.boundingBox.expandByPoint(ga.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Ht('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Vs);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ht("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new ie,1/0);return}if(e){let i=this.boundingSphere.center;if(ga.setFromBufferAttribute(e),t)for(let s=0,a=t.length;s<a;s++){let o=t[s];n_.setFromBufferAttribute(o),this.morphTargetsRelative?(Rn.addVectors(ga.min,n_.min),ga.expandByPoint(Rn),Rn.addVectors(ga.max,n_.max),ga.expandByPoint(Rn)):(ga.expandByPoint(n_.min),ga.expandByPoint(n_.max))}ga.getCenter(i);let r=0;for(let s=0,a=e.count;s<a;s++)Rn.fromBufferAttribute(e,s),r=Math.max(r,i.distanceToSquared(Rn));if(t)for(let s=0,a=t.length;s<a;s++){let o=t[s],l=this.morphTargetsRelative;for(let c=0,f=o.count;c<f;c++)Rn.fromBufferAttribute(o,c),l&&(Kh.fromBufferAttribute(e,c),Rn.add(Kh)),r=Math.max(r,i.distanceToSquared(Rn))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&Ht('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){Ht("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}let i=t.position,r=t.normal,s=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Tr(new Float32Array(4*i.count),4));let a=this.getAttribute("tangent"),o=[],l=[];for(let M=0;M<i.count;M++)o[M]=new ie,l[M]=new ie;let c=new ie,f=new ie,d=new ie,u=new Ct,h=new Ct,m=new Ct,g=new ie,p=new ie;function _(M,I,C){c.fromBufferAttribute(i,M),f.fromBufferAttribute(i,I),d.fromBufferAttribute(i,C),u.fromBufferAttribute(s,M),h.fromBufferAttribute(s,I),m.fromBufferAttribute(s,C),f.sub(c),d.sub(c),h.sub(u),m.sub(u);let L=1/(h.x*m.y-m.x*h.y);isFinite(L)&&(g.copy(f).multiplyScalar(m.y).addScaledVector(d,-h.y).multiplyScalar(L),p.copy(d).multiplyScalar(h.x).addScaledVector(f,-m.x).multiplyScalar(L),o[M].add(g),o[I].add(g),o[C].add(g),l[M].add(p),l[I].add(p),l[C].add(p))}let v=this.groups;v.length===0&&(v=[{start:0,count:e.count}]);for(let M=0,I=v.length;M<I;++M){let C=v[M],L=C.start,w=C.count;for(let G=L,O=L+w;G<O;G+=3)_(e.getX(G+0),e.getX(G+1),e.getX(G+2))}let E=new ie,S=new ie,T=new ie,A=new ie;function R(M){T.fromBufferAttribute(r,M),A.copy(T);let I=o[M];E.copy(I),E.sub(T.multiplyScalar(T.dot(I))).normalize(),S.crossVectors(A,I);let L=S.dot(l[M])<0?-1:1;a.setXYZW(M,E.x,E.y,E.z,L)}for(let M=0,I=v.length;M<I;++M){let C=v[M],L=C.start,w=C.count;for(let G=L,O=L+w;G<O;G+=3)R(e.getX(G+0)),R(e.getX(G+1)),R(e.getX(G+2))}}computeVertexNormals(){let e=this.index,t=this.getAttribute("position");if(t!==void 0){let i=this.getAttribute("normal");if(i===void 0)i=new Tr(new Float32Array(t.count*3),3),this.setAttribute("normal",i);else for(let u=0,h=i.count;u<h;u++)i.setXYZ(u,0,0,0);let r=new ie,s=new ie,a=new ie,o=new ie,l=new ie,c=new ie,f=new ie,d=new ie;if(e)for(let u=0,h=e.count;u<h;u+=3){let m=e.getX(u+0),g=e.getX(u+1),p=e.getX(u+2);r.fromBufferAttribute(t,m),s.fromBufferAttribute(t,g),a.fromBufferAttribute(t,p),f.subVectors(a,s),d.subVectors(r,s),f.cross(d),o.fromBufferAttribute(i,m),l.fromBufferAttribute(i,g),c.fromBufferAttribute(i,p),o.add(f),l.add(f),c.add(f),i.setXYZ(m,o.x,o.y,o.z),i.setXYZ(g,l.x,l.y,l.z),i.setXYZ(p,c.x,c.y,c.z)}else for(let u=0,h=t.count;u<h;u+=3)r.fromBufferAttribute(t,u+0),s.fromBufferAttribute(t,u+1),a.fromBufferAttribute(t,u+2),f.subVectors(a,s),d.subVectors(r,s),f.cross(d),i.setXYZ(u+0,f.x,f.y,f.z),i.setXYZ(u+1,f.x,f.y,f.z),i.setXYZ(u+2,f.x,f.y,f.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,i=e.count;t<i;t++)Rn.fromBufferAttribute(e,t),Rn.normalize(),e.setXYZ(t,Rn.x,Rn.y,Rn.z)}toNonIndexed(){function e(o,l){let c=o.array,f=o.itemSize,d=o.normalized,u=new c.constructor(l.length*f),h=0,m=0;for(let g=0,p=l.length;g<p;g++){o.isInterleavedBufferAttribute?h=l[g]*o.data.stride+o.offset:h=l[g]*f;for(let _=0;_<f;_++)u[m++]=c[h++]}return new Tr(u,f,d)}if(this.index===null)return Nt("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let t=new n,i=this.index.array,r=this.attributes;for(let o in r){let l=r[o],c=e(l,i);t.setAttribute(o,c)}let s=this.morphAttributes;for(let o in s){let l=[],c=s[o];for(let f=0,d=c.length;f<d;f++){let u=c[f],h=e(u,i);l.push(h)}t.morphAttributes[o]=l}t.morphTargetsRelative=this.morphTargetsRelative;let a=this.groups;for(let o=0,l=a.length;o<l;o++){let c=a[o];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){let e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){let l=this.parameters;for(let c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let i=this.attributes;for(let l in i){let c=i[l];e.data.attributes[l]=c.toJSON(e.data)}let r={},s=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],f=[];for(let d=0,u=c.length;d<u;d++){let h=c[d];f.push(h.toJSON(e.data))}f.length>0&&(r[l]=f,s=!0)}s&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let i=e.index;i!==null&&this.setIndex(i.clone());let r=e.attributes;for(let c in r){let f=r[c];this.setAttribute(c,f.clone(t))}let s=e.morphAttributes;for(let c in s){let f=[],d=s[c];for(let u=0,h=d.length;u<h;u++)f.push(d[u].clone(t));this.morphAttributes[c]=f}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let c=0,f=a.length;c<f;c++){let d=a[c];this.addGroup(d.start,d.count,d.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}},uu=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=nT,this.updateRanges=[],this.version=0,this.uuid=Ro()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,i){e*=this.stride,i*=t.stride;for(let r=0,s=this.stride;r<s;r++)this.array[e+r]=t.array[i+r];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Ro()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);let t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),i=new this.constructor(t,this.stride);return i.setUsage(this.usage),i}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Ro()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}},ms=new ie,Mf=class n{constructor(e,t,i,r=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=i,this.normalized=r}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,i=this.data.count;t<i;t++)ms.fromBufferAttribute(this,t),ms.applyMatrix4(e),this.setXYZ(t,ms.x,ms.y,ms.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)ms.fromBufferAttribute(this,t),ms.applyNormalMatrix(e),this.setXYZ(t,ms.x,ms.y,ms.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)ms.fromBufferAttribute(this,t),ms.transformDirection(e),this.setXYZ(t,ms.x,ms.y,ms.z);return this}getComponent(e,t){let i=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(i=Ao(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=or(i,this.array)),this.data.array[e*this.data.stride+this.offset+t]=i,this}setX(e,t){return this.normalized&&(t=or(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=or(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=or(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=or(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=Ao(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Ao(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Ao(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Ao(t,this.array)),t}setXY(e,t,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=or(t,this.array),i=or(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=i,this}setXYZ(e,t,i,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=or(t,this.array),i=or(i,this.array),r=or(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=i,this.data.array[e+2]=r,this}setXYZW(e,t,i,r,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=or(t,this.array),i=or(i,this.array),r=or(r,this.array),s=or(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=i,this.data.array[e+2]=r,this.data.array[e+3]=s,this}clone(e){if(e===void 0){g_("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");let t=[];for(let i=0;i<this.count;i++){let r=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[r+s])}return new Tr(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new n(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){g_("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");let t=[];for(let i=0;i<this.count;i++){let r=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[r+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}},Yie=0,Hr=class extends Ya{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Yie++}),this.uuid=Ro(),this.name="",this.type="Material",this.blending=au,this.side=va,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=ZS,this.blendDst=qS,this.blendEquation=bf,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new mt(0,0,0),this.blendAlpha=0,this.depthFunc=ou,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=EI,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=ru,this.stencilZFail=ru,this.stencilZPass=ru,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let i=e[t];if(i===void 0){Nt(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){Nt(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(i):r&&r.isVector3&&i&&i.isVector3?r.copy(i):this[t]=i}}toJSON(e){let t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});let i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==au&&(i.blending=this.blending),this.side!==va&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==ZS&&(i.blendSrc=this.blendSrc),this.blendDst!==qS&&(i.blendDst=this.blendDst),this.blendEquation!==bf&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==ou&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==EI&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ru&&(i.stencilFail=this.stencilFail),this.stencilZFail!==ru&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==ru&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.allowOverride===!1&&(i.allowOverride=!1),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function r(s){let a=[];for(let o in s){let l=s[o];delete l.metadata,a.push(l)}return a}if(t){let s=r(e.textures),a=r(e.images);s.length>0&&(i.textures=s),a.length>0&&(i.images=a)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,i=null;if(t!==null){let r=t.length;i=new Array(r);for(let s=0;s!==r;++s)i[s]=t[s].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}},fm=class extends Hr{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new mt(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},s_=new ie,Zh=new ie,qh=new ie,Qh=new Ct,a_=new Ct,V2=new pi,bS=new ie,o_=new ie,MS=new ie,MB=new Ct,aI=new Ct,yB=new Ct,S_=class extends sr{constructor(e=new fm){if(super(),this.isSprite=!0,this.type="Sprite",jh===void 0){jh=new Bi;let t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),i=new uu(t,5);jh.setIndex([0,1,2,0,2,3]),jh.setAttribute("position",new Mf(i,3,0,!1)),jh.setAttribute("uv",new Mf(i,2,3,!1))}this.geometry=jh,this.material=e,this.center=new Ct(.5,.5),this.count=1}raycast(e,t){e.camera===null&&Ht('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),Zh.setFromMatrixScale(this.matrixWorld),V2.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),qh.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&Zh.multiplyScalar(-qh.z);let i=this.material.rotation,r,s;i!==0&&(s=Math.cos(i),r=Math.sin(i));let a=this.center;yS(bS.set(-.5,-.5,0),qh,a,Zh,r,s),yS(o_.set(.5,-.5,0),qh,a,Zh,r,s),yS(MS.set(.5,.5,0),qh,a,Zh,r,s),MB.set(0,0),aI.set(1,0),yB.set(1,1);let o=e.ray.intersectTriangle(bS,o_,MS,!1,s_);if(o===null&&(yS(o_.set(-.5,.5,0),qh,a,Zh,r,s),aI.set(0,1),o=e.ray.intersectTriangle(bS,MS,o_,!1,s_),o===null))return;let l=e.ray.origin.distanceTo(s_);l<e.near||l>e.far||t.push({distance:l,point:s_.clone(),uv:uc.getInterpolation(s_,bS,o_,MS,MB,aI,yB,new Ct),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}};fc=new ie,oI=new ie,IS=new ie,xf=new ie,lI=new ie,CS=new ie,cI=new ie,ml=class{constructor(e=new ie,t=new ie(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,fc)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=fc.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(fc.copy(this.origin).addScaledVector(this.direction,t),fc.distanceToSquared(e))}distanceSqToSegment(e,t,i,r){oI.copy(e).add(t).multiplyScalar(.5),IS.copy(t).sub(e).normalize(),xf.copy(this.origin).sub(oI);let s=e.distanceTo(t)*.5,a=-this.direction.dot(IS),o=xf.dot(this.direction),l=-xf.dot(IS),c=xf.lengthSq(),f=Math.abs(1-a*a),d,u,h,m;if(f>0)if(d=a*l-o,u=a*o-l,m=s*f,d>=0)if(u>=-m)if(u<=m){let g=1/f;d*=g,u*=g,h=d*(d+a*u+2*o)+u*(a*d+u+2*l)+c}else u=s,d=Math.max(0,-(a*u+o)),h=-d*d+u*(u+2*l)+c;else u=-s,d=Math.max(0,-(a*u+o)),h=-d*d+u*(u+2*l)+c;else u<=-m?(d=Math.max(0,-(-a*s+o)),u=d>0?-s:Math.min(Math.max(-s,-l),s),h=-d*d+u*(u+2*l)+c):u<=m?(d=0,u=Math.min(Math.max(-s,-l),s),h=u*(u+2*l)+c):(d=Math.max(0,-(a*s+o)),u=d>0?s:Math.min(Math.max(-s,-l),s),h=-d*d+u*(u+2*l)+c);else u=a>0?-s:s,d=Math.max(0,-(a*u+o)),h=-d*d+u*(u+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,d),r&&r.copy(oI).addScaledVector(IS,u),h}intersectSphere(e,t){fc.subVectors(e.center,this.origin);let i=fc.dot(this.direction),r=fc.dot(fc)-i*i,s=e.radius*e.radius;if(r>s)return null;let a=Math.sqrt(s-r),o=i-a,l=i+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){let i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,r,s,a,o,l,c=1/this.direction.x,f=1/this.direction.y,d=1/this.direction.z,u=this.origin;return c>=0?(i=(e.min.x-u.x)*c,r=(e.max.x-u.x)*c):(i=(e.max.x-u.x)*c,r=(e.min.x-u.x)*c),f>=0?(s=(e.min.y-u.y)*f,a=(e.max.y-u.y)*f):(s=(e.max.y-u.y)*f,a=(e.min.y-u.y)*f),i>a||s>r||((s>i||isNaN(i))&&(i=s),(a<r||isNaN(r))&&(r=a),d>=0?(o=(e.min.z-u.z)*d,l=(e.max.z-u.z)*d):(o=(e.max.z-u.z)*d,l=(e.min.z-u.z)*d),i>l||o>r)||((o>i||i!==i)&&(i=o),(l<r||r!==r)&&(r=l),r<0)?null:this.at(i>=0?i:r,t)}intersectsBox(e){return this.intersectBox(e,fc)!==null}intersectTriangle(e,t,i,r,s){lI.subVectors(t,e),CS.subVectors(i,e),cI.crossVectors(lI,CS);let a=this.direction.dot(cI),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;xf.subVectors(this.origin,e);let l=o*this.direction.dot(CS.crossVectors(xf,CS));if(l<0)return null;let c=o*this.direction.dot(lI.cross(xf));if(c<0||l+c>a)return null;let f=-o*xf.dot(cI);return f<0?null:this.at(f/a,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},Kn=class extends Hr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new mt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new bo,this.combine=U_,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},IB=new pi,tu=new ml,PS=new Vs,CB=new ie,LS=new ie,DS=new ie,OS=new ie,fI=new ie,NS=new ie,PB=new ie,wS=new ie,ci=class extends sr{constructor(e=new Bi,t=new Kn){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){let r=t[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s<a;s++){let o=r[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=s}}}}getVertexPosition(e,t){let i=this.geometry,r=i.attributes.position,s=i.morphAttributes.position,a=i.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(s&&o){NS.set(0,0,0);for(let l=0,c=s.length;l<c;l++){let f=o[l],d=s[l];f!==0&&(fI.fromBufferAttribute(d,e),a?NS.addScaledVector(fI,f):NS.addScaledVector(fI.sub(t),f))}t.add(NS)}return t}raycast(e,t){let i=this.geometry,r=this.material,s=this.matrixWorld;r!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),PS.copy(i.boundingSphere),PS.applyMatrix4(s),tu.copy(e.ray).recast(e.near),!(PS.containsPoint(tu.origin)===!1&&(tu.intersectSphere(PS,CB)===null||tu.origin.distanceToSquared(CB)>(e.far-e.near)**2))&&(IB.copy(s).invert(),tu.copy(e.ray).applyMatrix4(IB),!(i.boundingBox!==null&&tu.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,tu)))}_computeIntersections(e,t,i){let r,s=this.geometry,a=this.material,o=s.index,l=s.attributes.position,c=s.attributes.uv,f=s.attributes.uv1,d=s.attributes.normal,u=s.groups,h=s.drawRange;if(o!==null)if(Array.isArray(a))for(let m=0,g=u.length;m<g;m++){let p=u[m],_=a[p.materialIndex],v=Math.max(p.start,h.start),E=Math.min(o.count,Math.min(p.start+p.count,h.start+h.count));for(let S=v,T=E;S<T;S+=3){let A=o.getX(S),R=o.getX(S+1),M=o.getX(S+2);r=FS(this,_,e,i,c,f,d,A,R,M),r&&(r.faceIndex=Math.floor(S/3),r.face.materialIndex=p.materialIndex,t.push(r))}}else{let m=Math.max(0,h.start),g=Math.min(o.count,h.start+h.count);for(let p=m,_=g;p<_;p+=3){let v=o.getX(p),E=o.getX(p+1),S=o.getX(p+2);r=FS(this,a,e,i,c,f,d,v,E,S),r&&(r.faceIndex=Math.floor(p/3),t.push(r))}}else if(l!==void 0)if(Array.isArray(a))for(let m=0,g=u.length;m<g;m++){let p=u[m],_=a[p.materialIndex],v=Math.max(p.start,h.start),E=Math.min(l.count,Math.min(p.start+p.count,h.start+h.count));for(let S=v,T=E;S<T;S+=3){let A=S,R=S+1,M=S+2;r=FS(this,_,e,i,c,f,d,A,R,M),r&&(r.faceIndex=Math.floor(S/3),r.face.materialIndex=p.materialIndex,t.push(r))}}else{let m=Math.max(0,h.start),g=Math.min(l.count,h.start+h.count);for(let p=m,_=g;p<_;p+=3){let v=p,E=p+1,S=p+2;r=FS(this,a,e,i,c,f,d,v,E,S),r&&(r.faceIndex=Math.floor(p/3),t.push(r))}}}};l_=new dr,LB=new dr,DB=new dr,jie=new dr,OB=new pi,BS=new ie,dI=new Vs,NB=new pi,uI=new ml,T_=class extends ci{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=_I,this.bindMatrix=new pi,this.bindMatrixInverse=new pi,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new Wr),this.boundingBox.makeEmpty();let t=e.getAttribute("position");for(let i=0;i<t.count;i++)this.getVertexPosition(i,BS),this.boundingBox.expandByPoint(BS)}computeBoundingSphere(){let e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new Vs),this.boundingSphere.makeEmpty();let t=e.getAttribute("position");for(let i=0;i<t.count;i++)this.getVertexPosition(i,BS),this.boundingSphere.expandByPoint(BS)}copy(e,t){return super.copy(e,t),this.bindMode=e.bindMode,this.bindMatrix.copy(e.bindMatrix),this.bindMatrixInverse.copy(e.bindMatrixInverse),this.skeleton=e.skeleton,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}raycast(e,t){let i=this.material,r=this.matrixWorld;i!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),dI.copy(this.boundingSphere),dI.applyMatrix4(r),e.ray.intersectsSphere(dI)!==!1&&(NB.copy(r).invert(),uI.copy(e.ray).applyMatrix4(NB),!(this.boundingBox!==null&&uI.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,uI)))}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){this.skeleton=e,t===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),t=this.matrixWorld),this.bindMatrix.copy(t),this.bindMatrixInverse.copy(t).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){let e=new dr,t=this.geometry.attributes.skinWeight;for(let i=0,r=t.count;i<r;i++){e.fromBufferAttribute(t,i);let s=1/e.manhattanLength();s!==1/0?e.multiplyScalar(s):e.set(1,0,0,0),t.setXYZW(i,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){super.updateMatrixWorld(e),this.bindMode===_I?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===T2?this.bindMatrixInverse.copy(this.bindMatrix).invert():Nt("SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){let i=this.skeleton,r=this.geometry;LB.fromBufferAttribute(r.attributes.skinIndex,e),DB.fromBufferAttribute(r.attributes.skinWeight,e),t.isVector4?(l_.copy(t),t.set(0,0,0,0)):(l_.set(...t,1),t.set(0,0,0)),l_.applyMatrix4(this.bindMatrix);for(let s=0;s<4;s++){let a=DB.getComponent(s);if(a!==0){let o=LB.getComponent(s);OB.multiplyMatrices(i.bones[o].matrixWorld,i.boneInverses[o]),t.addScaledVector(jie.copy(l_).applyMatrix4(OB),a)}}return t.isVector4&&(t.w=l_.w),t.applyMatrix4(this.bindMatrixInverse)}},dm=class extends sr{constructor(){super(),this.isBone=!0,this.type="Bone"}},um=class extends Lr{constructor(e=null,t=1,i=1,r,s,a,o,l,c=kr,f=kr,d,u){super(null,a,o,l,c,f,r,s,d,u),this.isDataTexture=!0,this.image={data:e,width:t,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},wB=new pi,Zie=new pi,A_=class n{constructor(e=[],t=[]){this.uuid=Ro(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=null,this.previousBoneMatrices=null,this.boneTexture=null,this.init()}init(){let e=this.bones,t=this.boneInverses;if(this.boneMatrices=new Float32Array(e.length*16),t.length===0)this.calculateInverses();else if(e.length!==t.length){Nt("Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let i=0,r=this.bones.length;i<r;i++)this.boneInverses.push(new pi)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){let i=new pi;this.bones[e]&&i.copy(this.bones[e].matrixWorld).invert(),this.boneInverses.push(i)}}pose(){for(let e=0,t=this.bones.length;e<t;e++){let i=this.bones[e];i&&i.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){let i=this.bones[e];i&&(i.parent&&i.parent.isBone?(i.matrix.copy(i.parent.matrixWorld).invert(),i.matrix.multiply(i.matrixWorld)):i.matrix.copy(i.matrixWorld),i.matrix.decompose(i.position,i.quaternion,i.scale))}}update(){let e=this.bones,t=this.boneInverses,i=this.boneMatrices,r=this.boneTexture;for(let s=0,a=e.length;s<a;s++){let o=e[s]?e[s].matrixWorld:Zie;wB.multiplyMatrices(o,t[s]),wB.toArray(i,s*16)}r!==null&&(r.needsUpdate=!0)}clone(){return new n(this.bones,this.boneInverses)}computeBoneTexture(){let e=Math.sqrt(this.bones.length*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);let t=new Float32Array(e*e*4);t.set(this.boneMatrices);let i=new um(t,e,e,Aa,Ta);return i.needsUpdate=!0,this.boneMatrices=t,this.boneTexture=i,this}getBoneByName(e){for(let t=0,i=this.bones.length;t<i;t++){let r=this.bones[t];if(r.name===e)return r}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(e,t){this.uuid=e.uuid;for(let i=0,r=e.bones.length;i<r;i++){let s=e.bones[i],a=t[s];a===void 0&&(Nt("Skeleton: No bone found with UUID:",s),a=new dm),this.bones.push(a),this.boneInverses.push(new pi().fromArray(e.boneInverses[i]))}return this.init(),this}toJSON(){let e={metadata:{version:4.7,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};e.uuid=this.uuid;let t=this.bones,i=this.boneInverses;for(let r=0,s=t.length;r<s;r++){let a=t[r];e.bones.push(a.uuid);let o=i[r];e.boneInverses.push(o.toArray())}return e}},yf=class extends Tr{constructor(e,t,i,r=1){super(e,t,i),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=r}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){let e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}},$h=new pi,FB=new pi,US=[],BB=new Wr,qie=new pi,c_=new ci,f_=new Vs,hu=class extends ci{constructor(e,t,i){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new yf(new Float32Array(i*16),16),this.previousInstanceMatrix=null,this.instanceColor=null,this.morphTexture=null,this.count=i,this.boundingBox=null,this.boundingSphere=null;for(let r=0;r<i;r++)this.setMatrixAt(r,qie)}computeBoundingBox(){let e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new Wr),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,$h),BB.copy(e.boundingBox).applyMatrix4($h),this.boundingBox.union(BB)}computeBoundingSphere(){let e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new Vs),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,$h),f_.copy(e.boundingSphere).applyMatrix4($h),this.boundingSphere.union(f_)}copy(e,t){return super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),e.previousInstanceMatrix!==null&&(this.previousInstanceMatrix=e.previousInstanceMatrix.clone()),e.morphTexture!==null&&(this.morphTexture=e.morphTexture.clone()),e.instanceColor!==null&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}getColorAt(e,t){return this.instanceColor===null?t.setRGB(1,1,1):t.fromArray(this.instanceColor.array,e*3)}getMatrixAt(e,t){return t.fromArray(this.instanceMatrix.array,e*16)}getMorphAt(e,t){let i=t.morphTargetInfluences,r=this.morphTexture.source.data.data,s=i.length+1,a=e*s+1;for(let o=0;o<i.length;o++)i[o]=r[a+o]}raycast(e,t){let i=this.matrixWorld,r=this.count;if(c_.geometry=this.geometry,c_.material=this.material,c_.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),f_.copy(this.boundingSphere),f_.applyMatrix4(i),e.ray.intersectsSphere(f_)!==!1))for(let s=0;s<r;s++){this.getMatrixAt(s,$h),FB.multiplyMatrices(i,$h),c_.matrixWorld=FB,c_.raycast(e,US);for(let a=0,o=US.length;a<o;a++){let l=US[a];l.instanceId=s,l.object=this,t.push(l)}US.length=0}}setColorAt(e,t){return this.instanceColor===null&&(this.instanceColor=new yf(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),t.toArray(this.instanceColor.array,e*3),this}setMatrixAt(e,t){return t.toArray(this.instanceMatrix.array,e*16),this}setMorphAt(e,t){let i=t.morphTargetInfluences,r=i.length+1;this.morphTexture===null&&(this.morphTexture=new um(new Float32Array(r*this.count),r,this.count,DT,Ta));let s=this.morphTexture.source.data.data,a=0;for(let c=0;c<i.length;c++)a+=i[c];let o=this.geometry.morphTargetsRelative?1:1-a,l=r*e;return s[l]=o,s.set(i,l+1),this}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}},hI=new ie,Qie=new ie,$ie=new li,ps=class{constructor(e=new ie(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,i,r){return this.normal.set(e,t,i),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,i){let r=hI.subVectors(i,t).cross(Qie.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,i=!0){let r=e.delta(hI),s=this.normal.dot(r);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let a=-(e.start.dot(this.normal)+this.constant)/s;return i===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let i=t||$ie.getNormalMatrix(e),r=this.coplanarPoint(hI).applyMatrix4(e),s=this.normal.applyMatrix3(i).normalize();return this.constant=-r.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},iu=new Vs,Jie=new Ct(.5,.5),VS=new ie,hm=class{constructor(e=new ps,t=new ps,i=new ps,r=new ps,s=new ps,a=new ps){this.planes=[e,t,i,r,s,a]}set(e,t,i,r,s,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(r),o[4].copy(s),o[5].copy(a),this}copy(e){let t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=xo,i=!1){let r=this.planes,s=e.elements,a=s[0],o=s[1],l=s[2],c=s[3],f=s[4],d=s[5],u=s[6],h=s[7],m=s[8],g=s[9],p=s[10],_=s[11],v=s[12],E=s[13],S=s[14],T=s[15];if(r[0].setComponents(c-a,h-f,_-m,T-v).normalize(),r[1].setComponents(c+a,h+f,_+m,T+v).normalize(),r[2].setComponents(c+o,h+d,_+g,T+E).normalize(),r[3].setComponents(c-o,h-d,_-g,T-E).normalize(),i)r[4].setComponents(l,u,p,S).normalize(),r[5].setComponents(c-l,h-u,_-p,T-S).normalize();else if(r[4].setComponents(c-l,h-u,_-p,T-S).normalize(),t===xo)r[5].setComponents(c+l,h+u,_+p,T+S).normalize();else if(t===nm)r[5].setComponents(l,u,p,S).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),iu.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),iu.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(iu)}intersectsSprite(e){iu.center.set(0,0,0);let t=Jie.distanceTo(e.center);return iu.radius=.7071067811865476+t,iu.applyMatrix4(e.matrixWorld),this.intersectsSphere(iu)}intersectsSphere(e){let t=this.planes,i=e.center,r=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(i)<r)return!1;return!0}intersectsBox(e){let t=this.planes;for(let i=0;i<6;i++){let r=t[i];if(VS.x=r.normal.x>0?e.max.x:e.min.x,VS.y=r.normal.y>0?e.max.y:e.min.y,VS.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(VS)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},Ln=class extends Hr{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new mt(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}},cT=new ie,fT=new ie,UB=new pi,d_=new ml,GS=new Vs,mI=new ie,VB=new ie,mu=class extends sr{constructor(e=new Bi,t=new Ln){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,i=[0];for(let r=1,s=t.count;r<s;r++)cT.fromBufferAttribute(t,r-1),fT.fromBufferAttribute(t,r),i[r]=i[r-1],i[r]+=cT.distanceTo(fT);e.setAttribute("lineDistance",new gi(i,1))}else Nt("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){let i=this.geometry,r=this.matrixWorld,s=e.params.Line.threshold,a=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),GS.copy(i.boundingSphere),GS.applyMatrix4(r),GS.radius+=s,e.ray.intersectsSphere(GS)===!1)return;UB.copy(r).invert(),d_.copy(e.ray).applyMatrix4(UB);let o=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=o*o,c=this.isLineSegments?2:1,f=i.index,u=i.attributes.position;if(f!==null){let h=Math.max(0,a.start),m=Math.min(f.count,a.start+a.count);for(let g=h,p=m-1;g<p;g+=c){let _=f.getX(g),v=f.getX(g+1),E=kS(this,e,d_,l,_,v,g);E&&t.push(E)}if(this.isLineLoop){let g=f.getX(m-1),p=f.getX(h),_=kS(this,e,d_,l,g,p,m-1);_&&t.push(_)}}else{let h=Math.max(0,a.start),m=Math.min(u.count,a.start+a.count);for(let g=h,p=m-1;g<p;g+=c){let _=kS(this,e,d_,l,g,g+1,g);_&&t.push(_)}if(this.isLineLoop){let g=kS(this,e,d_,l,m-1,h,m-1);g&&t.push(g)}}}updateMorphTargets(){let t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){let r=t[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s<a;s++){let o=r[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=s}}}}};GB=new ie,kB=new ie,_s=class extends mu{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,i=[];for(let r=0,s=t.count;r<s;r+=2)GB.fromBufferAttribute(t,r),kB.fromBufferAttribute(t,r+1),i[r]=r===0?0:i[r-1],i[r+1]=i[r]+GB.distanceTo(kB);e.setAttribute("lineDistance",new gi(i,1))}else Nt("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}},x_=class extends mu{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}},Gs=class extends Hr{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new mt(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},zB=new pi,SI=new ml,zS=new Vs,WS=new ie,ks=class extends sr{constructor(e=new Bi,t=new Gs){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){let i=this.geometry,r=this.matrixWorld,s=e.params.Points.threshold,a=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),zS.copy(i.boundingSphere),zS.applyMatrix4(r),zS.radius+=s,e.ray.intersectsSphere(zS)===!1)return;zB.copy(r).invert(),SI.copy(e.ray).applyMatrix4(zB);let o=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=o*o,c=i.index,d=i.attributes.position;if(c!==null){let u=Math.max(0,a.start),h=Math.min(c.count,a.start+a.count);for(let m=u,g=h;m<g;m++){let p=c.getX(m);WS.fromBufferAttribute(d,p),WB(WS,p,l,r,e,t,this)}}else{let u=Math.max(0,a.start),h=Math.min(d.count,a.start+a.count);for(let m=u,g=h;m<g;m++)WS.fromBufferAttribute(d,m),WB(WS,m,l,r,e,t,this)}}updateMorphTargets(){let t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){let r=t[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s<a;s++){let o=r[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=s}}}}};R_=class extends Lr{constructor(e=[],t=Of,i,r,s,a,o,l,c,f){super(e,t,i,r,s,a,o,l,c,f),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},b_=class extends Lr{constructor(e,t,i,r,s,a,o,l,c){super(e,t,i,r,s,a,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}},mc=class extends Lr{constructor(e,t,i=Co,r,s,a,o=kr,l=kr,c,f=hl,d=1){if(f!==hl&&f!==Nf)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");let u={width:e,height:t,depth:d};super(u,r,s,a,o,l,f,i,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new om(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},dT=class extends mc{constructor(e,t=Co,i=Of,r,s,a=kr,o=kr,l,c=hl){let f={width:e,height:e,depth:1},d=[f,f,f,f,f,f];super(e,e,t,i,r,s,a,o,l,c),this.image=d,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},M_=class extends Lr{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},If=class n extends Bi{constructor(e=1,t=1,i=1,r=1,s=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:r,heightSegments:s,depthSegments:a};let o=this;r=Math.floor(r),s=Math.floor(s),a=Math.floor(a);let l=[],c=[],f=[],d=[],u=0,h=0;m("z","y","x",-1,-1,i,t,e,a,s,0),m("z","y","x",1,-1,i,t,-e,a,s,1),m("x","z","y",1,1,e,i,t,r,a,2),m("x","z","y",1,-1,e,i,-t,r,a,3),m("x","y","z",1,-1,e,t,i,r,s,4),m("x","y","z",-1,-1,e,t,-i,r,s,5),this.setIndex(l),this.setAttribute("position",new gi(c,3)),this.setAttribute("normal",new gi(f,3)),this.setAttribute("uv",new gi(d,2));function m(g,p,_,v,E,S,T,A,R,M,I){let C=S/R,L=T/M,w=S/2,G=T/2,O=A/2,N=R+1,B=M+1,V=0,q=0,K=new ie;for(let J=0;J<B;J++){let Y=J*L-G;for(let j=0;j<N;j++){let ue=j*C-w;K[g]=ue*v,K[p]=Y*E,K[_]=O,c.push(K.x,K.y,K.z),K[g]=0,K[p]=0,K[_]=A>0?1:-1,f.push(K.x,K.y,K.z),d.push(j/R),d.push(1-J/M),V+=1}}for(let J=0;J<M;J++)for(let Y=0;Y<R;Y++){let j=u+Y+N*J,ue=u+Y+N*(J+1),Ee=u+(Y+1)+N*(J+1),Ue=u+(Y+1)+N*J;l.push(j,ue,Ue),l.push(ue,Ee,Ue),q+=6}o.addGroup(h,q,I),h+=q,u+=V}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new n(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}},pu=class n extends Bi{constructor(e=1,t=1,i=1,r=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:i,heightSegments:r};let s=e/2,a=t/2,o=Math.floor(i),l=Math.floor(r),c=o+1,f=l+1,d=e/o,u=t/l,h=[],m=[],g=[],p=[];for(let _=0;_<f;_++){let v=_*u-a;for(let E=0;E<c;E++){let S=E*d-s;m.push(S,-v,0),g.push(0,0,1),p.push(E/o),p.push(1-_/l)}}for(let _=0;_<l;_++)for(let v=0;v<o;v++){let E=v+c*_,S=v+c*(_+1),T=v+1+c*(_+1),A=v+1+c*_;h.push(E,S,A),h.push(S,T,A)}this.setIndex(h),this.setAttribute("position",new gi(m,3)),this.setAttribute("normal",new gi(g,3)),this.setAttribute("uv",new gi(p,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new n(e.width,e.height,e.widthSegments,e.heightSegments)}},mm=class n extends Bi{constructor(e=1,t=32,i=16,r=0,s=Math.PI*2,a=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:i,phiStart:r,phiLength:s,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),i=Math.max(2,Math.floor(i));let l=Math.min(a+o,Math.PI),c=0,f=[],d=new ie,u=new ie,h=[],m=[],g=[],p=[];for(let _=0;_<=i;_++){let v=[],E=_/i,S=0;_===0&&a===0?S=.5/t:_===i&&l===Math.PI&&(S=-.5/t);for(let T=0;T<=t;T++){let A=T/t;d.x=-e*Math.cos(r+A*s)*Math.sin(a+E*o),d.y=e*Math.cos(a+E*o),d.z=e*Math.sin(r+A*s)*Math.sin(a+E*o),m.push(d.x,d.y,d.z),u.copy(d).normalize(),g.push(u.x,u.y,u.z),p.push(A+S,1-E),v.push(c++)}f.push(v)}for(let _=0;_<i;_++)for(let v=0;v<t;v++){let E=f[_][v+1],S=f[_][v],T=f[_+1][v],A=f[_+1][v+1];(_!==0||a>0)&&h.push(E,S,A),(_!==i-1||l<Math.PI)&&h.push(S,T,A)}this.setIndex(h),this.setAttribute("position",new gi(m,3)),this.setAttribute("normal",new gi(g,3)),this.setAttribute("uv",new gi(p,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new n(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}},y_=class extends Hr{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new mt(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}};G2={clone:Tu,merge:jn},tre=`void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,ire=`void main() {
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`,Sa=class extends Hr{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=tre,this.fragmentShader=ire,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Tu(e.uniforms),this.uniformsGroups=ere(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let r in this.uniforms){let a=this.uniforms[r].value;a&&a.isTexture?t.uniforms[r]={type:"t",value:a.toJSON(e).uuid}:a&&a.isColor?t.uniforms[r]={type:"c",value:a.getHex()}:a&&a.isVector2?t.uniforms[r]={type:"v2",value:a.toArray()}:a&&a.isVector3?t.uniforms[r]={type:"v3",value:a.toArray()}:a&&a.isVector4?t.uniforms[r]={type:"v4",value:a.toArray()}:a&&a.isMatrix3?t.uniforms[r]={type:"m3",value:a.toArray()}:a&&a.isMatrix4?t.uniforms[r]={type:"m4",value:a.toArray()}:t.uniforms[r]={value:a}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let i={};for(let r in this.extensions)this.extensions[r]===!0&&(i[r]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}},uT=class extends Sa{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}},Dn=class extends Hr{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new mt(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new mt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=bm,this.normalScale=new Ct(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new bo,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},zs=class extends Dn{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new Ct(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Ai(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new mt(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new mt(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new mt(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}},gu=class extends Hr{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new mt(16777215),this.specular=new mt(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new mt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=bm,this.normalScale=new Ct(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new bo,this.combine=U_,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},I_=class extends Hr{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new mt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new mt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=bm,this.normalScale=new Ct(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new bo,this.combine=U_,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},hT=class extends Hr{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=M2,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},mT=class extends Hr{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};pl=class{constructor(e,t,i,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r!==void 0?r:new t.constructor(i),this.sampleValues=t,this.valueSize=i,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,i=this._cachedIndex,r=t[i],s=t[i-1];e:{t:{let a;i:{r:if(!(e<r)){for(let o=i+2;;){if(r===void 0){if(e<s)break r;return i=t.length,this._cachedIndex=i,this.copySampleValue_(i-1)}if(i===o)break;if(s=r,r=t[++i],e<r)break t}a=t.length;break i}if(!(e>=s)){let o=t[1];e<o&&(i=2,s=o);for(let l=i-2;;){if(s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(i===l)break;if(r=s,s=t[--i-1],e>=s)break t}a=i,i=0;break i}break e}for(;i<a;){let o=i+a>>>1;e<t[o]?a=o:i=o+1}if(r=t[i],s=t[i-1],s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return i=t.length,this._cachedIndex=i,this.copySampleValue_(i-1)}this._cachedIndex=i,this.intervalChanged_(i,s,r)}return this.interpolate_(i,s,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,i=this.sampleValues,r=this.valueSize,s=e*r;for(let a=0;a!==r;++a)t[a]=i[s+a];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}},pT=class extends pl{constructor(e,t,i,r){super(e,t,i,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:nu,endingEnd:nu}}intervalChanged_(e,t,i){let r=this.parameterPositions,s=e-2,a=e+1,o=r[s],l=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case su:s=e,o=2*t-i;break;case m_:s=r.length-2,o=t+r[s]-r[s+1];break;default:s=e,o=i}if(l===void 0)switch(this.getSettings_().endingEnd){case su:a=e,l=2*i-t;break;case m_:a=1,l=i+r[1]-r[0];break;default:a=e-1,l=t}let c=(i-t)*.5,f=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(l-i),this._offsetPrev=s*f,this._offsetNext=a*f}interpolate_(e,t,i,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,f=this._offsetPrev,d=this._offsetNext,u=this._weightPrev,h=this._weightNext,m=(i-t)/(r-t),g=m*m,p=g*m,_=-u*p+2*u*g-u*m,v=(1+u)*p+(-1.5-2*u)*g+(-.5+u)*m+1,E=(-1-h)*p+(1.5+h)*g+.5*m,S=h*p-h*g;for(let T=0;T!==o;++T)s[T]=_*a[f+T]+v*a[c+T]+E*a[l+T]+S*a[d+T];return s}},C_=class extends pl{constructor(e,t,i,r){super(e,t,i,r)}interpolate_(e,t,i,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,f=(i-t)/(r-t),d=1-f;for(let u=0;u!==o;++u)s[u]=a[c+u]*d+a[l+u]*f;return s}},gT=class extends pl{constructor(e,t,i,r){super(e,t,i,r)}interpolate_(e){return this.copySampleValue_(e-1)}},_T=class extends pl{interpolate_(e,t,i,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,f=this.settings||this.DefaultSettings_,d=f.inTangents,u=f.outTangents;if(!d||!u){let g=(i-t)/(r-t),p=1-g;for(let _=0;_!==o;++_)s[_]=a[c+_]*p+a[l+_]*g;return s}let h=o*2,m=e-1;for(let g=0;g!==o;++g){let p=a[c+g],_=a[l+g],v=m*h+g*2,E=u[v],S=u[v+1],T=e*h+g*2,A=d[T],R=d[T+1],M=(i-t)/(r-t),I,C,L,w,G;for(let O=0;O<8;O++){I=M*M,C=I*M,L=1-M,w=L*L,G=w*L;let B=G*t+3*w*M*E+3*L*I*A+C*r-i;if(Math.abs(B)<1e-10)break;let V=3*w*(E-t)+6*L*M*(A-E)+3*I*(r-A);if(Math.abs(V)<1e-10)break;M=M-B/V,M=Math.max(0,Math.min(1,M))}s[g]=G*p+3*w*M*S+3*L*I*R+C*_}return s}},Ws=class{constructor(e,t,i,r){if(e===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(t===void 0||t.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=HS(t,this.TimeBufferType),this.values=HS(i,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,i;if(t.toJSON!==this.toJSON)i=t.toJSON(e);else{i={name:e.name,times:HS(e.times,Array),values:HS(e.values,Array)};let r=e.getInterpolation();r!==e.DefaultInterpolation&&(i.interpolation=r)}return i.type=e.ValueTypeName,i}InterpolantFactoryMethodDiscrete(e){return new gT(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new C_(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new pT(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new _T(this.times,this.values,this.getValueSize(),e);return this.settings&&(t.settings=this.settings),t}setInterpolation(e){let t;switch(e){case lu:t=this.InterpolantFactoryMethodDiscrete;break;case cu:t=this.InterpolantFactoryMethodLinear;break;case jS:t=this.InterpolantFactoryMethodSmooth;break;case vI:t=this.InterpolantFactoryMethodBezier;break}if(t===void 0){let i="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw new Error(i);return Nt("KeyframeTrack:",i),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return lu;case this.InterpolantFactoryMethodLinear:return cu;case this.InterpolantFactoryMethodSmooth:return jS;case this.InterpolantFactoryMethodBezier:return vI}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let i=0,r=t.length;i!==r;++i)t[i]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let i=0,r=t.length;i!==r;++i)t[i]*=e}return this}trim(e,t){let i=this.times,r=i.length,s=0,a=r-1;for(;s!==r&&i[s]<e;)++s;for(;a!==-1&&i[a]>t;)--a;if(++a,s!==0||a!==r){s>=a&&(a=Math.max(a,1),s=a-1);let o=this.getValueSize();this.times=i.slice(s,a),this.values=this.values.slice(s*o,a*o)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(Ht("KeyframeTrack: Invalid value size in track.",this),e=!1);let i=this.times,r=this.values,s=i.length;s===0&&(Ht("KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==s;o++){let l=i[o];if(typeof l=="number"&&isNaN(l)){Ht("KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(a!==null&&a>l){Ht("KeyframeTrack: Out of order keys.",this,o,l,a),e=!1;break}a=l}if(r!==void 0&&gie(r))for(let o=0,l=r.length;o!==l;++o){let c=r[o];if(isNaN(c)){Ht("KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),r=this.getInterpolation()===jS,s=e.length-1,a=1;for(let o=1;o<s;++o){let l=!1,c=e[o],f=e[o+1];if(c!==f&&(o!==1||c!==e[0]))if(r)l=!0;else{let d=o*i,u=d-i,h=d+i;for(let m=0;m!==i;++m){let g=t[d+m];if(g!==t[u+m]||g!==t[h+m]){l=!0;break}}}if(l){if(o!==a){e[a]=e[o];let d=o*i,u=a*i;for(let h=0;h!==i;++h)t[u+h]=t[d+h]}++a}}if(s>0){e[a]=e[s];for(let o=s*i,l=a*i,c=0;c!==i;++c)t[l+c]=t[o+c];++a}return a!==e.length?(this.times=e.slice(0,a),this.values=t.slice(0,a*i)):(this.times=e,this.values=t),this}clone(){let e=this.times.slice(),t=this.values.slice(),i=this.constructor,r=new i(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};Ws.prototype.ValueTypeName="";Ws.prototype.TimeBufferType=Float32Array;Ws.prototype.ValueBufferType=Float32Array;Ws.prototype.DefaultInterpolation=cu;pc=class extends Ws{constructor(e,t,i){super(e,t,i)}};pc.prototype.ValueTypeName="bool";pc.prototype.ValueBufferType=Array;pc.prototype.DefaultInterpolation=lu;pc.prototype.InterpolantFactoryMethodLinear=void 0;pc.prototype.InterpolantFactoryMethodSmooth=void 0;P_=class extends Ws{constructor(e,t,i,r){super(e,t,i,r)}};P_.prototype.ValueTypeName="color";gl=class extends Ws{constructor(e,t,i,r){super(e,t,i,r)}};gl.prototype.ValueTypeName="number";vT=class extends pl{constructor(e,t,i,r){super(e,t,i,r)}interpolate_(e,t,i,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=(i-t)/(r-t),c=e*o;for(let f=c+o;c!==f;c+=4)un.slerpFlat(s,0,a,c-o,a,c,l);return s}},_l=class extends Ws{constructor(e,t,i,r){super(e,t,i,r)}InterpolantFactoryMethodLinear(e){return new vT(this.times,this.values,this.getValueSize(),e)}};_l.prototype.ValueTypeName="quaternion";_l.prototype.InterpolantFactoryMethodSmooth=void 0;gc=class extends Ws{constructor(e,t,i){super(e,t,i)}};gc.prototype.ValueTypeName="string";gc.prototype.ValueBufferType=Array;gc.prototype.DefaultInterpolation=lu;gc.prototype.InterpolantFactoryMethodLinear=void 0;gc.prototype.InterpolantFactoryMethodSmooth=void 0;vl=class extends Ws{constructor(e,t,i,r){super(e,t,i,r)}};vl.prototype.ValueTypeName="vector";_u=class{constructor(e="",t=-1,i=[],r=uA){this.name=e,this.tracks=i,this.duration=t,this.blendMode=r,this.uuid=Ro(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],i=e.tracks,r=1/(e.fps||1);for(let a=0,o=i.length;a!==o;++a)t.push(sre(i[a]).scale(r));let s=new this(e.name,e.duration,t,e.blendMode);return s.uuid=e.uuid,s.userData=JSON.parse(e.userData||"{}"),s}static toJSON(e){let t=[],i=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let s=0,a=i.length;s!==a;++s)t.push(Ws.toJSON(i[s]));return r}static CreateFromMorphTargetSequence(e,t,i,r){let s=t.length,a=[];for(let o=0;o<s;o++){let l=[],c=[];l.push((o+s-1)%s,o,(o+1)%s),c.push(0,1,0);let f=rre(l);l=XB(l,1,f),c=XB(c,1,f),!r&&l[0]===0&&(l.push(s),c.push(c[0])),a.push(new gl(".morphTargetInfluences["+t[o].name+"]",l,c).scale(1/i))}return new this(e,-1,a)}static findByName(e,t){let i=e;if(!Array.isArray(e)){let r=e;i=r.geometry&&r.geometry.animations||r.animations}for(let r=0;r<i.length;r++)if(i[r].name===t)return i[r];return null}static CreateClipsFromMorphTargetSequences(e,t,i){let r={},s=/^([\w-]*?)([\d]+)$/;for(let o=0,l=e.length;o<l;o++){let c=e[o],f=c.name.match(s);if(f&&f.length>1){let d=f[1],u=r[d];u||(r[d]=u=[]),u.push(c)}}let a=[];for(let o in r)a.push(this.CreateFromMorphTargetSequence(o,r[o],t,i));return a}static parseAnimation(e,t){if(Nt("AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return Ht("AnimationClip: No animation in JSONLoader data."),null;let i=function(d,u,h,m,g){if(h.length!==0){let p=[],_=[];k2(h,p,_,m),p.length!==0&&g.push(new d(u,p,_))}},r=[],s=e.name||"default",a=e.fps||30,o=e.blendMode,l=e.length||-1,c=e.hierarchy||[];for(let d=0;d<c.length;d++){let u=c[d].keys;if(!(!u||u.length===0))if(u[0].morphTargets){let h={},m;for(m=0;m<u.length;m++)if(u[m].morphTargets)for(let g=0;g<u[m].morphTargets.length;g++)h[u[m].morphTargets[g]]=-1;for(let g in h){let p=[],_=[];for(let v=0;v!==u[m].morphTargets.length;++v){let E=u[m];p.push(E.time),_.push(E.morphTarget===g?1:0)}r.push(new gl(".morphTargetInfluence["+g+"]",p,_))}l=h.length*a}else{let h=".bones["+t[d].name+"]";i(vl,h+".position",u,"pos",r),i(_l,h+".quaternion",u,"rot",r),i(vl,h+".scale",u,"scl",r)}}return r.length===0?null:new this(s,l,r,o)}resetDuration(){let e=this.tracks,t=0;for(let i=0,r=e.length;i!==r;++i){let s=this.tracks[i];t=Math.max(t,s.times[s.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e=e&&this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){let e=[];for(let i=0;i<this.tracks.length;i++)e.push(this.tracks[i].clone());let t=new this.constructor(this.name,this.duration,e,this.blendMode);return t.userData=JSON.parse(JSON.stringify(this.userData)),t}toJSON(){return this.constructor.toJSON(this)}};dl={enabled:!1,files:{},add:function(n,e){this.enabled!==!1&&(YB(n)||(this.files[n]=e))},get:function(n){if(this.enabled!==!1&&!YB(n))return this.files[n]},remove:function(n){delete this.files[n]},clear:function(){this.files={}}};pm=class{constructor(e,t,i){let r=this,s=!1,a=0,o=0,l,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i,this._abortController=null,this.itemStart=function(f){o++,s===!1&&r.onStart!==void 0&&r.onStart(f,a,o),s=!0},this.itemEnd=function(f){a++,r.onProgress!==void 0&&r.onProgress(f,a,o),a===o&&(s=!1,r.onLoad!==void 0&&r.onLoad())},this.itemError=function(f){r.onError!==void 0&&r.onError(f)},this.resolveURL=function(f){return l?l(f):f},this.setURLModifier=function(f){return l=f,this},this.addHandler=function(f,d){return c.push(f,d),this},this.removeHandler=function(f){let d=c.indexOf(f);return d!==-1&&c.splice(d,2),this},this.getHandler=function(f){for(let d=0,u=c.length;d<u;d+=2){let h=c[d],m=c[d+1];if(h.global&&(h.lastIndex=0),h.test(f))return m}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||(this._abortController=new AbortController),this._abortController}},pA=new pm,bn=class{constructor(e){this.manager=e!==void 0?e:pA,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={},typeof __THREE_DEVTOOLS__!="undefined"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}load(){}loadAsync(e,t){let i=this;return new Promise(function(r,s){i.load(e,r,t,s)})}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}abort(){return this}};bn.DEFAULT_MATERIAL_NAME="__DEFAULT";dc={},TI=class extends Error{constructor(e,t){super(e),this.response=t}},Hs=class extends bn{constructor(e){super(e),this.mimeType="",this.responseType="",this._abortController=new AbortController}load(e,t,i,r){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=dl.get(`file:${e}`);if(s!==void 0){this.manager.itemStart(e),setTimeout(()=>{t&&t(s),this.manager.itemEnd(e)},0);return}if(dc[e]!==void 0){dc[e].push({onLoad:t,onProgress:i,onError:r});return}dc[e]=[],dc[e].push({onLoad:t,onProgress:i,onError:r});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,l=this.responseType;fetch(a).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&Nt("FileLoader: HTTP Status 0 received."),typeof ReadableStream=="undefined"||c.body===void 0||c.body.getReader===void 0)return c;let f=dc[e],d=c.body.getReader(),u=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),h=u?parseInt(u):0,m=h!==0,g=0,p=new ReadableStream({start(_){v();function v(){d.read().then(({done:E,value:S})=>{if(E)_.close();else{g+=S.byteLength;let T=new ProgressEvent("progress",{lengthComputable:m,loaded:g,total:h});for(let A=0,R=f.length;A<R;A++){let M=f[A];M.onProgress&&M.onProgress(T)}_.enqueue(S),v()}},E=>{_.error(E)})}}});return new Response(p)}else throw new TI(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(f=>new DOMParser().parseFromString(f,o));case"json":return c.json();default:if(o==="")return c.text();{let d=/charset="?([^;"\s]*)"?/i.exec(o),u=d&&d[1]?d[1].toLowerCase():void 0,h=new TextDecoder(u);return c.arrayBuffer().then(m=>h.decode(m))}}}).then(c=>{dl.add(`file:${e}`,c);let f=dc[e];delete dc[e];for(let d=0,u=f.length;d<u;d++){let h=f[d];h.onLoad&&h.onLoad(c)}}).catch(c=>{let f=dc[e];if(f===void 0)throw this.manager.itemError(e),c;delete dc[e];for(let d=0,u=f.length;d<u;d++){let h=f[d];h.onError&&h.onError(c)}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}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},Jh=new WeakMap,ET=class extends bn{constructor(e){super(e)}load(e,t,i,r){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,a=dl.get(`image:${e}`);if(a!==void 0){if(a.complete===!0)s.manager.itemStart(e),setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0);else{let d=Jh.get(a);d===void 0&&(d=[],Jh.set(a,d)),d.push({onLoad:t,onError:r})}return a}let o=sm("img");function l(){f(),t&&t(this);let d=Jh.get(this)||[];for(let u=0;u<d.length;u++){let h=d[u];h.onLoad&&h.onLoad(this)}Jh.delete(this),s.manager.itemEnd(e)}function c(d){f(),r&&r(d),dl.remove(`image:${e}`);let u=Jh.get(this)||[];for(let h=0;h<u.length;h++){let m=u[h];m.onError&&m.onError(d)}Jh.delete(this),s.manager.itemError(e),s.manager.itemEnd(e)}function f(){o.removeEventListener("load",l,!1),o.removeEventListener("error",c,!1)}return o.addEventListener("load",l,!1),o.addEventListener("error",c,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),dl.add(`image:${e}`,o),s.manager.itemStart(e),o.src=e,o}},vu=class extends bn{constructor(e){super(e)}load(e,t,i,r){let s=new Lr,a=new ET(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(o){s.image=o,s.needsUpdate=!0,t!==void 0&&t(s)},i,r),s}},Cf=class extends sr{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new mt(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}},gm=class extends Cf{constructor(e,t,i){super(e,i),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(sr.DEFAULT_UP),this.updateMatrix(),this.groundColor=new mt(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}toJSON(e){let t=super.toJSON(e);return t.object.groundColor=this.groundColor.getHex(),t}},pI=new pi,KB=new ie,jB=new ie,L_=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Ct(512,512),this.mapType=Ks,this.map=null,this.mapPass=null,this.matrix=new pi,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new hm,this._frameExtents=new Ct(1,1),this._viewportCount=1,this._viewports=[new dr(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,i=this.matrix;KB.setFromMatrixPosition(e.matrixWorld),t.position.copy(KB),jB.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(jB),t.updateMatrixWorld(),pI.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(pI,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===nm||t.reversedDepth?i.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):i.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),i.multiply(pI)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},XS=new ie,YS=new un,fl=new ie,D_=class extends sr{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new pi,this.projectionMatrix=new pi,this.projectionMatrixInverse=new pi,this.coordinateSystem=xo,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(XS,YS,fl),fl.x===1&&fl.y===1&&fl.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(XS,YS,fl.set(1,1,1)).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorld.decompose(XS,YS,fl),fl.x===1&&fl.y===1&&fl.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(XS,YS,fl.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},Rf=new ie,ZB=new Ct,qB=new Ct,Sr=class extends D_{constructor(e=50,t=1,i=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=fu*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(u_*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return fu*2*Math.atan(Math.tan(u_*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,i){Rf.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Rf.x,Rf.y).multiplyScalar(-e/Rf.z),Rf.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(Rf.x,Rf.y).multiplyScalar(-e/Rf.z)}getViewSize(e,t){return this.getViewBounds(e,ZB,qB),t.subVectors(qB,ZB)}setViewOffset(e,t,i,r,s,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=r,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(u_*.5*this.fov)/this.zoom,i=2*t,r=this.aspect*i,s=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let l=a.fullWidth,c=a.fullHeight;s+=a.offsetX*r/l,t-=a.offsetY*i/c,r*=a.width/l,i*=a.height/c}let o=this.filmOffset;o!==0&&(s+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+r,t,t-i,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},AI=class extends L_{constructor(){super(new Sr(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){let t=this.camera,i=fu*2*e.angle*this.focus,r=this.mapSize.width/this.mapSize.height*this.aspect,s=e.distance||t.far;(i!==t.fov||r!==t.aspect||s!==t.far)&&(t.fov=i,t.aspect=r,t.far=s,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}},_c=class extends Cf{constructor(e,t,i=0,r=Math.PI/3,s=0,a=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(sr.DEFAULT_UP),this.updateMatrix(),this.target=new sr,this.distance=i,this.angle=r,this.penumbra=s,this.decay=a,this.map=null,this.shadow=new AI}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}},xI=class extends L_{constructor(){super(new Sr(90,1,.5,500)),this.isPointLightShadow=!0}},Mo=class extends Cf{constructor(e,t,i=0,r=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=i,this.decay=r,this.shadow=new xI}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}},vs=class extends D_{constructor(e=-1,t=1,i=1,r=-1,s=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=i,this.bottom=r,this.near=s,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,i,r,s,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=r,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,r=(this.top+this.bottom)/2,s=i-e,a=i+e,o=r+t,l=r-t;if(this.view!==null&&this.view.enabled){let c=(this.right-this.left)/this.view.fullWidth/this.zoom,f=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=c*this.view.offsetX,a=s+c*this.view.width,o-=f*this.view.offsetY,l=o-f*this.view.height}this.projectionMatrix.makeOrthographic(s,a,o,l,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},RI=class extends L_{constructor(){super(new vs(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},El=class extends Cf{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(sr.DEFAULT_UP),this.updateMatrix(),this.target=new sr,this.shadow=new RI}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}},_m=class extends Cf{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}},yo=class{static extractUrlBase(e){let t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}},gI=new WeakMap,O_=class extends bn{constructor(e){super(e),this.isImageBitmapLoader=!0,typeof createImageBitmap=="undefined"&&Nt("ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch=="undefined"&&Nt("ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,i,r){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,a=dl.get(`image-bitmap:${e}`);if(a!==void 0){if(s.manager.itemStart(e),a.then){a.then(c=>{gI.has(a)===!0?(r&&r(gI.get(a)),s.manager.itemError(e),s.manager.itemEnd(e)):(t&&t(c),s.manager.itemEnd(e))});return}setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0);return}let o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader,o.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(c){dl.add(`image-bitmap:${e}`,c),t&&t(c),s.manager.itemEnd(e)}).catch(function(c){r&&r(c),gI.set(l,c),dl.remove(`image-bitmap:${e}`),s.manager.itemError(e),s.manager.itemEnd(e)});dl.add(`image-bitmap:${e}`,l),s.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},em=-90,tm=1,ST=class extends sr{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new Sr(em,tm,e,t);r.layers=this.layers,this.add(r);let s=new Sr(em,tm,e,t);s.layers=this.layers,this.add(s);let a=new Sr(em,tm,e,t);a.layers=this.layers,this.add(a);let o=new Sr(em,tm,e,t);o.layers=this.layers,this.add(o);let l=new Sr(em,tm,e,t);l.layers=this.layers,this.add(l);let c=new Sr(em,tm,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[i,r,s,a,o,l]=t;for(let c of t)this.remove(c);if(e===xo)i.up.set(0,1,0),i.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===nm)i.up.set(0,-1,0),i.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(let c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:i,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[s,a,o,l,c,f]=this.children,d=e.getRenderTarget(),u=e.getActiveCubeFace(),h=e.getActiveMipmapLevel(),m=e.xr.enabled;e.xr.enabled=!1;let g=i.texture.generateMipmaps;i.texture.generateMipmaps=!1;let p=!1;e.isWebGLRenderer===!0?p=e.state.buffers.depth.getReversed():p=e.reversedDepthBuffer,e.setRenderTarget(i,0,r),p&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(i,1,r),p&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(i,2,r),p&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(i,3,r),p&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(i,4,r),p&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),i.texture.generateMipmaps=g,e.setRenderTarget(i,5,r),p&&e.autoClear===!1&&e.clearDepth(),e.render(t,f),e.setRenderTarget(d,u,h),e.xr.enabled=m,i.texture.needsPMREMUpdate=!0}},TT=class extends Sr{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},AT=class{constructor(e,t,i){this.binding=e,this.valueSize=i;let r,s,a;switch(t){case"quaternion":r=this._slerp,s=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(i*6),this._workIndex=5;break;case"string":case"bool":r=this._select,s=this._select,a=this._setAdditiveIdentityOther,this.buffer=new Array(i*5);break;default:r=this._lerp,s=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(i*5)}this._mixBufferRegion=r,this._mixBufferRegionAdditive=s,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let i=this.buffer,r=this.valueSize,s=e*r+r,a=this.cumulativeWeight;if(a===0){for(let o=0;o!==r;++o)i[s+o]=i[o];a=t}else{a+=t;let o=t/a;this._mixBufferRegion(i,s,0,o,r)}this.cumulativeWeight=a}accumulateAdditive(e){let t=this.buffer,i=this.valueSize,r=i*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,r,0,e,i),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,i=this.buffer,r=e*t+t,s=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,s<1){let l=t*this._origIndex;this._mixBufferRegion(i,r,l,1-s,t)}a>0&&this._mixBufferRegionAdditive(i,r,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(i[l]!==i[l+t]){o.setValue(i,r);break}}saveOriginalState(){let e=this.binding,t=this.buffer,i=this.valueSize,r=i*this._origIndex;e.getValue(t,r);for(let s=i,a=r;s!==a;++s)t[s]=t[r+s%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i<t;i++)this.buffer[i]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){let e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let i=0;i<this.valueSize;i++)this.buffer[t+i]=this.buffer[e+i]}_select(e,t,i,r,s){if(r>=.5)for(let a=0;a!==s;++a)e[t+a]=e[i+a]}_slerp(e,t,i,r){un.slerpFlat(e,t,e,t,e,i,r)}_slerpAdditive(e,t,i,r,s){let a=this._workIndex*s;un.multiplyQuaternionsFlat(e,a,e,t,e,i),un.slerpFlat(e,t,e,t,e,a,r)}_lerp(e,t,i,r,s){let a=1-r;for(let o=0;o!==s;++o){let l=t+o;e[l]=e[l]*a+e[i+o]*r}}_lerpAdditive(e,t,i,r,s){for(let a=0;a!==s;++a){let o=t+a;e[o]=e[o]+e[i+a]*r}}},qI="\\[\\]\\.:\\/",are=new RegExp("["+qI+"]","g"),QI="[^"+qI+"]",ore="[^"+qI.replace("\\.","")+"]",lre=/((?:WC+[\/:])*)/.source.replace("WC",QI),cre=/(WCOD+)?/.source.replace("WCOD",ore),fre=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",QI),dre=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",QI),ure=new RegExp("^"+lre+cre+fre+dre+"$"),hre=["material","materials","bones","map"],bI=class{constructor(e,t,i){let r=i||fr.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let i=this._targetGroup.nCachedObjects_,r=this._bindings[i];r!==void 0&&r.getValue(e,t)}setValue(e,t){let i=this._bindings;for(let r=this._targetGroup.nCachedObjects_,s=i.length;r!==s;++r)i[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}},fr=class n{constructor(e,t,i){this.path=t,this.parsedPath=i||n.parseTrackName(t),this.node=n.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new n.Composite(e,t,i):new n(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(are,"")}static parseTrackName(e){let t=ure.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);let i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=i.nodeName&&i.nodeName.lastIndexOf(".");if(r!==void 0&&r!==-1){let s=i.nodeName.substring(r+1);hre.indexOf(s)!==-1&&(i.nodeName=i.nodeName.substring(0,r),i.objectName=s)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){let i=function(s){for(let a=0;a<s.length;a++){let o=s[a];if(o.name===t||o.uuid===t)return o;let l=i(o.children);if(l)return l}return null},r=i(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let i=this.resolvedProperty;for(let r=0,s=i.length;r!==s;++r)e[t++]=i[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let i=this.resolvedProperty;for(let r=0,s=i.length;r!==s;++r)i[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let i=this.resolvedProperty;for(let r=0,s=i.length;r!==s;++r)i[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let i=this.resolvedProperty;for(let r=0,s=i.length;r!==s;++r)i[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let e=this.node,t=this.parsedPath,i=t.objectName,r=t.propertyName,s=t.propertyIndex;if(e||(e=n.findNode(this.rootNode,t.nodeName),this.node=e),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e){Nt("PropertyBinding: No target node found for track: "+this.path+".");return}if(i){let c=t.objectIndex;switch(i){case"materials":if(!e.material){Ht("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.materials){Ht("PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}e=e.material.materials;break;case"bones":if(!e.skeleton){Ht("PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}e=e.skeleton.bones;for(let f=0;f<e.length;f++)if(e[f].name===c){c=f;break}break;case"map":if("map"in e){e=e.map;break}if(!e.material){Ht("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.map){Ht("PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}e=e.material.map;break;default:if(e[i]===void 0){Ht("PropertyBinding: Can not bind to objectName of node undefined.",this);return}e=e[i]}if(c!==void 0){if(e[c]===void 0){Ht("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);return}e=e[c]}}let a=e[r];if(a===void 0){let c=t.nodeName;Ht("PropertyBinding: Trying to update property for track: "+c+"."+r+" but it wasn't found.",e);return}let o=this.Versioning.None;this.targetObject=e,e.isMaterial===!0?o=this.Versioning.NeedsUpdate:e.isObject3D===!0&&(o=this.Versioning.MatrixWorldNeedsUpdate);let l=this.BindingType.Direct;if(s!==void 0){if(r==="morphTargetInfluences"){if(!e.geometry){Ht("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!e.geometry.morphAttributes){Ht("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}e.morphTargetDictionary[s]!==void 0&&(s=e.morphTargetDictionary[s])}l=this.BindingType.ArrayElement,this.resolvedProperty=a,this.propertyIndex=s}else a.fromArray!==void 0&&a.toArray!==void 0?(l=this.BindingType.HasFromToArray,this.resolvedProperty=a):Array.isArray(a)?(l=this.BindingType.EntireArray,this.resolvedProperty=a):this.propertyName=r;this.getValue=this.GetterByBindingType[l],this.setValue=this.SetterByBindingTypeAndVersioning[l][o]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};fr.Composite=bI;fr.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};fr.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};fr.prototype.GetterByBindingType=[fr.prototype._getValue_direct,fr.prototype._getValue_array,fr.prototype._getValue_arrayElement,fr.prototype._getValue_toArray];fr.prototype.SetterByBindingTypeAndVersioning=[[fr.prototype._setValue_direct,fr.prototype._setValue_direct_setNeedsUpdate,fr.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[fr.prototype._setValue_array,fr.prototype._setValue_array_setNeedsUpdate,fr.prototype._setValue_array_setMatrixWorldNeedsUpdate],[fr.prototype._setValue_arrayElement,fr.prototype._setValue_arrayElement_setNeedsUpdate,fr.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[fr.prototype._setValue_fromArray,fr.prototype._setValue_fromArray_setNeedsUpdate,fr.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];xT=class{constructor(e,t,i=null,r=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=i,this.blendMode=r;let s=t.tracks,a=s.length,o=new Array(a),l={endingStart:nu,endingEnd:nu};for(let c=0;c!==a;++c){let f=s[c].createInterpolant(null);o[c]=f,f.settings&&Object.assign(l,f.settings),f.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=x2,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,i=!1){if(e.fadeOut(t),this.fadeIn(t),i===!0){let r=this._clip.duration,s=e._clip.duration,a=s/r,o=r/s;e.warp(1,a,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,i=!1){return e.crossFadeFrom(this,t,i)}stopFading(){let e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,i){let r=this._mixer,s=r.time,a=this.timeScale,o=this._timeScaleInterpolant;o===null&&(o=r._lendControlInterpolant(),this._timeScaleInterpolant=o);let l=o.parameterPositions,c=o.sampleValues;return l[0]=s,l[1]=s+i,c[0]=e/a,c[1]=t/a,this}stopWarping(){let e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,i,r){if(!this.enabled){this._updateWeight(e);return}let s=this._startTime;if(s!==null){let l=(e-s)*i;l<0||i===0?t=0:(this._startTime=null,t=i*l)}t*=this._updateTimeScale(e);let a=this._updateTime(t),o=this._updateWeight(e);if(o>0){let l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case b2:for(let f=0,d=l.length;f!==d;++f)l[f].evaluate(a),c[f].accumulateAdditive(o);break;case uA:default:for(let f=0,d=l.length;f!==d;++f)l[f].evaluate(a),c[f].accumulate(r,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let i=this._weightInterpolant;if(i!==null){let r=i.evaluate(e)[0];t*=r,e>i.parameterPositions[1]&&(this.stopFading(),r===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let i=this._timeScaleInterpolant;if(i!==null){let r=i.evaluate(e)[0];t*=r,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,i=this.loop,r=this.time+e,s=this._loopCount,a=i===R2;if(e===0)return s===-1?r:a&&(s&1)===1?t-r:r;if(i===A2){s===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(r>=t)r=t;else if(r<0)r=0;else{this.time=r;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(s===-1&&(e>=0?(s=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),r>=t||r<0){let o=Math.floor(r/t);r-=t*o,s+=Math.abs(o);let l=this.repetitions-s;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){let c=e<0;this._setEndings(c,!c,a)}else this._setEndings(!1,!1,a);this._loopCount=s,this.time=r,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this._loopCount=s,this.time=r;if(a&&(s&1)===1)return t-r}return r}_setEndings(e,t,i){let r=this._interpolantSettings;i?(r.endingStart=su,r.endingEnd=su):(e?r.endingStart=this.zeroSlopeAtStart?su:nu:r.endingStart=m_,t?r.endingEnd=this.zeroSlopeAtEnd?su:nu:r.endingEnd=m_)}_scheduleFading(e,t,i){let r=this._mixer,s=r.time,a=this._weightInterpolant;a===null&&(a=r._lendControlInterpolant(),this._weightInterpolant=a);let o=a.parameterPositions,l=a.sampleValues;return o[0]=s,l[0]=t,o[1]=s+e,l[1]=i,this}},mre=new Float32Array(1),N_=class extends Ya{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__!="undefined"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}_bindAction(e,t){let i=e._localRoot||this._root,r=e._clip.tracks,s=r.length,a=e._propertyBindings,o=e._interpolants,l=i.uuid,c=this._bindingsByRootAndName,f=c[l];f===void 0&&(f={},c[l]=f);for(let d=0;d!==s;++d){let u=r[d],h=u.name,m=f[h];if(m!==void 0)++m.referenceCount,a[d]=m;else{if(m=a[d],m!==void 0){m._cacheIndex===null&&(++m.referenceCount,this._addInactiveBinding(m,l,h));continue}let g=t&&t._propertyBindings[d].binding.parsedPath;m=new AT(fr.create(i,h,g),u.ValueTypeName,u.getValueSize()),++m.referenceCount,this._addInactiveBinding(m,l,h),a[d]=m}o[d].resultBuffer=m.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let i=(e._localRoot||this._root).uuid,r=e._clip.uuid,s=this._actionsByClip[r];this._bindAction(e,s&&s.knownActions[0]),this._addInactiveAction(e,r,i)}let t=e._propertyBindings;for(let i=0,r=t.length;i!==r;++i){let s=t[i];s.useCount++===0&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let i=0,r=t.length;i!==r;++i){let s=t[i];--s.useCount===0&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,i){let r=this._actions,s=this._actionsByClip,a=s[t];if(a===void 0)a={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,s[t]=a;else{let o=a.knownActions;e._byClipCacheIndex=o.length,o.push(e)}e._cacheIndex=r.length,r.push(e),a.actionByRoot[i]=e}_removeInactiveAction(e){let t=this._actions,i=t[t.length-1],r=e._cacheIndex;i._cacheIndex=r,t[r]=i,t.pop(),e._cacheIndex=null;let s=e._clip.uuid,a=this._actionsByClip,o=a[s],l=o.knownActions,c=l[l.length-1],f=e._byClipCacheIndex;c._byClipCacheIndex=f,l[f]=c,l.pop(),e._byClipCacheIndex=null;let d=o.actionByRoot,u=(e._localRoot||this._root).uuid;delete d[u],l.length===0&&delete a[s],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){let t=e._propertyBindings;for(let i=0,r=t.length;i!==r;++i){let s=t[i];--s.referenceCount===0&&this._removeInactiveBinding(s)}}_lendAction(e){let t=this._actions,i=e._cacheIndex,r=this._nActiveActions++,s=t[r];e._cacheIndex=r,t[r]=e,s._cacheIndex=i,t[i]=s}_takeBackAction(e){let t=this._actions,i=e._cacheIndex,r=--this._nActiveActions,s=t[r];e._cacheIndex=r,t[r]=e,s._cacheIndex=i,t[i]=s}_addInactiveBinding(e,t,i){let r=this._bindingsByRootAndName,s=this._bindings,a=r[t];a===void 0&&(a={},r[t]=a),a[i]=e,e._cacheIndex=s.length,s.push(e)}_removeInactiveBinding(e){let t=this._bindings,i=e.binding,r=i.rootNode.uuid,s=i.path,a=this._bindingsByRootAndName,o=a[r],l=t[t.length-1],c=e._cacheIndex;l._cacheIndex=c,t[c]=l,t.pop(),delete o[s],Object.keys(o).length===0&&delete a[r]}_lendBinding(e){let t=this._bindings,i=e._cacheIndex,r=this._nActiveBindings++,s=t[r];e._cacheIndex=r,t[r]=e,s._cacheIndex=i,t[i]=s}_takeBackBinding(e){let t=this._bindings,i=e._cacheIndex,r=--this._nActiveBindings,s=t[r];e._cacheIndex=r,t[r]=e,s._cacheIndex=i,t[i]=s}_lendControlInterpolant(){let e=this._controlInterpolants,t=this._nActiveControlInterpolants++,i=e[t];return i===void 0&&(i=new C_(new Float32Array(2),new Float32Array(2),1,mre),i.__cacheIndex=t,e[t]=i),i}_takeBackControlInterpolant(e){let t=this._controlInterpolants,i=e.__cacheIndex,r=--this._nActiveControlInterpolants,s=t[r];e.__cacheIndex=r,t[r]=e,s.__cacheIndex=i,t[i]=s}clipAction(e,t,i){let r=t||this._root,s=r.uuid,a=typeof e=="string"?_u.findByName(r,e):e,o=a!==null?a.uuid:e,l=this._actionsByClip[o],c=null;if(i===void 0&&(a!==null?i=a.blendMode:i=uA),l!==void 0){let d=l.actionByRoot[s];if(d!==void 0&&d.blendMode===i)return d;c=l.knownActions[0],a===null&&(a=c._clip)}if(a===null)return null;let f=new xT(this,a,t,i);return this._bindAction(f,c),this._addInactiveAction(f,o,s),f}existingAction(e,t){let i=t||this._root,r=i.uuid,s=typeof e=="string"?_u.findByName(i,e):e,a=s?s.uuid:e,o=this._actionsByClip[a];return o!==void 0&&o.actionByRoot[r]||null}stopAllAction(){let e=this._actions,t=this._nActiveActions;for(let i=t-1;i>=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;let t=this._actions,i=this._nActiveActions,r=this.time+=e,s=Math.sign(e),a=this._accuIndex^=1;for(let c=0;c!==i;++c)t[c]._update(r,e,s,a);let o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(a);return this}setTime(e){this.time=0;for(let t=0;t<this._actions.length;t++)this._actions[t].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){let t=this._actions,i=e.uuid,r=this._actionsByClip,s=r[i];if(s!==void 0){let a=s.knownActions;for(let o=0,l=a.length;o!==l;++o){let c=a[o];this._deactivateAction(c);let f=c._cacheIndex,d=t[t.length-1];c._cacheIndex=null,c._byClipCacheIndex=null,d._cacheIndex=f,t[f]=d,t.pop(),this._removeInactiveBindingsForAction(c)}delete r[i]}}uncacheRoot(e){let t=e.uuid,i=this._actionsByClip;for(let a in i){let o=i[a].actionByRoot,l=o[t];l!==void 0&&(this._deactivateAction(l),this._removeInactiveAction(l))}let r=this._bindingsByRootAndName,s=r[t];if(s!==void 0)for(let a in s){let o=s[a];o.restoreOriginalState(),this._removeInactiveBinding(o)}}uncacheAction(e,t){let i=this.existingAction(e,t);i!==null&&(this._deactivateAction(i),this._removeInactiveAction(i))}},QB=new pi,Pf=class{constructor(e,t,i=0,r=1/0){this.ray=new ml(e,t),this.near=i,this.far=r,this.camera=null,this.layers=new lm,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):Ht("Raycaster: Unsupported camera type: "+t.type)}setFromXRController(e){return QB.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(QB),this}intersectObject(e,t=!0,i=[]){return MI(e,this,i,t),i.sort($B),i}intersectObjects(e,t=!0,i=[]){for(let r=0,s=e.length;r<s;r++)MI(e[r],this,i,t);return i.sort($B),i}};vm=class{constructor(e=1,t=0,i=0){this.radius=e,this.phi=t,this.theta=i}set(e,t,i){return this.radius=e,this.phi=t,this.theta=i,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=Ai(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,i){return this.radius=Math.sqrt(e*e+t*t+i*i),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,i),this.phi=Math.acos(Ai(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}},rC=class rC{constructor(e,t,i,r){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,i,r)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let i=0;i<4;i++)this.elements[i]=e[i+t];return this}set(e,t,i,r){let s=this.elements;return s[0]=e,s[2]=t,s[1]=i,s[3]=r,this}};rC.prototype.isMatrix2=!0;yI=rC,w_=class extends _s{constructor(e=10,t=10,i=4473924,r=8947848){i=new mt(i),r=new mt(r);let s=t/2,a=e/t,o=e/2,l=[],c=[];for(let u=0,h=0,m=-o;u<=t;u++,m+=a){l.push(-o,0,m,o,0,m),l.push(m,0,-o,m,0,o);let g=u===s?i:r;g.toArray(c,h),h+=3,g.toArray(c,h),h+=3,g.toArray(c,h),h+=3,g.toArray(c,h),h+=3}let f=new Bi;f.setAttribute("position",new gi(l,3)),f.setAttribute("color",new gi(c,3));let d=new Ln({vertexColors:!0,toneMapped:!1});super(f,d),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}},KS=new Wr,Sl=class extends _s{constructor(e,t=16776960){let i=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),r=new Float32Array(24),s=new Bi;s.setIndex(new Tr(i,1)),s.setAttribute("position",new Tr(r,3)),super(s,new Ln({color:t,toneMapped:!1})),this.object=e,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(){if(this.object!==void 0&&KS.setFromObject(this.object),KS.isEmpty())return;let e=KS.min,t=KS.max,i=this.geometry.attributes.position,r=i.array;r[0]=t.x,r[1]=t.y,r[2]=t.z,r[3]=e.x,r[4]=t.y,r[5]=t.z,r[6]=e.x,r[7]=e.y,r[8]=t.z,r[9]=t.x,r[10]=e.y,r[11]=t.z,r[12]=t.x,r[13]=t.y,r[14]=e.z,r[15]=e.x,r[16]=t.y,r[17]=e.z,r[18]=e.x,r[19]=e.y,r[20]=e.z,r[21]=t.x,r[22]=e.y,r[23]=e.z,i.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(e){return this.object=e,this.update(),this}copy(e,t){return super.copy(e,t),this.object=e.object,this}dispose(){this.geometry.dispose(),this.material.dispose()}},Em=class extends _s{constructor(e=1){let t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],i=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],r=new Bi;r.setAttribute("position",new gi(t,3)),r.setAttribute("color",new gi(i,3));let s=new Ln({vertexColors:!0,toneMapped:!1});super(r,s),this.type="AxesHelper"}setColors(e,t,i){let r=new mt,s=this.geometry.attributes.color.array;return r.set(e),r.toArray(s,0),r.toArray(s,3),r.set(t),r.toArray(s,6),r.toArray(s,9),r.set(i),r.toArray(s,12),r.toArray(s,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}},F_=class extends Ya{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){Nt("Controls: connect() now requires an element.");return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}};typeof __THREE_DEVTOOLS__!="undefined"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"184"}}));typeof window!="undefined"&&(window.__THREE__?Nt("WARNING: Multiple instances of Three.js being imported."):window.__THREE__="184")});function fU(){let n=null,e=!1,t=null,i=null;function r(s,a){t(s,a),i=n.requestAnimationFrame(r)}return{start:function(){e!==!0&&t!==null&&n!==null&&(i=n.requestAnimationFrame(r),e=!0)},stop:function(){n!==null&&n.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(s){t=s},setContext:function(s){n=s}}}function _re(n){let e=new WeakMap;function t(o,l){let c=o.array,f=o.usage,d=c.byteLength,u=n.createBuffer();n.bindBuffer(l,u),n.bufferData(l,c,f),o.onUploadCallback();let h;if(c instanceof Float32Array)h=n.FLOAT;else if(typeof Float16Array!="undefined"&&c instanceof Float16Array)h=n.HALF_FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?h=n.HALF_FLOAT:h=n.UNSIGNED_SHORT;else if(c instanceof Int16Array)h=n.SHORT;else if(c instanceof Uint32Array)h=n.UNSIGNED_INT;else if(c instanceof Int32Array)h=n.INT;else if(c instanceof Int8Array)h=n.BYTE;else if(c instanceof Uint8Array)h=n.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)h=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:u,type:h,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:d}}function i(o,l,c){let f=l.array,d=l.updateRanges;if(n.bindBuffer(c,o),d.length===0)n.bufferSubData(c,0,f);else{d.sort((h,m)=>h.start-m.start);let u=0;for(let h=1;h<d.length;h++){let m=d[u],g=d[h];g.start<=m.start+m.count+1?m.count=Math.max(m.count,g.start+g.count-m.start):(++u,d[u]=g)}d.length=u+1;for(let h=0,m=d.length;h<m;h++){let g=d[h];n.bufferSubData(c,g.start*f.BYTES_PER_ELEMENT,f,g.start,g.count)}l.clearUpdateRanges()}l.onUploadCallback()}function r(o){return o.isInterleavedBufferAttribute&&(o=o.data),e.get(o)}function s(o){o.isInterleavedBufferAttribute&&(o=o.data);let l=e.get(o);l&&(n.deleteBuffer(l.buffer),e.delete(o))}function a(o,l){if(o.isInterleavedBufferAttribute&&(o=o.data),o.isGLBufferAttribute){let f=e.get(o);(!f||f.version<o.version)&&e.set(o,{buffer:o.buffer,type:o.type,bytesPerElement:o.elementSize,version:o.version});return}let c=e.get(o);if(c===void 0)e.set(o,t(o,l));else if(c.version<o.version){if(c.size!==o.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");i(c.buffer,o,l),c.version=o.version}}return{get:r,remove:s,update:a}}function Jse(n,e,t,i,r,s){let a=new mt(0),o=r===!0?0:1,l,c,f=null,d=0,u=null;function h(v){let E=v.isScene===!0?v.background:null;if(E&&E.isTexture){let S=v.backgroundBlurriness>0;E=e.get(E,S)}return E}function m(v){let E=!1,S=h(v);S===null?p(a,o):S&&S.isColor&&(p(S,1),E=!0);let T=n.xr.getEnvironmentBlendMode();T==="additive"?t.buffers.color.setClear(0,0,0,1,s):T==="alpha-blend"&&t.buffers.color.setClear(0,0,0,0,s),(n.autoClear||E)&&(t.buffers.depth.setTest(!0),t.buffers.depth.setMask(!0),t.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function g(v,E){let S=h(E);S&&(S.isCubeTexture||S.mapping===V_)?(c===void 0&&(c=new ci(new If(1,1,1),new Sa({name:"BackgroundCubeMaterial",uniforms:Tu(Rl.backgroundCube.uniforms),vertexShader:Rl.backgroundCube.vertexShader,fragmentShader:Rl.backgroundCube.fragmentShader,side:On,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(T,A,R){this.matrixWorld.copyPosition(R.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(c)),c.material.uniforms.envMap.value=S,c.material.uniforms.backgroundBlurriness.value=E.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4($se.makeRotationFromEuler(E.backgroundRotation)).transpose(),S.isCubeTexture&&S.isRenderTargetTexture===!1&&c.material.uniforms.backgroundRotation.value.premultiply(dU),c.material.toneMapped=mi.getTransfer(S.colorSpace)!==nr,(f!==S||d!==S.version||u!==n.toneMapping)&&(c.material.needsUpdate=!0,f=S,d=S.version,u=n.toneMapping),c.layers.enableAll(),v.unshift(c,c.geometry,c.material,0,0,null)):S&&S.isTexture&&(l===void 0&&(l=new ci(new pu(2,2),new Sa({name:"BackgroundMaterial",uniforms:Tu(Rl.background.uniforms),vertexShader:Rl.background.vertexShader,fragmentShader:Rl.background.fragmentShader,side:va,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=S,l.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,l.material.toneMapped=mi.getTransfer(S.colorSpace)!==nr,S.matrixAutoUpdate===!0&&S.updateMatrix(),l.material.uniforms.uvTransform.value.copy(S.matrix),(f!==S||d!==S.version||u!==n.toneMapping)&&(l.material.needsUpdate=!0,f=S,d=S.version,u=n.toneMapping),l.layers.enableAll(),v.unshift(l,l.geometry,l.material,0,0,null))}function p(v,E){v.getRGB(gA,ZI(n)),t.buffers.color.setClear(gA.r,gA.g,gA.b,E,s)}function _(){c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return a},setClearColor:function(v,E=1){a.set(v),o=E,p(a,o)},getClearAlpha:function(){return o},setClearAlpha:function(v){o=v,p(a,o)},render:m,addToRenderList:g,dispose:_}}function eae(n,e){let t=n.getParameter(n.MAX_VERTEX_ATTRIBS),i={},r=u(null),s=r,a=!1;function o(L,w,G,O,N){let B=!1,V=d(L,O,G,w);s!==V&&(s=V,c(s.object)),B=h(L,O,G,N),B&&m(L,O,G,N),N!==null&&e.update(N,n.ELEMENT_ARRAY_BUFFER),(B||a)&&(a=!1,S(L,w,G,O),N!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(N).buffer))}function l(){return n.createVertexArray()}function c(L){return n.bindVertexArray(L)}function f(L){return n.deleteVertexArray(L)}function d(L,w,G,O){let N=O.wireframe===!0,B=i[w.id];B===void 0&&(B={},i[w.id]=B);let V=L.isInstancedMesh===!0?L.id:0,q=B[V];q===void 0&&(q={},B[V]=q);let K=q[G.id];K===void 0&&(K={},q[G.id]=K);let J=K[N];return J===void 0&&(J=u(l()),K[N]=J),J}function u(L){let w=[],G=[],O=[];for(let N=0;N<t;N++)w[N]=0,G[N]=0,O[N]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:w,enabledAttributes:G,attributeDivisors:O,object:L,attributes:{},index:null}}function h(L,w,G,O){let N=s.attributes,B=w.attributes,V=0,q=G.getAttributes();for(let K in q)if(q[K].location>=0){let Y=N[K],j=B[K];if(j===void 0&&(K==="instanceMatrix"&&L.instanceMatrix&&(j=L.instanceMatrix),K==="instanceColor"&&L.instanceColor&&(j=L.instanceColor)),Y===void 0||Y.attribute!==j||j&&Y.data!==j.data)return!0;V++}return s.attributesNum!==V||s.index!==O}function m(L,w,G,O){let N={},B=w.attributes,V=0,q=G.getAttributes();for(let K in q)if(q[K].location>=0){let Y=B[K];Y===void 0&&(K==="instanceMatrix"&&L.instanceMatrix&&(Y=L.instanceMatrix),K==="instanceColor"&&L.instanceColor&&(Y=L.instanceColor));let j={};j.attribute=Y,Y&&Y.data&&(j.data=Y.data),N[K]=j,V++}s.attributes=N,s.attributesNum=V,s.index=O}function g(){let L=s.newAttributes;for(let w=0,G=L.length;w<G;w++)L[w]=0}function p(L){_(L,0)}function _(L,w){let G=s.newAttributes,O=s.enabledAttributes,N=s.attributeDivisors;G[L]=1,O[L]===0&&(n.enableVertexAttribArray(L),O[L]=1),N[L]!==w&&(n.vertexAttribDivisor(L,w),N[L]=w)}function v(){let L=s.newAttributes,w=s.enabledAttributes;for(let G=0,O=w.length;G<O;G++)w[G]!==L[G]&&(n.disableVertexAttribArray(G),w[G]=0)}function E(L,w,G,O,N,B,V){V===!0?n.vertexAttribIPointer(L,w,G,N,B):n.vertexAttribPointer(L,w,G,O,N,B)}function S(L,w,G,O){g();let N=O.attributes,B=G.getAttributes(),V=w.defaultAttributeValues;for(let q in B){let K=B[q];if(K.location>=0){let J=N[q];if(J===void 0&&(q==="instanceMatrix"&&L.instanceMatrix&&(J=L.instanceMatrix),q==="instanceColor"&&L.instanceColor&&(J=L.instanceColor)),J!==void 0){let Y=J.normalized,j=J.itemSize,ue=e.get(J);if(ue===void 0)continue;let Ee=ue.buffer,Ue=ue.type,se=ue.bytesPerElement,ve=Ue===n.INT||Ue===n.UNSIGNED_INT||J.gpuType===CT;if(J.isInterleavedBufferAttribute){let ne=J.data,me=ne.stride,Le=J.offset;if(ne.isInstancedInterleavedBuffer){for(let de=0;de<K.locationSize;de++)_(K.location+de,ne.meshPerAttribute);L.isInstancedMesh!==!0&&O._maxInstanceCount===void 0&&(O._maxInstanceCount=ne.meshPerAttribute*ne.count)}else for(let de=0;de<K.locationSize;de++)p(K.location+de);n.bindBuffer(n.ARRAY_BUFFER,Ee);for(let de=0;de<K.locationSize;de++)E(K.location+de,j/K.locationSize,Ue,Y,me*se,(Le+j/K.locationSize*de)*se,ve)}else{if(J.isInstancedBufferAttribute){for(let ne=0;ne<K.locationSize;ne++)_(K.location+ne,J.meshPerAttribute);L.isInstancedMesh!==!0&&O._maxInstanceCount===void 0&&(O._maxInstanceCount=J.meshPerAttribute*J.count)}else for(let ne=0;ne<K.locationSize;ne++)p(K.location+ne);n.bindBuffer(n.ARRAY_BUFFER,Ee);for(let ne=0;ne<K.locationSize;ne++)E(K.location+ne,j/K.locationSize,Ue,Y,j*se,j/K.locationSize*ne*se,ve)}}else if(V!==void 0){let Y=V[q];if(Y!==void 0)switch(Y.length){case 2:n.vertexAttrib2fv(K.location,Y);break;case 3:n.vertexAttrib3fv(K.location,Y);break;case 4:n.vertexAttrib4fv(K.location,Y);break;default:n.vertexAttrib1fv(K.location,Y)}}}}v()}function T(){I();for(let L in i){let w=i[L];for(let G in w){let O=w[G];for(let N in O){let B=O[N];for(let V in B)f(B[V].object),delete B[V];delete O[N]}}delete i[L]}}function A(L){if(i[L.id]===void 0)return;let w=i[L.id];for(let G in w){let O=w[G];for(let N in O){let B=O[N];for(let V in B)f(B[V].object),delete B[V];delete O[N]}}delete i[L.id]}function R(L){for(let w in i){let G=i[w];for(let O in G){let N=G[O];if(N[L.id]===void 0)continue;let B=N[L.id];for(let V in B)f(B[V].object),delete B[V];delete N[L.id]}}}function M(L){for(let w in i){let G=i[w],O=L.isInstancedMesh===!0?L.id:0,N=G[O];if(N!==void 0){for(let B in N){let V=N[B];for(let q in V)f(V[q].object),delete V[q];delete N[B]}delete G[O],Object.keys(G).length===0&&delete i[w]}}}function I(){C(),a=!0,s!==r&&(s=r,c(s.object))}function C(){r.geometry=null,r.program=null,r.wireframe=!1}return{setup:o,reset:I,resetDefaultState:C,dispose:T,releaseStatesOfGeometry:A,releaseStatesOfObject:M,releaseStatesOfProgram:R,initAttributes:g,enableAttribute:p,disableUnusedAttributes:v}}function tae(n,e,t){let i;function r(l){i=l}function s(l,c){n.drawArrays(i,l,c),t.update(c,i,1)}function a(l,c,f){f!==0&&(n.drawArraysInstanced(i,l,c,f),t.update(c,i,f))}function o(l,c,f){if(f===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,l,0,c,0,f);let u=0;for(let h=0;h<f;h++)u+=c[h];t.update(u,i,1)}this.setMode=r,this.render=s,this.renderInstances=a,this.renderMultiDraw=o}function iae(n,e,t,i){let r;function s(){if(r!==void 0)return r;if(e.has("EXT_texture_filter_anisotropic")===!0){let R=e.get("EXT_texture_filter_anisotropic");r=n.getParameter(R.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r}function a(R){return!(R!==Aa&&i.convert(R)!==n.getParameter(n.IMPLEMENTATION_COLOR_READ_FORMAT))}function o(R){let M=R===Al&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(R!==Ks&&i.convert(R)!==n.getParameter(n.IMPLEMENTATION_COLOR_READ_TYPE)&&R!==Ta&&!M)}function l(R){if(R==="highp"){if(n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.HIGH_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";R="mediump"}return R==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp",f=l(c);f!==c&&(Nt("WebGLRenderer:",c,"not supported, using",f,"instead."),c=f);let d=t.logarithmicDepthBuffer===!0,u=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control");t.reversedDepthBuffer===!0&&u===!1&&Nt("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");let h=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),m=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),g=n.getParameter(n.MAX_TEXTURE_SIZE),p=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),_=n.getParameter(n.MAX_VERTEX_ATTRIBS),v=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),E=n.getParameter(n.MAX_VARYING_VECTORS),S=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),T=n.getParameter(n.MAX_SAMPLES),A=n.getParameter(n.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:l,textureFormatReadable:a,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:u,maxTextures:h,maxVertexTextures:m,maxTextureSize:g,maxCubemapSize:p,maxAttributes:_,maxVertexUniforms:v,maxVaryings:E,maxFragmentUniforms:S,maxSamples:T,samples:A}}function rae(n){let e=this,t=null,i=0,r=!1,s=!1,a=new ps,o=new li,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,u){let h=d.length!==0||u||i!==0||r;return r=u,i=d.length,h},this.beginShadows=function(){s=!0,f(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(d,u){t=f(d,u,0)},this.setState=function(d,u,h){let m=d.clippingPlanes,g=d.clipIntersection,p=d.clipShadows,_=n.get(d);if(!r||m===null||m.length===0||s&&!p)s?f(null):c();else{let v=s?0:i,E=v*4,S=_.clippingState||null;l.value=S,S=f(m,u,E,h);for(let T=0;T!==E;++T)S[T]=t[T];_.clippingState=S,this.numIntersection=g?this.numPlanes:0,this.numPlanes+=v}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function f(d,u,h,m){let g=d!==null?d.length:0,p=null;if(g!==0){if(p=l.value,m!==!0||p===null){let _=h+g*4,v=u.matrixWorldInverse;o.getNormalMatrix(v),(p===null||p.length<_)&&(p=new Float32Array(_));for(let E=0,S=h;E!==g;++E,S+=4)a.copy(d[E]).applyMatrix4(v,o),a.normal.toArray(p,S),p[S+3]=a.constant}l.value=p,l.needsUpdate=!0}return e.numPlanes=g,e.numIntersection=0,p}}function aae(n){let e=[],t=[],i=[],r=n,s=n-Ff+1+z2.length;for(let a=0;a<s;a++){let o=Math.pow(2,r);e.push(o);let l=1/o;a>n-Ff?l=z2[a-n+Ff-1]:a===0&&(l=0),t.push(l);let c=1/(o-2),f=-c,d=1+c,u=[f,f,d,f,d,d,f,f,d,d,f,d],h=6,m=6,g=3,p=2,_=1,v=new Float32Array(g*m*h),E=new Float32Array(p*m*h),S=new Float32Array(_*m*h);for(let A=0;A<h;A++){let R=A%3*2/3-1,M=A>2?0:-1,I=[R,M,0,R+2/3,M,0,R+2/3,M+1,0,R,M,0,R+2/3,M+1,0,R,M+1,0];v.set(I,g*m*A),E.set(u,p*m*A);let C=[A,A,A,A,A,A];S.set(C,_*m*A)}let T=new Bi;T.setAttribute("position",new Tr(v,g)),T.setAttribute("uv",new Tr(E,p)),T.setAttribute("faceIndex",new Tr(S,_)),i.push(new ci(T,null)),r>Ff&&r--}return{lodMeshes:i,sizeLods:e,sigmas:t}}function H2(n,e,t){let i=new Ea(n,e,t);return i.texture.mapping=V_,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Mm(n,e,t,i,r){n.viewport.set(e,t,i,r),n.scissor.set(e,t,i,r)}function oae(n,e,t){return new Sa({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:nae,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:SA(),fragmentShader:`
precision highp float;
precision highp int;
varying vec3 vOutputDirection;
uniform sampler2D envMap;
uniform float roughness;
uniform float mipInt;
#define ENVMAP_TYPE_CUBE_UV
#include <cube_uv_reflection_fragment>
#define PI 3.14159265359
// Van der Corput radical inverse
float radicalInverse_VdC(uint bits) {
bits = (bits << 16u) | (bits >> 16u);
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
return float(bits) * 2.3283064365386963e-10; // / 0x100000000
}
// Hammersley sequence
vec2 hammersley(uint i, uint N) {
return vec2(float(i) / float(N), radicalInverse_VdC(i));
}
// GGX VNDF importance sampling (Eric Heitz 2018)
// "Sampling the GGX Distribution of Visible Normals"
// https://jcgt.org/published/0007/04/01/
vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
float alpha = roughness * roughness;
// Section 4.1: Orthonormal basis
vec3 T1 = vec3(1.0, 0.0, 0.0);
vec3 T2 = cross(V, T1);
// Section 4.2: Parameterization of projected area
float r = sqrt(Xi.x);
float phi = 2.0 * PI * Xi.y;
float t1 = r * cos(phi);
float t2 = r * sin(phi);
float s = 0.5 * (1.0 + V.z);
t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
// Section 4.3: Reprojection onto hemisphere
vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V;
// Section 3.4: Transform back to ellipsoid configuration
return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
}
void main() {
vec3 N = normalize(vOutputDirection);
vec3 V = N; // Assume view direction equals normal for pre-filtering
vec3 prefilteredColor = vec3(0.0);
float totalWeight = 0.0;
// For very low roughness, just sample the environment directly
if (roughness < 0.001) {
gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
return;
}
// Tangent space basis for VNDF sampling
vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
vec3 tangent = normalize(cross(up, N));
vec3 bitangent = cross(N, tangent);
for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
// For PMREM, V = N, so in tangent space V is always (0, 0, 1)
vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
// Transform H back to world space
vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
vec3 L = normalize(2.0 * dot(V, H) * H - V);
float NdotL = max(dot(N, L), 0.0);
if(NdotL > 0.0) {
// Sample environment at fixed mip level
// VNDF importance sampling handles the distribution filtering
vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
// Weight by NdotL for the split-sum approximation
// VNDF PDF naturally accounts for the visible microfacet distribution
prefilteredColor += sampleColor * NdotL;
totalWeight += NdotL;
}
}
if (totalWeight > 0.0) {
prefilteredColor = prefilteredColor / totalWeight;
}
gl_FragColor = vec4(prefilteredColor, 1.0);
}
`,blending:Tl,depthTest:!1,depthWrite:!1})}function lae(n,e,t){let i=new Float32Array(Au),r=new ie(0,1,0);return new Sa({name:"SphericalGaussianBlur",defines:{n:Au,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:SA(),fragmentShader:`
precision mediump float;
precision mediump int;
varying vec3 vOutputDirection;
uniform sampler2D envMap;
uniform int samples;
uniform float weights[ n ];
uniform bool latitudinal;
uniform float dTheta;
uniform float mipInt;
uniform vec3 poleAxis;
#define ENVMAP_TYPE_CUBE_UV
#include <cube_uv_reflection_fragment>
vec3 getSample( float theta, vec3 axis ) {
float cosTheta = cos( theta );
// Rodrigues' axis-angle rotation
vec3 sampleDirection = vOutputDirection * cosTheta
+ cross( axis, vOutputDirection ) * sin( theta )
+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
return bilinearCubeUV( envMap, sampleDirection, mipInt );
}
void main() {
vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
}
axis = normalize( axis );
gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
for ( int i = 1; i < n; i++ ) {
if ( i >= samples ) {
break;
}
float theta = dTheta * float( i );
gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
}
}
`,blending:Tl,depthTest:!1,depthWrite:!1})}function X2(){return new Sa({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:SA(),fragmentShader:`
precision mediump float;
precision mediump int;
varying vec3 vOutputDirection;
uniform sampler2D envMap;
#include <common>
void main() {
vec3 outputDirection = normalize( vOutputDirection );
vec2 uv = equirectUv( outputDirection );
gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
}
`,blending:Tl,depthTest:!1,depthWrite:!1})}function Y2(){return new Sa({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:SA(),fragmentShader:`
precision mediump float;
precision mediump int;
uniform float flipEnvMap;
varying vec3 vOutputDirection;
uniform samplerCube envMap;
void main() {
gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
}
`,blending:Tl,depthTest:!1,depthWrite:!1})}function SA(){return`
precision mediump float;
precision mediump int;
attribute float faceIndex;
varying vec3 vOutputDirection;
// RH coordinate system; PMREM face-indexing convention
vec3 getDirection( vec2 uv, float face ) {
uv = 2.0 * uv - 1.0;
vec3 direction = vec3( uv, 1.0 );
if ( face == 0.0 ) {
direction = direction.zyx; // ( 1, v, u ) pos x
} else if ( face == 1.0 ) {
direction = direction.xzy;
direction.xz *= -1.0; // ( -u, 1, -v ) pos y
} else if ( face == 2.0 ) {
direction.x *= -1.0; // ( -u, v, 1 ) pos z
} else if ( face == 3.0 ) {
direction = direction.zyx;
direction.xz *= -1.0; // ( -1, v, -u ) neg x
} else if ( face == 4.0 ) {
direction = direction.xzy;
direction.xy *= -1.0; // ( -u, -1, v ) neg y
} else if ( face == 5.0 ) {
direction.z *= -1.0; // ( u, v, -1 ) neg z
}
return direction;
}
void main() {
vOutputDirection = getDirection( uv, faceIndex );
gl_Position = vec4( position, 1.0 );
}
`}function cae(n){let e=new WeakMap,t=new WeakMap,i=null;function r(u,h=!1){return u==null?null:h?a(u):s(u)}function s(u){if(u&&u.isTexture){let h=u.mapping;if(h===MT||h===yT)if(e.has(u)){let m=e.get(u).texture;return o(m,u.mapping)}else{let m=u.image;if(m&&m.height>0){let g=new vA(m.height);return g.fromEquirectangularTexture(n,u),e.set(u,g),u.addEventListener("dispose",c),o(g.texture,u.mapping)}else return null}}return u}function a(u){if(u&&u.isTexture){let h=u.mapping,m=h===MT||h===yT,g=h===Of||h===Eu;if(m||g){let p=t.get(u),_=p!==void 0?p.texture.pmremVersion:0;if(u.isRenderTargetTexture&&u.pmremVersion!==_)return i===null&&(i=new Im(n)),p=m?i.fromEquirectangular(u,p):i.fromCubemap(u,p),p.texture.pmremVersion=u.pmremVersion,t.set(u,p),p.texture;if(p!==void 0)return p.texture;{let v=u.image;return m&&v&&v.height>0||g&&v&&l(v)?(i===null&&(i=new Im(n)),p=m?i.fromEquirectangular(u):i.fromCubemap(u),p.texture.pmremVersion=u.pmremVersion,t.set(u,p),u.addEventListener("dispose",f),p.texture):null}}}return u}function o(u,h){return h===MT?u.mapping=Of:h===yT&&(u.mapping=Eu),u}function l(u){let h=0,m=6;for(let g=0;g<m;g++)u[g]!==void 0&&h++;return h===m}function c(u){let h=u.target;h.removeEventListener("dispose",c);let m=e.get(h);m!==void 0&&(e.delete(h),m.dispose())}function f(u){let h=u.target;h.removeEventListener("dispose",f);let m=t.get(h);m!==void 0&&(t.delete(h),m.dispose())}function d(){e=new WeakMap,t=new WeakMap,i!==null&&(i.dispose(),i=null)}return{get:r,dispose:d}}function fae(n){let e={};function t(i){if(e[i]!==void 0)return e[i];let r=n.getExtension(i);return e[i]=r,r}return{has:function(i){return t(i)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(i){let r=t(i);return r===null&&sT("WebGLRenderer: "+i+" extension not supported."),r}}}function dae(n,e,t,i){let r={},s=new WeakMap;function a(d){let u=d.target;u.index!==null&&e.remove(u.index);for(let m in u.attributes)e.remove(u.attributes[m]);u.removeEventListener("dispose",a),delete r[u.id];let h=s.get(u);h&&(e.remove(h),s.delete(u)),i.releaseStatesOfGeometry(u),u.isInstancedBufferGeometry===!0&&delete u._maxInstanceCount,t.memory.geometries--}function o(d,u){return r[u.id]===!0||(u.addEventListener("dispose",a),r[u.id]=!0,t.memory.geometries++),u}function l(d){let u=d.attributes;for(let h in u)e.update(u[h],n.ARRAY_BUFFER)}function c(d){let u=[],h=d.index,m=d.attributes.position,g=0;if(m===void 0)return;if(h!==null){let v=h.array;g=h.version;for(let E=0,S=v.length;E<S;E+=3){let T=v[E+0],A=v[E+1],R=v[E+2];u.push(T,A,A,R,R,T)}}else{let v=m.array;g=m.version;for(let E=0,S=v.length/3-1;E<S;E+=3){let T=E+0,A=E+1,R=E+2;u.push(T,A,A,R,R,T)}}let p=new(m.count>=65535?E_:v_)(u,1);p.version=g;let _=s.get(d);_&&e.remove(_),s.set(d,p)}function f(d){let u=s.get(d);if(u){let h=d.index;h!==null&&u.version<h.version&&c(d)}else c(d);return s.get(d)}return{get:o,update:l,getWireframeAttribute:f}}function uae(n,e,t){let i;function r(d){i=d}let s,a;function o(d){s=d.type,a=d.bytesPerElement}function l(d,u){n.drawElements(i,u,s,d*a),t.update(u,i,1)}function c(d,u,h){h!==0&&(n.drawElementsInstanced(i,u,s,d*a,h),t.update(u,i,h))}function f(d,u,h){if(h===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,u,0,s,d,0,h);let g=0;for(let p=0;p<h;p++)g+=u[p];t.update(g,i,1)}this.setMode=r,this.setIndex=o,this.render=l,this.renderInstances=c,this.renderMultiDraw=f}function hae(n){let e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function i(s,a,o){switch(t.calls++,a){case n.TRIANGLES:t.triangles+=o*(s/3);break;case n.LINES:t.lines+=o*(s/2);break;case n.LINE_STRIP:t.lines+=o*(s-1);break;case n.LINE_LOOP:t.lines+=o*s;break;case n.POINTS:t.points+=o*s;break;default:Ht("WebGLInfo: Unknown draw mode:",a);break}}function r(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:r,update:i}}function mae(n,e,t){let i=new WeakMap,r=new dr;function s(a,o,l){let c=a.morphTargetInfluences,f=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,d=f!==void 0?f.length:0,u=i.get(o);if(u===void 0||u.count!==d){let I=function(){R.dispose(),i.delete(o),o.removeEventListener("dispose",I)};u!==void 0&&u.texture.dispose();let h=o.morphAttributes.position!==void 0,m=o.morphAttributes.normal!==void 0,g=o.morphAttributes.color!==void 0,p=o.morphAttributes.position||[],_=o.morphAttributes.normal||[],v=o.morphAttributes.color||[],E=0;h===!0&&(E=1),m===!0&&(E=2),g===!0&&(E=3);let S=o.attributes.position.count*E,T=1;S>e.maxTextureSize&&(T=Math.ceil(S/e.maxTextureSize),S=e.maxTextureSize);let A=new Float32Array(S*T*4*d),R=new __(A,S,T,d);R.type=Ta,R.needsUpdate=!0;let M=E*4;for(let C=0;C<d;C++){let L=p[C],w=_[C],G=v[C],O=S*T*4*C;for(let N=0;N<L.count;N++){let B=N*M;h===!0&&(r.fromBufferAttribute(L,N),A[O+B+0]=r.x,A[O+B+1]=r.y,A[O+B+2]=r.z,A[O+B+3]=0),m===!0&&(r.fromBufferAttribute(w,N),A[O+B+4]=r.x,A[O+B+5]=r.y,A[O+B+6]=r.z,A[O+B+7]=0),g===!0&&(r.fromBufferAttribute(G,N),A[O+B+8]=r.x,A[O+B+9]=r.y,A[O+B+10]=r.z,A[O+B+11]=G.itemSize===4?r.w:1)}}u={count:d,texture:R,size:new Ct(S,T)},i.set(o,u),o.addEventListener("dispose",I)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)l.getUniforms().setValue(n,"morphTexture",a.morphTexture,t);else{let h=0;for(let g=0;g<c.length;g++)h+=c[g];let m=o.morphTargetsRelative?1:1-h;l.getUniforms().setValue(n,"morphTargetBaseInfluence",m),l.getUniforms().setValue(n,"morphTargetInfluences",c)}l.getUniforms().setValue(n,"morphTargetsTexture",u.texture,t),l.getUniforms().setValue(n,"morphTargetsTextureSize",u.size)}return{update:s}}function pae(n,e,t,i,r){let s=new WeakMap;function a(c){let f=r.render.frame,d=c.geometry,u=e.get(c,d);if(s.get(u)!==f&&(e.update(u),s.set(u,f)),c.isInstancedMesh&&(c.hasEventListener("dispose",l)===!1&&c.addEventListener("dispose",l),s.get(c)!==f&&(t.update(c.instanceMatrix,n.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,n.ARRAY_BUFFER),s.set(c,f))),c.isSkinnedMesh){let h=c.skeleton;s.get(h)!==f&&(h.update(),s.set(h,f))}return u}function o(){s=new WeakMap}function l(c){let f=c.target;f.removeEventListener("dispose",l),i.releaseStatesOfObject(f),t.remove(f.instanceMatrix),f.instanceColor!==null&&t.remove(f.instanceColor)}return{update:a,dispose:o}}function _ae(n,e,t,i,r){let s=new Ea(e,t,{type:n,depthBuffer:i,stencilBuffer:r,depthTexture:i?new mc(e,t):void 0}),a=new Ea(e,t,{type:Al,depthBuffer:!1,stencilBuffer:!1}),o=new Bi;o.setAttribute("position",new gi([-1,3,0,-1,-1,0,3,-1,0],3)),o.setAttribute("uv",new gi([0,2,0,0,2,0],2));let l=new uT({uniforms:{tDiffuse:{value:null}},vertexShader:`
precision highp float;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
attribute vec3 position;
attribute vec2 uv;
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,fragmentShader:`
precision highp float;
uniform sampler2D tDiffuse;
varying vec2 vUv;
#include <tonemapping_pars_fragment>
#include <colorspace_pars_fragment>
void main() {
gl_FragColor = texture2D( tDiffuse, vUv );
#ifdef LINEAR_TONE_MAPPING
gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );
#elif defined( REINHARD_TONE_MAPPING )
gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );
#elif defined( CINEON_TONE_MAPPING )
gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );
#elif defined( ACES_FILMIC_TONE_MAPPING )
gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );
#elif defined( AGX_TONE_MAPPING )
gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );
#elif defined( NEUTRAL_TONE_MAPPING )
gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );
#elif defined( CUSTOM_TONE_MAPPING )
gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );
#endif
#ifdef SRGB_TRANSFER
gl_FragColor = sRGBTransferOETF( gl_FragColor );
#endif
}`,depthTest:!1,depthWrite:!1}),c=new ci(o,l),f=new vs(-1,1,1,-1,0,1),d=null,u=null,h=!1,m,g=null,p=[],_=!1;this.setSize=function(v,E){s.setSize(v,E),a.setSize(v,E);for(let S=0;S<p.length;S++){let T=p[S];T.setSize&&T.setSize(v,E)}},this.setEffects=function(v){p=v,_=p.length>0&&p[0].isRenderPass===!0;let E=s.width,S=s.height;for(let T=0;T<p.length;T++){let A=p[T];A.setSize&&A.setSize(E,S)}},this.begin=function(v,E){if(h||v.toneMapping===Ys&&p.length===0)return!1;if(g=E,E!==null){let S=E.width,T=E.height;(s.width!==S||s.height!==T)&&this.setSize(S,T)}return _===!1&&v.setRenderTarget(s),m=v.toneMapping,v.toneMapping=Ys,!0},this.hasRenderPass=function(){return _},this.end=function(v,E){v.toneMapping=m,h=!0;let S=s,T=a;for(let A=0;A<p.length;A++){let R=p[A];if(R.enabled!==!1&&(R.render(v,T,S,E),R.needsSwap!==!1)){let M=S;S=T,T=M}}if(d!==v.outputColorSpace||u!==v.toneMapping){d=v.outputColorSpace,u=v.toneMapping,l.defines={},mi.getTransfer(d)===nr&&(l.defines.SRGB_TRANSFER="");let A=gae[u];A&&(l.defines[A]=""),l.needsUpdate=!0}l.uniforms.tDiffuse.value=S.texture,v.setRenderTarget(g),v.render(c,f),g=null,h=!1},this.isCompositing=function(){return h},this.dispose=function(){s.depthTexture&&s.depthTexture.dispose(),s.dispose(),a.dispose(),o.dispose(),l.dispose()}}function Cm(n,e,t){let i=n[0];if(i<=0||i>0)return n;let r=e*t,s=K2[r];if(s===void 0&&(s=new Float32Array(r),K2[r]=s),e!==0){i.toArray(s,0);for(let a=1,o=0;a!==e;++a)o+=t,n[a].toArray(s,o)}return s}function hn(n,e){if(n.length!==e.length)return!1;for(let t=0,i=n.length;t<i;t++)if(n[t]!==e[t])return!1;return!0}function mn(n,e){for(let t=0,i=e.length;t<i;t++)n[t]=e[t]}function TA(n,e){let t=j2[e];t===void 0&&(t=new Int32Array(e),j2[e]=t);for(let i=0;i!==e;++i)t[i]=n.allocateTextureUnit();return t}function vae(n,e){let t=this.cache;t[0]!==e&&(n.uniform1f(this.addr,e),t[0]=e)}function Eae(n,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(n.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(hn(t,e))return;n.uniform2fv(this.addr,e),mn(t,e)}}function Sae(n,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(n.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(n.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(hn(t,e))return;n.uniform3fv(this.addr,e),mn(t,e)}}function Tae(n,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(n.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(hn(t,e))return;n.uniform4fv(this.addr,e),mn(t,e)}}function Aae(n,e){let t=this.cache,i=e.elements;if(i===void 0){if(hn(t,e))return;n.uniformMatrix2fv(this.addr,!1,e),mn(t,e)}else{if(hn(t,i))return;Q2.set(i),n.uniformMatrix2fv(this.addr,!1,Q2),mn(t,i)}}function xae(n,e){let t=this.cache,i=e.elements;if(i===void 0){if(hn(t,e))return;n.uniformMatrix3fv(this.addr,!1,e),mn(t,e)}else{if(hn(t,i))return;q2.set(i),n.uniformMatrix3fv(this.addr,!1,q2),mn(t,i)}}function Rae(n,e){let t=this.cache,i=e.elements;if(i===void 0){if(hn(t,e))return;n.uniformMatrix4fv(this.addr,!1,e),mn(t,e)}else{if(hn(t,i))return;Z2.set(i),n.uniformMatrix4fv(this.addr,!1,Z2),mn(t,i)}}function bae(n,e){let t=this.cache;t[0]!==e&&(n.uniform1i(this.addr,e),t[0]=e)}function Mae(n,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(n.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(hn(t,e))return;n.uniform2iv(this.addr,e),mn(t,e)}}function yae(n,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(n.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(hn(t,e))return;n.uniform3iv(this.addr,e),mn(t,e)}}function Iae(n,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(n.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(hn(t,e))return;n.uniform4iv(this.addr,e),mn(t,e)}}function Cae(n,e){let t=this.cache;t[0]!==e&&(n.uniform1ui(this.addr,e),t[0]=e)}function Pae(n,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(n.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(hn(t,e))return;n.uniform2uiv(this.addr,e),mn(t,e)}}function Lae(n,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(n.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(hn(t,e))return;n.uniform3uiv(this.addr,e),mn(t,e)}}function Dae(n,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(n.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(hn(t,e))return;n.uniform4uiv(this.addr,e),mn(t,e)}}function Oae(n,e,t){let i=this.cache,r=t.allocateTextureUnit();i[0]!==r&&(n.uniform1i(this.addr,r),i[0]=r);let s;this.type===n.SAMPLER_2D_SHADOW?(dC.compareFunction=t.isReversedDepthBuffer()?mA:hA,s=dC):s=uU,t.setTexture2D(e||s,r)}function Nae(n,e,t){let i=this.cache,r=t.allocateTextureUnit();i[0]!==r&&(n.uniform1i(this.addr,r),i[0]=r),t.setTexture3D(e||mU,r)}function wae(n,e,t){let i=this.cache,r=t.allocateTextureUnit();i[0]!==r&&(n.uniform1i(this.addr,r),i[0]=r),t.setTextureCube(e||pU,r)}function Fae(n,e,t){let i=this.cache,r=t.allocateTextureUnit();i[0]!==r&&(n.uniform1i(this.addr,r),i[0]=r),t.setTexture2DArray(e||hU,r)}function Bae(n){switch(n){case 5126:return vae;case 35664:return Eae;case 35665:return Sae;case 35666:return Tae;case 35674:return Aae;case 35675:return xae;case 35676:return Rae;case 5124:case 35670:return bae;case 35667:case 35671:return Mae;case 35668:case 35672:return yae;case 35669:case 35673:return Iae;case 5125:return Cae;case 36294:return Pae;case 36295:return Lae;case 36296:return Dae;case 35678:case 36198:case 36298:case 36306:case 35682:return Oae;case 35679:case 36299:case 36307:return Nae;case 35680:case 36300:case 36308:case 36293:return wae;case 36289:case 36303:case 36311:case 36292:return Fae}}function Uae(n,e){n.uniform1fv(this.addr,e)}function Vae(n,e){let t=Cm(e,this.size,2);n.uniform2fv(this.addr,t)}function Gae(n,e){let t=Cm(e,this.size,3);n.uniform3fv(this.addr,t)}function kae(n,e){let t=Cm(e,this.size,4);n.uniform4fv(this.addr,t)}function zae(n,e){let t=Cm(e,this.size,4);n.uniformMatrix2fv(this.addr,!1,t)}function Wae(n,e){let t=Cm(e,this.size,9);n.uniformMatrix3fv(this.addr,!1,t)}function Hae(n,e){let t=Cm(e,this.size,16);n.uniformMatrix4fv(this.addr,!1,t)}function Xae(n,e){n.uniform1iv(this.addr,e)}function Yae(n,e){n.uniform2iv(this.addr,e)}function Kae(n,e){n.uniform3iv(this.addr,e)}function jae(n,e){n.uniform4iv(this.addr,e)}function Zae(n,e){n.uniform1uiv(this.addr,e)}function qae(n,e){n.uniform2uiv(this.addr,e)}function Qae(n,e){n.uniform3uiv(this.addr,e)}function $ae(n,e){n.uniform4uiv(this.addr,e)}function Jae(n,e,t){let i=this.cache,r=e.length,s=TA(t,r);hn(i,s)||(n.uniform1iv(this.addr,s),mn(i,s));let a;this.type===n.SAMPLER_2D_SHADOW?a=dC:a=uU;for(let o=0;o!==r;++o)t.setTexture2D(e[o]||a,s[o])}function eoe(n,e,t){let i=this.cache,r=e.length,s=TA(t,r);hn(i,s)||(n.uniform1iv(this.addr,s),mn(i,s));for(let a=0;a!==r;++a)t.setTexture3D(e[a]||mU,s[a])}function toe(n,e,t){let i=this.cache,r=e.length,s=TA(t,r);hn(i,s)||(n.uniform1iv(this.addr,s),mn(i,s));for(let a=0;a!==r;++a)t.setTextureCube(e[a]||pU,s[a])}function ioe(n,e,t){let i=this.cache,r=e.length,s=TA(t,r);hn(i,s)||(n.uniform1iv(this.addr,s),mn(i,s));for(let a=0;a!==r;++a)t.setTexture2DArray(e[a]||hU,s[a])}function roe(n){switch(n){case 5126:return Uae;case 35664:return Vae;case 35665:return Gae;case 35666:return kae;case 35674:return zae;case 35675:return Wae;case 35676:return Hae;case 5124:case 35670:return Xae;case 35667:case 35671:return Yae;case 35668:case 35672:return Kae;case 35669:case 35673:return jae;case 5125:return Zae;case 36294:return qae;case 36295:return Qae;case 36296:return $ae;case 35678:case 36198:case 36298:case 36306:case 35682:return Jae;case 35679:case 36299:case 36307:return eoe;case 35680:case 36300:case 36308:case 36293:return toe;case 36289:case 36303:case 36311:case 36292:return ioe}}function $2(n,e){n.seq.push(e),n.map[e.id]=e}function noe(n,e,t){let i=n.name,r=i.length;for(cC.lastIndex=0;;){let s=cC.exec(i),a=cC.lastIndex,o=s[1],l=s[2]==="]",c=s[3];if(l&&(o=o|0),c===void 0||c==="["&&a+2===r){$2(t,c===void 0?new uC(o,n,e):new hC(o,n,e));break}else{let d=t.map[o];d===void 0&&(d=new mC(o),$2(t,d)),t=d}}}function J2(n,e,t){let i=n.createShader(e);return n.shaderSource(i,t),n.compileShader(i),i}function ooe(n,e){let t=n.split(`
`),i=[],r=Math.max(e-6,0),s=Math.min(e+6,t.length);for(let a=r;a<s;a++){let o=a+1;i.push(`${o===e?">":" "} ${o}: ${t[a]}`)}return i.join(`
`)}function loe(n){mi._getMatrix(eU,mi.workingColorSpace,n);let e=`mat3( ${eU.elements.map(t=>t.toFixed(4))} )`;switch(mi.getTransfer(n)){case p_:return[e,"LinearTransferOETF"];case nr:return[e,"sRGBTransferOETF"];default:return Nt("WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function tU(n,e,t){let i=n.getShaderParameter(e,n.COMPILE_STATUS),s=(n.getShaderInfoLog(e)||"").trim();if(i&&s==="")return"";let a=/ERROR: 0:(\d+)/.exec(s);if(a){let o=parseInt(a[1]);return t.toUpperCase()+`
`+s+`
`+ooe(n.getShaderSource(e),o)}else return s}function coe(n,e){let t=loe(e);return[`vec4 ${n}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(`
`)}function doe(n,e){let t=foe[e];return t===void 0?(Nt("WebGLProgram: Unsupported toneMapping:",e),"vec3 "+n+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+n+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}function uoe(){mi.getLuminanceCoefficients(_A);let n=_A.x.toFixed(4),e=_A.y.toFixed(4),t=_A.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${n}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(`
`)}function hoe(n){return[n.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",n.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(q_).join(`
`)}function moe(n){let e=[];for(let t in n){let i=n[t];i!==!1&&e.push("#define "+t+" "+i)}return e.join(`
`)}function poe(n,e){let t={},i=n.getProgramParameter(e,n.ACTIVE_ATTRIBUTES);for(let r=0;r<i;r++){let s=n.getActiveAttrib(e,r),a=s.name,o=1;s.type===n.FLOAT_MAT2&&(o=2),s.type===n.FLOAT_MAT3&&(o=3),s.type===n.FLOAT_MAT4&&(o=4),t[a]={type:s.type,location:n.getAttribLocation(e,a),locationSize:o}}return t}function q_(n){return n!==""}function iU(n,e){let t=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return n.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,t).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function rU(n,e){return n.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}function pC(n){return n.replace(goe,voe)}function voe(n,e){let t=Ei[e];if(t===void 0){let i=_oe.get(e);if(i!==void 0)t=Ei[i],Nt('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return pC(t)}function nU(n){return n.replace(Eoe,Soe)}function Soe(n,e,t,i){let r="";for(let s=parseInt(e);s<parseInt(t);s++)r+=i.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return r}function sU(n){let e=`precision ${n.precision} float;
precision ${n.precision} int;
precision ${n.precision} sampler2D;
precision ${n.precision} samplerCube;
precision ${n.precision} sampler3D;
precision ${n.precision} sampler2DArray;
precision ${n.precision} sampler2DShadow;
precision ${n.precision} samplerCubeShadow;
precision ${n.precision} sampler2DArrayShadow;
precision ${n.precision} isampler2D;
precision ${n.precision} isampler3D;
precision ${n.precision} isamplerCube;
precision ${n.precision} isampler2DArray;
precision ${n.precision} usampler2D;
precision ${n.precision} usampler3D;
precision ${n.precision} usamplerCube;
precision ${n.precision} usampler2DArray;
`;return n.precision==="highp"?e+=`
#define HIGH_PRECISION`:n.precision==="mediump"?e+=`
#define MEDIUM_PRECISION`:n.precision==="lowp"&&(e+=`
#define LOW_PRECISION`),e}function Aoe(n){return Toe[n.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}function Roe(n){return n.envMap===!1?"ENVMAP_TYPE_CUBE":xoe[n.envMapMode]||"ENVMAP_TYPE_CUBE"}function Moe(n){return n.envMap===!1?"ENVMAP_MODE_REFLECTION":boe[n.envMapMode]||"ENVMAP_MODE_REFLECTION"}function Ioe(n){return n.envMap===!1?"ENVMAP_BLENDING_NONE":yoe[n.combine]||"ENVMAP_BLENDING_NONE"}function Coe(n){let e=n.envMapCubeUVHeight;if(e===null)return null;let t=Math.log2(e)-2,i=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:i,maxMip:t}}function Poe(n,e,t,i){let r=n.getContext(),s=t.defines,a=t.vertexShader,o=t.fragmentShader,l=Aoe(t),c=Roe(t),f=Moe(t),d=Ioe(t),u=Coe(t),h=hoe(t),m=moe(s),g=r.createProgram(),p,_,v=t.glslVersion?"#version "+t.glslVersion+`
`:"";t.isRawShaderMaterial?(p=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m].filter(q_).join(`
`),p.length>0&&(p+=`
`),_=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m].filter(q_).join(`
`),_.length>0&&(_+=`
`)):(p=[sU(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+f:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexNormals?"#define HAS_NORMAL":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",`
`].filter(q_).join(`
`),_=[sU(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+f:"",t.envMap?"#define "+d:"",u?"#define CUBEUV_TEXEL_WIDTH "+u.texelWidth:"",u?"#define CUBEUV_TEXEL_HEIGHT "+u.texelHeight:"",u?"#define CUBEUV_MAX_MIP "+u.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor?"#define USE_COLOR":"",t.vertexAlphas||t.batchingColor?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Ys?"#define TONE_MAPPING":"",t.toneMapping!==Ys?Ei.tonemapping_pars_fragment:"",t.toneMapping!==Ys?doe("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",Ei.colorspace_pars_fragment,coe("linearToOutputTexel",t.outputColorSpace),uoe(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`
`].filter(q_).join(`
`)),a=pC(a),a=iU(a,t),a=rU(a,t),o=pC(o),o=iU(o,t),o=rU(o,t),a=nU(a),o=nU(o),t.isRawShaderMaterial!==!0&&(v=`#version 300 es
`,p=[h,"#define attribute in","#define varying out","#define texture2D texture"].join(`
`)+`
`+p,_=["#define varying in",t.glslVersion===KI?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===KI?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(`
`)+`
`+_);let E=v+p+a,S=v+_+o,T=J2(r,r.VERTEX_SHADER,E),A=J2(r,r.FRAGMENT_SHADER,S);r.attachShader(g,T),r.attachShader(g,A),t.index0AttributeName!==void 0?r.bindAttribLocation(g,0,t.index0AttributeName):t.morphTargets===!0&&r.bindAttribLocation(g,0,"position"),r.linkProgram(g);function R(L){if(n.debug.checkShaderErrors){let w=r.getProgramInfoLog(g)||"",G=r.getShaderInfoLog(T)||"",O=r.getShaderInfoLog(A)||"",N=w.trim(),B=G.trim(),V=O.trim(),q=!0,K=!0;if(r.getProgramParameter(g,r.LINK_STATUS)===!1)if(q=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(r,g,T,A);else{let J=tU(r,T,"vertex"),Y=tU(r,A,"fragment");Ht("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(g,r.VALIDATE_STATUS)+`
Material Name: `+L.name+`
Material Type: `+L.type+`
Program Info Log: `+N+`
`+J+`
`+Y)}else N!==""?Nt("WebGLProgram: Program Info Log:",N):(B===""||V==="")&&(K=!1);K&&(L.diagnostics={runnable:q,programLog:N,vertexShader:{log:B,prefix:p},fragmentShader:{log:V,prefix:_}})}r.deleteShader(T),r.deleteShader(A),M=new ym(r,g),I=poe(r,g)}let M;this.getUniforms=function(){return M===void 0&&R(this),M};let I;this.getAttributes=function(){return I===void 0&&R(this),I};let C=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return C===!1&&(C=r.getProgramParameter(g,soe)),C},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(g),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=aoe++,this.cacheKey=e,this.usedTimes=1,this.program=g,this.vertexShader=T,this.fragmentShader=A,this}function Doe(n){return n===wf||n===H_||n===X_}function Ooe(n,e,t,i,r,s){let a=new lm,o=new gC,l=new Set,c=[],f=new Map,d=i.logarithmicDepthBuffer,u=i.precision,h={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function m(M){return l.add(M),M===0?"uv":`uv${M}`}function g(M,I,C,L,w,G){let O=L.fog,N=w.geometry,B=M.isMeshStandardMaterial||M.isMeshLambertMaterial||M.isMeshPhongMaterial?L.environment:null,V=M.isMeshStandardMaterial||M.isMeshLambertMaterial&&!M.envMap||M.isMeshPhongMaterial&&!M.envMap,q=e.get(M.envMap||B,V),K=q&&q.mapping===V_?q.image.height:null,J=h[M.type];M.precision!==null&&(u=i.getMaxPrecision(M.precision),u!==M.precision&&Nt("WebGLProgram.getParameters:",M.precision,"not supported, using",u,"instead."));let Y=N.morphAttributes.position||N.morphAttributes.normal||N.morphAttributes.color,j=Y!==void 0?Y.length:0,ue=0;N.morphAttributes.position!==void 0&&(ue=1),N.morphAttributes.normal!==void 0&&(ue=2),N.morphAttributes.color!==void 0&&(ue=3);let Ee,Ue,se,ve;if(J){let qt=Rl[J];Ee=qt.vertexShader,Ue=qt.fragmentShader}else Ee=M.vertexShader,Ue=M.fragmentShader,o.update(M),se=o.getVertexShaderID(M),ve=o.getFragmentShaderID(M);let ne=n.getRenderTarget(),me=n.state.buffers.depth.getReversed(),Le=w.isInstancedMesh===!0,de=w.isBatchedMesh===!0,be=!!M.map,we=!!M.matcap,dt=!!q,Ve=!!M.aoMap,Ze=!!M.lightMap,Kt=!!M.bumpMap,Bt=!!M.normalMap,wi=!!M.displacementMap,ae=!!M.emissiveMap,Ti=!!M.metalnessMap,hi=!!M.roughnessMap,rr=M.anisotropy>0,Ke=M.clearcoat>0,ar=M.dispersion>0,Z=M.iridescence>0,U=M.sheen>0,ge=M.transmission>0,De=rr&&!!M.anisotropyMap,ke=Ke&&!!M.clearcoatMap,it=Ke&&!!M.clearcoatNormalMap,Qe=Ke&&!!M.clearcoatRoughnessMap,Me=Z&&!!M.iridescenceMap,Pe=Z&&!!M.iridescenceThicknessMap,ut=U&&!!M.sheenColorMap,bt=U&&!!M.sheenRoughnessMap,qe=!!M.specularMap,Je=!!M.specularColorMap,Wt=!!M.specularIntensityMap,Ut=ge&&!!M.transmissionMap,yi=ge&&!!M.thicknessMap,oe=!!M.gradientMap,rt=!!M.alphaMap,Ce=M.alphaTest>0,ft=!!M.alphaHash,nt=!!M.extensions,Ge=Ys;M.toneMapped&&(ne===null||ne.isXRRenderTarget===!0)&&(Ge=n.toneMapping);let Mt={shaderID:J,shaderType:M.type,shaderName:M.name,vertexShader:Ee,fragmentShader:Ue,defines:M.defines,customVertexShaderID:se,customFragmentShaderID:ve,isRawShaderMaterial:M.isRawShaderMaterial===!0,glslVersion:M.glslVersion,precision:u,batching:de,batchingColor:de&&w._colorsTexture!==null,instancing:Le,instancingColor:Le&&w.instanceColor!==null,instancingMorph:Le&&w.morphTexture!==null,outputColorSpace:ne===null?n.outputColorSpace:ne.isXRRenderTarget===!0?ne.texture.colorSpace:mi.workingColorSpace,alphaToCoverage:!!M.alphaToCoverage,map:be,matcap:we,envMap:dt,envMapMode:dt&&q.mapping,envMapCubeUVHeight:K,aoMap:Ve,lightMap:Ze,bumpMap:Kt,normalMap:Bt,displacementMap:wi,emissiveMap:ae,normalMapObjectSpace:Bt&&M.normalMapType===y2,normalMapTangentSpace:Bt&&M.normalMapType===bm,packedNormalMap:Bt&&M.normalMapType===bm&&Doe(M.normalMap.format),metalnessMap:Ti,roughnessMap:hi,anisotropy:rr,anisotropyMap:De,clearcoat:Ke,clearcoatMap:ke,clearcoatNormalMap:it,clearcoatRoughnessMap:Qe,dispersion:ar,iridescence:Z,iridescenceMap:Me,iridescenceThicknessMap:Pe,sheen:U,sheenColorMap:ut,sheenRoughnessMap:bt,specularMap:qe,specularColorMap:Je,specularIntensityMap:Wt,transmission:ge,transmissionMap:Ut,thicknessMap:yi,gradientMap:oe,opaque:M.transparent===!1&&M.blending===au&&M.alphaToCoverage===!1,alphaMap:rt,alphaTest:Ce,alphaHash:ft,combine:M.combine,mapUv:be&&m(M.map.channel),aoMapUv:Ve&&m(M.aoMap.channel),lightMapUv:Ze&&m(M.lightMap.channel),bumpMapUv:Kt&&m(M.bumpMap.channel),normalMapUv:Bt&&m(M.normalMap.channel),displacementMapUv:wi&&m(M.displacementMap.channel),emissiveMapUv:ae&&m(M.emissiveMap.channel),metalnessMapUv:Ti&&m(M.metalnessMap.channel),roughnessMapUv:hi&&m(M.roughnessMap.channel),anisotropyMapUv:De&&m(M.anisotropyMap.channel),clearcoatMapUv:ke&&m(M.clearcoatMap.channel),clearcoatNormalMapUv:it&&m(M.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Qe&&m(M.clearcoatRoughnessMap.channel),iridescenceMapUv:Me&&m(M.iridescenceMap.channel),iridescenceThicknessMapUv:Pe&&m(M.iridescenceThicknessMap.channel),sheenColorMapUv:ut&&m(M.sheenColorMap.channel),sheenRoughnessMapUv:bt&&m(M.sheenRoughnessMap.channel),specularMapUv:qe&&m(M.specularMap.channel),specularColorMapUv:Je&&m(M.specularColorMap.channel),specularIntensityMapUv:Wt&&m(M.specularIntensityMap.channel),transmissionMapUv:Ut&&m(M.transmissionMap.channel),thicknessMapUv:yi&&m(M.thicknessMap.channel),alphaMapUv:rt&&m(M.alphaMap.channel),vertexTangents:!!N.attributes.tangent&&(Bt||rr),vertexNormals:!!N.attributes.normal,vertexColors:M.vertexColors,vertexAlphas:M.vertexColors===!0&&!!N.attributes.color&&N.attributes.color.itemSize===4,pointsUvs:w.isPoints===!0&&!!N.attributes.uv&&(be||rt),fog:!!O,useFog:M.fog===!0,fogExp2:!!O&&O.isFogExp2,flatShading:M.wireframe===!1&&(M.flatShading===!0||N.attributes.normal===void 0&&Bt===!1&&(M.isMeshLambertMaterial||M.isMeshPhongMaterial||M.isMeshStandardMaterial||M.isMeshPhysicalMaterial)),sizeAttenuation:M.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:me,skinning:w.isSkinnedMesh===!0,morphTargets:N.morphAttributes.position!==void 0,morphNormals:N.morphAttributes.normal!==void 0,morphColors:N.morphAttributes.color!==void 0,morphTargetsCount:j,morphTextureStride:ue,numDirLights:I.directional.length,numPointLights:I.point.length,numSpotLights:I.spot.length,numSpotLightMaps:I.spotLightMap.length,numRectAreaLights:I.rectArea.length,numHemiLights:I.hemi.length,numDirLightShadows:I.directionalShadowMap.length,numPointLightShadows:I.pointShadowMap.length,numSpotLightShadows:I.spotShadowMap.length,numSpotLightShadowsWithMaps:I.numSpotLightShadowsWithMaps,numLightProbes:I.numLightProbes,numLightProbeGrids:G.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:M.dithering,shadowMapEnabled:n.shadowMap.enabled&&C.length>0,shadowMapType:n.shadowMap.type,toneMapping:Ge,decodeVideoTexture:be&&M.map.isVideoTexture===!0&&mi.getTransfer(M.map.colorSpace)===nr,decodeVideoTextureEmissive:ae&&M.emissiveMap.isVideoTexture===!0&&mi.getTransfer(M.emissiveMap.colorSpace)===nr,premultipliedAlpha:M.premultipliedAlpha,doubleSided:M.side===Xs,flipSided:M.side===On,useDepthPacking:M.depthPacking>=0,depthPacking:M.depthPacking||0,index0AttributeName:M.index0AttributeName,extensionClipCullDistance:nt&&M.extensions.clipCullDistance===!0&&t.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(nt&&M.extensions.multiDraw===!0||de)&&t.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:t.has("KHR_parallel_shader_compile"),customProgramCacheKey:M.customProgramCacheKey()};return Mt.vertexUv1s=l.has(1),Mt.vertexUv2s=l.has(2),Mt.vertexUv3s=l.has(3),l.clear(),Mt}function p(M){let I=[];if(M.shaderID?I.push(M.shaderID):(I.push(M.customVertexShaderID),I.push(M.customFragmentShaderID)),M.defines!==void 0)for(let C in M.defines)I.push(C),I.push(M.defines[C]);return M.isRawShaderMaterial===!1&&(_(I,M),v(I,M),I.push(n.outputColorSpace)),I.push(M.customProgramCacheKey),I.join()}function _(M,I){M.push(I.precision),M.push(I.outputColorSpace),M.push(I.envMapMode),M.push(I.envMapCubeUVHeight),M.push(I.mapUv),M.push(I.alphaMapUv),M.push(I.lightMapUv),M.push(I.aoMapUv),M.push(I.bumpMapUv),M.push(I.normalMapUv),M.push(I.displacementMapUv),M.push(I.emissiveMapUv),M.push(I.metalnessMapUv),M.push(I.roughnessMapUv),M.push(I.anisotropyMapUv),M.push(I.clearcoatMapUv),M.push(I.clearcoatNormalMapUv),M.push(I.clearcoatRoughnessMapUv),M.push(I.iridescenceMapUv),M.push(I.iridescenceThicknessMapUv),M.push(I.sheenColorMapUv),M.push(I.sheenRoughnessMapUv),M.push(I.specularMapUv),M.push(I.specularColorMapUv),M.push(I.specularIntensityMapUv),M.push(I.transmissionMapUv),M.push(I.thicknessMapUv),M.push(I.combine),M.push(I.fogExp2),M.push(I.sizeAttenuation),M.push(I.morphTargetsCount),M.push(I.morphAttributeCount),M.push(I.numDirLights),M.push(I.numPointLights),M.push(I.numSpotLights),M.push(I.numSpotLightMaps),M.push(I.numHemiLights),M.push(I.numRectAreaLights),M.push(I.numDirLightShadows),M.push(I.numPointLightShadows),M.push(I.numSpotLightShadows),M.push(I.numSpotLightShadowsWithMaps),M.push(I.numLightProbes),M.push(I.shadowMapType),M.push(I.toneMapping),M.push(I.numClippingPlanes),M.push(I.numClipIntersection),M.push(I.depthPacking)}function v(M,I){a.disableAll(),I.instancing&&a.enable(0),I.instancingColor&&a.enable(1),I.instancingMorph&&a.enable(2),I.matcap&&a.enable(3),I.envMap&&a.enable(4),I.normalMapObjectSpace&&a.enable(5),I.normalMapTangentSpace&&a.enable(6),I.clearcoat&&a.enable(7),I.iridescence&&a.enable(8),I.alphaTest&&a.enable(9),I.vertexColors&&a.enable(10),I.vertexAlphas&&a.enable(11),I.vertexUv1s&&a.enable(12),I.vertexUv2s&&a.enable(13),I.vertexUv3s&&a.enable(14),I.vertexTangents&&a.enable(15),I.anisotropy&&a.enable(16),I.alphaHash&&a.enable(17),I.batching&&a.enable(18),I.dispersion&&a.enable(19),I.batchingColor&&a.enable(20),I.gradientMap&&a.enable(21),I.packedNormalMap&&a.enable(22),I.vertexNormals&&a.enable(23),M.push(a.mask),a.disableAll(),I.fog&&a.enable(0),I.useFog&&a.enable(1),I.flatShading&&a.enable(2),I.logarithmicDepthBuffer&&a.enable(3),I.reversedDepthBuffer&&a.enable(4),I.skinning&&a.enable(5),I.morphTargets&&a.enable(6),I.morphNormals&&a.enable(7),I.morphColors&&a.enable(8),I.premultipliedAlpha&&a.enable(9),I.shadowMapEnabled&&a.enable(10),I.doubleSided&&a.enable(11),I.flipSided&&a.enable(12),I.useDepthPacking&&a.enable(13),I.dithering&&a.enable(14),I.transmission&&a.enable(15),I.sheen&&a.enable(16),I.opaque&&a.enable(17),I.pointsUvs&&a.enable(18),I.decodeVideoTexture&&a.enable(19),I.decodeVideoTextureEmissive&&a.enable(20),I.alphaToCoverage&&a.enable(21),I.numLightProbeGrids>0&&a.enable(22),M.push(a.mask)}function E(M){let I=h[M.type],C;if(I){let L=Rl[I];C=G2.clone(L.uniforms)}else C=M.uniforms;return C}function S(M,I){let C=f.get(I);return C!==void 0?++C.usedTimes:(C=new Poe(n,I,M,r),c.push(C),f.set(I,C)),C}function T(M){if(--M.usedTimes===0){let I=c.indexOf(M);c[I]=c[c.length-1],c.pop(),f.delete(M.cacheKey),M.destroy()}}function A(M){o.remove(M)}function R(){o.dispose()}return{getParameters:g,getProgramCacheKey:p,getUniforms:E,acquireProgram:S,releaseProgram:T,releaseShaderCache:A,programs:c,dispose:R}}function Noe(){let n=new WeakMap;function e(a){return n.has(a)}function t(a){let o=n.get(a);return o===void 0&&(o={},n.set(a,o)),o}function i(a){n.delete(a)}function r(a,o,l){n.get(a)[o]=l}function s(){n=new WeakMap}return{has:e,get:t,remove:i,update:r,dispose:s}}function woe(n,e){return n.groupOrder!==e.groupOrder?n.groupOrder-e.groupOrder:n.renderOrder!==e.renderOrder?n.renderOrder-e.renderOrder:n.material.id!==e.material.id?n.material.id-e.material.id:n.materialVariant!==e.materialVariant?n.materialVariant-e.materialVariant:n.z!==e.z?n.z-e.z:n.id-e.id}function aU(n,e){return n.groupOrder!==e.groupOrder?n.groupOrder-e.groupOrder:n.renderOrder!==e.renderOrder?n.renderOrder-e.renderOrder:n.z!==e.z?e.z-n.z:n.id-e.id}function oU(){let n=[],e=0,t=[],i=[],r=[];function s(){e=0,t.length=0,i.length=0,r.length=0}function a(u){let h=0;return u.isInstancedMesh&&(h+=2),u.isSkinnedMesh&&(h+=1),h}function o(u,h,m,g,p,_){let v=n[e];return v===void 0?(v={id:u.id,object:u,geometry:h,material:m,materialVariant:a(u),groupOrder:g,renderOrder:u.renderOrder,z:p,group:_},n[e]=v):(v.id=u.id,v.object=u,v.geometry=h,v.material=m,v.materialVariant=a(u),v.groupOrder=g,v.renderOrder=u.renderOrder,v.z=p,v.group=_),e++,v}function l(u,h,m,g,p,_){let v=o(u,h,m,g,p,_);m.transmission>0?i.push(v):m.transparent===!0?r.push(v):t.push(v)}function c(u,h,m,g,p,_){let v=o(u,h,m,g,p,_);m.transmission>0?i.unshift(v):m.transparent===!0?r.unshift(v):t.unshift(v)}function f(u,h){t.length>1&&t.sort(u||woe),i.length>1&&i.sort(h||aU),r.length>1&&r.sort(h||aU)}function d(){for(let u=e,h=n.length;u<h;u++){let m=n[u];if(m.id===null)break;m.id=null,m.object=null,m.geometry=null,m.material=null,m.group=null}}return{opaque:t,transmissive:i,transparent:r,init:s,push:l,unshift:c,finish:d,sort:f}}function Foe(){let n=new WeakMap;function e(i,r){let s=n.get(i),a;return s===void 0?(a=new oU,n.set(i,[a])):r>=s.length?(a=new oU,s.push(a)):a=s[r],a}function t(){n=new WeakMap}return{get:e,dispose:t}}function Boe(){let n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new ie,color:new mt};break;case"SpotLight":t={position:new ie,direction:new ie,color:new mt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new ie,color:new mt,distance:0,decay:0};break;case"HemisphereLight":t={direction:new ie,skyColor:new mt,groundColor:new mt};break;case"RectAreaLight":t={color:new mt,position:new ie,halfWidth:new ie,halfHeight:new ie};break}return n[e.id]=t,t}}}function Uoe(){let n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ct};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ct};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ct,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}function Goe(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function koe(n){let e=new Boe,t=Uoe(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new ie);let r=new ie,s=new pi,a=new pi;function o(c){let f=0,d=0,u=0;for(let I=0;I<9;I++)i.probe[I].set(0,0,0);let h=0,m=0,g=0,p=0,_=0,v=0,E=0,S=0,T=0,A=0,R=0;c.sort(Goe);for(let I=0,C=c.length;I<C;I++){let L=c[I],w=L.color,G=L.intensity,O=L.distance,N=null;if(L.shadow&&L.shadow.map&&(L.shadow.map.texture.format===wf?N=L.shadow.map.texture:N=L.shadow.map.depthTexture||L.shadow.map.texture),L.isAmbientLight)f+=w.r*G,d+=w.g*G,u+=w.b*G;else if(L.isLightProbe){for(let B=0;B<9;B++)i.probe[B].addScaledVector(L.sh.coefficients[B],G);R++}else if(L.isDirectionalLight){let B=e.get(L);if(B.color.copy(L.color).multiplyScalar(L.intensity),L.castShadow){let V=L.shadow,q=t.get(L);q.shadowIntensity=V.intensity,q.shadowBias=V.bias,q.shadowNormalBias=V.normalBias,q.shadowRadius=V.radius,q.shadowMapSize=V.mapSize,i.directionalShadow[h]=q,i.directionalShadowMap[h]=N,i.directionalShadowMatrix[h]=L.shadow.matrix,v++}i.directional[h]=B,h++}else if(L.isSpotLight){let B=e.get(L);B.position.setFromMatrixPosition(L.matrixWorld),B.color.copy(w).multiplyScalar(G),B.distance=O,B.coneCos=Math.cos(L.angle),B.penumbraCos=Math.cos(L.angle*(1-L.penumbra)),B.decay=L.decay,i.spot[g]=B;let V=L.shadow;if(L.map&&(i.spotLightMap[T]=L.map,T++,V.updateMatrices(L),L.castShadow&&A++),i.spotLightMatrix[g]=V.matrix,L.castShadow){let q=t.get(L);q.shadowIntensity=V.intensity,q.shadowBias=V.bias,q.shadowNormalBias=V.normalBias,q.shadowRadius=V.radius,q.shadowMapSize=V.mapSize,i.spotShadow[g]=q,i.spotShadowMap[g]=N,S++}g++}else if(L.isRectAreaLight){let B=e.get(L);B.color.copy(w).multiplyScalar(G),B.halfWidth.set(L.width*.5,0,0),B.halfHeight.set(0,L.height*.5,0),i.rectArea[p]=B,p++}else if(L.isPointLight){let B=e.get(L);if(B.color.copy(L.color).multiplyScalar(L.intensity),B.distance=L.distance,B.decay=L.decay,L.castShadow){let V=L.shadow,q=t.get(L);q.shadowIntensity=V.intensity,q.shadowBias=V.bias,q.shadowNormalBias=V.normalBias,q.shadowRadius=V.radius,q.shadowMapSize=V.mapSize,q.shadowCameraNear=V.camera.near,q.shadowCameraFar=V.camera.far,i.pointShadow[m]=q,i.pointShadowMap[m]=N,i.pointShadowMatrix[m]=L.shadow.matrix,E++}i.point[m]=B,m++}else if(L.isHemisphereLight){let B=e.get(L);B.skyColor.copy(L.color).multiplyScalar(G),B.groundColor.copy(L.groundColor).multiplyScalar(G),i.hemi[_]=B,_++}}p>0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Tt.LTC_FLOAT_1,i.rectAreaLTC2=Tt.LTC_FLOAT_2):(i.rectAreaLTC1=Tt.LTC_HALF_1,i.rectAreaLTC2=Tt.LTC_HALF_2)),i.ambient[0]=f,i.ambient[1]=d,i.ambient[2]=u;let M=i.hash;(M.directionalLength!==h||M.pointLength!==m||M.spotLength!==g||M.rectAreaLength!==p||M.hemiLength!==_||M.numDirectionalShadows!==v||M.numPointShadows!==E||M.numSpotShadows!==S||M.numSpotMaps!==T||M.numLightProbes!==R)&&(i.directional.length=h,i.spot.length=g,i.rectArea.length=p,i.point.length=m,i.hemi.length=_,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.pointShadow.length=E,i.pointShadowMap.length=E,i.spotShadow.length=S,i.spotShadowMap.length=S,i.directionalShadowMatrix.length=v,i.pointShadowMatrix.length=E,i.spotLightMatrix.length=S+T-A,i.spotLightMap.length=T,i.numSpotLightShadowsWithMaps=A,i.numLightProbes=R,M.directionalLength=h,M.pointLength=m,M.spotLength=g,M.rectAreaLength=p,M.hemiLength=_,M.numDirectionalShadows=v,M.numPointShadows=E,M.numSpotShadows=S,M.numSpotMaps=T,M.numLightProbes=R,i.version=Voe++)}function l(c,f){let d=0,u=0,h=0,m=0,g=0,p=f.matrixWorldInverse;for(let _=0,v=c.length;_<v;_++){let E=c[_];if(E.isDirectionalLight){let S=i.directional[d];S.direction.setFromMatrixPosition(E.matrixWorld),r.setFromMatrixPosition(E.target.matrixWorld),S.direction.sub(r),S.direction.transformDirection(p),d++}else if(E.isSpotLight){let S=i.spot[h];S.position.setFromMatrixPosition(E.matrixWorld),S.position.applyMatrix4(p),S.direction.setFromMatrixPosition(E.matrixWorld),r.setFromMatrixPosition(E.target.matrixWorld),S.direction.sub(r),S.direction.transformDirection(p),h++}else if(E.isRectAreaLight){let S=i.rectArea[m];S.position.setFromMatrixPosition(E.matrixWorld),S.position.applyMatrix4(p),a.identity(),s.copy(E.matrixWorld),s.premultiply(p),a.extractRotation(s),S.halfWidth.set(E.width*.5,0,0),S.halfHeight.set(0,E.height*.5,0),S.halfWidth.applyMatrix4(a),S.halfHeight.applyMatrix4(a),m++}else if(E.isPointLight){let S=i.point[u];S.position.setFromMatrixPosition(E.matrixWorld),S.position.applyMatrix4(p),u++}else if(E.isHemisphereLight){let S=i.hemi[g];S.direction.setFromMatrixPosition(E.matrixWorld),S.direction.transformDirection(p),g++}}}return{setup:o,setupView:l,state:i}}function lU(n){let e=new koe(n),t=[],i=[],r=[];function s(u){d.camera=u,t.length=0,i.length=0,r.length=0}function a(u){t.push(u)}function o(u){i.push(u)}function l(u){r.push(u)}function c(){e.setup(t)}function f(u){e.setupView(t,u)}let d={lightsArray:t,shadowsArray:i,lightProbeGridArray:r,camera:null,lights:e,transmissionRenderTarget:{},textureUnits:0};return{init:s,state:d,setupLights:c,setupLightsView:f,pushLight:a,pushShadow:o,pushLightProbeGrid:l}}function zoe(n){let e=new WeakMap;function t(r,s=0){let a=e.get(r),o;return a===void 0?(o=new lU(n),e.set(r,[o])):s>=a.length?(o=new lU(n),a.push(o)):o=a[s],o}function i(){e=new WeakMap}return{get:t,dispose:i}}function Koe(n,e,t){let i=new hm,r=new Ct,s=new Ct,a=new dr,o=new hT,l=new mT,c={},f=t.maxTextureSize,d={[va]:On,[On]:va,[Xs]:Xs},u=new Sa({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Ct},radius:{value:4}},vertexShader:Woe,fragmentShader:Hoe}),h=u.clone();h.defines.HORIZONTAL_PASS=1;let m=new Bi;m.setAttribute("position",new Tr(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let g=new ci(m,u),p=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=B_;let _=this.type;this.render=function(A,R,M){if(p.enabled===!1||p.autoUpdate===!1&&p.needsUpdate===!1||A.length===0)return;this.type===bT&&(Nt("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=B_);let I=n.getRenderTarget(),C=n.getActiveCubeFace(),L=n.getActiveMipmapLevel(),w=n.state;w.setBlending(Tl),w.buffers.depth.getReversed()===!0?w.buffers.color.setClear(0,0,0,0):w.buffers.color.setClear(1,1,1,1),w.buffers.depth.setTest(!0),w.setScissorTest(!1);let G=_!==this.type;G&&R.traverse(function(O){O.material&&(Array.isArray(O.material)?O.material.forEach(N=>N.needsUpdate=!0):O.material.needsUpdate=!0)});for(let O=0,N=A.length;O<N;O++){let B=A[O],V=B.shadow;if(V===void 0){Nt("WebGLShadowMap:",B,"has no shadow.");continue}if(V.autoUpdate===!1&&V.needsUpdate===!1)continue;r.copy(V.mapSize);let q=V.getFrameExtents();r.multiply(q),s.copy(V.mapSize),(r.x>f||r.y>f)&&(r.x>f&&(s.x=Math.floor(f/q.x),r.x=s.x*q.x,V.mapSize.x=s.x),r.y>f&&(s.y=Math.floor(f/q.y),r.y=s.y*q.y,V.mapSize.y=s.y));let K=n.state.buffers.depth.getReversed();if(V.camera._reversedDepth=K,V.map===null||G===!0){if(V.map!==null&&(V.map.depthTexture!==null&&(V.map.depthTexture.dispose(),V.map.depthTexture=null),V.map.dispose()),this.type===Sm){if(B.isPointLight){Nt("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}V.map=new Ea(r.x,r.y,{format:wf,type:Al,minFilter:zr,magFilter:zr,generateMipmaps:!1}),V.map.texture.name=B.name+".shadowMap",V.map.depthTexture=new mc(r.x,r.y,Ta),V.map.depthTexture.name=B.name+".shadowMapDepth",V.map.depthTexture.format=hl,V.map.depthTexture.compareFunction=null,V.map.depthTexture.minFilter=kr,V.map.depthTexture.magFilter=kr}else B.isPointLight?(V.map=new vA(r.x),V.map.depthTexture=new dT(r.x,Co)):(V.map=new Ea(r.x,r.y),V.map.depthTexture=new mc(r.x,r.y,Co)),V.map.depthTexture.name=B.name+".shadowMap",V.map.depthTexture.format=hl,this.type===B_?(V.map.depthTexture.compareFunction=K?mA:hA,V.map.depthTexture.minFilter=zr,V.map.depthTexture.magFilter=zr):(V.map.depthTexture.compareFunction=null,V.map.depthTexture.minFilter=kr,V.map.depthTexture.magFilter=kr);V.camera.updateProjectionMatrix()}let J=V.map.isWebGLCubeRenderTarget?6:1;for(let Y=0;Y<J;Y++){if(V.map.isWebGLCubeRenderTarget)n.setRenderTarget(V.map,Y),n.clear();else{Y===0&&(n.setRenderTarget(V.map),n.clear());let j=V.getViewport(Y);a.set(s.x*j.x,s.y*j.y,s.x*j.z,s.y*j.w),w.viewport(a)}if(B.isPointLight){let j=V.camera,ue=V.matrix,Ee=B.distance||j.far;Ee!==j.far&&(j.far=Ee,j.updateProjectionMatrix()),Z_.setFromMatrixPosition(B.matrixWorld),j.position.copy(Z_),fC.copy(j.position),fC.add(Xoe[Y]),j.up.copy(Yoe[Y]),j.lookAt(fC),j.updateMatrixWorld(),ue.makeTranslation(-Z_.x,-Z_.y,-Z_.z),cU.multiplyMatrices(j.projectionMatrix,j.matrixWorldInverse),V._frustum.setFromProjectionMatrix(cU,j.coordinateSystem,j.reversedDepth)}else V.updateMatrices(B);i=V.getFrustum(),S(R,M,V.camera,B,this.type)}V.isPointLightShadow!==!0&&this.type===Sm&&v(V,M),V.needsUpdate=!1}_=this.type,p.needsUpdate=!1,n.setRenderTarget(I,C,L)};function v(A,R){let M=e.update(g);u.defines.VSM_SAMPLES!==A.blurSamples&&(u.defines.VSM_SAMPLES=A.blurSamples,h.defines.VSM_SAMPLES=A.blurSamples,u.needsUpdate=!0,h.needsUpdate=!0),A.mapPass===null&&(A.mapPass=new Ea(r.x,r.y,{format:wf,type:Al})),u.uniforms.shadow_pass.value=A.map.depthTexture,u.uniforms.resolution.value=A.mapSize,u.uniforms.radius.value=A.radius,n.setRenderTarget(A.mapPass),n.clear(),n.renderBufferDirect(R,null,M,u,g,null),h.uniforms.shadow_pass.value=A.mapPass.texture,h.uniforms.resolution.value=A.mapSize,h.uniforms.radius.value=A.radius,n.setRenderTarget(A.map),n.clear(),n.renderBufferDirect(R,null,M,h,g,null)}function E(A,R,M,I){let C=null,L=M.isPointLight===!0?A.customDistanceMaterial:A.customDepthMaterial;if(L!==void 0)C=L;else if(C=M.isPointLight===!0?l:o,n.localClippingEnabled&&R.clipShadows===!0&&Array.isArray(R.clippingPlanes)&&R.clippingPlanes.length!==0||R.displacementMap&&R.displacementScale!==0||R.alphaMap&&R.alphaTest>0||R.map&&R.alphaTest>0||R.alphaToCoverage===!0){let w=C.uuid,G=R.uuid,O=c[w];O===void 0&&(O={},c[w]=O);let N=O[G];N===void 0&&(N=C.clone(),O[G]=N,R.addEventListener("dispose",T)),C=N}if(C.visible=R.visible,C.wireframe=R.wireframe,I===Sm?C.side=R.shadowSide!==null?R.shadowSide:R.side:C.side=R.shadowSide!==null?R.shadowSide:d[R.side],C.alphaMap=R.alphaMap,C.alphaTest=R.alphaToCoverage===!0?.5:R.alphaTest,C.map=R.map,C.clipShadows=R.clipShadows,C.clippingPlanes=R.clippingPlanes,C.clipIntersection=R.clipIntersection,C.displacementMap=R.displacementMap,C.displacementScale=R.displacementScale,C.displacementBias=R.displacementBias,C.wireframeLinewidth=R.wireframeLinewidth,C.linewidth=R.linewidth,M.isPointLight===!0&&C.isMeshDistanceMaterial===!0){let w=n.properties.get(C);w.light=M}return C}function S(A,R,M,I,C){if(A.visible===!1)return;if(A.layers.test(R.layers)&&(A.isMesh||A.isLine||A.isPoints)&&(A.castShadow||A.receiveShadow&&C===Sm)&&(!A.frustumCulled||i.intersectsObject(A))){A.modelViewMatrix.multiplyMatrices(M.matrixWorldInverse,A.matrixWorld);let G=e.update(A),O=A.material;if(Array.isArray(O)){let N=G.groups;for(let B=0,V=N.length;B<V;B++){let q=N[B],K=O[q.materialIndex];if(K&&K.visible){let J=E(A,K,I,C);A.onBeforeShadow(n,A,R,M,G,J,q),n.renderBufferDirect(M,null,G,J,A,q),A.onAfterShadow(n,A,R,M,G,J,q)}}}else if(O.visible){let N=E(A,O,I,C);A.onBeforeShadow(n,A,R,M,G,N,null),n.renderBufferDirect(M,null,G,N,A,null),A.onAfterShadow(n,A,R,M,G,N,null)}}let w=A.children;for(let G=0,O=w.length;G<O;G++)S(w[G],R,M,I,C)}function T(A){A.target.removeEventListener("dispose",T);for(let M in c){let I=c[M],C=A.target.uuid;C in I&&(I[C].dispose(),delete I[C])}}}function joe(n,e){function t(){let oe=!1,rt=new dr,Ce=null,ft=new dr(0,0,0,0);return{setMask:function(nt){Ce!==nt&&!oe&&(n.colorMask(nt,nt,nt,nt),Ce=nt)},setLocked:function(nt){oe=nt},setClear:function(nt,Ge,Mt,qt,Er){Er===!0&&(nt*=qt,Ge*=qt,Mt*=qt),rt.set(nt,Ge,Mt,qt),ft.equals(rt)===!1&&(n.clearColor(nt,Ge,Mt,qt),ft.copy(rt))},reset:function(){oe=!1,Ce=null,ft.set(-1,0,0,0)}}}function i(){let oe=!1,rt=!1,Ce=null,ft=null,nt=null;return{setReversed:function(Ge){if(rt!==Ge){let Mt=e.get("EXT_clip_control");Ge?Mt.clipControlEXT(Mt.LOWER_LEFT_EXT,Mt.ZERO_TO_ONE_EXT):Mt.clipControlEXT(Mt.LOWER_LEFT_EXT,Mt.NEGATIVE_ONE_TO_ONE_EXT),rt=Ge;let qt=nt;nt=null,this.setClear(qt)}},getReversed:function(){return rt},setTest:function(Ge){Ge?ne(n.DEPTH_TEST):me(n.DEPTH_TEST)},setMask:function(Ge){Ce!==Ge&&!oe&&(n.depthMask(Ge),Ce=Ge)},setFunc:function(Ge){if(rt&&(Ge=B2[Ge]),ft!==Ge){switch(Ge){case QS:n.depthFunc(n.NEVER);break;case $S:n.depthFunc(n.ALWAYS);break;case JS:n.depthFunc(n.LESS);break;case ou:n.depthFunc(n.LEQUAL);break;case eT:n.depthFunc(n.EQUAL);break;case tT:n.depthFunc(n.GEQUAL);break;case iT:n.depthFunc(n.GREATER);break;case rT:n.depthFunc(n.NOTEQUAL);break;default:n.depthFunc(n.LEQUAL)}ft=Ge}},setLocked:function(Ge){oe=Ge},setClear:function(Ge){nt!==Ge&&(nt=Ge,rt&&(Ge=1-Ge),n.clearDepth(Ge))},reset:function(){oe=!1,Ce=null,ft=null,nt=null,rt=!1}}}function r(){let oe=!1,rt=null,Ce=null,ft=null,nt=null,Ge=null,Mt=null,qt=null,Er=null;return{setTest:function(_i){oe||(_i?ne(n.STENCIL_TEST):me(n.STENCIL_TEST))},setMask:function(_i){rt!==_i&&!oe&&(n.stencilMask(_i),rt=_i)},setFunc:function(_i,Gr,cr){(Ce!==_i||ft!==Gr||nt!==cr)&&(n.stencilFunc(_i,Gr,cr),Ce=_i,ft=Gr,nt=cr)},setOp:function(_i,Gr,cr){(Ge!==_i||Mt!==Gr||qt!==cr)&&(n.stencilOp(_i,Gr,cr),Ge=_i,Mt=Gr,qt=cr)},setLocked:function(_i){oe=_i},setClear:function(_i){Er!==_i&&(n.clearStencil(_i),Er=_i)},reset:function(){oe=!1,rt=null,Ce=null,ft=null,nt=null,Ge=null,Mt=null,qt=null,Er=null}}}let s=new t,a=new i,o=new r,l=new WeakMap,c=new WeakMap,f={},d={},u={},h=new WeakMap,m=[],g=null,p=!1,_=null,v=null,E=null,S=null,T=null,A=null,R=null,M=new mt(0,0,0),I=0,C=!1,L=null,w=null,G=null,O=null,N=null,B=n.getParameter(n.MAX_COMBINED_TEXTURE_IMAGE_UNITS),V=!1,q=0,K=n.getParameter(n.VERSION);K.indexOf("WebGL")!==-1?(q=parseFloat(/^WebGL (\d)/.exec(K)[1]),V=q>=1):K.indexOf("OpenGL ES")!==-1&&(q=parseFloat(/^OpenGL ES (\d)/.exec(K)[1]),V=q>=2);let J=null,Y={},j=n.getParameter(n.SCISSOR_BOX),ue=n.getParameter(n.VIEWPORT),Ee=new dr().fromArray(j),Ue=new dr().fromArray(ue);function se(oe,rt,Ce,ft){let nt=new Uint8Array(4),Ge=n.createTexture();n.bindTexture(oe,Ge),n.texParameteri(oe,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(oe,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let Mt=0;Mt<Ce;Mt++)oe===n.TEXTURE_3D||oe===n.TEXTURE_2D_ARRAY?n.texImage3D(rt,0,n.RGBA,1,1,ft,0,n.RGBA,n.UNSIGNED_BYTE,nt):n.texImage2D(rt+Mt,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,nt);return Ge}let ve={};ve[n.TEXTURE_2D]=se(n.TEXTURE_2D,n.TEXTURE_2D,1),ve[n.TEXTURE_CUBE_MAP]=se(n.TEXTURE_CUBE_MAP,n.TEXTURE_CUBE_MAP_POSITIVE_X,6),ve[n.TEXTURE_2D_ARRAY]=se(n.TEXTURE_2D_ARRAY,n.TEXTURE_2D_ARRAY,1,1),ve[n.TEXTURE_3D]=se(n.TEXTURE_3D,n.TEXTURE_3D,1,1),s.setClear(0,0,0,1),a.setClear(1),o.setClear(0),ne(n.DEPTH_TEST),a.setFunc(ou),Kt(!1),Bt(II),ne(n.CULL_FACE),Ve(Tl);function ne(oe){f[oe]!==!0&&(n.enable(oe),f[oe]=!0)}function me(oe){f[oe]!==!1&&(n.disable(oe),f[oe]=!1)}function Le(oe,rt){return u[oe]!==rt?(n.bindFramebuffer(oe,rt),u[oe]=rt,oe===n.DRAW_FRAMEBUFFER&&(u[n.FRAMEBUFFER]=rt),oe===n.FRAMEBUFFER&&(u[n.DRAW_FRAMEBUFFER]=rt),!0):!1}function de(oe,rt){let Ce=m,ft=!1;if(oe){Ce=h.get(rt),Ce===void 0&&(Ce=[],h.set(rt,Ce));let nt=oe.textures;if(Ce.length!==nt.length||Ce[0]!==n.COLOR_ATTACHMENT0){for(let Ge=0,Mt=nt.length;Ge<Mt;Ge++)Ce[Ge]=n.COLOR_ATTACHMENT0+Ge;Ce.length=nt.length,ft=!0}}else Ce[0]!==n.BACK&&(Ce[0]=n.BACK,ft=!0);ft&&n.drawBuffers(Ce)}function be(oe){return g!==oe?(n.useProgram(oe),g=oe,!0):!1}let we={[bf]:n.FUNC_ADD,[i2]:n.FUNC_SUBTRACT,[r2]:n.FUNC_REVERSE_SUBTRACT};we[n2]=n.MIN,we[s2]=n.MAX;let dt={[a2]:n.ZERO,[o2]:n.ONE,[l2]:n.SRC_COLOR,[ZS]:n.SRC_ALPHA,[m2]:n.SRC_ALPHA_SATURATE,[u2]:n.DST_COLOR,[f2]:n.DST_ALPHA,[c2]:n.ONE_MINUS_SRC_COLOR,[qS]:n.ONE_MINUS_SRC_ALPHA,[h2]:n.ONE_MINUS_DST_COLOR,[d2]:n.ONE_MINUS_DST_ALPHA,[p2]:n.CONSTANT_COLOR,[g2]:n.ONE_MINUS_CONSTANT_COLOR,[_2]:n.CONSTANT_ALPHA,[v2]:n.ONE_MINUS_CONSTANT_ALPHA};function Ve(oe,rt,Ce,ft,nt,Ge,Mt,qt,Er,_i){if(oe===Tl){p===!0&&(me(n.BLEND),p=!1);return}if(p===!1&&(ne(n.BLEND),p=!0),oe!==t2){if(oe!==_||_i!==C){if((v!==bf||T!==bf)&&(n.blendEquation(n.FUNC_ADD),v=bf,T=bf),_i)switch(oe){case au:n.blendFuncSeparate(n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case CI:n.blendFunc(n.ONE,n.ONE);break;case PI:n.blendFuncSeparate(n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case LI:n.blendFuncSeparate(n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE);break;default:Ht("WebGLState: Invalid blending: ",oe);break}else switch(oe){case au:n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case CI:n.blendFuncSeparate(n.SRC_ALPHA,n.ONE,n.ONE,n.ONE);break;case PI:Ht("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case LI:Ht("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Ht("WebGLState: Invalid blending: ",oe);break}E=null,S=null,A=null,R=null,M.set(0,0,0),I=0,_=oe,C=_i}return}nt=nt||rt,Ge=Ge||Ce,Mt=Mt||ft,(rt!==v||nt!==T)&&(n.blendEquationSeparate(we[rt],we[nt]),v=rt,T=nt),(Ce!==E||ft!==S||Ge!==A||Mt!==R)&&(n.blendFuncSeparate(dt[Ce],dt[ft],dt[Ge],dt[Mt]),E=Ce,S=ft,A=Ge,R=Mt),(qt.equals(M)===!1||Er!==I)&&(n.blendColor(qt.r,qt.g,qt.b,Er),M.copy(qt),I=Er),_=oe,C=!1}function Ze(oe,rt){oe.side===Xs?me(n.CULL_FACE):ne(n.CULL_FACE);let Ce=oe.side===On;rt&&(Ce=!Ce),Kt(Ce),oe.blending===au&&oe.transparent===!1?Ve(Tl):Ve(oe.blending,oe.blendEquation,oe.blendSrc,oe.blendDst,oe.blendEquationAlpha,oe.blendSrcAlpha,oe.blendDstAlpha,oe.blendColor,oe.blendAlpha,oe.premultipliedAlpha),a.setFunc(oe.depthFunc),a.setTest(oe.depthTest),a.setMask(oe.depthWrite),s.setMask(oe.colorWrite);let ft=oe.stencilWrite;o.setTest(ft),ft&&(o.setMask(oe.stencilWriteMask),o.setFunc(oe.stencilFunc,oe.stencilRef,oe.stencilFuncMask),o.setOp(oe.stencilFail,oe.stencilZFail,oe.stencilZPass)),ae(oe.polygonOffset,oe.polygonOffsetFactor,oe.polygonOffsetUnits),oe.alphaToCoverage===!0?ne(n.SAMPLE_ALPHA_TO_COVERAGE):me(n.SAMPLE_ALPHA_TO_COVERAGE)}function Kt(oe){L!==oe&&(oe?n.frontFace(n.CW):n.frontFace(n.CCW),L=oe)}function Bt(oe){oe!==JB?(ne(n.CULL_FACE),oe!==w&&(oe===II?n.cullFace(n.BACK):oe===e2?n.cullFace(n.FRONT):n.cullFace(n.FRONT_AND_BACK))):me(n.CULL_FACE),w=oe}function wi(oe){oe!==G&&(V&&n.lineWidth(oe),G=oe)}function ae(oe,rt,Ce){oe?(ne(n.POLYGON_OFFSET_FILL),(O!==rt||N!==Ce)&&(O=rt,N=Ce,a.getReversed()&&(rt=-rt),n.polygonOffset(rt,Ce))):me(n.POLYGON_OFFSET_FILL)}function Ti(oe){oe?ne(n.SCISSOR_TEST):me(n.SCISSOR_TEST)}function hi(oe){oe===void 0&&(oe=n.TEXTURE0+B-1),J!==oe&&(n.activeTexture(oe),J=oe)}function rr(oe,rt,Ce){Ce===void 0&&(J===null?Ce=n.TEXTURE0+B-1:Ce=J);let ft=Y[Ce];ft===void 0&&(ft={type:void 0,texture:void 0},Y[Ce]=ft),(ft.type!==oe||ft.texture!==rt)&&(J!==Ce&&(n.activeTexture(Ce),J=Ce),n.bindTexture(oe,rt||ve[oe]),ft.type=oe,ft.texture=rt)}function Ke(){let oe=Y[J];oe!==void 0&&oe.type!==void 0&&(n.bindTexture(oe.type,null),oe.type=void 0,oe.texture=void 0)}function ar(){try{n.compressedTexImage2D(...arguments)}catch(oe){Ht("WebGLState:",oe)}}function Z(){try{n.compressedTexImage3D(...arguments)}catch(oe){Ht("WebGLState:",oe)}}function U(){try{n.texSubImage2D(...arguments)}catch(oe){Ht("WebGLState:",oe)}}function ge(){try{n.texSubImage3D(...arguments)}catch(oe){Ht("WebGLState:",oe)}}function De(){try{n.compressedTexSubImage2D(...arguments)}catch(oe){Ht("WebGLState:",oe)}}function ke(){try{n.compressedTexSubImage3D(...arguments)}catch(oe){Ht("WebGLState:",oe)}}function it(){try{n.texStorage2D(...arguments)}catch(oe){Ht("WebGLState:",oe)}}function Qe(){try{n.texStorage3D(...arguments)}catch(oe){Ht("WebGLState:",oe)}}function Me(){try{n.texImage2D(...arguments)}catch(oe){Ht("WebGLState:",oe)}}function Pe(){try{n.texImage3D(...arguments)}catch(oe){Ht("WebGLState:",oe)}}function ut(oe){return d[oe]!==void 0?d[oe]:n.getParameter(oe)}function bt(oe,rt){d[oe]!==rt&&(n.pixelStorei(oe,rt),d[oe]=rt)}function qe(oe){Ee.equals(oe)===!1&&(n.scissor(oe.x,oe.y,oe.z,oe.w),Ee.copy(oe))}function Je(oe){Ue.equals(oe)===!1&&(n.viewport(oe.x,oe.y,oe.z,oe.w),Ue.copy(oe))}function Wt(oe,rt){let Ce=c.get(rt);Ce===void 0&&(Ce=new WeakMap,c.set(rt,Ce));let ft=Ce.get(oe);ft===void 0&&(ft=n.getUniformBlockIndex(rt,oe.name),Ce.set(oe,ft))}function Ut(oe,rt){let ft=c.get(rt).get(oe);l.get(rt)!==ft&&(n.uniformBlockBinding(rt,ft,oe.__bindingPointIndex),l.set(rt,ft))}function yi(){n.disable(n.BLEND),n.disable(n.CULL_FACE),n.disable(n.DEPTH_TEST),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SCISSOR_TEST),n.disable(n.STENCIL_TEST),n.disable(n.SAMPLE_ALPHA_TO_COVERAGE),n.blendEquation(n.FUNC_ADD),n.blendFunc(n.ONE,n.ZERO),n.blendFuncSeparate(n.ONE,n.ZERO,n.ONE,n.ZERO),n.blendColor(0,0,0,0),n.colorMask(!0,!0,!0,!0),n.clearColor(0,0,0,0),n.depthMask(!0),n.depthFunc(n.LESS),a.setReversed(!1),n.clearDepth(1),n.stencilMask(4294967295),n.stencilFunc(n.ALWAYS,0,4294967295),n.stencilOp(n.KEEP,n.KEEP,n.KEEP),n.clearStencil(0),n.cullFace(n.BACK),n.frontFace(n.CCW),n.polygonOffset(0,0),n.activeTexture(n.TEXTURE0),n.bindFramebuffer(n.FRAMEBUFFER,null),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,null),n.bindFramebuffer(n.READ_FRAMEBUFFER,null),n.useProgram(null),n.lineWidth(1),n.scissor(0,0,n.canvas.width,n.canvas.height),n.viewport(0,0,n.canvas.width,n.canvas.height),n.pixelStorei(n.PACK_ALIGNMENT,4),n.pixelStorei(n.UNPACK_ALIGNMENT,4),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,n.BROWSER_DEFAULT_WEBGL),n.pixelStorei(n.PACK_ROW_LENGTH,0),n.pixelStorei(n.PACK_SKIP_PIXELS,0),n.pixelStorei(n.PACK_SKIP_ROWS,0),n.pixelStorei(n.UNPACK_ROW_LENGTH,0),n.pixelStorei(n.UNPACK_IMAGE_HEIGHT,0),n.pixelStorei(n.UNPACK_SKIP_PIXELS,0),n.pixelStorei(n.UNPACK_SKIP_ROWS,0),n.pixelStorei(n.UNPACK_SKIP_IMAGES,0),f={},d={},J=null,Y={},u={},h=new WeakMap,m=[],g=null,p=!1,_=null,v=null,E=null,S=null,T=null,A=null,R=null,M=new mt(0,0,0),I=0,C=!1,L=null,w=null,G=null,O=null,N=null,Ee.set(0,0,n.canvas.width,n.canvas.height),Ue.set(0,0,n.canvas.width,n.canvas.height),s.reset(),a.reset(),o.reset()}return{buffers:{color:s,depth:a,stencil:o},enable:ne,disable:me,bindFramebuffer:Le,drawBuffers:de,useProgram:be,setBlending:Ve,setMaterial:Ze,setFlipSided:Kt,setCullFace:Bt,setLineWidth:wi,setPolygonOffset:ae,setScissorTest:Ti,activeTexture:hi,bindTexture:rr,unbindTexture:Ke,compressedTexImage2D:ar,compressedTexImage3D:Z,texImage2D:Me,texImage3D:Pe,pixelStorei:bt,getParameter:ut,updateUBOMapping:Wt,uniformBlockBinding:Ut,texStorage2D:it,texStorage3D:Qe,texSubImage2D:U,texSubImage3D:ge,compressedTexSubImage2D:De,compressedTexSubImage3D:ke,scissor:qe,viewport:Je,reset:yi}}function Zoe(n,e,t,i,r,s,a){let o=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,l=typeof navigator=="undefined"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new Ct,f=new WeakMap,d=new Set,u,h=new WeakMap,m=!1;try{m=typeof OffscreenCanvas!="undefined"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch(Z){}function g(Z,U){return m?new OffscreenCanvas(Z,U):sm("canvas")}function p(Z,U,ge){let De=1,ke=ar(Z);if((ke.width>ge||ke.height>ge)&&(De=ge/Math.max(ke.width,ke.height)),De<1)if(typeof HTMLImageElement!="undefined"&&Z instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&Z instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&Z instanceof ImageBitmap||typeof VideoFrame!="undefined"&&Z instanceof VideoFrame){let it=Math.floor(De*ke.width),Qe=Math.floor(De*ke.height);u===void 0&&(u=g(it,Qe));let Me=U?g(it,Qe):u;return Me.width=it,Me.height=Qe,Me.getContext("2d").drawImage(Z,0,0,it,Qe),Nt("WebGLRenderer: Texture has been resized from ("+ke.width+"x"+ke.height+") to ("+it+"x"+Qe+")."),Me}else return"data"in Z&&Nt("WebGLRenderer: Image in DataTexture is too big ("+ke.width+"x"+ke.height+")."),Z;return Z}function _(Z){return Z.generateMipmaps}function v(Z){n.generateMipmap(Z)}function E(Z){return Z.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:Z.isWebGL3DRenderTarget?n.TEXTURE_3D:Z.isWebGLArrayRenderTarget||Z.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function S(Z,U,ge,De,ke,it=!1){if(Z!==null){if(n[Z]!==void 0)return n[Z];Nt("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+Z+"'")}let Qe;De&&(Qe=e.get("EXT_texture_norm16"),Qe||Nt("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let Me=U;if(U===n.RED&&(ge===n.FLOAT&&(Me=n.R32F),ge===n.HALF_FLOAT&&(Me=n.R16F),ge===n.UNSIGNED_BYTE&&(Me=n.R8),ge===n.UNSIGNED_SHORT&&Qe&&(Me=Qe.R16_EXT),ge===n.SHORT&&Qe&&(Me=Qe.R16_SNORM_EXT)),U===n.RED_INTEGER&&(ge===n.UNSIGNED_BYTE&&(Me=n.R8UI),ge===n.UNSIGNED_SHORT&&(Me=n.R16UI),ge===n.UNSIGNED_INT&&(Me=n.R32UI),ge===n.BYTE&&(Me=n.R8I),ge===n.SHORT&&(Me=n.R16I),ge===n.INT&&(Me=n.R32I)),U===n.RG&&(ge===n.FLOAT&&(Me=n.RG32F),ge===n.HALF_FLOAT&&(Me=n.RG16F),ge===n.UNSIGNED_BYTE&&(Me=n.RG8),ge===n.UNSIGNED_SHORT&&Qe&&(Me=Qe.RG16_EXT),ge===n.SHORT&&Qe&&(Me=Qe.RG16_SNORM_EXT)),U===n.RG_INTEGER&&(ge===n.UNSIGNED_BYTE&&(Me=n.RG8UI),ge===n.UNSIGNED_SHORT&&(Me=n.RG16UI),ge===n.UNSIGNED_INT&&(Me=n.RG32UI),ge===n.BYTE&&(Me=n.RG8I),ge===n.SHORT&&(Me=n.RG16I),ge===n.INT&&(Me=n.RG32I)),U===n.RGB_INTEGER&&(ge===n.UNSIGNED_BYTE&&(Me=n.RGB8UI),ge===n.UNSIGNED_SHORT&&(Me=n.RGB16UI),ge===n.UNSIGNED_INT&&(Me=n.RGB32UI),ge===n.BYTE&&(Me=n.RGB8I),ge===n.SHORT&&(Me=n.RGB16I),ge===n.INT&&(Me=n.RGB32I)),U===n.RGBA_INTEGER&&(ge===n.UNSIGNED_BYTE&&(Me=n.RGBA8UI),ge===n.UNSIGNED_SHORT&&(Me=n.RGBA16UI),ge===n.UNSIGNED_INT&&(Me=n.RGBA32UI),ge===n.BYTE&&(Me=n.RGBA8I),ge===n.SHORT&&(Me=n.RGBA16I),ge===n.INT&&(Me=n.RGBA32I)),U===n.RGB&&(ge===n.UNSIGNED_SHORT&&Qe&&(Me=Qe.RGB16_EXT),ge===n.SHORT&&Qe&&(Me=Qe.RGB16_SNORM_EXT),ge===n.UNSIGNED_INT_5_9_9_9_REV&&(Me=n.RGB9_E5),ge===n.UNSIGNED_INT_10F_11F_11F_REV&&(Me=n.R11F_G11F_B10F)),U===n.RGBA){let Pe=it?p_:mi.getTransfer(ke);ge===n.FLOAT&&(Me=n.RGBA32F),ge===n.HALF_FLOAT&&(Me=n.RGBA16F),ge===n.UNSIGNED_BYTE&&(Me=Pe===nr?n.SRGB8_ALPHA8:n.RGBA8),ge===n.UNSIGNED_SHORT&&Qe&&(Me=Qe.RGBA16_EXT),ge===n.SHORT&&Qe&&(Me=Qe.RGBA16_SNORM_EXT),ge===n.UNSIGNED_SHORT_4_4_4_4&&(Me=n.RGBA4),ge===n.UNSIGNED_SHORT_5_5_5_1&&(Me=n.RGB5_A1)}return(Me===n.R16F||Me===n.R32F||Me===n.RG16F||Me===n.RG32F||Me===n.RGBA16F||Me===n.RGBA32F)&&e.get("EXT_color_buffer_float"),Me}function T(Z,U){let ge;return Z?U===null||U===Co||U===xm?ge=n.DEPTH24_STENCIL8:U===Ta?ge=n.DEPTH32F_STENCIL8:U===Am&&(ge=n.DEPTH24_STENCIL8,Nt("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):U===null||U===Co||U===xm?ge=n.DEPTH_COMPONENT24:U===Ta?ge=n.DEPTH_COMPONENT32F:U===Am&&(ge=n.DEPTH_COMPONENT16),ge}function A(Z,U){return _(Z)===!0||Z.isFramebufferTexture&&Z.minFilter!==kr&&Z.minFilter!==zr?Math.log2(Math.max(U.width,U.height))+1:Z.mipmaps!==void 0&&Z.mipmaps.length>0?Z.mipmaps.length:Z.isCompressedTexture&&Array.isArray(Z.image)?U.mipmaps.length:1}function R(Z){let U=Z.target;U.removeEventListener("dispose",R),I(U),U.isVideoTexture&&f.delete(U),U.isHTMLTexture&&d.delete(U)}function M(Z){let U=Z.target;U.removeEventListener("dispose",M),L(U)}function I(Z){let U=i.get(Z);if(U.__webglInit===void 0)return;let ge=Z.source,De=h.get(ge);if(De){let ke=De[U.__cacheKey];ke.usedTimes--,ke.usedTimes===0&&C(Z),Object.keys(De).length===0&&h.delete(ge)}i.remove(Z)}function C(Z){let U=i.get(Z);n.deleteTexture(U.__webglTexture);let ge=Z.source,De=h.get(ge);delete De[U.__cacheKey],a.memory.textures--}function L(Z){let U=i.get(Z);if(Z.depthTexture&&(Z.depthTexture.dispose(),i.remove(Z.depthTexture)),Z.isWebGLCubeRenderTarget)for(let De=0;De<6;De++){if(Array.isArray(U.__webglFramebuffer[De]))for(let ke=0;ke<U.__webglFramebuffer[De].length;ke++)n.deleteFramebuffer(U.__webglFramebuffer[De][ke]);else n.deleteFramebuffer(U.__webglFramebuffer[De]);U.__webglDepthbuffer&&n.deleteRenderbuffer(U.__webglDepthbuffer[De])}else{if(Array.isArray(U.__webglFramebuffer))for(let De=0;De<U.__webglFramebuffer.length;De++)n.deleteFramebuffer(U.__webglFramebuffer[De]);else n.deleteFramebuffer(U.__webglFramebuffer);if(U.__webglDepthbuffer&&n.deleteRenderbuffer(U.__webglDepthbuffer),U.__webglMultisampledFramebuffer&&n.deleteFramebuffer(U.__webglMultisampledFramebuffer),U.__webglColorRenderbuffer)for(let De=0;De<U.__webglColorRenderbuffer.length;De++)U.__webglColorRenderbuffer[De]&&n.deleteRenderbuffer(U.__webglColorRenderbuffer[De]);U.__webglDepthRenderbuffer&&n.deleteRenderbuffer(U.__webglDepthRenderbuffer)}let ge=Z.textures;for(let De=0,ke=ge.length;De<ke;De++){let it=i.get(ge[De]);it.__webglTexture&&(n.deleteTexture(it.__webglTexture),a.memory.textures--),i.remove(ge[De])}i.remove(Z)}let w=0;function G(){w=0}function O(){return w}function N(Z){w=Z}function B(){let Z=w;return Z>=r.maxTextures&&Nt("WebGLTextures: Trying to use "+Z+" texture units while this GPU supports only "+r.maxTextures),w+=1,Z}function V(Z){let U=[];return U.push(Z.wrapS),U.push(Z.wrapT),U.push(Z.wrapR||0),U.push(Z.magFilter),U.push(Z.minFilter),U.push(Z.anisotropy),U.push(Z.internalFormat),U.push(Z.format),U.push(Z.type),U.push(Z.generateMipmaps),U.push(Z.premultiplyAlpha),U.push(Z.flipY),U.push(Z.unpackAlignment),U.push(Z.colorSpace),U.join()}function q(Z,U){let ge=i.get(Z);if(Z.isVideoTexture&&rr(Z),Z.isRenderTargetTexture===!1&&Z.isExternalTexture!==!0&&Z.version>0&&ge.__version!==Z.version){let De=Z.image;if(De===null)Nt("WebGLRenderer: Texture marked for update but no image data found.");else if(De.complete===!1)Nt("WebGLRenderer: Texture marked for update but image is incomplete");else{me(ge,Z,U);return}}else Z.isExternalTexture&&(ge.__webglTexture=Z.sourceTexture?Z.sourceTexture:null);t.bindTexture(n.TEXTURE_2D,ge.__webglTexture,n.TEXTURE0+U)}function K(Z,U){let ge=i.get(Z);if(Z.isRenderTargetTexture===!1&&Z.version>0&&ge.__version!==Z.version){me(ge,Z,U);return}else Z.isExternalTexture&&(ge.__webglTexture=Z.sourceTexture?Z.sourceTexture:null);t.bindTexture(n.TEXTURE_2D_ARRAY,ge.__webglTexture,n.TEXTURE0+U)}function J(Z,U){let ge=i.get(Z);if(Z.isRenderTargetTexture===!1&&Z.version>0&&ge.__version!==Z.version){me(ge,Z,U);return}t.bindTexture(n.TEXTURE_3D,ge.__webglTexture,n.TEXTURE0+U)}function Y(Z,U){let ge=i.get(Z);if(Z.isCubeDepthTexture!==!0&&Z.version>0&&ge.__version!==Z.version){Le(ge,Z,U);return}t.bindTexture(n.TEXTURE_CUBE_MAP,ge.__webglTexture,n.TEXTURE0+U)}let j={[ul]:n.REPEAT,[Xa]:n.CLAMP_TO_EDGE,[rm]:n.MIRRORED_REPEAT},ue={[kr]:n.NEAREST,[IT]:n.NEAREST_MIPMAP_NEAREST,[Su]:n.NEAREST_MIPMAP_LINEAR,[zr]:n.LINEAR,[Tm]:n.LINEAR_MIPMAP_NEAREST,[Io]:n.LINEAR_MIPMAP_LINEAR},Ee={[I2]:n.NEVER,[O2]:n.ALWAYS,[C2]:n.LESS,[hA]:n.LEQUAL,[P2]:n.EQUAL,[mA]:n.GEQUAL,[L2]:n.GREATER,[D2]:n.NOTEQUAL};function Ue(Z,U){if(U.type===Ta&&e.has("OES_texture_float_linear")===!1&&(U.magFilter===zr||U.magFilter===Tm||U.magFilter===Su||U.magFilter===Io||U.minFilter===zr||U.minFilter===Tm||U.minFilter===Su||U.minFilter===Io)&&Nt("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(Z,n.TEXTURE_WRAP_S,j[U.wrapS]),n.texParameteri(Z,n.TEXTURE_WRAP_T,j[U.wrapT]),(Z===n.TEXTURE_3D||Z===n.TEXTURE_2D_ARRAY)&&n.texParameteri(Z,n.TEXTURE_WRAP_R,j[U.wrapR]),n.texParameteri(Z,n.TEXTURE_MAG_FILTER,ue[U.magFilter]),n.texParameteri(Z,n.TEXTURE_MIN_FILTER,ue[U.minFilter]),U.compareFunction&&(n.texParameteri(Z,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(Z,n.TEXTURE_COMPARE_FUNC,Ee[U.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(U.magFilter===kr||U.minFilter!==Su&&U.minFilter!==Io||U.type===Ta&&e.has("OES_texture_float_linear")===!1)return;if(U.anisotropy>1||i.get(U).__currentAnisotropy){let ge=e.get("EXT_texture_filter_anisotropic");n.texParameterf(Z,ge.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(U.anisotropy,r.getMaxAnisotropy())),i.get(U).__currentAnisotropy=U.anisotropy}}}function se(Z,U){let ge=!1;Z.__webglInit===void 0&&(Z.__webglInit=!0,U.addEventListener("dispose",R));let De=U.source,ke=h.get(De);ke===void 0&&(ke={},h.set(De,ke));let it=V(U);if(it!==Z.__cacheKey){ke[it]===void 0&&(ke[it]={texture:n.createTexture(),usedTimes:0},a.memory.textures++,ge=!0),ke[it].usedTimes++;let Qe=ke[Z.__cacheKey];Qe!==void 0&&(ke[Z.__cacheKey].usedTimes--,Qe.usedTimes===0&&C(U)),Z.__cacheKey=it,Z.__webglTexture=ke[it].texture}return ge}function ve(Z,U,ge){return Math.floor(Math.floor(Z/ge)/U)}function ne(Z,U,ge,De){let it=Z.updateRanges;if(it.length===0)t.texSubImage2D(n.TEXTURE_2D,0,0,0,U.width,U.height,ge,De,U.data);else{it.sort((bt,qe)=>bt.start-qe.start);let Qe=0;for(let bt=1;bt<it.length;bt++){let qe=it[Qe],Je=it[bt],Wt=qe.start+qe.count,Ut=ve(Je.start,U.width,4),yi=ve(qe.start,U.width,4);Je.start<=Wt+1&&Ut===yi&&ve(Je.start+Je.count-1,U.width,4)===Ut?qe.count=Math.max(qe.count,Je.start+Je.count-qe.start):(++Qe,it[Qe]=Je)}it.length=Qe+1;let Me=t.getParameter(n.UNPACK_ROW_LENGTH),Pe=t.getParameter(n.UNPACK_SKIP_PIXELS),ut=t.getParameter(n.UNPACK_SKIP_ROWS);t.pixelStorei(n.UNPACK_ROW_LENGTH,U.width);for(let bt=0,qe=it.length;bt<qe;bt++){let Je=it[bt],Wt=Math.floor(Je.start/4),Ut=Math.ceil(Je.count/4),yi=Wt%U.width,oe=Math.floor(Wt/U.width),rt=Ut,Ce=1;t.pixelStorei(n.UNPACK_SKIP_PIXELS,yi),t.pixelStorei(n.UNPACK_SKIP_ROWS,oe),t.texSubImage2D(n.TEXTURE_2D,0,yi,oe,rt,Ce,ge,De,U.data)}Z.clearUpdateRanges(),t.pixelStorei(n.UNPACK_ROW_LENGTH,Me),t.pixelStorei(n.UNPACK_SKIP_PIXELS,Pe),t.pixelStorei(n.UNPACK_SKIP_ROWS,ut)}}function me(Z,U,ge){let De=n.TEXTURE_2D;(U.isDataArrayTexture||U.isCompressedArrayTexture)&&(De=n.TEXTURE_2D_ARRAY),U.isData3DTexture&&(De=n.TEXTURE_3D);let ke=se(Z,U),it=U.source;t.bindTexture(De,Z.__webglTexture,n.TEXTURE0+ge);let Qe=i.get(it);if(it.version!==Qe.__version||ke===!0){if(t.activeTexture(n.TEXTURE0+ge),(typeof ImageBitmap!="undefined"&&U.image instanceof ImageBitmap)===!1){let Ce=mi.getPrimaries(mi.workingColorSpace),ft=U.colorSpace===vc?null:mi.getPrimaries(U.colorSpace),nt=U.colorSpace===vc||Ce===ft?n.NONE:n.BROWSER_DEFAULT_WEBGL;t.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,U.flipY),t.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,U.premultiplyAlpha),t.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,nt)}t.pixelStorei(n.UNPACK_ALIGNMENT,U.unpackAlignment);let Pe=p(U.image,!1,r.maxTextureSize);Pe=Ke(U,Pe);let ut=s.convert(U.format,U.colorSpace),bt=s.convert(U.type),qe=S(U.internalFormat,ut,bt,U.normalized,U.colorSpace,U.isVideoTexture);Ue(De,U);let Je,Wt=U.mipmaps,Ut=U.isVideoTexture!==!0,yi=Qe.__version===void 0||ke===!0,oe=it.dataReady,rt=A(U,Pe);if(U.isDepthTexture)qe=T(U.format===Nf,U.type),yi&&(Ut?t.texStorage2D(n.TEXTURE_2D,1,qe,Pe.width,Pe.height):t.texImage2D(n.TEXTURE_2D,0,qe,Pe.width,Pe.height,0,ut,bt,null));else if(U.isDataTexture)if(Wt.length>0){Ut&&yi&&t.texStorage2D(n.TEXTURE_2D,rt,qe,Wt[0].width,Wt[0].height);for(let Ce=0,ft=Wt.length;Ce<ft;Ce++)Je=Wt[Ce],Ut?oe&&t.texSubImage2D(n.TEXTURE_2D,Ce,0,0,Je.width,Je.height,ut,bt,Je.data):t.texImage2D(n.TEXTURE_2D,Ce,qe,Je.width,Je.height,0,ut,bt,Je.data);U.generateMipmaps=!1}else Ut?(yi&&t.texStorage2D(n.TEXTURE_2D,rt,qe,Pe.width,Pe.height),oe&&ne(U,Pe,ut,bt)):t.texImage2D(n.TEXTURE_2D,0,qe,Pe.width,Pe.height,0,ut,bt,Pe.data);else if(U.isCompressedTexture)if(U.isCompressedArrayTexture){Ut&&yi&&t.texStorage3D(n.TEXTURE_2D_ARRAY,rt,qe,Wt[0].width,Wt[0].height,Pe.depth);for(let Ce=0,ft=Wt.length;Ce<ft;Ce++)if(Je=Wt[Ce],U.format!==Aa)if(ut!==null)if(Ut){if(oe)if(U.layerUpdates.size>0){let nt=$I(Je.width,Je.height,U.format,U.type);for(let Ge of U.layerUpdates){let Mt=Je.data.subarray(Ge*nt/Je.data.BYTES_PER_ELEMENT,(Ge+1)*nt/Je.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ce,0,0,Ge,Je.width,Je.height,1,ut,Mt)}U.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ce,0,0,0,Je.width,Je.height,Pe.depth,ut,Je.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,Ce,qe,Je.width,Je.height,Pe.depth,0,Je.data,0,0);else Nt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Ut?oe&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,Ce,0,0,0,Je.width,Je.height,Pe.depth,ut,bt,Je.data):t.texImage3D(n.TEXTURE_2D_ARRAY,Ce,qe,Je.width,Je.height,Pe.depth,0,ut,bt,Je.data)}else{Ut&&yi&&t.texStorage2D(n.TEXTURE_2D,rt,qe,Wt[0].width,Wt[0].height);for(let Ce=0,ft=Wt.length;Ce<ft;Ce++)Je=Wt[Ce],U.format!==Aa?ut!==null?Ut?oe&&t.compressedTexSubImage2D(n.TEXTURE_2D,Ce,0,0,Je.width,Je.height,ut,Je.data):t.compressedTexImage2D(n.TEXTURE_2D,Ce,qe,Je.width,Je.height,0,Je.data):Nt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):Ut?oe&&t.texSubImage2D(n.TEXTURE_2D,Ce,0,0,Je.width,Je.height,ut,bt,Je.data):t.texImage2D(n.TEXTURE_2D,Ce,qe,Je.width,Je.height,0,ut,bt,Je.data)}else if(U.isDataArrayTexture)if(Ut){if(yi&&t.texStorage3D(n.TEXTURE_2D_ARRAY,rt,qe,Pe.width,Pe.height,Pe.depth),oe)if(U.layerUpdates.size>0){let Ce=$I(Pe.width,Pe.height,U.format,U.type);for(let ft of U.layerUpdates){let nt=Pe.data.subarray(ft*Ce/Pe.data.BYTES_PER_ELEMENT,(ft+1)*Ce/Pe.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,ft,Pe.width,Pe.height,1,ut,bt,nt)}U.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,Pe.width,Pe.height,Pe.depth,ut,bt,Pe.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,qe,Pe.width,Pe.height,Pe.depth,0,ut,bt,Pe.data);else if(U.isData3DTexture)Ut?(yi&&t.texStorage3D(n.TEXTURE_3D,rt,qe,Pe.width,Pe.height,Pe.depth),oe&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,Pe.width,Pe.height,Pe.depth,ut,bt,Pe.data)):t.texImage3D(n.TEXTURE_3D,0,qe,Pe.width,Pe.height,Pe.depth,0,ut,bt,Pe.data);else if(U.isFramebufferTexture){if(yi)if(Ut)t.texStorage2D(n.TEXTURE_2D,rt,qe,Pe.width,Pe.height);else{let Ce=Pe.width,ft=Pe.height;for(let nt=0;nt<rt;nt++)t.texImage2D(n.TEXTURE_2D,nt,qe,Ce,ft,0,ut,bt,null),Ce>>=1,ft>>=1}}else if(U.isHTMLTexture){if("texElementImage2D"in n){let Ce=n.canvas;if(Ce.hasAttribute("layoutsubtree")||Ce.setAttribute("layoutsubtree","true"),Pe.parentNode!==Ce){Ce.appendChild(Pe),d.add(U),Ce.onpaint=qt=>{let Er=qt.changedElements;for(let _i of d)Er.includes(_i.image)&&(_i.needsUpdate=!0)},Ce.requestPaint();return}let ft=0,nt=n.RGBA,Ge=n.RGBA,Mt=n.UNSIGNED_BYTE;n.texElementImage2D(n.TEXTURE_2D,ft,nt,Ge,Mt,Pe),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)}}else if(Wt.length>0){if(Ut&&yi){let Ce=ar(Wt[0]);t.texStorage2D(n.TEXTURE_2D,rt,qe,Ce.width,Ce.height)}for(let Ce=0,ft=Wt.length;Ce<ft;Ce++)Je=Wt[Ce],Ut?oe&&t.texSubImage2D(n.TEXTURE_2D,Ce,0,0,ut,bt,Je):t.texImage2D(n.TEXTURE_2D,Ce,qe,ut,bt,Je);U.generateMipmaps=!1}else if(Ut){if(yi){let Ce=ar(Pe);t.texStorage2D(n.TEXTURE_2D,rt,qe,Ce.width,Ce.height)}oe&&t.texSubImage2D(n.TEXTURE_2D,0,0,0,ut,bt,Pe)}else t.texImage2D(n.TEXTURE_2D,0,qe,ut,bt,Pe);_(U)&&v(De),Qe.__version=it.version,U.onUpdate&&U.onUpdate(U)}Z.__version=U.version}function Le(Z,U,ge){if(U.image.length!==6)return;let De=se(Z,U),ke=U.source;t.bindTexture(n.TEXTURE_CUBE_MAP,Z.__webglTexture,n.TEXTURE0+ge);let it=i.get(ke);if(ke.version!==it.__version||De===!0){t.activeTexture(n.TEXTURE0+ge);let Qe=mi.getPrimaries(mi.workingColorSpace),Me=U.colorSpace===vc?null:mi.getPrimaries(U.colorSpace),Pe=U.colorSpace===vc||Qe===Me?n.NONE:n.BROWSER_DEFAULT_WEBGL;t.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,U.flipY),t.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,U.premultiplyAlpha),t.pixelStorei(n.UNPACK_ALIGNMENT,U.unpackAlignment),t.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,Pe);let ut=U.isCompressedTexture||U.image[0].isCompressedTexture,bt=U.image[0]&&U.image[0].isDataTexture,qe=[];for(let Ge=0;Ge<6;Ge++)!ut&&!bt?qe[Ge]=p(U.image[Ge],!0,r.maxCubemapSize):qe[Ge]=bt?U.image[Ge].image:U.image[Ge],qe[Ge]=Ke(U,qe[Ge]);let Je=qe[0],Wt=s.convert(U.format,U.colorSpace),Ut=s.convert(U.type),yi=S(U.internalFormat,Wt,Ut,U.normalized,U.colorSpace),oe=U.isVideoTexture!==!0,rt=it.__version===void 0||De===!0,Ce=ke.dataReady,ft=A(U,Je);Ue(n.TEXTURE_CUBE_MAP,U);let nt;if(ut){oe&&rt&&t.texStorage2D(n.TEXTURE_CUBE_MAP,ft,yi,Je.width,Je.height);for(let Ge=0;Ge<6;Ge++){nt=qe[Ge].mipmaps;for(let Mt=0;Mt<nt.length;Mt++){let qt=nt[Mt];U.format!==Aa?Wt!==null?oe?Ce&&t.compressedTexSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ge,Mt,0,0,qt.width,qt.height,Wt,qt.data):t.compressedTexImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ge,Mt,yi,qt.width,qt.height,0,qt.data):Nt("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):oe?Ce&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ge,Mt,0,0,qt.width,qt.height,Wt,Ut,qt.data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ge,Mt,yi,qt.width,qt.height,0,Wt,Ut,qt.data)}}}else{if(nt=U.mipmaps,oe&&rt){nt.length>0&&ft++;let Ge=ar(qe[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,ft,yi,Ge.width,Ge.height)}for(let Ge=0;Ge<6;Ge++)if(bt){oe?Ce&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ge,0,0,0,qe[Ge].width,qe[Ge].height,Wt,Ut,qe[Ge].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ge,0,yi,qe[Ge].width,qe[Ge].height,0,Wt,Ut,qe[Ge].data);for(let Mt=0;Mt<nt.length;Mt++){let Er=nt[Mt].image[Ge].image;oe?Ce&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ge,Mt+1,0,0,Er.width,Er.height,Wt,Ut,Er.data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ge,Mt+1,yi,Er.width,Er.height,0,Wt,Ut,Er.data)}}else{oe?Ce&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ge,0,0,0,Wt,Ut,qe[Ge]):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ge,0,yi,Wt,Ut,qe[Ge]);for(let Mt=0;Mt<nt.length;Mt++){let qt=nt[Mt];oe?Ce&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ge,Mt+1,0,0,Wt,Ut,qt.image[Ge]):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ge,Mt+1,yi,Wt,Ut,qt.image[Ge])}}}_(U)&&v(n.TEXTURE_CUBE_MAP),it.__version=ke.version,U.onUpdate&&U.onUpdate(U)}Z.__version=U.version}function de(Z,U,ge,De,ke,it){let Qe=s.convert(ge.format,ge.colorSpace),Me=s.convert(ge.type),Pe=S(ge.internalFormat,Qe,Me,ge.normalized,ge.colorSpace),ut=i.get(U),bt=i.get(ge);if(bt.__renderTarget=U,!ut.__hasExternalTextures){let qe=Math.max(1,U.width>>it),Je=Math.max(1,U.height>>it);ke===n.TEXTURE_3D||ke===n.TEXTURE_2D_ARRAY?t.texImage3D(ke,it,Pe,qe,Je,U.depth,0,Qe,Me,null):t.texImage2D(ke,it,Pe,qe,Je,0,Qe,Me,null)}t.bindFramebuffer(n.FRAMEBUFFER,Z),hi(U)?o.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,De,ke,bt.__webglTexture,0,Ti(U)):(ke===n.TEXTURE_2D||ke>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&ke<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,De,ke,bt.__webglTexture,it),t.bindFramebuffer(n.FRAMEBUFFER,null)}function be(Z,U,ge){if(n.bindRenderbuffer(n.RENDERBUFFER,Z),U.depthBuffer){let De=U.depthTexture,ke=De&&De.isDepthTexture?De.type:null,it=T(U.stencilBuffer,ke),Qe=U.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT;hi(U)?o.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,Ti(U),it,U.width,U.height):ge?n.renderbufferStorageMultisample(n.RENDERBUFFER,Ti(U),it,U.width,U.height):n.renderbufferStorage(n.RENDERBUFFER,it,U.width,U.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,Qe,n.RENDERBUFFER,Z)}else{let De=U.textures;for(let ke=0;ke<De.length;ke++){let it=De[ke],Qe=s.convert(it.format,it.colorSpace),Me=s.convert(it.type),Pe=S(it.internalFormat,Qe,Me,it.normalized,it.colorSpace);hi(U)?o.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,Ti(U),Pe,U.width,U.height):ge?n.renderbufferStorageMultisample(n.RENDERBUFFER,Ti(U),Pe,U.width,U.height):n.renderbufferStorage(n.RENDERBUFFER,Pe,U.width,U.height)}}n.bindRenderbuffer(n.RENDERBUFFER,null)}function we(Z,U,ge){let De=U.isWebGLCubeRenderTarget===!0;if(t.bindFramebuffer(n.FRAMEBUFFER,Z),!(U.depthTexture&&U.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");let ke=i.get(U.depthTexture);if(ke.__renderTarget=U,(!ke.__webglTexture||U.depthTexture.image.width!==U.width||U.depthTexture.image.height!==U.height)&&(U.depthTexture.image.width=U.width,U.depthTexture.image.height=U.height,U.depthTexture.needsUpdate=!0),De){if(ke.__webglInit===void 0&&(ke.__webglInit=!0,U.depthTexture.addEventListener("dispose",R)),ke.__webglTexture===void 0){ke.__webglTexture=n.createTexture(),t.bindTexture(n.TEXTURE_CUBE_MAP,ke.__webglTexture),Ue(n.TEXTURE_CUBE_MAP,U.depthTexture);let ut=s.convert(U.depthTexture.format),bt=s.convert(U.depthTexture.type),qe;U.depthTexture.format===hl?qe=n.DEPTH_COMPONENT24:U.depthTexture.format===Nf&&(qe=n.DEPTH24_STENCIL8);for(let Je=0;Je<6;Je++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Je,0,qe,U.width,U.height,0,ut,bt,null)}}else q(U.depthTexture,0);let it=ke.__webglTexture,Qe=Ti(U),Me=De?n.TEXTURE_CUBE_MAP_POSITIVE_X+ge:n.TEXTURE_2D,Pe=U.depthTexture.format===Nf?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT;if(U.depthTexture.format===hl)hi(U)?o.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,Pe,Me,it,0,Qe):n.framebufferTexture2D(n.FRAMEBUFFER,Pe,Me,it,0);else if(U.depthTexture.format===Nf)hi(U)?o.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,Pe,Me,it,0,Qe):n.framebufferTexture2D(n.FRAMEBUFFER,Pe,Me,it,0);else throw new Error("Unknown depthTexture format")}function dt(Z){let U=i.get(Z),ge=Z.isWebGLCubeRenderTarget===!0;if(U.__boundDepthTexture!==Z.depthTexture){let De=Z.depthTexture;if(U.__depthDisposeCallback&&U.__depthDisposeCallback(),De){let ke=()=>{delete U.__boundDepthTexture,delete U.__depthDisposeCallback,De.removeEventListener("dispose",ke)};De.addEventListener("dispose",ke),U.__depthDisposeCallback=ke}U.__boundDepthTexture=De}if(Z.depthTexture&&!U.__autoAllocateDepthBuffer)if(ge)for(let De=0;De<6;De++)we(U.__webglFramebuffer[De],Z,De);else{let De=Z.texture.mipmaps;De&&De.length>0?we(U.__webglFramebuffer[0],Z,0):we(U.__webglFramebuffer,Z,0)}else if(ge){U.__webglDepthbuffer=[];for(let De=0;De<6;De++)if(t.bindFramebuffer(n.FRAMEBUFFER,U.__webglFramebuffer[De]),U.__webglDepthbuffer[De]===void 0)U.__webglDepthbuffer[De]=n.createRenderbuffer(),be(U.__webglDepthbuffer[De],Z,!1);else{let ke=Z.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,it=U.__webglDepthbuffer[De];n.bindRenderbuffer(n.RENDERBUFFER,it),n.framebufferRenderbuffer(n.FRAMEBUFFER,ke,n.RENDERBUFFER,it)}}else{let De=Z.texture.mipmaps;if(De&&De.length>0?t.bindFramebuffer(n.FRAMEBUFFER,U.__webglFramebuffer[0]):t.bindFramebuffer(n.FRAMEBUFFER,U.__webglFramebuffer),U.__webglDepthbuffer===void 0)U.__webglDepthbuffer=n.createRenderbuffer(),be(U.__webglDepthbuffer,Z,!1);else{let ke=Z.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,it=U.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,it),n.framebufferRenderbuffer(n.FRAMEBUFFER,ke,n.RENDERBUFFER,it)}}t.bindFramebuffer(n.FRAMEBUFFER,null)}function Ve(Z,U,ge){let De=i.get(Z);U!==void 0&&de(De.__webglFramebuffer,Z,Z.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),ge!==void 0&&dt(Z)}function Ze(Z){let U=Z.texture,ge=i.get(Z),De=i.get(U);Z.addEventListener("dispose",M);let ke=Z.textures,it=Z.isWebGLCubeRenderTarget===!0,Qe=ke.length>1;if(Qe||(De.__webglTexture===void 0&&(De.__webglTexture=n.createTexture()),De.__version=U.version,a.memory.textures++),it){ge.__webglFramebuffer=[];for(let Me=0;Me<6;Me++)if(U.mipmaps&&U.mipmaps.length>0){ge.__webglFramebuffer[Me]=[];for(let Pe=0;Pe<U.mipmaps.length;Pe++)ge.__webglFramebuffer[Me][Pe]=n.createFramebuffer()}else ge.__webglFramebuffer[Me]=n.createFramebuffer()}else{if(U.mipmaps&&U.mipmaps.length>0){ge.__webglFramebuffer=[];for(let Me=0;Me<U.mipmaps.length;Me++)ge.__webglFramebuffer[Me]=n.createFramebuffer()}else ge.__webglFramebuffer=n.createFramebuffer();if(Qe)for(let Me=0,Pe=ke.length;Me<Pe;Me++){let ut=i.get(ke[Me]);ut.__webglTexture===void 0&&(ut.__webglTexture=n.createTexture(),a.memory.textures++)}if(Z.samples>0&&hi(Z)===!1){ge.__webglMultisampledFramebuffer=n.createFramebuffer(),ge.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,ge.__webglMultisampledFramebuffer);for(let Me=0;Me<ke.length;Me++){let Pe=ke[Me];ge.__webglColorRenderbuffer[Me]=n.createRenderbuffer(),n.bindRenderbuffer(n.RENDERBUFFER,ge.__webglColorRenderbuffer[Me]);let ut=s.convert(Pe.format,Pe.colorSpace),bt=s.convert(Pe.type),qe=S(Pe.internalFormat,ut,bt,Pe.normalized,Pe.colorSpace,Z.isXRRenderTarget===!0),Je=Ti(Z);n.renderbufferStorageMultisample(n.RENDERBUFFER,Je,qe,Z.width,Z.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+Me,n.RENDERBUFFER,ge.__webglColorRenderbuffer[Me])}n.bindRenderbuffer(n.RENDERBUFFER,null),Z.depthBuffer&&(ge.__webglDepthRenderbuffer=n.createRenderbuffer(),be(ge.__webglDepthRenderbuffer,Z,!0)),t.bindFramebuffer(n.FRAMEBUFFER,null)}}if(it){t.bindTexture(n.TEXTURE_CUBE_MAP,De.__webglTexture),Ue(n.TEXTURE_CUBE_MAP,U);for(let Me=0;Me<6;Me++)if(U.mipmaps&&U.mipmaps.length>0)for(let Pe=0;Pe<U.mipmaps.length;Pe++)de(ge.__webglFramebuffer[Me][Pe],Z,U,n.COLOR_ATTACHMENT0,n.TEXTURE_CUBE_MAP_POSITIVE_X+Me,Pe);else de(ge.__webglFramebuffer[Me],Z,U,n.COLOR_ATTACHMENT0,n.TEXTURE_CUBE_MAP_POSITIVE_X+Me,0);_(U)&&v(n.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(Qe){for(let Me=0,Pe=ke.length;Me<Pe;Me++){let ut=ke[Me],bt=i.get(ut),qe=n.TEXTURE_2D;(Z.isWebGL3DRenderTarget||Z.isWebGLArrayRenderTarget)&&(qe=Z.isWebGL3DRenderTarget?n.TEXTURE_3D:n.TEXTURE_2D_ARRAY),t.bindTexture(qe,bt.__webglTexture),Ue(qe,ut),de(ge.__webglFramebuffer,Z,ut,n.COLOR_ATTACHMENT0+Me,qe,0),_(ut)&&v(qe)}t.unbindTexture()}else{let Me=n.TEXTURE_2D;if((Z.isWebGL3DRenderTarget||Z.isWebGLArrayRenderTarget)&&(Me=Z.isWebGL3DRenderTarget?n.TEXTURE_3D:n.TEXTURE_2D_ARRAY),t.bindTexture(Me,De.__webglTexture),Ue(Me,U),U.mipmaps&&U.mipmaps.length>0)for(let Pe=0;Pe<U.mipmaps.length;Pe++)de(ge.__webglFramebuffer[Pe],Z,U,n.COLOR_ATTACHMENT0,Me,Pe);else de(ge.__webglFramebuffer,Z,U,n.COLOR_ATTACHMENT0,Me,0);_(U)&&v(Me),t.unbindTexture()}Z.depthBuffer&&dt(Z)}function Kt(Z){let U=Z.textures;for(let ge=0,De=U.length;ge<De;ge++){let ke=U[ge];if(_(ke)){let it=E(Z),Qe=i.get(ke).__webglTexture;t.bindTexture(it,Qe),v(it),t.unbindTexture()}}}let Bt=[],wi=[];function ae(Z){if(Z.samples>0){if(hi(Z)===!1){let U=Z.textures,ge=Z.width,De=Z.height,ke=n.COLOR_BUFFER_BIT,it=Z.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Qe=i.get(Z),Me=U.length>1;if(Me)for(let ut=0;ut<U.length;ut++)t.bindFramebuffer(n.FRAMEBUFFER,Qe.__webglMultisampledFramebuffer),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+ut,n.RENDERBUFFER,null),t.bindFramebuffer(n.FRAMEBUFFER,Qe.__webglFramebuffer),n.framebufferTexture2D(n.DRAW_FRAMEBUFFER,n.COLOR_ATTACHMENT0+ut,n.TEXTURE_2D,null,0);t.bindFramebuffer(n.READ_FRAMEBUFFER,Qe.__webglMultisampledFramebuffer);let Pe=Z.texture.mipmaps;Pe&&Pe.length>0?t.bindFramebuffer(n.DRAW_FRAMEBUFFER,Qe.__webglFramebuffer[0]):t.bindFramebuffer(n.DRAW_FRAMEBUFFER,Qe.__webglFramebuffer);for(let ut=0;ut<U.length;ut++){if(Z.resolveDepthBuffer&&(Z.depthBuffer&&(ke|=n.DEPTH_BUFFER_BIT),Z.stencilBuffer&&Z.resolveStencilBuffer&&(ke|=n.STENCIL_BUFFER_BIT)),Me){n.framebufferRenderbuffer(n.READ_FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.RENDERBUFFER,Qe.__webglColorRenderbuffer[ut]);let bt=i.get(U[ut]).__webglTexture;n.framebufferTexture2D(n.DRAW_FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,bt,0)}n.blitFramebuffer(0,0,ge,De,0,0,ge,De,ke,n.NEAREST),l===!0&&(Bt.length=0,wi.length=0,Bt.push(n.COLOR_ATTACHMENT0+ut),Z.depthBuffer&&Z.resolveDepthBuffer===!1&&(Bt.push(it),wi.push(it),n.invalidateFramebuffer(n.DRAW_FRAMEBUFFER,wi)),n.invalidateFramebuffer(n.READ_FRAMEBUFFER,Bt))}if(t.bindFramebuffer(n.READ_FRAMEBUFFER,null),t.bindFramebuffer(n.DRAW_FRAMEBUFFER,null),Me)for(let ut=0;ut<U.length;ut++){t.bindFramebuffer(n.FRAMEBUFFER,Qe.__webglMultisampledFramebuffer),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+ut,n.RENDERBUFFER,Qe.__webglColorRenderbuffer[ut]);let bt=i.get(U[ut]).__webglTexture;t.bindFramebuffer(n.FRAMEBUFFER,Qe.__webglFramebuffer),n.framebufferTexture2D(n.DRAW_FRAMEBUFFER,n.COLOR_ATTACHMENT0+ut,n.TEXTURE_2D,bt,0)}t.bindFramebuffer(n.DRAW_FRAMEBUFFER,Qe.__webglMultisampledFramebuffer)}else if(Z.depthBuffer&&Z.resolveDepthBuffer===!1&&l){let U=Z.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT;n.invalidateFramebuffer(n.DRAW_FRAMEBUFFER,[U])}}}function Ti(Z){return Math.min(r.maxSamples,Z.samples)}function hi(Z){let U=i.get(Z);return Z.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&U.__useRenderToTexture!==!1}function rr(Z){let U=a.render.frame;f.get(Z)!==U&&(f.set(Z,U),Z.update())}function Ke(Z,U){let ge=Z.colorSpace,De=Z.format,ke=Z.type;return Z.isCompressedTexture===!0||Z.isVideoTexture===!0||ge!==gs&&ge!==vc&&(mi.getTransfer(ge)===nr?(De!==Aa||ke!==Ks)&&Nt("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Ht("WebGLTextures: Unsupported texture color space:",ge)),U}function ar(Z){return typeof HTMLImageElement!="undefined"&&Z instanceof HTMLImageElement?(c.width=Z.naturalWidth||Z.width,c.height=Z.naturalHeight||Z.height):typeof VideoFrame!="undefined"&&Z instanceof VideoFrame?(c.width=Z.displayWidth,c.height=Z.displayHeight):(c.width=Z.width,c.height=Z.height),c}this.allocateTextureUnit=B,this.resetTextureUnits=G,this.getTextureUnits=O,this.setTextureUnits=N,this.setTexture2D=q,this.setTexture2DArray=K,this.setTexture3D=J,this.setTextureCube=Y,this.rebindTextures=Ve,this.setupRenderTarget=Ze,this.updateRenderTargetMipmap=Kt,this.updateMultisampleRenderTarget=ae,this.setupDepthRenderbuffer=dt,this.setupFrameBufferTexture=de,this.useMultisampledRTT=hi,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function qoe(n,e){function t(i,r=vc){let s,a=mi.getTransfer(r);if(i===Ks)return n.UNSIGNED_BYTE;if(i===PT)return n.UNSIGNED_SHORT_4_4_4_4;if(i===LT)return n.UNSIGNED_SHORT_5_5_5_1;if(i===zI)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===WI)return n.UNSIGNED_INT_10F_11F_11F_REV;if(i===GI)return n.BYTE;if(i===kI)return n.SHORT;if(i===Am)return n.UNSIGNED_SHORT;if(i===CT)return n.INT;if(i===Co)return n.UNSIGNED_INT;if(i===Ta)return n.FLOAT;if(i===Al)return n.HALF_FLOAT;if(i===HI)return n.ALPHA;if(i===XI)return n.RGB;if(i===Aa)return n.RGBA;if(i===hl)return n.DEPTH_COMPONENT;if(i===Nf)return n.DEPTH_STENCIL;if(i===DT)return n.RED;if(i===OT)return n.RED_INTEGER;if(i===wf)return n.RG;if(i===NT)return n.RG_INTEGER;if(i===wT)return n.RGBA_INTEGER;if(i===G_||i===k_||i===z_||i===W_)if(a===nr)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===G_)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===k_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===z_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===W_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===G_)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===k_)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===z_)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===W_)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===FT||i===BT||i===UT||i===VT)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===FT)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===BT)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===UT)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===VT)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===GT||i===kT||i===zT||i===WT||i===HT||i===H_||i===XT)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(i===GT||i===kT)return a===nr?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===zT)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(i===WT)return s.COMPRESSED_R11_EAC;if(i===HT)return s.COMPRESSED_SIGNED_R11_EAC;if(i===H_)return s.COMPRESSED_RG11_EAC;if(i===XT)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===YT||i===KT||i===jT||i===ZT||i===qT||i===QT||i===$T||i===JT||i===eA||i===tA||i===iA||i===rA||i===nA||i===sA)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(i===YT)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===KT)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===jT)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===ZT)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===qT)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===QT)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===$T)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===JT)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===eA)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===tA)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===iA)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===rA)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===nA)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===sA)return a===nr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===aA||i===oA||i===lA)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(i===aA)return a===nr?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===oA)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===lA)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===cA||i===fA||i===X_||i===dA)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(i===cA)return s.COMPRESSED_RED_RGTC1_EXT;if(i===fA)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===X_)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===dA)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===xm?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}function ele(n,e){function t(p,_){p.matrixAutoUpdate===!0&&p.updateMatrix(),_.value.copy(p.matrix)}function i(p,_){_.color.getRGB(p.fogColor.value,ZI(n)),_.isFog?(p.fogNear.value=_.near,p.fogFar.value=_.far):_.isFogExp2&&(p.fogDensity.value=_.density)}function r(p,_,v,E,S){_.isNodeMaterial?_.uniformsNeedUpdate=!1:_.isMeshBasicMaterial?s(p,_):_.isMeshLambertMaterial?(s(p,_),_.envMap&&(p.envMapIntensity.value=_.envMapIntensity)):_.isMeshToonMaterial?(s(p,_),d(p,_)):_.isMeshPhongMaterial?(s(p,_),f(p,_),_.envMap&&(p.envMapIntensity.value=_.envMapIntensity)):_.isMeshStandardMaterial?(s(p,_),u(p,_),_.isMeshPhysicalMaterial&&h(p,_,S)):_.isMeshMatcapMaterial?(s(p,_),m(p,_)):_.isMeshDepthMaterial?s(p,_):_.isMeshDistanceMaterial?(s(p,_),g(p,_)):_.isMeshNormalMaterial?s(p,_):_.isLineBasicMaterial?(a(p,_),_.isLineDashedMaterial&&o(p,_)):_.isPointsMaterial?l(p,_,v,E):_.isSpriteMaterial?c(p,_):_.isShadowMaterial?(p.color.value.copy(_.color),p.opacity.value=_.opacity):_.isShaderMaterial&&(_.uniformsNeedUpdate=!1)}function s(p,_){p.opacity.value=_.opacity,_.color&&p.diffuse.value.copy(_.color),_.emissive&&p.emissive.value.copy(_.emissive).multiplyScalar(_.emissiveIntensity),_.map&&(p.map.value=_.map,t(_.map,p.mapTransform)),_.alphaMap&&(p.alphaMap.value=_.alphaMap,t(_.alphaMap,p.alphaMapTransform)),_.bumpMap&&(p.bumpMap.value=_.bumpMap,t(_.bumpMap,p.bumpMapTransform),p.bumpScale.value=_.bumpScale,_.side===On&&(p.bumpScale.value*=-1)),_.normalMap&&(p.normalMap.value=_.normalMap,t(_.normalMap,p.normalMapTransform),p.normalScale.value.copy(_.normalScale),_.side===On&&p.normalScale.value.negate()),_.displacementMap&&(p.displacementMap.value=_.displacementMap,t(_.displacementMap,p.displacementMapTransform),p.displacementScale.value=_.displacementScale,p.displacementBias.value=_.displacementBias),_.emissiveMap&&(p.emissiveMap.value=_.emissiveMap,t(_.emissiveMap,p.emissiveMapTransform)),_.specularMap&&(p.specularMap.value=_.specularMap,t(_.specularMap,p.specularMapTransform)),_.alphaTest>0&&(p.alphaTest.value=_.alphaTest);let v=e.get(_),E=v.envMap,S=v.envMapRotation;E&&(p.envMap.value=E,p.envMapRotation.value.setFromMatrix4(Joe.makeRotationFromEuler(S)).transpose(),E.isCubeTexture&&E.isRenderTargetTexture===!1&&p.envMapRotation.value.premultiply(gU),p.reflectivity.value=_.reflectivity,p.ior.value=_.ior,p.refractionRatio.value=_.refractionRatio),_.lightMap&&(p.lightMap.value=_.lightMap,p.lightMapIntensity.value=_.lightMapIntensity,t(_.lightMap,p.lightMapTransform)),_.aoMap&&(p.aoMap.value=_.aoMap,p.aoMapIntensity.value=_.aoMapIntensity,t(_.aoMap,p.aoMapTransform))}function a(p,_){p.diffuse.value.copy(_.color),p.opacity.value=_.opacity,_.map&&(p.map.value=_.map,t(_.map,p.mapTransform))}function o(p,_){p.dashSize.value=_.dashSize,p.totalSize.value=_.dashSize+_.gapSize,p.scale.value=_.scale}function l(p,_,v,E){p.diffuse.value.copy(_.color),p.opacity.value=_.opacity,p.size.value=_.size*v,p.scale.value=E*.5,_.map&&(p.map.value=_.map,t(_.map,p.uvTransform)),_.alphaMap&&(p.alphaMap.value=_.alphaMap,t(_.alphaMap,p.alphaMapTransform)),_.alphaTest>0&&(p.alphaTest.value=_.alphaTest)}function c(p,_){p.diffuse.value.copy(_.color),p.opacity.value=_.opacity,p.rotation.value=_.rotation,_.map&&(p.map.value=_.map,t(_.map,p.mapTransform)),_.alphaMap&&(p.alphaMap.value=_.alphaMap,t(_.alphaMap,p.alphaMapTransform)),_.alphaTest>0&&(p.alphaTest.value=_.alphaTest)}function f(p,_){p.specular.value.copy(_.specular),p.shininess.value=Math.max(_.shininess,1e-4)}function d(p,_){_.gradientMap&&(p.gradientMap.value=_.gradientMap)}function u(p,_){p.metalness.value=_.metalness,_.metalnessMap&&(p.metalnessMap.value=_.metalnessMap,t(_.metalnessMap,p.metalnessMapTransform)),p.roughness.value=_.roughness,_.roughnessMap&&(p.roughnessMap.value=_.roughnessMap,t(_.roughnessMap,p.roughnessMapTransform)),_.envMap&&(p.envMapIntensity.value=_.envMapIntensity)}function h(p,_,v){p.ior.value=_.ior,_.sheen>0&&(p.sheenColor.value.copy(_.sheenColor).multiplyScalar(_.sheen),p.sheenRoughness.value=_.sheenRoughness,_.sheenColorMap&&(p.sheenColorMap.value=_.sheenColorMap,t(_.sheenColorMap,p.sheenColorMapTransform)),_.sheenRoughnessMap&&(p.sheenRoughnessMap.value=_.sheenRoughnessMap,t(_.sheenRoughnessMap,p.sheenRoughnessMapTransform))),_.clearcoat>0&&(p.clearcoat.value=_.clearcoat,p.clearcoatRoughness.value=_.clearcoatRoughness,_.clearcoatMap&&(p.clearcoatMap.value=_.clearcoatMap,t(_.clearcoatMap,p.clearcoatMapTransform)),_.clearcoatRoughnessMap&&(p.clearcoatRoughnessMap.value=_.clearcoatRoughnessMap,t(_.clearcoatRoughnessMap,p.clearcoatRoughnessMapTransform)),_.clearcoatNormalMap&&(p.clearcoatNormalMap.value=_.clearcoatNormalMap,t(_.clearcoatNormalMap,p.clearcoatNormalMapTransform),p.clearcoatNormalScale.value.copy(_.clearcoatNormalScale),_.side===On&&p.clearcoatNormalScale.value.negate())),_.dispersion>0&&(p.dispersion.value=_.dispersion),_.iridescence>0&&(p.iridescence.value=_.iridescence,p.iridescenceIOR.value=_.iridescenceIOR,p.iridescenceThicknessMinimum.value=_.iridescenceThicknessRange[0],p.iridescenceThicknessMaximum.value=_.iridescenceThicknessRange[1],_.iridescenceMap&&(p.iridescenceMap.value=_.iridescenceMap,t(_.iridescenceMap,p.iridescenceMapTransform)),_.iridescenceThicknessMap&&(p.iridescenceThicknessMap.value=_.iridescenceThicknessMap,t(_.iridescenceThicknessMap,p.iridescenceThicknessMapTransform))),_.transmission>0&&(p.transmission.value=_.transmission,p.transmissionSamplerMap.value=v.texture,p.transmissionSamplerSize.value.set(v.width,v.height),_.transmissionMap&&(p.transmissionMap.value=_.transmissionMap,t(_.transmissionMap,p.transmissionMapTransform)),p.thickness.value=_.thickness,_.thicknessMap&&(p.thicknessMap.value=_.thicknessMap,t(_.thicknessMap,p.thicknessMapTransform)),p.attenuationDistance.value=_.attenuationDistance,p.attenuationColor.value.copy(_.attenuationColor)),_.anisotropy>0&&(p.anisotropyVector.value.set(_.anisotropy*Math.cos(_.anisotropyRotation),_.anisotropy*Math.sin(_.anisotropyRotation)),_.anisotropyMap&&(p.anisotropyMap.value=_.anisotropyMap,t(_.anisotropyMap,p.anisotropyMapTransform))),p.specularIntensity.value=_.specularIntensity,p.specularColor.value.copy(_.specularColor),_.specularColorMap&&(p.specularColorMap.value=_.specularColorMap,t(_.specularColorMap,p.specularColorMapTransform)),_.specularIntensityMap&&(p.specularIntensityMap.value=_.specularIntensityMap,t(_.specularIntensityMap,p.specularIntensityMapTransform))}function m(p,_){_.matcap&&(p.matcap.value=_.matcap)}function g(p,_){let v=e.get(_).light;p.referencePosition.value.setFromMatrixPosition(v.matrixWorld),p.nearDistance.value=v.shadow.camera.near,p.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:r}}function tle(n,e,t,i){let r={},s={},a=[],o=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function l(v,E){let S=E.program;i.uniformBlockBinding(v,S)}function c(v,E){let S=r[v.id];S===void 0&&(m(v),S=f(v),r[v.id]=S,v.addEventListener("dispose",p));let T=E.program;i.updateUBOMapping(v,T);let A=e.render.frame;s[v.id]!==A&&(u(v),s[v.id]=A)}function f(v){let E=d();v.__bindingPointIndex=E;let S=n.createBuffer(),T=v.__size,A=v.usage;return n.bindBuffer(n.UNIFORM_BUFFER,S),n.bufferData(n.UNIFORM_BUFFER,T,A),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,E,S),S}function d(){for(let v=0;v<o;v++)if(a.indexOf(v)===-1)return a.push(v),v;return Ht("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function u(v){let E=r[v.id],S=v.uniforms,T=v.__cache;n.bindBuffer(n.UNIFORM_BUFFER,E);for(let A=0,R=S.length;A<R;A++){let M=Array.isArray(S[A])?S[A]:[S[A]];for(let I=0,C=M.length;I<C;I++){let L=M[I];if(h(L,A,I,T)===!0){let w=L.__offset,G=Array.isArray(L.value)?L.value:[L.value],O=0;for(let N=0;N<G.length;N++){let B=G[N],V=g(B);typeof B=="number"||typeof B=="boolean"?(L.__data[0]=B,n.bufferSubData(n.UNIFORM_BUFFER,w+O,L.__data)):B.isMatrix3?(L.__data[0]=B.elements[0],L.__data[1]=B.elements[1],L.__data[2]=B.elements[2],L.__data[3]=0,L.__data[4]=B.elements[3],L.__data[5]=B.elements[4],L.__data[6]=B.elements[5],L.__data[7]=0,L.__data[8]=B.elements[6],L.__data[9]=B.elements[7],L.__data[10]=B.elements[8],L.__data[11]=0):ArrayBuffer.isView(B)?L.__data.set(new B.constructor(B.buffer,B.byteOffset,L.__data.length)):(B.toArray(L.__data,O),O+=V.storage/Float32Array.BYTES_PER_ELEMENT)}n.bufferSubData(n.UNIFORM_BUFFER,w,L.__data)}}}n.bindBuffer(n.UNIFORM_BUFFER,null)}function h(v,E,S,T){let A=v.value,R=E+"_"+S;if(T[R]===void 0)return typeof A=="number"||typeof A=="boolean"?T[R]=A:ArrayBuffer.isView(A)?T[R]=A.slice():T[R]=A.clone(),!0;{let M=T[R];if(typeof A=="number"||typeof A=="boolean"){if(M!==A)return T[R]=A,!0}else{if(ArrayBuffer.isView(A))return!0;if(M.equals(A)===!1)return M.copy(A),!0}}return!1}function m(v){let E=v.uniforms,S=0,T=16;for(let R=0,M=E.length;R<M;R++){let I=Array.isArray(E[R])?E[R]:[E[R]];for(let C=0,L=I.length;C<L;C++){let w=I[C],G=Array.isArray(w.value)?w.value:[w.value];for(let O=0,N=G.length;O<N;O++){let B=G[O],V=g(B),q=S%T,K=q%V.boundary,J=q+K;S+=K,J!==0&&T-J<V.storage&&(S+=T-J),w.__data=new Float32Array(V.storage/Float32Array.BYTES_PER_ELEMENT),w.__offset=S,S+=V.storage}}}let A=S%T;return A>0&&(S+=T-A),v.__size=S,v.__cache={},this}function g(v){let E={boundary:0,storage:0};return typeof v=="number"||typeof v=="boolean"?(E.boundary=4,E.storage=4):v.isVector2?(E.boundary=8,E.storage=8):v.isVector3||v.isColor?(E.boundary=16,E.storage=12):v.isVector4?(E.boundary=16,E.storage=16):v.isMatrix3?(E.boundary=48,E.storage=48):v.isMatrix4?(E.boundary=64,E.storage=64):v.isTexture?Nt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(v)?(E.boundary=16,E.storage=v.byteLength):Nt("WebGLRenderer: Unsupported uniform value type.",v),E}function p(v){let E=v.target;E.removeEventListener("dispose",p);let S=a.indexOf(E.__bindingPointIndex);a.splice(S,1),n.deleteBuffer(r[E.id]),delete r[E.id],delete s[E.id]}function _(){for(let v in r)n.deleteBuffer(r[v]);a=[],r={},s={}}return{bind:l,update:c,dispose:_}}function rle(){return xl===null&&(xl=new um(ile,16,16,wf,Al),xl.name="DFG_LUT",xl.minFilter=zr,xl.magFilter=zr,xl.wrapS=Xa,xl.wrapT=Xa,xl.generateMipmaps=!1,xl.needsUpdate=!0),xl}var vre,Ere,Sre,Tre,Are,xre,Rre,bre,Mre,yre,Ire,Cre,Pre,Lre,Dre,Ore,Nre,wre,Fre,Bre,Ure,Vre,Gre,kre,zre,Wre,Hre,Xre,Yre,Kre,jre,Zre,qre,Qre,$re,Jre,ene,tne,ine,rne,nne,sne,ane,one,lne,cne,fne,dne,une,hne,mne,pne,gne,_ne,vne,Ene,Sne,Tne,Ane,xne,Rne,bne,Mne,yne,Ine,Cne,Pne,Lne,Dne,One,Nne,wne,Fne,Bne,Une,Vne,Gne,kne,zne,Wne,Hne,Xne,Yne,Kne,jne,Zne,qne,Qne,$ne,Jne,ese,tse,ise,rse,nse,sse,ase,ose,lse,cse,fse,dse,use,hse,mse,pse,gse,_se,vse,Ese,Sse,Tse,Ase,xse,Rse,bse,Mse,yse,Ise,Cse,Pse,Lse,Dse,Ose,Nse,wse,Fse,Bse,Use,Vse,Gse,kse,zse,Wse,Hse,Xse,Yse,Kse,jse,Zse,qse,Qse,Ei,Tt,Rl,gA,$se,dU,Ff,z2,Au,nae,j_,W2,sC,aC,oC,lC,sae,Im,vA,gae,uU,dC,hU,mU,pU,K2,j2,Z2,q2,Q2,uC,hC,mC,cC,ym,soe,aoe,eU,foe,_A,goe,_oe,Eoe,Toe,xoe,boe,yoe,Loe,gC,_C,Voe,Woe,Hoe,Xoe,Yoe,cU,Z_,fC,Qoe,$oe,vC,EC,Joe,gU,ile,xl,EA,Es=y(()=>{nC();nC();vre=`#ifdef USE_ALPHAHASH
if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`,Ere=`#ifdef USE_ALPHAHASH
const float ALPHA_HASH_SCALE = 0.05;
float hash2D( vec2 value ) {
return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
}
float hash3D( vec3 value ) {
return hash2D( vec2( hash2D( value.xy ), value.z ) );
}
float getAlphaHashThreshold( vec3 position ) {
float maxDeriv = max(
length( dFdx( position.xyz ) ),
length( dFdy( position.xyz ) )
);
float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
vec2 pixScales = vec2(
exp2( floor( log2( pixScale ) ) ),
exp2( ceil( log2( pixScale ) ) )
);
vec2 alpha = vec2(
hash3D( floor( pixScales.x * position.xyz ) ),
hash3D( floor( pixScales.y * position.xyz ) )
);
float lerpFactor = fract( log2( pixScale ) );
float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
float a = min( lerpFactor, 1.0 - lerpFactor );
vec3 cases = vec3(
x * x / ( 2.0 * a * ( 1.0 - a ) ),
( x - 0.5 * a ) / ( 1.0 - a ),
1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
);
float threshold = ( x < ( 1.0 - a ) )
? ( ( x < a ) ? cases.x : cases.y )
: cases.z;
return clamp( threshold , 1.0e-6, 1.0 );
}
#endif`,Sre=`#ifdef USE_ALPHAMAP
diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`,Tre=`#ifdef USE_ALPHAMAP
uniform sampler2D alphaMap;
#endif`,Are=`#ifdef USE_ALPHATEST
#ifdef ALPHA_TO_COVERAGE
diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
if ( diffuseColor.a == 0.0 ) discard;
#else
if ( diffuseColor.a < alphaTest ) discard;
#endif
#endif`,xre=`#ifdef USE_ALPHATEST
uniform float alphaTest;
#endif`,Rre=`#ifdef USE_AOMAP
float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
reflectedLight.indirectDiffuse *= ambientOcclusion;
#if defined( USE_CLEARCOAT )
clearcoatSpecularIndirect *= ambientOcclusion;
#endif
#if defined( USE_SHEEN )
sheenSpecularIndirect *= ambientOcclusion;
#endif
#if defined( USE_ENVMAP ) && defined( STANDARD )
float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
#endif
#endif`,bre=`#ifdef USE_AOMAP
uniform sampler2D aoMap;
uniform float aoMapIntensity;
#endif`,Mre=`#ifdef USE_BATCHING
#if ! defined( GL_ANGLE_multi_draw )
#define gl_DrawID _gl_DrawID
uniform int _gl_DrawID;
#endif
uniform highp sampler2D batchingTexture;
uniform highp usampler2D batchingIdTexture;
mat4 getBatchingMatrix( const in float i ) {
int size = textureSize( batchingTexture, 0 ).x;
int j = int( i ) * 4;
int x = j % size;
int y = j / size;
vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
return mat4( v1, v2, v3, v4 );
}
float getIndirectIndex( const in int i ) {
int size = textureSize( batchingIdTexture, 0 ).x;
int x = i % size;
int y = i / size;
return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
}
#endif
#ifdef USE_BATCHING_COLOR
uniform sampler2D batchingColorTexture;
vec4 getBatchingColor( const in float i ) {
int size = textureSize( batchingColorTexture, 0 ).x;
int j = int( i );
int x = j % size;
int y = j / size;
return texelFetch( batchingColorTexture, ivec2( x, y ), 0 );
}
#endif`,yre=`#ifdef USE_BATCHING
mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`,Ire=`vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
vPosition = vec3( position );
#endif`,Cre=`vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
vec3 objectTangent = vec3( tangent.xyz );
#endif`,Pre=`float G_BlinnPhong_Implicit( ) {
return 0.25;
}
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
}
vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
vec3 halfDir = normalize( lightDir + viewDir );
float dotNH = saturate( dot( normal, halfDir ) );
float dotVH = saturate( dot( viewDir, halfDir ) );
vec3 F = F_Schlick( specularColor, 1.0, dotVH );
float G = G_BlinnPhong_Implicit( );
float D = D_BlinnPhong( shininess, dotNH );
return F * ( G * D );
} // validated`,Lre=`#ifdef USE_IRIDESCENCE
const mat3 XYZ_TO_REC709 = mat3(
3.2404542, -0.9692660, 0.0556434,
-1.5371385, 1.8760108, -0.2040259,
-0.4985314, 0.0415560, 1.0572252
);
vec3 Fresnel0ToIor( vec3 fresnel0 ) {
vec3 sqrtF0 = sqrt( fresnel0 );
return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
}
vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
}
float IorToFresnel0( float transmittedIor, float incidentIor ) {
return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
}
vec3 evalSensitivity( float OPD, vec3 shift ) {
float phase = 2.0 * PI * OPD * 1.0e-9;
vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
xyz /= 1.0685e-7;
vec3 rgb = XYZ_TO_REC709 * xyz;
return rgb;
}
vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
vec3 I;
float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
float cosTheta2Sq = 1.0 - sinTheta2Sq;
if ( cosTheta2Sq < 0.0 ) {
return vec3( 1.0 );
}
float cosTheta2 = sqrt( cosTheta2Sq );
float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
float R12 = F_Schlick( R0, 1.0, cosTheta1 );
float T121 = 1.0 - R12;
float phi12 = 0.0;
if ( iridescenceIOR < outsideIOR ) phi12 = PI;
float phi21 = PI - phi12;
vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
vec3 phi23 = vec3( 0.0 );
if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
vec3 phi = vec3( phi21 ) + phi23;
vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
vec3 r123 = sqrt( R123 );
vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
vec3 C0 = R12 + Rs;
I = C0;
vec3 Cm = Rs - T121;
for ( int m = 1; m <= 2; ++ m ) {
Cm *= r123;
vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
I += Cm * Sm;
}
return max( I, vec3( 0.0 ) );
}
#endif`,Dre=`#ifdef USE_BUMPMAP
uniform sampler2D bumpMap;
uniform float bumpScale;
vec2 dHdxy_fwd() {
vec2 dSTdx = dFdx( vBumpMapUv );
vec2 dSTdy = dFdy( vBumpMapUv );
float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
return vec2( dBx, dBy );
}
vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
vec3 vN = surf_norm;
vec3 R1 = cross( vSigmaY, vN );
vec3 R2 = cross( vN, vSigmaX );
float fDet = dot( vSigmaX, R1 ) * faceDirection;
vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
return normalize( abs( fDet ) * surf_norm - vGrad );
}
#endif`,Ore=`#if NUM_CLIPPING_PLANES > 0
vec4 plane;
#ifdef ALPHA_TO_COVERAGE
float distanceToPlane, distanceGradient;
float clipOpacity = 1.0;
#pragma unroll_loop_start
for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
plane = clippingPlanes[ i ];
distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
distanceGradient = fwidth( distanceToPlane ) / 2.0;
clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
if ( clipOpacity == 0.0 ) discard;
}
#pragma unroll_loop_end
#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
float unionClipOpacity = 1.0;
#pragma unroll_loop_start
for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
plane = clippingPlanes[ i ];
distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
distanceGradient = fwidth( distanceToPlane ) / 2.0;
unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
}
#pragma unroll_loop_end
clipOpacity *= 1.0 - unionClipOpacity;
#endif
diffuseColor.a *= clipOpacity;
if ( diffuseColor.a == 0.0 ) discard;
#else
#pragma unroll_loop_start
for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
plane = clippingPlanes[ i ];
if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
}
#pragma unroll_loop_end
#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
bool clipped = true;
#pragma unroll_loop_start
for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
plane = clippingPlanes[ i ];
clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
}
#pragma unroll_loop_end
if ( clipped ) discard;
#endif
#endif
#endif`,Nre=`#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`,wre=`#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
#endif`,Fre=`#if NUM_CLIPPING_PLANES > 0
vClipPosition = - mvPosition.xyz;
#endif`,Bre=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
diffuseColor *= vColor;
#endif`,Ure=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
varying vec4 vColor;
#endif`,Vre=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
varying vec4 vColor;
#endif`,Gre=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
vColor = vec4( 1.0 );
#endif
#ifdef USE_COLOR_ALPHA
vColor *= color;
#elif defined( USE_COLOR )
vColor.rgb *= color;
#endif
#ifdef USE_INSTANCING_COLOR
vColor.rgb *= instanceColor.rgb;
#endif
#ifdef USE_BATCHING_COLOR
vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );
#endif`,kre=`#define PI 3.141592653589793
#define PI2 6.283185307179586
#define PI_HALF 1.5707963267948966
#define RECIPROCAL_PI 0.3183098861837907
#define RECIPROCAL_PI2 0.15915494309189535
#define EPSILON 1e-6
#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
#define whiteComplement( a ) ( 1.0 - saturate( a ) )
float pow2( const in float x ) { return x*x; }
vec3 pow2( const in vec3 x ) { return x*x; }
float pow3( const in float x ) { return x*x*x; }
float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
highp float rand( const in vec2 uv ) {
const highp float a = 12.9898, b = 78.233, c = 43758.5453;
highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
return fract( sin( sn ) * c );
}
#ifdef HIGH_PRECISION
float precisionSafeLength( vec3 v ) { return length( v ); }
#else
float precisionSafeLength( vec3 v ) {
float maxComponent = max3( abs( v ) );
return length( v / maxComponent ) * maxComponent;
}
#endif
struct IncidentLight {
vec3 color;
vec3 direction;
bool visible;
};
struct ReflectedLight {
vec3 directDiffuse;
vec3 directSpecular;
vec3 indirectDiffuse;
vec3 indirectSpecular;
};
#ifdef USE_ALPHAHASH
varying vec3 vPosition;
#endif
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
}
bool isPerspectiveMatrix( mat4 m ) {
return m[ 2 ][ 3 ] == - 1.0;
}
vec2 equirectUv( in vec3 dir ) {
float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
return vec2( u, v );
}
vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
return RECIPROCAL_PI * diffuseColor;
}
vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
}
float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
} // validated`,zre=`#ifdef ENVMAP_TYPE_CUBE_UV
#define cubeUV_minMipLevel 4.0
#define cubeUV_minTileSize 16.0
float getFace( vec3 direction ) {
vec3 absDirection = abs( direction );
float face = - 1.0;
if ( absDirection.x > absDirection.z ) {
if ( absDirection.x > absDirection.y )
face = direction.x > 0.0 ? 0.0 : 3.0;
else
face = direction.y > 0.0 ? 1.0 : 4.0;
} else {
if ( absDirection.z > absDirection.y )
face = direction.z > 0.0 ? 2.0 : 5.0;
else
face = direction.y > 0.0 ? 1.0 : 4.0;
}
return face;
}
vec2 getUV( vec3 direction, float face ) {
vec2 uv;
if ( face == 0.0 ) {
uv = vec2( direction.z, direction.y ) / abs( direction.x );
} else if ( face == 1.0 ) {
uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
} else if ( face == 2.0 ) {
uv = vec2( - direction.x, direction.y ) / abs( direction.z );
} else if ( face == 3.0 ) {
uv = vec2( - direction.z, direction.y ) / abs( direction.x );
} else if ( face == 4.0 ) {
uv = vec2( - direction.x, direction.z ) / abs( direction.y );
} else {
uv = vec2( direction.x, direction.y ) / abs( direction.z );
}
return 0.5 * ( uv + 1.0 );
}
vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
float face = getFace( direction );
float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
mipInt = max( mipInt, cubeUV_minMipLevel );
float faceSize = exp2( mipInt );
highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
if ( face > 2.0 ) {
uv.y += faceSize;
face -= 3.0;
}
uv.x += face * faceSize;
uv.x += filterInt * 3.0 * cubeUV_minTileSize;
uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
uv.x *= CUBEUV_TEXEL_WIDTH;
uv.y *= CUBEUV_TEXEL_HEIGHT;
#ifdef texture2DGradEXT
return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
#else
return texture2D( envMap, uv ).rgb;
#endif
}
#define cubeUV_r0 1.0
#define cubeUV_m0 - 2.0
#define cubeUV_r1 0.8
#define cubeUV_m1 - 1.0
#define cubeUV_r4 0.4
#define cubeUV_m4 2.0
#define cubeUV_r5 0.305
#define cubeUV_m5 3.0
#define cubeUV_r6 0.21
#define cubeUV_m6 4.0
float roughnessToMip( float roughness ) {
float mip = 0.0;
if ( roughness >= cubeUV_r1 ) {
mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
} else if ( roughness >= cubeUV_r4 ) {
mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
} else if ( roughness >= cubeUV_r5 ) {
mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
} else if ( roughness >= cubeUV_r6 ) {
mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
} else {
mip = - 2.0 * log2( 1.16 * roughness ); }
return mip;
}
vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
float mipF = fract( mip );
float mipInt = floor( mip );
vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
if ( mipF == 0.0 ) {
return vec4( color0, 1.0 );
} else {
vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
return vec4( mix( color0, color1, mipF ), 1.0 );
}
}
#endif`,Wre=`vec3 transformedNormal = objectNormal;
#ifdef USE_TANGENT
vec3 transformedTangent = objectTangent;
#endif
#ifdef USE_BATCHING
mat3 bm = mat3( batchingMatrix );
transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
transformedNormal = bm * transformedNormal;
#ifdef USE_TANGENT
transformedTangent = bm * transformedTangent;
#endif
#endif
#ifdef USE_INSTANCING
mat3 im = mat3( instanceMatrix );
transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
transformedNormal = im * transformedNormal;
#ifdef USE_TANGENT
transformedTangent = im * transformedTangent;
#endif
#endif
transformedNormal = normalMatrix * transformedNormal;
#ifdef FLIP_SIDED
transformedNormal = - transformedNormal;
#endif
#ifdef USE_TANGENT
transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
#ifdef FLIP_SIDED
transformedTangent = - transformedTangent;
#endif
#endif`,Hre=`#ifdef USE_DISPLACEMENTMAP
uniform sampler2D displacementMap;
uniform float displacementScale;
uniform float displacementBias;
#endif`,Xre=`#ifdef USE_DISPLACEMENTMAP
transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`,Yre=`#ifdef USE_EMISSIVEMAP
vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
emissiveColor = sRGBTransferEOTF( emissiveColor );
#endif
totalEmissiveRadiance *= emissiveColor.rgb;
#endif`,Kre=`#ifdef USE_EMISSIVEMAP
uniform sampler2D emissiveMap;
#endif`,jre="gl_FragColor = linearToOutputTexel( gl_FragColor );",Zre=`vec4 LinearTransferOETF( in vec4 value ) {
return value;
}
vec4 sRGBTransferEOTF( in vec4 value ) {
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.a );
}
vec4 sRGBTransferOETF( in vec4 value ) {
return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
}`,qre=`#ifdef USE_ENVMAP
#ifdef ENV_WORLDPOS
vec3 cameraToFrag;
if ( isOrthographic ) {
cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
} else {
cameraToFrag = normalize( vWorldPosition - cameraPosition );
}
vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
#ifdef ENVMAP_MODE_REFLECTION
vec3 reflectVec = reflect( cameraToFrag, worldNormal );
#else
vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
#endif
#else
vec3 reflectVec = vReflect;
#endif
#ifdef ENVMAP_TYPE_CUBE
vec4 envColor = textureCube( envMap, envMapRotation * reflectVec );
#ifdef ENVMAP_BLENDING_MULTIPLY
outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
#elif defined( ENVMAP_BLENDING_MIX )
outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
#elif defined( ENVMAP_BLENDING_ADD )
outgoingLight += envColor.xyz * specularStrength * reflectivity;
#endif
#endif
#endif`,Qre=`#ifdef USE_ENVMAP
uniform float envMapIntensity;
uniform mat3 envMapRotation;
#ifdef ENVMAP_TYPE_CUBE
uniform samplerCube envMap;
#else
uniform sampler2D envMap;
#endif
#endif`,$re=`#ifdef USE_ENVMAP
uniform float reflectivity;
#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
#define ENV_WORLDPOS
#endif
#ifdef ENV_WORLDPOS
varying vec3 vWorldPosition;
uniform float refractionRatio;
#else
varying vec3 vReflect;
#endif
#endif`,Jre=`#ifdef USE_ENVMAP
#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
#define ENV_WORLDPOS
#endif
#ifdef ENV_WORLDPOS
varying vec3 vWorldPosition;
#else
varying vec3 vReflect;
uniform float refractionRatio;
#endif
#endif`,ene=`#ifdef USE_ENVMAP
#ifdef ENV_WORLDPOS
vWorldPosition = worldPosition.xyz;
#else
vec3 cameraToVertex;
if ( isOrthographic ) {
cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
} else {
cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
}
vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
#ifdef ENVMAP_MODE_REFLECTION
vReflect = reflect( cameraToVertex, worldNormal );
#else
vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
#endif
#endif
#endif`,tne=`#ifdef USE_FOG
vFogDepth = - mvPosition.z;
#endif`,ine=`#ifdef USE_FOG
varying float vFogDepth;
#endif`,rne=`#ifdef USE_FOG
#ifdef FOG_EXP2
float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
#else
float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
#endif
gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
#endif`,nne=`#ifdef USE_FOG
uniform vec3 fogColor;
varying float vFogDepth;
#ifdef FOG_EXP2
uniform float fogDensity;
#else
uniform float fogNear;
uniform float fogFar;
#endif
#endif`,sne=`#ifdef USE_GRADIENTMAP
uniform sampler2D gradientMap;
#endif
vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
float dotNL = dot( normal, lightDirection );
vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
#ifdef USE_GRADIENTMAP
return vec3( texture2D( gradientMap, coord ).r );
#else
vec2 fw = fwidth( coord ) * 0.5;
return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
#endif
}`,ane=`#ifdef USE_LIGHTMAP
uniform sampler2D lightMap;
uniform float lightMapIntensity;
#endif`,one=`LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`,lne=`varying vec3 vViewPosition;
struct LambertMaterial {
vec3 diffuseColor;
float specularStrength;
};
void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
vec3 irradiance = dotNL * directLight.color;
reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct RE_Direct_Lambert
#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,cne=`uniform bool receiveShadow;
uniform vec3 ambientLightColor;
#if defined( USE_LIGHT_PROBES )
uniform vec3 lightProbe[ 9 ];
#endif
vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
float x = normal.x, y = normal.y, z = normal.z;
vec3 result = shCoefficients[ 0 ] * 0.886227;
result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
return result;
}
vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
return irradiance;
}
vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
vec3 irradiance = ambientLightColor;
return irradiance;
}
float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
if ( cutoffDistance > 0.0 ) {
distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
}
return distanceFalloff;
}
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
return smoothstep( coneCosine, penumbraCosine, angleCosine );
}
#if NUM_DIR_LIGHTS > 0
struct DirectionalLight {
vec3 direction;
vec3 color;
};
uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
light.color = directionalLight.color;
light.direction = directionalLight.direction;
light.visible = true;
}
#endif
#if NUM_POINT_LIGHTS > 0
struct PointLight {
vec3 position;
vec3 color;
float distance;
float decay;
};
uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
vec3 lVector = pointLight.position - geometryPosition;
light.direction = normalize( lVector );
float lightDistance = length( lVector );
light.color = pointLight.color;
light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
light.visible = ( light.color != vec3( 0.0 ) );
}
#endif
#if NUM_SPOT_LIGHTS > 0
struct SpotLight {
vec3 position;
vec3 direction;
vec3 color;
float distance;
float decay;
float coneCos;
float penumbraCos;
};
uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
vec3 lVector = spotLight.position - geometryPosition;
light.direction = normalize( lVector );
float angleCos = dot( light.direction, spotLight.direction );
float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
if ( spotAttenuation > 0.0 ) {
float lightDistance = length( lVector );
light.color = spotLight.color * spotAttenuation;
light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
light.visible = ( light.color != vec3( 0.0 ) );
} else {
light.color = vec3( 0.0 );
light.visible = false;
}
}
#endif
#if NUM_RECT_AREA_LIGHTS > 0
struct RectAreaLight {
vec3 color;
vec3 position;
vec3 halfWidth;
vec3 halfHeight;
};
uniform sampler2D ltc_1; uniform sampler2D ltc_2;
uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
#endif
#if NUM_HEMI_LIGHTS > 0
struct HemisphereLight {
vec3 direction;
vec3 skyColor;
vec3 groundColor;
};
uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
float dotNL = dot( normal, hemiLight.direction );
float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
return irradiance;
}
#endif
#include <lightprobes_pars_fragment>`,fne=`#ifdef USE_ENVMAP
vec3 getIBLIrradiance( const in vec3 normal ) {
#ifdef ENVMAP_TYPE_CUBE_UV
vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
return PI * envMapColor.rgb * envMapIntensity;
#else
return vec3( 0.0 );
#endif
}
vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
#ifdef ENVMAP_TYPE_CUBE_UV
vec3 reflectVec = reflect( - viewDir, normal );
reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );
reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
return envMapColor.rgb * envMapIntensity;
#else
return vec3( 0.0 );
#endif
}
#ifdef USE_ANISOTROPY
vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
#ifdef ENVMAP_TYPE_CUBE_UV
vec3 bentNormal = cross( bitangent, viewDir );
bentNormal = normalize( cross( bentNormal, bitangent ) );
bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
return getIBLRadiance( viewDir, bentNormal, roughness );
#else
return vec3( 0.0 );
#endif
}
#endif
#endif`,dne=`ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`,une=`varying vec3 vViewPosition;
struct ToonMaterial {
vec3 diffuseColor;
};
void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct RE_Direct_Toon
#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,hne=`BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`,mne=`varying vec3 vViewPosition;
struct BlinnPhongMaterial {
vec3 diffuseColor;
vec3 specularColor;
float specularShininess;
float specularStrength;
};
void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
vec3 irradiance = dotNL * directLight.color;
reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
}
void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct RE_Direct_BlinnPhong
#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,pne=`PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );
material.metalness = metalnessFactor;
vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
material.roughness = min( material.roughness, 1.0 );
#ifdef IOR
material.ior = ior;
#ifdef USE_SPECULAR
float specularIntensityFactor = specularIntensity;
vec3 specularColorFactor = specularColor;
#ifdef USE_SPECULAR_COLORMAP
specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
#endif
material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
#else
float specularIntensityFactor = 1.0;
vec3 specularColorFactor = vec3( 1.0 );
material.specularF90 = 1.0;
#endif
material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;
material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );
#else
material.specularColor = vec3( 0.04 );
material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );
material.specularF90 = 1.0;
#endif
#ifdef USE_CLEARCOAT
material.clearcoat = clearcoat;
material.clearcoatRoughness = clearcoatRoughness;
material.clearcoatF0 = vec3( 0.04 );
material.clearcoatF90 = 1.0;
#ifdef USE_CLEARCOATMAP
material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
#endif
material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
material.clearcoatRoughness += geometryRoughness;
material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
#endif
#ifdef USE_DISPERSION
material.dispersion = dispersion;
#endif
#ifdef USE_IRIDESCENCE
material.iridescence = iridescence;
material.iridescenceIOR = iridescenceIOR;
#ifdef USE_IRIDESCENCEMAP
material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
#else
material.iridescenceThickness = iridescenceThicknessMaximum;
#endif
#endif
#ifdef USE_SHEEN
material.sheenColor = sheenColor;
#ifdef USE_SHEEN_COLORMAP
material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
#endif
material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 );
#ifdef USE_SHEEN_ROUGHNESSMAP
material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
#endif
#endif
#ifdef USE_ANISOTROPY
#ifdef USE_ANISOTROPYMAP
mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
#else
vec2 anisotropyV = anisotropyVector;
#endif
material.anisotropy = length( anisotropyV );
if( material.anisotropy == 0.0 ) {
anisotropyV = vec2( 1.0, 0.0 );
} else {
anisotropyV /= material.anisotropy;
material.anisotropy = saturate( material.anisotropy );
}
material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
#endif`,gne=`uniform sampler2D dfgLUT;
struct PhysicalMaterial {
vec3 diffuseColor;
vec3 diffuseContribution;
vec3 specularColor;
vec3 specularColorBlended;
float roughness;
float metalness;
float specularF90;
float dispersion;
#ifdef USE_CLEARCOAT
float clearcoat;
float clearcoatRoughness;
vec3 clearcoatF0;
float clearcoatF90;
#endif
#ifdef USE_IRIDESCENCE
float iridescence;
float iridescenceIOR;
float iridescenceThickness;
vec3 iridescenceFresnel;
vec3 iridescenceF0;
vec3 iridescenceFresnelDielectric;
vec3 iridescenceFresnelMetallic;
#endif
#ifdef USE_SHEEN
vec3 sheenColor;
float sheenRoughness;
#endif
#ifdef IOR
float ior;
#endif
#ifdef USE_TRANSMISSION
float transmission;
float transmissionAlpha;
float thickness;
float attenuationDistance;
vec3 attenuationColor;
#endif
#ifdef USE_ANISOTROPY
float anisotropy;
float alphaT;
vec3 anisotropyT;
vec3 anisotropyB;
#endif
};
vec3 clearcoatSpecularDirect = vec3( 0.0 );
vec3 clearcoatSpecularIndirect = vec3( 0.0 );
vec3 sheenSpecularDirect = vec3( 0.0 );
vec3 sheenSpecularIndirect = vec3(0.0 );
vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
float x2 = x * x;
float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
}
float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
float a2 = pow2( alpha );
float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
return 0.5 / max( gv + gl, EPSILON );
}
float D_GGX( const in float alpha, const in float dotNH ) {
float a2 = pow2( alpha );
float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
return RECIPROCAL_PI * a2 / pow2( denom );
}
#ifdef USE_ANISOTROPY
float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {
float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
return 0.5 / max( gv + gl, EPSILON );
}
float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
float a2 = alphaT * alphaB;
highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
highp float v2 = dot( v, v );
float w2 = a2 / v2;
return RECIPROCAL_PI * a2 * pow2 ( w2 );
}
#endif
#ifdef USE_CLEARCOAT
vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
vec3 f0 = material.clearcoatF0;
float f90 = material.clearcoatF90;
float roughness = material.clearcoatRoughness;
float alpha = pow2( roughness );
vec3 halfDir = normalize( lightDir + viewDir );
float dotNL = saturate( dot( normal, lightDir ) );
float dotNV = saturate( dot( normal, viewDir ) );
float dotNH = saturate( dot( normal, halfDir ) );
float dotVH = saturate( dot( viewDir, halfDir ) );
vec3 F = F_Schlick( f0, f90, dotVH );
float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
float D = D_GGX( alpha, dotNH );
return F * ( V * D );
}
#endif
vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
vec3 f0 = material.specularColorBlended;
float f90 = material.specularF90;
float roughness = material.roughness;
float alpha = pow2( roughness );
vec3 halfDir = normalize( lightDir + viewDir );
float dotNL = saturate( dot( normal, lightDir ) );
float dotNV = saturate( dot( normal, viewDir ) );
float dotNH = saturate( dot( normal, halfDir ) );
float dotVH = saturate( dot( viewDir, halfDir ) );
vec3 F = F_Schlick( f0, f90, dotVH );
#ifdef USE_IRIDESCENCE
F = mix( F, material.iridescenceFresnel, material.iridescence );
#endif
#ifdef USE_ANISOTROPY
float dotTL = dot( material.anisotropyT, lightDir );
float dotTV = dot( material.anisotropyT, viewDir );
float dotTH = dot( material.anisotropyT, halfDir );
float dotBL = dot( material.anisotropyB, lightDir );
float dotBV = dot( material.anisotropyB, viewDir );
float dotBH = dot( material.anisotropyB, halfDir );
float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
#else
float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
float D = D_GGX( alpha, dotNH );
#endif
return F * ( V * D );
}
vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
const float LUT_SIZE = 64.0;
const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
const float LUT_BIAS = 0.5 / LUT_SIZE;
float dotNV = saturate( dot( N, V ) );
vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
uv = uv * LUT_SCALE + LUT_BIAS;
return uv;
}
float LTC_ClippedSphereFormFactor( const in vec3 f ) {
float l = length( f );
return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
float x = dot( v1, v2 );
float y = abs( x );
float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
float b = 3.4175940 + ( 4.1616724 + y ) * y;
float v = a / b;
float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
return cross( v1, v2 ) * theta_sintheta;
}
vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
vec3 lightNormal = cross( v1, v2 );
if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
vec3 T1, T2;
T1 = normalize( V - N * dot( V, N ) );
T2 = - cross( N, T1 );
mat3 mat = mInv * transpose( mat3( T1, T2, N ) );
vec3 coords[ 4 ];
coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
coords[ 0 ] = normalize( coords[ 0 ] );
coords[ 1 ] = normalize( coords[ 1 ] );
coords[ 2 ] = normalize( coords[ 2 ] );
coords[ 3 ] = normalize( coords[ 3 ] );
vec3 vectorFormFactor = vec3( 0.0 );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
return vec3( result );
}
#if defined( USE_SHEEN )
float D_Charlie( float roughness, float dotNH ) {
float alpha = pow2( roughness );
float invAlpha = 1.0 / alpha;
float cos2h = dotNH * dotNH;
float sin2h = max( 1.0 - cos2h, 0.0078125 );
return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
}
float V_Neubelt( float dotNV, float dotNL ) {
return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
}
vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
vec3 halfDir = normalize( lightDir + viewDir );
float dotNL = saturate( dot( normal, lightDir ) );
float dotNV = saturate( dot( normal, viewDir ) );
float dotNH = saturate( dot( normal, halfDir ) );
float D = D_Charlie( sheenRoughness, dotNH );
float V = V_Neubelt( dotNV, dotNL );
return sheenColor * ( D * V );
}
#endif
float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
float dotNV = saturate( dot( normal, viewDir ) );
float r2 = roughness * roughness;
float rInv = 1.0 / ( roughness + 0.1 );
float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;
float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;
float DG = exp( a * dotNV + b );
return saturate( DG );
}
vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
float dotNV = saturate( dot( normal, viewDir ) );
vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;
return specularColor * fab.x + specularF90 * fab.y;
}
#ifdef USE_IRIDESCENCE
void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#else
void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#endif
float dotNV = saturate( dot( normal, viewDir ) );
vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;
#ifdef USE_IRIDESCENCE
vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
#else
vec3 Fr = specularColor;
#endif
vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
float Ess = fab.x + fab.y;
float Ems = 1.0 - Ess;
vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
singleScatter += FssEss;
multiScatter += Fms * Ems;
}
vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );
float dotNL = saturate( dot( normal, lightDir ) );
float dotNV = saturate( dot( normal, viewDir ) );
vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;
vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;
vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;
vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;
float Ess_V = dfgV.x + dfgV.y;
float Ess_L = dfgL.x + dfgL.y;
float Ems_V = 1.0 - Ess_V;
float Ems_L = 1.0 - Ess_L;
vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;
vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );
float compensationFactor = Ems_V * Ems_L;
vec3 multiScatter = Fms * compensationFactor;
return singleScatter + multiScatter;
}
#if NUM_RECT_AREA_LIGHTS > 0
void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
vec3 normal = geometryNormal;
vec3 viewDir = geometryViewDir;
vec3 position = geometryPosition;
vec3 lightPos = rectAreaLight.position;
vec3 halfWidth = rectAreaLight.halfWidth;
vec3 halfHeight = rectAreaLight.halfHeight;
vec3 lightColor = rectAreaLight.color;
float roughness = material.roughness;
vec3 rectCoords[ 4 ];
rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
vec2 uv = LTC_Uv( normal, viewDir, roughness );
vec4 t1 = texture2D( ltc_1, uv );
vec4 t2 = texture2D( ltc_2, uv );
mat3 mInv = mat3(
vec3( t1.x, 0, t1.y ),
vec3( 0, 1, 0 ),
vec3( t1.z, 0, t1.w )
);
vec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y );
reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
#ifdef USE_CLEARCOAT
vec3 Ncc = geometryClearcoatNormal;
vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness );
vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat );
vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat );
mat3 mInvClearcoat = mat3(
vec3( t1Clearcoat.x, 0, t1Clearcoat.y ),
vec3( 0, 1, 0 ),
vec3( t1Clearcoat.z, 0, t1Clearcoat.w )
);
vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y;
clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords );
#endif
}
#endif
void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
vec3 irradiance = dotNL * directLight.color;
#ifdef USE_CLEARCOAT
float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
vec3 ccIrradiance = dotNLcc * directLight.color;
clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
#endif
#ifdef USE_SHEEN
sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );
float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );
irradiance *= sheenEnergyComp;
#endif
reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );
reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );
}
void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );
#ifdef USE_SHEEN
float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;
diffuse *= sheenEnergyComp;
#endif
reflectedLight.indirectDiffuse += diffuse;
}
void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {
#ifdef USE_CLEARCOAT
clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
#endif
#ifdef USE_SHEEN
sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;
#endif
vec3 singleScatteringDielectric = vec3( 0.0 );
vec3 multiScatteringDielectric = vec3( 0.0 );
vec3 singleScatteringMetallic = vec3( 0.0 );
vec3 multiScatteringMetallic = vec3( 0.0 );
#ifdef USE_IRIDESCENCE
computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );
computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );
#else
computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );
computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );
#endif
vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );
vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );
vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;
vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );
vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
vec3 indirectSpecular = radiance * singleScattering;
indirectSpecular += multiScattering * cosineWeightedIrradiance;
vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;
#ifdef USE_SHEEN
float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;
indirectSpecular *= sheenEnergyComp;
indirectDiffuse *= sheenEnergyComp;
#endif
reflectedLight.indirectSpecular += indirectSpecular;
reflectedLight.indirectDiffuse += indirectDiffuse;
}
#define RE_Direct RE_Direct_Physical
#define RE_Direct_RectArea RE_Direct_RectArea_Physical
#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical
#define RE_IndirectSpecular RE_IndirectSpecular_Physical
float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
}`,_ne=`
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
vec3 geometryClearcoatNormal = vec3( 0.0 );
#ifdef USE_CLEARCOAT
geometryClearcoatNormal = clearcoatNormal;
#endif
#ifdef USE_IRIDESCENCE
float dotNVi = saturate( dot( normal, geometryViewDir ) );
if ( material.iridescenceThickness == 0.0 ) {
material.iridescence = 0.0;
} else {
material.iridescence = saturate( material.iridescence );
}
if ( material.iridescence > 0.0 ) {
material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );
material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );
material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
}
#endif
IncidentLight directLight;
#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
PointLight pointLight;
#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
PointLightShadow pointLightShadow;
#endif
#pragma unroll_loop_start
for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
pointLight = pointLights[ i ];
getPointLightInfo( pointLight, geometryPosition, directLight );
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )
pointLightShadow = pointLightShadows[ i ];
directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
#endif
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
}
#pragma unroll_loop_end
#endif
#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
SpotLight spotLight;
vec4 spotColor;
vec3 spotLightCoord;
bool inSpotLightMap;
#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
SpotLightShadow spotLightShadow;
#endif
#pragma unroll_loop_start
for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
spotLight = spotLights[ i ];
getSpotLightInfo( spotLight, geometryPosition, directLight );
#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
#else
#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
#endif
#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
#endif
#undef SPOT_LIGHT_MAP_INDEX
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
spotLightShadow = spotLightShadows[ i ];
directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
#endif
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
}
#pragma unroll_loop_end
#endif
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
DirectionalLight directionalLight;
#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
DirectionalLightShadow directionalLightShadow;
#endif
#pragma unroll_loop_start
for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
directionalLight = directionalLights[ i ];
getDirectionalLightInfo( directionalLight, directLight );
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
directionalLightShadow = directionalLightShadows[ i ];
directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
#endif
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
}
#pragma unroll_loop_end
#endif
#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
RectAreaLight rectAreaLight;
#pragma unroll_loop_start
for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
rectAreaLight = rectAreaLights[ i ];
RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
}
#pragma unroll_loop_end
#endif
#if defined( RE_IndirectDiffuse )
vec3 iblIrradiance = vec3( 0.0 );
vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
#if defined( USE_LIGHT_PROBES )
irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
#endif
#if ( NUM_HEMI_LIGHTS > 0 )
#pragma unroll_loop_start
for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
}
#pragma unroll_loop_end
#endif
#ifdef USE_LIGHT_PROBES_GRID
vec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz;
vec3 probeWorldNormal = inverseTransformDirection( geometryNormal, viewMatrix );
irradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal );
#endif
#endif
#if defined( RE_IndirectSpecular )
vec3 radiance = vec3( 0.0 );
vec3 clearcoatRadiance = vec3( 0.0 );
#endif`,vne=`#if defined( RE_IndirectDiffuse )
#ifdef USE_LIGHTMAP
vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
irradiance += lightMapIrradiance;
#endif
#if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV )
#if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )
iblIrradiance += getIBLIrradiance( geometryNormal );
#endif
#endif
#endif
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
#ifdef USE_ANISOTROPY
radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
#else
radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
#endif
#ifdef USE_CLEARCOAT
clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
#endif
#endif`,Ene=`#if defined( RE_IndirectDiffuse )
#if defined( LAMBERT ) || defined( PHONG )
irradiance += iblIrradiance;
#endif
RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
#if defined( RE_IndirectSpecular )
RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif`,Sne=`#ifdef USE_LIGHT_PROBES_GRID
uniform highp sampler3D probesSH;
uniform vec3 probesMin;
uniform vec3 probesMax;
uniform vec3 probesResolution;
vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {
vec3 res = probesResolution;
vec3 gridRange = probesMax - probesMin;
vec3 resMinusOne = res - 1.0;
vec3 probeSpacing = gridRange / resMinusOne;
vec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5;
vec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 );
uvw = uvw * resMinusOne / res + 0.5 / res;
float nz = res.z;
float paddedSlices = nz + 2.0;
float atlasDepth = 7.0 * paddedSlices;
float uvZBase = uvw.z * nz + 1.0;
vec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) );
vec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) );
vec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) );
vec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) );
vec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) );
vec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) );
vec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) );
vec3 c0 = s0.xyz;
vec3 c1 = vec3( s0.w, s1.xy );
vec3 c2 = vec3( s1.zw, s2.x );
vec3 c3 = s2.yzw;
vec3 c4 = s3.xyz;
vec3 c5 = vec3( s3.w, s4.xy );
vec3 c6 = vec3( s4.zw, s5.x );
vec3 c7 = s5.yzw;
vec3 c8 = s6.xyz;
float x = worldNormal.x, y = worldNormal.y, z = worldNormal.z;
vec3 result = c0 * 0.886227;
result += c1 * 2.0 * 0.511664 * y;
result += c2 * 2.0 * 0.511664 * z;
result += c3 * 2.0 * 0.511664 * x;
result += c4 * 2.0 * 0.429043 * x * y;
result += c5 * 2.0 * 0.429043 * y * z;
result += c6 * ( 0.743125 * z * z - 0.247708 );
result += c7 * 2.0 * 0.429043 * x * z;
result += c8 * 0.429043 * ( x * x - y * y );
return max( result, vec3( 0.0 ) );
}
#endif`,Tne=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`,Ane=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
uniform float logDepthBufFC;
varying float vFragDepth;
varying float vIsPerspective;
#endif`,xne=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
varying float vFragDepth;
varying float vIsPerspective;
#endif`,Rne=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
vFragDepth = 1.0 + gl_Position.w;
vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`,bne=`#ifdef USE_MAP
vec4 sampledDiffuseColor = texture2D( map, vMapUv );
#ifdef DECODE_VIDEO_TEXTURE
sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
#endif
diffuseColor *= sampledDiffuseColor;
#endif`,Mne=`#ifdef USE_MAP
uniform sampler2D map;
#endif`,yne=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
#if defined( USE_POINTS_UV )
vec2 uv = vUv;
#else
vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
#endif
#endif
#ifdef USE_MAP
diffuseColor *= texture2D( map, uv );
#endif
#ifdef USE_ALPHAMAP
diffuseColor.a *= texture2D( alphaMap, uv ).g;
#endif`,Ine=`#if defined( USE_POINTS_UV )
varying vec2 vUv;
#else
#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
uniform mat3 uvTransform;
#endif
#endif
#ifdef USE_MAP
uniform sampler2D map;
#endif
#ifdef USE_ALPHAMAP
uniform sampler2D alphaMap;
#endif`,Cne=`float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
metalnessFactor *= texelMetalness.b;
#endif`,Pne=`#ifdef USE_METALNESSMAP
uniform sampler2D metalnessMap;
#endif`,Lne=`#ifdef USE_INSTANCING_MORPH
float morphTargetInfluences[ MORPHTARGETS_COUNT ];
float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
}
#endif`,Dne=`#if defined( USE_MORPHCOLORS )
vColor *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
#if defined( USE_COLOR_ALPHA )
if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
#elif defined( USE_COLOR )
if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
#endif
}
#endif`,One=`#ifdef USE_MORPHNORMALS
objectNormal *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
}
#endif`,Nne=`#ifdef USE_MORPHTARGETS
#ifndef USE_INSTANCING_MORPH
uniform float morphTargetBaseInfluence;
uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
#endif
uniform sampler2DArray morphTargetsTexture;
uniform ivec2 morphTargetsTextureSize;
vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
int y = texelIndex / morphTargetsTextureSize.x;
int x = texelIndex - y * morphTargetsTextureSize.x;
ivec3 morphUV = ivec3( x, y, morphTargetIndex );
return texelFetch( morphTargetsTexture, morphUV, 0 );
}
#endif`,wne=`#ifdef USE_MORPHTARGETS
transformed *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
}
#endif`,Fne=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
#ifdef FLAT_SHADED
vec3 fdx = dFdx( vViewPosition );
vec3 fdy = dFdy( vViewPosition );
vec3 normal = normalize( cross( fdx, fdy ) );
#else
vec3 normal = normalize( vNormal );
#ifdef DOUBLE_SIDED
normal *= faceDirection;
#endif
#endif
#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
#ifdef USE_TANGENT
mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
#else
mat3 tbn = getTangentFrame( - vViewPosition, normal,
#if defined( USE_NORMALMAP )
vNormalMapUv
#elif defined( USE_CLEARCOAT_NORMALMAP )
vClearcoatNormalMapUv
#else
vUv
#endif
);
#endif
#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
tbn[0] *= faceDirection;
tbn[1] *= faceDirection;
#endif
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
#ifdef USE_TANGENT
mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
#else
mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
#endif
#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
tbn2[0] *= faceDirection;
tbn2[1] *= faceDirection;
#endif
#endif
vec3 nonPerturbedNormal = normal;`,Bne=`#ifdef USE_NORMALMAP_OBJECTSPACE
normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
#ifdef FLIP_SIDED
normal = - normal;
#endif
#ifdef DOUBLE_SIDED
normal = normal * faceDirection;
#endif
normal = normalize( normalMatrix * normal );
#elif defined( USE_NORMALMAP_TANGENTSPACE )
vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
#if defined( USE_PACKED_NORMALMAP )
mapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) );
#endif
mapN.xy *= normalScale;
normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
#endif`,Une=`#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
#endif`,Vne=`#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
#endif`,Gne=`#ifndef FLAT_SHADED
vNormal = normalize( transformedNormal );
#ifdef USE_TANGENT
vTangent = normalize( transformedTangent );
vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
#endif
#endif`,kne=`#ifdef USE_NORMALMAP
uniform sampler2D normalMap;
uniform vec2 normalScale;
#endif
#ifdef USE_NORMALMAP_OBJECTSPACE
uniform mat3 normalMatrix;
#endif
#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
vec3 q0 = dFdx( eye_pos.xyz );
vec3 q1 = dFdy( eye_pos.xyz );
vec2 st0 = dFdx( uv.st );
vec2 st1 = dFdy( uv.st );
vec3 N = surf_norm;
vec3 q1perp = cross( q1, N );
vec3 q0perp = cross( N, q0 );
vec3 T = q1perp * st0.x + q0perp * st1.x;
vec3 B = q1perp * st0.y + q0perp * st1.y;
float det = max( dot( T, T ), dot( B, B ) );
float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
return mat3( T * scale, B * scale, N );
}
#endif`,zne=`#ifdef USE_CLEARCOAT
vec3 clearcoatNormal = nonPerturbedNormal;
#endif`,Wne=`#ifdef USE_CLEARCOAT_NORMALMAP
vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
clearcoatMapN.xy *= clearcoatNormalScale;
clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`,Hne=`#ifdef USE_CLEARCOATMAP
uniform sampler2D clearcoatMap;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
uniform sampler2D clearcoatNormalMap;
uniform vec2 clearcoatNormalScale;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
uniform sampler2D clearcoatRoughnessMap;
#endif`,Xne=`#ifdef USE_IRIDESCENCEMAP
uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
uniform sampler2D iridescenceThicknessMap;
#endif`,Yne=`#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Kne=`vec3 packNormalToRGB( const in vec3 normal ) {
return normalize( normal ) * 0.5 + 0.5;
}
vec3 unpackRGBToNormal( const in vec3 rgb ) {
return 2.0 * rgb.xyz - 1.0;
}
const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
const float Inv255 = 1. / 255.;
const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
vec4 packDepthToRGBA( const in float v ) {
if( v <= 0.0 )
return vec4( 0., 0., 0., 0. );
if( v >= 1.0 )
return vec4( 1., 1., 1., 1. );
float vuf;
float af = modf( v * PackFactors.a, vuf );
float bf = modf( vuf * ShiftRight8, vuf );
float gf = modf( vuf * ShiftRight8, vuf );
return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
}
vec3 packDepthToRGB( const in float v ) {
if( v <= 0.0 )
return vec3( 0., 0., 0. );
if( v >= 1.0 )
return vec3( 1., 1., 1. );
float vuf;
float bf = modf( v * PackFactors.b, vuf );
float gf = modf( vuf * ShiftRight8, vuf );
return vec3( vuf * Inv255, gf * PackUpscale, bf );
}
vec2 packDepthToRG( const in float v ) {
if( v <= 0.0 )
return vec2( 0., 0. );
if( v >= 1.0 )
return vec2( 1., 1. );
float vuf;
float gf = modf( v * 256., vuf );
return vec2( vuf * Inv255, gf );
}
float unpackRGBAToDepth( const in vec4 v ) {
return dot( v, UnpackFactors4 );
}
float unpackRGBToDepth( const in vec3 v ) {
return dot( v, UnpackFactors3 );
}
float unpackRGToDepth( const in vec2 v ) {
return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
}
vec4 pack2HalfToRGBA( const in vec2 v ) {
vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
}
vec2 unpackRGBATo2Half( const in vec4 v ) {
return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
}
float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
return ( viewZ + near ) / ( near - far );
}
float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
#ifdef USE_REVERSED_DEPTH_BUFFER
return depth * ( far - near ) - far;
#else
return depth * ( near - far ) - near;
#endif
}
float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
}
float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
#ifdef USE_REVERSED_DEPTH_BUFFER
return ( near * far ) / ( ( near - far ) * depth - near );
#else
return ( near * far ) / ( ( far - near ) * depth - far );
#endif
}`,jne=`#ifdef PREMULTIPLIED_ALPHA
gl_FragColor.rgb *= gl_FragColor.a;
#endif`,Zne=`vec4 mvPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
mvPosition = batchingMatrix * mvPosition;
#endif
#ifdef USE_INSTANCING
mvPosition = instanceMatrix * mvPosition;
#endif
mvPosition = modelViewMatrix * mvPosition;
gl_Position = projectionMatrix * mvPosition;`,qne=`#ifdef DITHERING
gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`,Qne=`#ifdef DITHERING
vec3 dithering( vec3 color ) {
float grid_position = rand( gl_FragCoord.xy );
vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
return color + dither_shift_RGB;
}
#endif`,$ne=`float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
roughnessFactor *= texelRoughness.g;
#endif`,Jne=`#ifdef USE_ROUGHNESSMAP
uniform sampler2D roughnessMap;
#endif`,ese=`#if NUM_SPOT_LIGHT_COORDS > 0
varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#if NUM_SPOT_LIGHT_MAPS > 0
uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
#endif
#ifdef USE_SHADOWMAP
#if NUM_DIR_LIGHT_SHADOWS > 0
#if defined( SHADOWMAP_TYPE_PCF )
uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
#else
uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
#endif
varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
struct DirectionalLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
};
uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
#endif
#if NUM_SPOT_LIGHT_SHADOWS > 0
#if defined( SHADOWMAP_TYPE_PCF )
uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
#else
uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
#endif
struct SpotLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
};
uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
#endif
#if NUM_POINT_LIGHT_SHADOWS > 0
#if defined( SHADOWMAP_TYPE_PCF )
uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
#elif defined( SHADOWMAP_TYPE_BASIC )
uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
#endif
varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
struct PointLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
float shadowCameraNear;
float shadowCameraFar;
};
uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
#endif
#if defined( SHADOWMAP_TYPE_PCF )
float interleavedGradientNoise( vec2 position ) {
return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );
}
vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {
const float goldenAngle = 2.399963229728653;
float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );
float theta = float( sampleIndex ) * goldenAngle + phi;
return vec2( cos( theta ), sin( theta ) ) * r;
}
#endif
#if defined( SHADOWMAP_TYPE_PCF )
float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
float shadow = 1.0;
shadowCoord.xyz /= shadowCoord.w;
shadowCoord.z += shadowBias;
bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
if ( frustumTest ) {
vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
float radius = shadowRadius * texelSize.x;
float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;
shadow = (
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )
) * 0.2;
}
return mix( 1.0, shadow, shadowIntensity );
}
#elif defined( SHADOWMAP_TYPE_VSM )
float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
float shadow = 1.0;
shadowCoord.xyz /= shadowCoord.w;
#ifdef USE_REVERSED_DEPTH_BUFFER
shadowCoord.z -= shadowBias;
#else
shadowCoord.z += shadowBias;
#endif
bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
if ( frustumTest ) {
vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;
float mean = distribution.x;
float variance = distribution.y * distribution.y;
#ifdef USE_REVERSED_DEPTH_BUFFER
float hard_shadow = step( mean, shadowCoord.z );
#else
float hard_shadow = step( shadowCoord.z, mean );
#endif
if ( hard_shadow == 1.0 ) {
shadow = 1.0;
} else {
variance = max( variance, 0.0000001 );
float d = shadowCoord.z - mean;
float p_max = variance / ( variance + d * d );
p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );
shadow = max( hard_shadow, p_max );
}
}
return mix( 1.0, shadow, shadowIntensity );
}
#else
float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
float shadow = 1.0;
shadowCoord.xyz /= shadowCoord.w;
#ifdef USE_REVERSED_DEPTH_BUFFER
shadowCoord.z -= shadowBias;
#else
shadowCoord.z += shadowBias;
#endif
bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
if ( frustumTest ) {
float depth = texture2D( shadowMap, shadowCoord.xy ).r;
#ifdef USE_REVERSED_DEPTH_BUFFER
shadow = step( depth, shadowCoord.z );
#else
shadow = step( shadowCoord.z, depth );
#endif
}
return mix( 1.0, shadow, shadowIntensity );
}
#endif
#if NUM_POINT_LIGHT_SHADOWS > 0
#if defined( SHADOWMAP_TYPE_PCF )
float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
float shadow = 1.0;
vec3 lightToPosition = shadowCoord.xyz;
vec3 bd3D = normalize( lightToPosition );
vec3 absVec = abs( lightToPosition );
float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );
if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {
#ifdef USE_REVERSED_DEPTH_BUFFER
float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );
dp -= shadowBias;
#else
float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );
dp += shadowBias;
#endif
float texelSize = shadowRadius / shadowMapSize.x;
vec3 absDir = abs( bd3D );
vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );
tangent = normalize( cross( bd3D, tangent ) );
vec3 bitangent = cross( bd3D, tangent );
float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;
vec2 sample0 = vogelDiskSample( 0, 5, phi );
vec2 sample1 = vogelDiskSample( 1, 5, phi );
vec2 sample2 = vogelDiskSample( 2, 5, phi );
vec2 sample3 = vogelDiskSample( 3, 5, phi );
vec2 sample4 = vogelDiskSample( 4, 5, phi );
shadow = (
texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +
texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +
texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +
texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +
texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )
) * 0.2;
}
return mix( 1.0, shadow, shadowIntensity );
}
#elif defined( SHADOWMAP_TYPE_BASIC )
float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
float shadow = 1.0;
vec3 lightToPosition = shadowCoord.xyz;
vec3 absVec = abs( lightToPosition );
float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );
if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {
float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );
dp += shadowBias;
vec3 bd3D = normalize( lightToPosition );
float depth = textureCube( shadowMap, bd3D ).r;
#ifdef USE_REVERSED_DEPTH_BUFFER
depth = 1.0 - depth;
#endif
shadow = step( dp, depth );
}
return mix( 1.0, shadow, shadowIntensity );
}
#endif
#endif
#endif`,tse=`#if NUM_SPOT_LIGHT_COORDS > 0
uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#ifdef USE_SHADOWMAP
#if NUM_DIR_LIGHT_SHADOWS > 0
uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
struct DirectionalLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
};
uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
#endif
#if NUM_SPOT_LIGHT_SHADOWS > 0
struct SpotLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
};
uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
#endif
#if NUM_POINT_LIGHT_SHADOWS > 0
uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
struct PointLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
float shadowCameraNear;
float shadowCameraFar;
};
uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
#endif
#endif`,ise=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
#ifdef HAS_NORMAL
vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
#else
vec3 shadowWorldNormal = vec3( 0.0 );
#endif
vec4 shadowWorldPosition;
#endif
#if defined( USE_SHADOWMAP )
#if NUM_DIR_LIGHT_SHADOWS > 0
#pragma unroll_loop_start
for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
}
#pragma unroll_loop_end
#endif
#if NUM_POINT_LIGHT_SHADOWS > 0
#pragma unroll_loop_start
for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
}
#pragma unroll_loop_end
#endif
#endif
#if NUM_SPOT_LIGHT_COORDS > 0
#pragma unroll_loop_start
for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
shadowWorldPosition = worldPosition;
#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
#endif
vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
}
#pragma unroll_loop_end
#endif`,rse=`float getShadowMask() {
float shadow = 1.0;
#ifdef USE_SHADOWMAP
#if NUM_DIR_LIGHT_SHADOWS > 0
DirectionalLightShadow directionalLight;
#pragma unroll_loop_start
for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
directionalLight = directionalLightShadows[ i ];
shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
}
#pragma unroll_loop_end
#endif
#if NUM_SPOT_LIGHT_SHADOWS > 0
SpotLightShadow spotLight;
#pragma unroll_loop_start
for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
spotLight = spotLightShadows[ i ];
shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
}
#pragma unroll_loop_end
#endif
#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )
PointLightShadow pointLight;
#pragma unroll_loop_start
for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
pointLight = pointLightShadows[ i ];
shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
}
#pragma unroll_loop_end
#endif
#endif
return shadow;
}`,nse=`#ifdef USE_SKINNING
mat4 boneMatX = getBoneMatrix( skinIndex.x );
mat4 boneMatY = getBoneMatrix( skinIndex.y );
mat4 boneMatZ = getBoneMatrix( skinIndex.z );
mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`,sse=`#ifdef USE_SKINNING
uniform mat4 bindMatrix;
uniform mat4 bindMatrixInverse;
uniform highp sampler2D boneTexture;
mat4 getBoneMatrix( const in float i ) {
int size = textureSize( boneTexture, 0 ).x;
int j = int( i ) * 4;
int x = j % size;
int y = j / size;
vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
return mat4( v1, v2, v3, v4 );
}
#endif`,ase=`#ifdef USE_SKINNING
vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
vec4 skinned = vec4( 0.0 );
skinned += boneMatX * skinVertex * skinWeight.x;
skinned += boneMatY * skinVertex * skinWeight.y;
skinned += boneMatZ * skinVertex * skinWeight.z;
skinned += boneMatW * skinVertex * skinWeight.w;
transformed = ( bindMatrixInverse * skinned ).xyz;
#endif`,ose=`#ifdef USE_SKINNING
mat4 skinMatrix = mat4( 0.0 );
skinMatrix += skinWeight.x * boneMatX;
skinMatrix += skinWeight.y * boneMatY;
skinMatrix += skinWeight.z * boneMatZ;
skinMatrix += skinWeight.w * boneMatW;
skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
#ifdef USE_TANGENT
objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
#endif
#endif`,lse=`float specularStrength;
#ifdef USE_SPECULARMAP
vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
specularStrength = texelSpecular.r;
#else
specularStrength = 1.0;
#endif`,cse=`#ifdef USE_SPECULARMAP
uniform sampler2D specularMap;
#endif`,fse=`#if defined( TONE_MAPPING )
gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`,dse=`#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
uniform float toneMappingExposure;
vec3 LinearToneMapping( vec3 color ) {
return saturate( toneMappingExposure * color );
}
vec3 ReinhardToneMapping( vec3 color ) {
color *= toneMappingExposure;
return saturate( color / ( vec3( 1.0 ) + color ) );
}
vec3 CineonToneMapping( vec3 color ) {
color *= toneMappingExposure;
color = max( vec3( 0.0 ), color - 0.004 );
return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
}
vec3 RRTAndODTFit( vec3 v ) {
vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
return a / b;
}
vec3 ACESFilmicToneMapping( vec3 color ) {
const mat3 ACESInputMat = mat3(
vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),
vec3( 0.04823, 0.01566, 0.83777 )
);
const mat3 ACESOutputMat = mat3(
vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),
vec3( -0.07367, -0.00605, 1.07602 )
);
color *= toneMappingExposure / 0.6;
color = ACESInputMat * color;
color = RRTAndODTFit( color );
color = ACESOutputMat * color;
return saturate( color );
}
const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
vec3( 1.6605, - 0.1246, - 0.0182 ),
vec3( - 0.5876, 1.1329, - 0.1006 ),
vec3( - 0.0728, - 0.0083, 1.1187 )
);
const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
vec3( 0.6274, 0.0691, 0.0164 ),
vec3( 0.3293, 0.9195, 0.0880 ),
vec3( 0.0433, 0.0113, 0.8956 )
);
vec3 agxDefaultContrastApprox( vec3 x ) {
vec3 x2 = x * x;
vec3 x4 = x2 * x2;
return + 15.5 * x4 * x2
- 40.14 * x4 * x
+ 31.96 * x4
- 6.868 * x2 * x
+ 0.4298 * x2
+ 0.1191 * x
- 0.00232;
}
vec3 AgXToneMapping( vec3 color ) {
const mat3 AgXInsetMatrix = mat3(
vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
);
const mat3 AgXOutsetMatrix = mat3(
vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
);
const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;
color *= toneMappingExposure;
color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
color = AgXInsetMatrix * color;
color = max( color, 1e-10 ); color = log2( color );
color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
color = clamp( color, 0.0, 1.0 );
color = agxDefaultContrastApprox( color );
color = AgXOutsetMatrix * color;
color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
color = clamp( color, 0.0, 1.0 );
return color;
}
vec3 NeutralToneMapping( vec3 color ) {
const float StartCompression = 0.8 - 0.04;
const float Desaturation = 0.15;
color *= toneMappingExposure;
float x = min( color.r, min( color.g, color.b ) );
float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
color -= offset;
float peak = max( color.r, max( color.g, color.b ) );
if ( peak < StartCompression ) return color;
float d = 1. - StartCompression;
float newPeak = 1. - d * d / ( peak + d - StartCompression );
color *= newPeak / peak;
float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
return mix( color, vec3( newPeak ), g );
}
vec3 CustomToneMapping( vec3 color ) { return color; }`,use=`#ifdef USE_TRANSMISSION
material.transmission = transmission;
material.transmissionAlpha = 1.0;
material.thickness = thickness;
material.attenuationDistance = attenuationDistance;
material.attenuationColor = attenuationColor;
#ifdef USE_TRANSMISSIONMAP
material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
#endif
#ifdef USE_THICKNESSMAP
material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
#endif
vec3 pos = vWorldPosition;
vec3 v = normalize( cameraPosition - pos );
vec3 n = inverseTransformDirection( normal, viewMatrix );
vec4 transmitted = getIBLVolumeRefraction(
n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,
pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
material.attenuationColor, material.attenuationDistance );
material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
#endif`,hse=`#ifdef USE_TRANSMISSION
uniform float transmission;
uniform float thickness;
uniform float attenuationDistance;
uniform vec3 attenuationColor;
#ifdef USE_TRANSMISSIONMAP
uniform sampler2D transmissionMap;
#endif
#ifdef USE_THICKNESSMAP
uniform sampler2D thicknessMap;
#endif
uniform vec2 transmissionSamplerSize;
uniform sampler2D transmissionSamplerMap;
uniform mat4 modelMatrix;
uniform mat4 projectionMatrix;
varying vec3 vWorldPosition;
float w0( float a ) {
return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
}
float w1( float a ) {
return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );
}
float w2( float a ){
return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
}
float w3( float a ) {
return ( 1.0 / 6.0 ) * ( a * a * a );
}
float g0( float a ) {
return w0( a ) + w1( a );
}
float g1( float a ) {
return w2( a ) + w3( a );
}
float h0( float a ) {
return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
}
float h1( float a ) {
return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
}
vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
uv = uv * texelSize.zw + 0.5;
vec2 iuv = floor( uv );
vec2 fuv = fract( uv );
float g0x = g0( fuv.x );
float g1x = g1( fuv.x );
float h0x = h0( fuv.x );
float h1x = h1( fuv.x );
float h0y = h0( fuv.y );
float h1y = h1( fuv.y );
vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
}
vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
vec2 fLodSizeInv = 1.0 / fLodSize;
vec2 cLodSizeInv = 1.0 / cLodSize;
vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
return mix( fSample, cSample, fract( lod ) );
}
vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
vec3 modelScale;
modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
return normalize( refractionVector ) * thickness * modelScale;
}
float applyIorToRoughness( const in float roughness, const in float ior ) {
return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
}
vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
}
vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
if ( isinf( attenuationDistance ) ) {
return vec3( 1.0 );
} else {
vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;
}
}
vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,
const in vec3 attenuationColor, const in float attenuationDistance ) {
vec4 transmittedLight;
vec3 transmittance;
#ifdef USE_DISPERSION
float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
for ( int i = 0; i < 3; i ++ ) {
vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );
vec3 refractedRayExit = position + transmissionRay;
vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
vec2 refractionCoords = ndcPos.xy / ndcPos.w;
refractionCoords += 1.0;
refractionCoords /= 2.0;
vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
transmittedLight[ i ] = transmissionSample[ i ];
transmittedLight.a += transmissionSample.a;
transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
}
transmittedLight.a /= 3.0;
#else
vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
vec3 refractedRayExit = position + transmissionRay;
vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
vec2 refractionCoords = ndcPos.xy / ndcPos.w;
refractionCoords += 1.0;
refractionCoords /= 2.0;
transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
#endif
vec3 attenuatedColor = transmittance * transmittedLight.rgb;
vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
}
#endif`,mse=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
varying vec2 vUv;
#endif
#ifdef USE_MAP
varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
varying vec2 vNormalMapUv;
#endif
#ifdef USE_EMISSIVEMAP
varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_SPECULARMAP
varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
uniform mat3 transmissionMapTransform;
varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
uniform mat3 thicknessMapTransform;
varying vec2 vThicknessMapUv;
#endif`,pse=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
varying vec2 vUv;
#endif
#ifdef USE_MAP
uniform mat3 mapTransform;
varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
uniform mat3 alphaMapTransform;
varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
uniform mat3 lightMapTransform;
varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
uniform mat3 aoMapTransform;
varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
uniform mat3 bumpMapTransform;
varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
uniform mat3 normalMapTransform;
varying vec2 vNormalMapUv;
#endif
#ifdef USE_DISPLACEMENTMAP
uniform mat3 displacementMapTransform;
varying vec2 vDisplacementMapUv;
#endif
#ifdef USE_EMISSIVEMAP
uniform mat3 emissiveMapTransform;
varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
uniform mat3 metalnessMapTransform;
varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
uniform mat3 roughnessMapTransform;
varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
uniform mat3 anisotropyMapTransform;
varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
uniform mat3 clearcoatMapTransform;
varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
uniform mat3 clearcoatNormalMapTransform;
varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
uniform mat3 clearcoatRoughnessMapTransform;
varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
uniform mat3 sheenColorMapTransform;
varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
uniform mat3 sheenRoughnessMapTransform;
varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
uniform mat3 iridescenceMapTransform;
varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
uniform mat3 iridescenceThicknessMapTransform;
varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SPECULARMAP
uniform mat3 specularMapTransform;
varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
uniform mat3 specularColorMapTransform;
varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
uniform mat3 specularIntensityMapTransform;
varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
uniform mat3 transmissionMapTransform;
varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
uniform mat3 thicknessMapTransform;
varying vec2 vThicknessMapUv;
#endif`,gse=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
vUv = vec3( uv, 1 ).xy;
#endif
#ifdef USE_MAP
vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ALPHAMAP
vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_LIGHTMAP
vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_AOMAP
vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_BUMPMAP
vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_NORMALMAP
vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_DISPLACEMENTMAP
vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_EMISSIVEMAP
vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_METALNESSMAP
vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ROUGHNESSMAP
vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ANISOTROPYMAP
vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOATMAP
vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCEMAP
vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_COLORMAP
vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULARMAP
vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_COLORMAP
vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_TRANSMISSIONMAP
vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_THICKNESSMAP
vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
#endif`,_se=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
vec4 worldPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
worldPosition = batchingMatrix * worldPosition;
#endif
#ifdef USE_INSTANCING
worldPosition = instanceMatrix * worldPosition;
#endif
worldPosition = modelMatrix * worldPosition;
#endif`,vse=`varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
gl_Position = vec4( position.xy, 1.0, 1.0 );
}`,Ese=`uniform sampler2D t2D;
uniform float backgroundIntensity;
varying vec2 vUv;
void main() {
vec4 texColor = texture2D( t2D, vUv );
#ifdef DECODE_VIDEO_TEXTURE
texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
#endif
texColor.rgb *= backgroundIntensity;
gl_FragColor = texColor;
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`,Sse=`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
gl_Position.z = gl_Position.w;
}`,Tse=`#ifdef ENVMAP_TYPE_CUBE
uniform samplerCube envMap;
#elif defined( ENVMAP_TYPE_CUBE_UV )
uniform sampler2D envMap;
#endif
uniform float backgroundBlurriness;
uniform float backgroundIntensity;
uniform mat3 backgroundRotation;
varying vec3 vWorldDirection;
#include <cube_uv_reflection_fragment>
void main() {
#ifdef ENVMAP_TYPE_CUBE
vec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection );
#elif defined( ENVMAP_TYPE_CUBE_UV )
vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
#else
vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
#endif
texColor.rgb *= backgroundIntensity;
gl_FragColor = texColor;
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`,Ase=`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
gl_Position.z = gl_Position.w;
}`,xse=`uniform samplerCube tCube;
uniform float tFlip;
uniform float opacity;
varying vec3 vWorldDirection;
void main() {
vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
gl_FragColor = texColor;
gl_FragColor.a *= opacity;
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`,Rse=`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
varying vec2 vHighPrecisionZW;
void main() {
#include <uv_vertex>
#include <batching_vertex>
#include <skinbase_vertex>
#include <morphinstance_vertex>
#ifdef USE_DISPLACEMENTMAP
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinnormal_vertex>
#endif
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vHighPrecisionZW = gl_Position.zw;
}`,bse=`#if DEPTH_PACKING == 3200
uniform float opacity;
#endif
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
varying vec2 vHighPrecisionZW;
void main() {
vec4 diffuseColor = vec4( 1.0 );
#include <clipping_planes_fragment>
#if DEPTH_PACKING == 3200
diffuseColor.a = opacity;
#endif
#include <map_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <logdepthbuf_fragment>
#ifdef USE_REVERSED_DEPTH_BUFFER
float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];
#else
float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;
#endif
#if DEPTH_PACKING == 3200
gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
#elif DEPTH_PACKING == 3201
gl_FragColor = packDepthToRGBA( fragCoordZ );
#elif DEPTH_PACKING == 3202
gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
#elif DEPTH_PACKING == 3203
gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
#endif
}`,Mse=`#define DISTANCE
varying vec3 vWorldPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <batching_vertex>
#include <skinbase_vertex>
#include <morphinstance_vertex>
#ifdef USE_DISPLACEMENTMAP
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinnormal_vertex>
#endif
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <worldpos_vertex>
#include <clipping_planes_vertex>
vWorldPosition = worldPosition.xyz;
}`,yse=`#define DISTANCE
uniform vec3 referencePosition;
uniform float nearDistance;
uniform float farDistance;
varying vec3 vWorldPosition;
#include <common>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <clipping_planes_pars_fragment>
void main () {
vec4 diffuseColor = vec4( 1.0 );
#include <clipping_planes_fragment>
#include <map_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
float dist = length( vWorldPosition - referencePosition );
dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
dist = saturate( dist );
gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );
}`,Ise=`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
}`,Cse=`uniform sampler2D tEquirect;
varying vec3 vWorldDirection;
#include <common>
void main() {
vec3 direction = normalize( vWorldDirection );
vec2 sampleUV = equirectUv( direction );
gl_FragColor = texture2D( tEquirect, sampleUV );
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`,Pse=`uniform float scale;
attribute float lineDistance;
varying float vLineDistance;
#include <common>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
vLineDistance = scale * lineDistance;
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <fog_vertex>
}`,Lse=`uniform vec3 diffuse;
uniform float opacity;
uniform float dashSize;
uniform float totalSize;
varying float vLineDistance;
#include <common>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
if ( mod( vLineDistance, totalSize ) > dashSize ) {
discard;
}
vec3 outgoingLight = vec3( 0.0 );
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
outgoingLight = diffuseColor.rgb;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
}`,Dse=`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#endif
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <worldpos_vertex>
#include <envmap_vertex>
#include <fog_vertex>
}`,Ose=`uniform vec3 diffuse;
uniform float opacity;
#ifndef FLAT_SHADED
varying vec3 vNormal;
#endif
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <specularmap_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
#ifdef USE_LIGHTMAP
vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
#else
reflectedLight.indirectDiffuse += vec3( 1.0 );
#endif
#include <aomap_fragment>
reflectedLight.indirectDiffuse *= diffuseColor.rgb;
vec3 outgoingLight = reflectedLight.indirectDiffuse;
#include <envmap_fragment>
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,Nse=`#define LAMBERT
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vViewPosition = - mvPosition.xyz;
#include <worldpos_vertex>
#include <envmap_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
}`,wse=`#define LAMBERT
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_lambert_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <specularmap_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <emissivemap_fragment>
#include <lights_lambert_fragment>
#include <lights_fragment_begin>
#include <lights_fragment_maps>
#include <lights_fragment_end>
#include <aomap_fragment>
vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
#include <envmap_fragment>
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,Fse=`#define MATCAP
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <displacementmap_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <fog_vertex>
vViewPosition = - mvPosition.xyz;
}`,Bse=`#define MATCAP
uniform vec3 diffuse;
uniform float opacity;
uniform sampler2D matcap;
varying vec3 vViewPosition;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
vec3 viewDir = normalize( vViewPosition );
vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
vec3 y = cross( viewDir, x );
vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
#ifdef USE_MATCAP
vec4 matcapColor = texture2D( matcap, uv );
#else
vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
#endif
vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,Use=`#define NORMAL
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
varying vec3 vViewPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphinstance_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
vViewPosition = - mvPosition.xyz;
#endif
}`,Vse=`#define NORMAL
uniform float opacity;
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
varying vec3 vViewPosition;
#endif
#include <uv_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
#include <clipping_planes_fragment>
#include <logdepthbuf_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );
#ifdef OPAQUE
gl_FragColor.a = 1.0;
#endif
}`,Gse=`#define PHONG
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphinstance_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vViewPosition = - mvPosition.xyz;
#include <worldpos_vertex>
#include <envmap_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
}`,kse=`#define PHONG
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_phong_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <specularmap_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <emissivemap_fragment>
#include <lights_phong_fragment>
#include <lights_fragment_begin>
#include <lights_fragment_maps>
#include <lights_fragment_end>
#include <aomap_fragment>
vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
#include <envmap_fragment>
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,zse=`#define STANDARD
varying vec3 vViewPosition;
#ifdef USE_TRANSMISSION
varying vec3 vWorldPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vViewPosition = - mvPosition.xyz;
#include <worldpos_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
#ifdef USE_TRANSMISSION
vWorldPosition = worldPosition.xyz;
#endif
}`,Wse=`#define STANDARD
#ifdef PHYSICAL
#define IOR
#define USE_SPECULAR
#endif
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float roughness;
uniform float metalness;
uniform float opacity;
#ifdef IOR
uniform float ior;
#endif
#ifdef USE_SPECULAR
uniform float specularIntensity;
uniform vec3 specularColor;
#ifdef USE_SPECULAR_COLORMAP
uniform sampler2D specularColorMap;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
uniform sampler2D specularIntensityMap;
#endif
#endif
#ifdef USE_CLEARCOAT
uniform float clearcoat;
uniform float clearcoatRoughness;
#endif
#ifdef USE_DISPERSION
uniform float dispersion;
#endif
#ifdef USE_IRIDESCENCE
uniform float iridescence;
uniform float iridescenceIOR;
uniform float iridescenceThicknessMinimum;
uniform float iridescenceThicknessMaximum;
#endif
#ifdef USE_SHEEN
uniform vec3 sheenColor;
uniform float sheenRoughness;
#ifdef USE_SHEEN_COLORMAP
uniform sampler2D sheenColorMap;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
uniform sampler2D sheenRoughnessMap;
#endif
#endif
#ifdef USE_ANISOTROPY
uniform vec2 anisotropyVector;
#ifdef USE_ANISOTROPYMAP
uniform sampler2D anisotropyMap;
#endif
#endif
varying vec3 vViewPosition;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <iridescence_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_physical_pars_fragment>
#include <transmission_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <clearcoat_pars_fragment>
#include <iridescence_pars_fragment>
#include <roughnessmap_pars_fragment>
#include <metalnessmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <roughnessmap_fragment>
#include <metalnessmap_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <clearcoat_normal_fragment_begin>
#include <clearcoat_normal_fragment_maps>
#include <emissivemap_fragment>
#include <lights_physical_fragment>
#include <lights_fragment_begin>
#include <lights_fragment_maps>
#include <lights_fragment_end>
#include <aomap_fragment>
vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
#include <transmission_fragment>
vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
#ifdef USE_SHEEN
outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;
#endif
#ifdef USE_CLEARCOAT
float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
#endif
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,Hse=`#define TOON
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vViewPosition = - mvPosition.xyz;
#include <worldpos_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
}`,Xse=`#define TOON
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <gradientmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_toon_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <emissivemap_fragment>
#include <lights_toon_fragment>
#include <lights_fragment_begin>
#include <lights_fragment_maps>
#include <lights_fragment_end>
#include <aomap_fragment>
vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,Yse=`uniform float size;
uniform float scale;
#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
#ifdef USE_POINTS_UV
varying vec2 vUv;
uniform mat3 uvTransform;
#endif
void main() {
#ifdef USE_POINTS_UV
vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
#endif
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <project_vertex>
gl_PointSize = size;
#ifdef USE_SIZEATTENUATION
bool isPerspective = isPerspectiveMatrix( projectionMatrix );
if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
#endif
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <worldpos_vertex>
#include <fog_vertex>
}`,Kse=`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <color_pars_fragment>
#include <map_particle_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
vec3 outgoingLight = vec3( 0.0 );
#include <logdepthbuf_fragment>
#include <map_particle_fragment>
#include <color_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
outgoingLight = diffuseColor.rgb;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
}`,jse=`#include <common>
#include <batching_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <shadowmap_pars_vertex>
void main() {
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphinstance_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <worldpos_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
}`,Zse=`uniform vec3 color;
uniform float opacity;
#include <common>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <logdepthbuf_pars_fragment>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
void main() {
#include <logdepthbuf_fragment>
gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
}`,qse=`uniform float rotation;
uniform vec2 center;
#include <common>
#include <uv_pars_vertex>
#include <fog_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
vec4 mvPosition = modelViewMatrix[ 3 ];
vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
#ifndef USE_SIZEATTENUATION
bool isPerspective = isPerspectiveMatrix( projectionMatrix );
if ( isPerspective ) scale *= - mvPosition.z;
#endif
vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
vec2 rotatedPosition;
rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
mvPosition.xy += rotatedPosition;
gl_Position = projectionMatrix * mvPosition;
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <fog_vertex>
}`,Qse=`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
vec3 outgoingLight = vec3( 0.0 );
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
outgoingLight = diffuseColor.rgb;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
}`,Ei={alphahash_fragment:vre,alphahash_pars_fragment:Ere,alphamap_fragment:Sre,alphamap_pars_fragment:Tre,alphatest_fragment:Are,alphatest_pars_fragment:xre,aomap_fragment:Rre,aomap_pars_fragment:bre,batching_pars_vertex:Mre,batching_vertex:yre,begin_vertex:Ire,beginnormal_vertex:Cre,bsdfs:Pre,iridescence_fragment:Lre,bumpmap_pars_fragment:Dre,clipping_planes_fragment:Ore,clipping_planes_pars_fragment:Nre,clipping_planes_pars_vertex:wre,clipping_planes_vertex:Fre,color_fragment:Bre,color_pars_fragment:Ure,color_pars_vertex:Vre,color_vertex:Gre,common:kre,cube_uv_reflection_fragment:zre,defaultnormal_vertex:Wre,displacementmap_pars_vertex:Hre,displacementmap_vertex:Xre,emissivemap_fragment:Yre,emissivemap_pars_fragment:Kre,colorspace_fragment:jre,colorspace_pars_fragment:Zre,envmap_fragment:qre,envmap_common_pars_fragment:Qre,envmap_pars_fragment:$re,envmap_pars_vertex:Jre,envmap_physical_pars_fragment:fne,envmap_vertex:ene,fog_vertex:tne,fog_pars_vertex:ine,fog_fragment:rne,fog_pars_fragment:nne,gradientmap_pars_fragment:sne,lightmap_pars_fragment:ane,lights_lambert_fragment:one,lights_lambert_pars_fragment:lne,lights_pars_begin:cne,lights_toon_fragment:dne,lights_toon_pars_fragment:une,lights_phong_fragment:hne,lights_phong_pars_fragment:mne,lights_physical_fragment:pne,lights_physical_pars_fragment:gne,lights_fragment_begin:_ne,lights_fragment_maps:vne,lights_fragment_end:Ene,lightprobes_pars_fragment:Sne,logdepthbuf_fragment:Tne,logdepthbuf_pars_fragment:Ane,logdepthbuf_pars_vertex:xne,logdepthbuf_vertex:Rne,map_fragment:bne,map_pars_fragment:Mne,map_particle_fragment:yne,map_particle_pars_fragment:Ine,metalnessmap_fragment:Cne,metalnessmap_pars_fragment:Pne,morphinstance_vertex:Lne,morphcolor_vertex:Dne,morphnormal_vertex:One,morphtarget_pars_vertex:Nne,morphtarget_vertex:wne,normal_fragment_begin:Fne,normal_fragment_maps:Bne,normal_pars_fragment:Une,normal_pars_vertex:Vne,normal_vertex:Gne,normalmap_pars_fragment:kne,clearcoat_normal_fragment_begin:zne,clearcoat_normal_fragment_maps:Wne,clearcoat_pars_fragment:Hne,iridescence_pars_fragment:Xne,opaque_fragment:Yne,packing:Kne,premultiplied_alpha_fragment:jne,project_vertex:Zne,dithering_fragment:qne,dithering_pars_fragment:Qne,roughnessmap_fragment:$ne,roughnessmap_pars_fragment:Jne,shadowmap_pars_fragment:ese,shadowmap_pars_vertex:tse,shadowmap_vertex:ise,shadowmask_pars_fragment:rse,skinbase_vertex:nse,skinning_pars_vertex:sse,skinning_vertex:ase,skinnormal_vertex:ose,specularmap_fragment:lse,specularmap_pars_fragment:cse,tonemapping_fragment:fse,tonemapping_pars_fragment:dse,transmission_fragment:use,transmission_pars_fragment:hse,uv_pars_fragment:mse,uv_pars_vertex:pse,uv_vertex:gse,worldpos_vertex:_se,background_vert:vse,background_frag:Ese,backgroundCube_vert:Sse,backgroundCube_frag:Tse,cube_vert:Ase,cube_frag:xse,depth_vert:Rse,depth_frag:bse,distance_vert:Mse,distance_frag:yse,equirect_vert:Ise,equirect_frag:Cse,linedashed_vert:Pse,linedashed_frag:Lse,meshbasic_vert:Dse,meshbasic_frag:Ose,meshlambert_vert:Nse,meshlambert_frag:wse,meshmatcap_vert:Fse,meshmatcap_frag:Bse,meshnormal_vert:Use,meshnormal_frag:Vse,meshphong_vert:Gse,meshphong_frag:kse,meshphysical_vert:zse,meshphysical_frag:Wse,meshtoon_vert:Hse,meshtoon_frag:Xse,points_vert:Yse,points_frag:Kse,shadow_vert:jse,shadow_frag:Zse,sprite_vert:qse,sprite_frag:Qse},Tt={common:{diffuse:{value:new mt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new li},alphaMap:{value:null},alphaMapTransform:{value:new li},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new li}},envmap:{envMap:{value:null},envMapRotation:{value:new li},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new li}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new li}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new li},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new li},normalScale:{value:new Ct(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new li},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new li}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new li}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new li}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new mt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new ie},probesMax:{value:new ie},probesResolution:{value:new ie}},points:{diffuse:{value:new mt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new li},alphaTest:{value:0},uvTransform:{value:new li}},sprite:{diffuse:{value:new mt(16777215)},opacity:{value:1},center:{value:new Ct(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new li},alphaMap:{value:null},alphaMapTransform:{value:new li},alphaTest:{value:0}}},Rl={basic:{uniforms:jn([Tt.common,Tt.specularmap,Tt.envmap,Tt.aomap,Tt.lightmap,Tt.fog]),vertexShader:Ei.meshbasic_vert,fragmentShader:Ei.meshbasic_frag},lambert:{uniforms:jn([Tt.common,Tt.specularmap,Tt.envmap,Tt.aomap,Tt.lightmap,Tt.emissivemap,Tt.bumpmap,Tt.normalmap,Tt.displacementmap,Tt.fog,Tt.lights,{emissive:{value:new mt(0)},envMapIntensity:{value:1}}]),vertexShader:Ei.meshlambert_vert,fragmentShader:Ei.meshlambert_frag},phong:{uniforms:jn([Tt.common,Tt.specularmap,Tt.envmap,Tt.aomap,Tt.lightmap,Tt.emissivemap,Tt.bumpmap,Tt.normalmap,Tt.displacementmap,Tt.fog,Tt.lights,{emissive:{value:new mt(0)},specular:{value:new mt(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Ei.meshphong_vert,fragmentShader:Ei.meshphong_frag},standard:{uniforms:jn([Tt.common,Tt.envmap,Tt.aomap,Tt.lightmap,Tt.emissivemap,Tt.bumpmap,Tt.normalmap,Tt.displacementmap,Tt.roughnessmap,Tt.metalnessmap,Tt.fog,Tt.lights,{emissive:{value:new mt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ei.meshphysical_vert,fragmentShader:Ei.meshphysical_frag},toon:{uniforms:jn([Tt.common,Tt.aomap,Tt.lightmap,Tt.emissivemap,Tt.bumpmap,Tt.normalmap,Tt.displacementmap,Tt.gradientmap,Tt.fog,Tt.lights,{emissive:{value:new mt(0)}}]),vertexShader:Ei.meshtoon_vert,fragmentShader:Ei.meshtoon_frag},matcap:{uniforms:jn([Tt.common,Tt.bumpmap,Tt.normalmap,Tt.displacementmap,Tt.fog,{matcap:{value:null}}]),vertexShader:Ei.meshmatcap_vert,fragmentShader:Ei.meshmatcap_frag},points:{uniforms:jn([Tt.points,Tt.fog]),vertexShader:Ei.points_vert,fragmentShader:Ei.points_frag},dashed:{uniforms:jn([Tt.common,Tt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ei.linedashed_vert,fragmentShader:Ei.linedashed_frag},depth:{uniforms:jn([Tt.common,Tt.displacementmap]),vertexShader:Ei.depth_vert,fragmentShader:Ei.depth_frag},normal:{uniforms:jn([Tt.common,Tt.bumpmap,Tt.normalmap,Tt.displacementmap,{opacity:{value:1}}]),vertexShader:Ei.meshnormal_vert,fragmentShader:Ei.meshnormal_frag},sprite:{uniforms:jn([Tt.sprite,Tt.fog]),vertexShader:Ei.sprite_vert,fragmentShader:Ei.sprite_frag},background:{uniforms:{uvTransform:{value:new li},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Ei.background_vert,fragmentShader:Ei.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new li}},vertexShader:Ei.backgroundCube_vert,fragmentShader:Ei.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ei.cube_vert,fragmentShader:Ei.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ei.equirect_vert,fragmentShader:Ei.equirect_frag},distance:{uniforms:jn([Tt.common,Tt.displacementmap,{referencePosition:{value:new ie},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Ei.distance_vert,fragmentShader:Ei.distance_frag},shadow:{uniforms:jn([Tt.lights,Tt.fog,{color:{value:new mt(0)},opacity:{value:1}}]),vertexShader:Ei.shadow_vert,fragmentShader:Ei.shadow_frag}};Rl.physical={uniforms:jn([Rl.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new li},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new li},clearcoatNormalScale:{value:new Ct(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new li},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new li},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new li},sheen:{value:0},sheenColor:{value:new mt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new li},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new li},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new li},transmissionSamplerSize:{value:new Ct},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new li},attenuationDistance:{value:0},attenuationColor:{value:new mt(0)},specularColor:{value:new mt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new li},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new li},anisotropyVector:{value:new Ct},anisotropyMap:{value:null},anisotropyMapTransform:{value:new li}}]),vertexShader:Ei.meshphysical_vert,fragmentShader:Ei.meshphysical_frag};gA={r:0,b:0,g:0},$se=new pi,dU=new li;dU.set(-1,0,0,0,1,0,0,0,1);Ff=4,z2=[.125,.215,.35,.446,.526,.582],Au=20,nae=256,j_=new vs,W2=new mt,sC=null,aC=0,oC=0,lC=!1,sae=new ie,Im=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,i=.1,r=100,s={}){let{size:a=256,position:o=sae}=s;sC=this._renderer.getRenderTarget(),aC=this._renderer.getActiveCubeFace(),oC=this._renderer.getActiveMipmapLevel(),lC=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,i,r,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Y2(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=X2(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(sC,aC,oC),this._renderer.xr.enabled=lC,e.scissorTest=!1,Mm(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===Of||e.mapping===Eu?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),sC=this._renderer.getRenderTarget(),aC=this._renderer.getActiveCubeFace(),oC=this._renderer.getActiveMipmapLevel(),lC=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let i=t||this._allocateTargets();return this._textureToCubeUV(e,i),this._applyPMREM(i),this._cleanup(i),i}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,i={magFilter:zr,minFilter:zr,generateMipmaps:!1,type:Al,format:Aa,colorSpace:gs,depthBuffer:!1},r=H2(e,t,i);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=H2(e,t,i);let{_lodMax:s}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=aae(s)),this._blurMaterial=lae(s,e,t),this._ggxMaterial=oae(s,e,t)}return r}_compileMaterial(e){let t=new ci(new Bi,e);this._renderer.compile(t,j_)}_sceneToCubeUV(e,t,i,r,s){let l=new Sr(90,1,t,i),c=[1,-1,1,1,1,1],f=[1,1,1,-1,-1,-1],d=this._renderer,u=d.autoClear,h=d.toneMapping;d.getClearColor(W2),d.toneMapping=Ys,d.autoClear=!1,d.state.buffers.depth.getReversed()&&(d.setRenderTarget(r),d.clearDepth(),d.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new ci(new If,new Kn({name:"PMREM.Background",side:On,depthWrite:!1,depthTest:!1})));let g=this._backgroundBox,p=g.material,_=!1,v=e.background;v?v.isColor&&(p.color.copy(v),e.background=null,_=!0):(p.color.copy(W2),_=!0);for(let E=0;E<6;E++){let S=E%3;S===0?(l.up.set(0,c[E],0),l.position.set(s.x,s.y,s.z),l.lookAt(s.x+f[E],s.y,s.z)):S===1?(l.up.set(0,0,c[E]),l.position.set(s.x,s.y,s.z),l.lookAt(s.x,s.y+f[E],s.z)):(l.up.set(0,c[E],0),l.position.set(s.x,s.y,s.z),l.lookAt(s.x,s.y,s.z+f[E]));let T=this._cubeSize;Mm(r,S*T,E>2?T:0,T,T),d.setRenderTarget(r),_&&d.render(g,l),d.render(e,l)}d.toneMapping=h,d.autoClear=u,e.background=v}_textureToCubeUV(e,t){let i=this._renderer,r=e.mapping===Of||e.mapping===Eu;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=Y2()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=X2());let s=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=s;let o=s.uniforms;o.envMap.value=e;let l=this._cubeSize;Mm(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(a,j_)}_applyPMREM(e){let t=this._renderer,i=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let s=1;s<r;s++)this._applyGGXFilter(e,s-1,s);t.autoClear=i}_applyGGXFilter(e,t,i){let r=this._renderer,s=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[i];o.material=a;let l=a.uniforms,c=i/(this._lodMeshes.length-1),f=t/(this._lodMeshes.length-1),d=Math.sqrt(c*c-f*f),u=0+c*1.25,h=d*u,{_lodMax:m}=this,g=this._sizeLods[i],p=3*g*(i>m-Ff?i-m+Ff:0),_=4*(this._cubeSize-g);l.envMap.value=e.texture,l.roughness.value=h,l.mipInt.value=m-t,Mm(s,p,_,3*g,2*g),r.setRenderTarget(s),r.render(o,j_),l.envMap.value=s.texture,l.roughness.value=0,l.mipInt.value=m-i,Mm(e,p,_,3*g,2*g),r.setRenderTarget(e),r.render(o,j_)}_blur(e,t,i,r,s){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,i,r,"latitudinal",s),this._halfBlur(a,e,i,i,r,"longitudinal",s)}_halfBlur(e,t,i,r,s,a,o){let l=this._renderer,c=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&Ht("blur direction must be either latitudinal or longitudinal!");let f=3,d=this._lodMeshes[r];d.material=c;let u=c.uniforms,h=this._sizeLods[i]-1,m=isFinite(s)?Math.PI/(2*h):2*Math.PI/(2*Au-1),g=s/m,p=isFinite(s)?1+Math.floor(f*g):Au;p>Au&&Nt(`sigmaRadians, ${s}, is too large and will clip, as it requested ${p} samples when the maximum is set to ${Au}`);let _=[],v=0;for(let R=0;R<Au;++R){let M=R/g,I=Math.exp(-M*M/2);_.push(I),R===0?v+=I:R<p&&(v+=2*I)}for(let R=0;R<_.length;R++)_[R]=_[R]/v;u.envMap.value=e.texture,u.samples.value=p,u.weights.value=_,u.latitudinal.value=a==="latitudinal",o&&(u.poleAxis.value=o);let{_lodMax:E}=this;u.dTheta.value=m,u.mipInt.value=E-i;let S=this._sizeLods[r],T=3*S*(r>E-Ff?r-E+Ff:0),A=4*(this._cubeSize-S);Mm(t,T,A,3*S,2*S),l.setRenderTarget(t),l.render(d,j_)}};vA=class extends Ea{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let i={width:e,height:e,depth:1},r=[i,i,i,i,i,i];this.texture=new R_(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let i={uniforms:{tEquirect:{value:null}},vertexShader:`
varying vec3 vWorldDirection;
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
}
`,fragmentShader:`
uniform sampler2D tEquirect;
varying vec3 vWorldDirection;
#include <common>
void main() {
vec3 direction = normalize( vWorldDirection );
vec2 sampleUV = equirectUv( direction );
gl_FragColor = texture2D( tEquirect, sampleUV );
}
`},r=new If(5,5,5),s=new Sa({name:"CubemapFromEquirect",uniforms:Tu(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:On,blending:Tl});s.uniforms.tEquirect.value=t;let a=new ci(r,s),o=t.minFilter;return t.minFilter===Io&&(t.minFilter=zr),new ST(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,i=!0,r=!0){let s=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,i,r);e.setRenderTarget(s)}};gae={[DI]:"LINEAR_TONE_MAPPING",[OI]:"REINHARD_TONE_MAPPING",[NI]:"CINEON_TONE_MAPPING",[wI]:"ACES_FILMIC_TONE_MAPPING",[BI]:"AGX_TONE_MAPPING",[UI]:"NEUTRAL_TONE_MAPPING",[FI]:"CUSTOM_TONE_MAPPING"};uU=new Lr,dC=new mc(1,1),hU=new __,mU=new lT,pU=new R_,K2=[],j2=[],Z2=new Float32Array(16),q2=new Float32Array(9),Q2=new Float32Array(4);uC=class{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.setValue=Bae(t.type)}},hC=class{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=roe(t.type)}},mC=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,i){let r=this.seq;for(let s=0,a=r.length;s!==a;++s){let o=r[s];o.setValue(e,t[o.id],i)}}},cC=/(\w+)(\])?(\[|\.)?/g;ym=class{constructor(e,t){this.seq=[],this.map={};let i=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let a=0;a<i;++a){let o=e.getActiveUniform(t,a),l=e.getUniformLocation(t,o.name);noe(o,l,this)}let r=[],s=[];for(let a of this.seq)a.type===e.SAMPLER_2D_SHADOW||a.type===e.SAMPLER_CUBE_SHADOW||a.type===e.SAMPLER_2D_ARRAY_SHADOW?r.push(a):s.push(a);r.length>0&&(this.seq=r.concat(s))}setValue(e,t,i,r){let s=this.map[t];s!==void 0&&s.setValue(e,i,r)}setOptional(e,t,i){let r=t[i];r!==void 0&&this.setValue(e,i,r)}static upload(e,t,i,r){for(let s=0,a=t.length;s!==a;++s){let o=t[s],l=i[o.id];l.needsUpdate!==!1&&o.setValue(e,l.value,r)}}static seqWithValue(e,t){let i=[];for(let r=0,s=e.length;r!==s;++r){let a=e[r];a.id in t&&i.push(a)}return i}};soe=37297,aoe=0;eU=new li;foe={[DI]:"Linear",[OI]:"Reinhard",[NI]:"Cineon",[wI]:"ACESFilmic",[BI]:"AgX",[UI]:"Neutral",[FI]:"Custom"};_A=new ie;goe=/^[ \t]*#include +<([\w\d./]+)>/gm;_oe=new Map;Eoe=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;Toe={[B_]:"SHADOWMAP_TYPE_PCF",[Sm]:"SHADOWMAP_TYPE_VSM"};xoe={[Of]:"ENVMAP_TYPE_CUBE",[Eu]:"ENVMAP_TYPE_CUBE",[V_]:"ENVMAP_TYPE_CUBE_UV"};boe={[Eu]:"ENVMAP_MODE_REFRACTION"};yoe={[U_]:"ENVMAP_BLENDING_MULTIPLY",[E2]:"ENVMAP_BLENDING_MIX",[S2]:"ENVMAP_BLENDING_ADD"};Loe=0,gC=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,i=e.fragmentShader,r=this._getShaderStage(t),s=this._getShaderStage(i),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(s)===!1&&(a.add(s),s.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){let t=this.shaderCache,i=t.get(e);return i===void 0&&(i=new _C(e),t.set(e,i)),i}},_C=class{constructor(e){this.id=Loe++,this.code=e,this.usedTimes=0}};Voe=0;Woe=`void main() {
gl_Position = vec4( position, 1.0 );
}`,Hoe=`uniform sampler2D shadow_pass;
uniform vec2 resolution;
uniform float radius;
void main() {
const float samples = float( VSM_SAMPLES );
float mean = 0.0;
float squared_mean = 0.0;
float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
for ( float i = 0.0; i < samples; i ++ ) {
float uvOffset = uvStart + i * uvStride;
#ifdef HORIZONTAL_PASS
vec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;
mean += distribution.x;
squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
#else
float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;
mean += depth;
squared_mean += depth * depth;
#endif
}
mean = mean / samples;
squared_mean = squared_mean / samples;
float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
}`,Xoe=[new ie(1,0,0),new ie(-1,0,0),new ie(0,1,0),new ie(0,-1,0),new ie(0,0,1),new ie(0,0,-1)],Yoe=[new ie(0,-1,0),new ie(0,-1,0),new ie(0,0,1),new ie(0,0,-1),new ie(0,-1,0),new ie(0,-1,0)],cU=new pi,Z_=new ie,fC=new ie;Qoe=`
void main() {
gl_Position = vec4( position, 1.0 );
}`,$oe=`
uniform sampler2DArray depthColor;
uniform float depthWidth;
uniform float depthHeight;
void main() {
vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
if ( coord.x >= 1.0 ) {
gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
} else {
gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
}
}`,vC=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let i=new M_(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,i=new Sa({vertexShader:Qoe,fragmentShader:$oe,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new ci(new pu(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},EC=class extends Ya{constructor(e,t){super();let i=this,r=null,s=1,a=null,o="local-floor",l=1,c=null,f=null,d=null,u=null,h=null,m=null,g=typeof XRWebGLBinding!="undefined",p=new vC,_={},v=t.getContextAttributes(),E=null,S=null,T=[],A=[],R=new Ct,M=null,I=new Sr;I.viewport=new dr;let C=new Sr;C.viewport=new dr;let L=[I,C],w=new TT,G=null,O=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(se){let ve=T[se];return ve===void 0&&(ve=new cm,T[se]=ve),ve.getTargetRaySpace()},this.getControllerGrip=function(se){let ve=T[se];return ve===void 0&&(ve=new cm,T[se]=ve),ve.getGripSpace()},this.getHand=function(se){let ve=T[se];return ve===void 0&&(ve=new cm,T[se]=ve),ve.getHandSpace()};function N(se){let ve=A.indexOf(se.inputSource);if(ve===-1)return;let ne=T[ve];ne!==void 0&&(ne.update(se.inputSource,se.frame,c||a),ne.dispatchEvent({type:se.type,data:se.inputSource}))}function B(){r.removeEventListener("select",N),r.removeEventListener("selectstart",N),r.removeEventListener("selectend",N),r.removeEventListener("squeeze",N),r.removeEventListener("squeezestart",N),r.removeEventListener("squeezeend",N),r.removeEventListener("end",B),r.removeEventListener("inputsourceschange",V);for(let se=0;se<T.length;se++){let ve=A[se];ve!==null&&(A[se]=null,T[se].disconnect(ve))}G=null,O=null,p.reset();for(let se in _)delete _[se];e.setRenderTarget(E),h=null,u=null,d=null,r=null,S=null,Ue.stop(),i.isPresenting=!1,e.setPixelRatio(M),e.setSize(R.width,R.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(se){s=se,i.isPresenting===!0&&Nt("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(se){o=se,i.isPresenting===!0&&Nt("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(se){c=se},this.getBaseLayer=function(){return u!==null?u:h},this.getBinding=function(){return d===null&&g&&(d=new XRWebGLBinding(r,t)),d},this.getFrame=function(){return m},this.getSession=function(){return r},this.setSession=async function(se){if(r=se,r!==null){if(E=e.getRenderTarget(),r.addEventListener("select",N),r.addEventListener("selectstart",N),r.addEventListener("selectend",N),r.addEventListener("squeeze",N),r.addEventListener("squeezestart",N),r.addEventListener("squeezeend",N),r.addEventListener("end",B),r.addEventListener("inputsourceschange",V),v.xrCompatible!==!0&&await t.makeXRCompatible(),M=e.getPixelRatio(),e.getSize(R),g&&"createProjectionLayer"in XRWebGLBinding.prototype){let ne=null,me=null,Le=null;v.depth&&(Le=v.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,ne=v.stencil?Nf:hl,me=v.stencil?xm:Co);let de={colorFormat:t.RGBA8,depthFormat:Le,scaleFactor:s};d=this.getBinding(),u=d.createProjectionLayer(de),r.updateRenderState({layers:[u]}),e.setPixelRatio(1),e.setSize(u.textureWidth,u.textureHeight,!1),S=new Ea(u.textureWidth,u.textureHeight,{format:Aa,type:Ks,depthTexture:new mc(u.textureWidth,u.textureHeight,me,void 0,void 0,void 0,void 0,void 0,void 0,ne),stencilBuffer:v.stencil,colorSpace:e.outputColorSpace,samples:v.antialias?4:0,resolveDepthBuffer:u.ignoreDepthValues===!1,resolveStencilBuffer:u.ignoreDepthValues===!1})}else{let ne={antialias:v.antialias,alpha:!0,depth:v.depth,stencil:v.stencil,framebufferScaleFactor:s};h=new XRWebGLLayer(r,t,ne),r.updateRenderState({baseLayer:h}),e.setPixelRatio(1),e.setSize(h.framebufferWidth,h.framebufferHeight,!1),S=new Ea(h.framebufferWidth,h.framebufferHeight,{format:Aa,type:Ks,colorSpace:e.outputColorSpace,stencilBuffer:v.stencil,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1})}S.isXRRenderTarget=!0,this.setFoveation(l),c=null,a=await r.requestReferenceSpace(o),Ue.setContext(r),Ue.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return p.getDepthTexture()};function V(se){for(let ve=0;ve<se.removed.length;ve++){let ne=se.removed[ve],me=A.indexOf(ne);me>=0&&(A[me]=null,T[me].disconnect(ne))}for(let ve=0;ve<se.added.length;ve++){let ne=se.added[ve],me=A.indexOf(ne);if(me===-1){for(let de=0;de<T.length;de++)if(de>=A.length){A.push(ne),me=de;break}else if(A[de]===null){A[de]=ne,me=de;break}if(me===-1)break}let Le=T[me];Le&&Le.connect(ne)}}let q=new ie,K=new ie;function J(se,ve,ne){q.setFromMatrixPosition(ve.matrixWorld),K.setFromMatrixPosition(ne.matrixWorld);let me=q.distanceTo(K),Le=ve.projectionMatrix.elements,de=ne.projectionMatrix.elements,be=Le[14]/(Le[10]-1),we=Le[14]/(Le[10]+1),dt=(Le[9]+1)/Le[5],Ve=(Le[9]-1)/Le[5],Ze=(Le[8]-1)/Le[0],Kt=(de[8]+1)/de[0],Bt=be*Ze,wi=be*Kt,ae=me/(-Ze+Kt),Ti=ae*-Ze;if(ve.matrixWorld.decompose(se.position,se.quaternion,se.scale),se.translateX(Ti),se.translateZ(ae),se.matrixWorld.compose(se.position,se.quaternion,se.scale),se.matrixWorldInverse.copy(se.matrixWorld).invert(),Le[10]===-1)se.projectionMatrix.copy(ve.projectionMatrix),se.projectionMatrixInverse.copy(ve.projectionMatrixInverse);else{let hi=be+ae,rr=we+ae,Ke=Bt-Ti,ar=wi+(me-Ti),Z=dt*we/rr*hi,U=Ve*we/rr*hi;se.projectionMatrix.makePerspective(Ke,ar,Z,U,hi,rr),se.projectionMatrixInverse.copy(se.projectionMatrix).invert()}}function Y(se,ve){ve===null?se.matrixWorld.copy(se.matrix):se.matrixWorld.multiplyMatrices(ve.matrixWorld,se.matrix),se.matrixWorldInverse.copy(se.matrixWorld).invert()}this.updateCamera=function(se){if(r===null)return;let ve=se.near,ne=se.far;p.texture!==null&&(p.depthNear>0&&(ve=p.depthNear),p.depthFar>0&&(ne=p.depthFar)),w.near=C.near=I.near=ve,w.far=C.far=I.far=ne,(G!==w.near||O!==w.far)&&(r.updateRenderState({depthNear:w.near,depthFar:w.far}),G=w.near,O=w.far),w.layers.mask=se.layers.mask|6,I.layers.mask=w.layers.mask&-5,C.layers.mask=w.layers.mask&-3;let me=se.parent,Le=w.cameras;Y(w,me);for(let de=0;de<Le.length;de++)Y(Le[de],me);Le.length===2?J(w,I,C):w.projectionMatrix.copy(I.projectionMatrix),j(se,w,me)};function j(se,ve,ne){ne===null?se.matrix.copy(ve.matrixWorld):(se.matrix.copy(ne.matrixWorld),se.matrix.invert(),se.matrix.multiply(ve.matrixWorld)),se.matrix.decompose(se.position,se.quaternion,se.scale),se.updateMatrixWorld(!0),se.projectionMatrix.copy(ve.projectionMatrix),se.projectionMatrixInverse.copy(ve.projectionMatrixInverse),se.isPerspectiveCamera&&(se.fov=fu*2*Math.atan(1/se.projectionMatrix.elements[5]),se.zoom=1)}this.getCamera=function(){return w},this.getFoveation=function(){if(!(u===null&&h===null))return l},this.setFoveation=function(se){l=se,u!==null&&(u.fixedFoveation=se),h!==null&&h.fixedFoveation!==void 0&&(h.fixedFoveation=se)},this.hasDepthSensing=function(){return p.texture!==null},this.getDepthSensingMesh=function(){return p.getMesh(w)},this.getCameraTexture=function(se){return _[se]};let ue=null;function Ee(se,ve){if(f=ve.getViewerPose(c||a),m=ve,f!==null){let ne=f.views;h!==null&&(e.setRenderTargetFramebuffer(S,h.framebuffer),e.setRenderTarget(S));let me=!1;ne.length!==w.cameras.length&&(w.cameras.length=0,me=!0);for(let we=0;we<ne.length;we++){let dt=ne[we],Ve=null;if(h!==null)Ve=h.getViewport(dt);else{let Kt=d.getViewSubImage(u,dt);Ve=Kt.viewport,we===0&&(e.setRenderTargetTextures(S,Kt.colorTexture,Kt.depthStencilTexture),e.setRenderTarget(S))}let Ze=L[we];Ze===void 0&&(Ze=new Sr,Ze.layers.enable(we),Ze.viewport=new dr,L[we]=Ze),Ze.matrix.fromArray(dt.transform.matrix),Ze.matrix.decompose(Ze.position,Ze.quaternion,Ze.scale),Ze.projectionMatrix.fromArray(dt.projectionMatrix),Ze.projectionMatrixInverse.copy(Ze.projectionMatrix).invert(),Ze.viewport.set(Ve.x,Ve.y,Ve.width,Ve.height),we===0&&(w.matrix.copy(Ze.matrix),w.matrix.decompose(w.position,w.quaternion,w.scale)),me===!0&&w.cameras.push(Ze)}let Le=r.enabledFeatures;if(Le&&Le.includes("depth-sensing")&&r.depthUsage=="gpu-optimized"&&g){d=i.getBinding();let we=d.getDepthInformation(ne[0]);we&&we.isValid&&we.texture&&p.init(we,r.renderState)}if(Le&&Le.includes("camera-access")&&g){e.state.unbindTexture(),d=i.getBinding();for(let we=0;we<ne.length;we++){let dt=ne[we].camera;if(dt){let Ve=_[dt];Ve||(Ve=new M_,_[dt]=Ve);let Ze=d.getCameraImage(dt);Ve.sourceTexture=Ze}}}}for(let ne=0;ne<T.length;ne++){let me=A[ne],Le=T[ne];me!==null&&Le!==void 0&&Le.update(me,ve,c||a)}ue&&ue(se,ve),ve.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:ve}),m=null}let Ue=new fU;Ue.setAnimationLoop(Ee),this.setAnimationLoop=function(se){ue=se},this.dispose=function(){}}},Joe=new pi,gU=new li;gU.set(-1,0,0,0,1,0,0,0,1);ile=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),xl=null;EA=class{constructor(e={}){let{canvas:t=N2(),context:i=null,depth:r=!0,stencil:s=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:f="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:u=!1,outputBufferType:h=Ks}=e;this.isWebGLRenderer=!0;let m;if(i!==null){if(typeof WebGLRenderingContext!="undefined"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");m=i.getContextAttributes().alpha}else m=a;let g=h,p=new Set([wT,NT,OT]),_=new Set([Ks,Co,Am,xm,PT,LT]),v=new Uint32Array(4),E=new Int32Array(4),S=new ie,T=null,A=null,R=[],M=[],I=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Ys,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let C=this,L=!1,w=null;this._outputColorSpace=Fi;let G=0,O=0,N=null,B=-1,V=null,q=new dr,K=new dr,J=null,Y=new mt(0),j=0,ue=t.width,Ee=t.height,Ue=1,se=null,ve=null,ne=new dr(0,0,ue,Ee),me=new dr(0,0,ue,Ee),Le=!1,de=new hm,be=!1,we=!1,dt=new pi,Ve=new ie,Ze=new dr,Kt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Bt=!1;function wi(){return N===null?Ue:1}let ae=i;function Ti(W,ce){return t.getContext(W,ce)}try{let W={alpha:!0,depth:r,stencil:s,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:f,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${"184"}`),t.addEventListener("webglcontextlost",Ge,!1),t.addEventListener("webglcontextrestored",Mt,!1),t.addEventListener("webglcontextcreationerror",qt,!1),ae===null){let ce="webgl2";if(ae=Ti(ce,W),ae===null)throw Ti(ce)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(W){throw Ht("WebGLRenderer: "+W.message),W}let hi,rr,Ke,ar,Z,U,ge,De,ke,it,Qe,Me,Pe,ut,bt,qe,Je,Wt,Ut,yi,oe,rt,Ce;function ft(){hi=new fae(ae),hi.init(),oe=new qoe(ae,hi),rr=new iae(ae,hi,e,oe),Ke=new joe(ae,hi),rr.reversedDepthBuffer&&u&&Ke.buffers.depth.setReversed(!0),ar=new hae(ae),Z=new Noe,U=new Zoe(ae,hi,Ke,Z,rr,oe,ar),ge=new cae(C),De=new _re(ae),rt=new eae(ae,De),ke=new dae(ae,De,ar,rt),it=new pae(ae,ke,De,rt,ar),Wt=new mae(ae,rr,U),bt=new rae(Z),Qe=new Ooe(C,ge,hi,rr,rt,bt),Me=new ele(C,Z),Pe=new Foe,ut=new zoe(hi),Je=new Jse(C,ge,Ke,it,m,l),qe=new Koe(C,it,rr),Ce=new tle(ae,ar,rr,Ke),Ut=new tae(ae,hi,ar),yi=new uae(ae,hi,ar),ar.programs=Qe.programs,C.capabilities=rr,C.extensions=hi,C.properties=Z,C.renderLists=Pe,C.shadowMap=qe,C.state=Ke,C.info=ar}ft(),g!==Ks&&(I=new _ae(g,t.width,t.height,r,s));let nt=new EC(C,ae);this.xr=nt,this.getContext=function(){return ae},this.getContextAttributes=function(){return ae.getContextAttributes()},this.forceContextLoss=function(){let W=hi.get("WEBGL_lose_context");W&&W.loseContext()},this.forceContextRestore=function(){let W=hi.get("WEBGL_lose_context");W&&W.restoreContext()},this.getPixelRatio=function(){return Ue},this.setPixelRatio=function(W){W!==void 0&&(Ue=W,this.setSize(ue,Ee,!1))},this.getSize=function(W){return W.set(ue,Ee)},this.setSize=function(W,ce,Re=!0){if(nt.isPresenting){Nt("WebGLRenderer: Can't change size while VR device is presenting.");return}ue=W,Ee=ce,t.width=Math.floor(W*Ue),t.height=Math.floor(ce*Ue),Re===!0&&(t.style.width=W+"px",t.style.height=ce+"px"),I!==null&&I.setSize(t.width,t.height),this.setViewport(0,0,W,ce)},this.getDrawingBufferSize=function(W){return W.set(ue*Ue,Ee*Ue).floor()},this.setDrawingBufferSize=function(W,ce,Re){ue=W,Ee=ce,Ue=Re,t.width=Math.floor(W*Re),t.height=Math.floor(ce*Re),this.setViewport(0,0,W,ce)},this.setEffects=function(W){if(g===Ks){Ht("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(W){for(let ce=0;ce<W.length;ce++)if(W[ce].isOutputPass===!0){Nt("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}I.setEffects(W||[])},this.getCurrentViewport=function(W){return W.copy(q)},this.getViewport=function(W){return W.copy(ne)},this.setViewport=function(W,ce,Re,Se){W.isVector4?ne.set(W.x,W.y,W.z,W.w):ne.set(W,ce,Re,Se),Ke.viewport(q.copy(ne).multiplyScalar(Ue).round())},this.getScissor=function(W){return W.copy(me)},this.setScissor=function(W,ce,Re,Se){W.isVector4?me.set(W.x,W.y,W.z,W.w):me.set(W,ce,Re,Se),Ke.scissor(K.copy(me).multiplyScalar(Ue).round())},this.getScissorTest=function(){return Le},this.setScissorTest=function(W){Ke.setScissorTest(Le=W)},this.setOpaqueSort=function(W){se=W},this.setTransparentSort=function(W){ve=W},this.getClearColor=function(W){return W.copy(Je.getClearColor())},this.setClearColor=function(){Je.setClearColor(...arguments)},this.getClearAlpha=function(){return Je.getClearAlpha()},this.setClearAlpha=function(){Je.setClearAlpha(...arguments)},this.clear=function(W=!0,ce=!0,Re=!0){let Se=0;if(W){let Te=!1;if(N!==null){let St=N.texture.format;Te=p.has(St)}if(Te){let St=N.texture.type,It=_.has(St),pt=Je.getClearColor(),Lt=Je.getClearAlpha(),Dt=pt.r,oi=pt.g,si=pt.b;It?(v[0]=Dt,v[1]=oi,v[2]=si,v[3]=Lt,ae.clearBufferuiv(ae.COLOR,0,v)):(E[0]=Dt,E[1]=oi,E[2]=si,E[3]=Lt,ae.clearBufferiv(ae.COLOR,0,E))}else Se|=ae.COLOR_BUFFER_BIT}ce&&(Se|=ae.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),Re&&(Se|=ae.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),Se!==0&&ae.clear(Se)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(W){W.setRenderer(this),w=W},this.dispose=function(){t.removeEventListener("webglcontextlost",Ge,!1),t.removeEventListener("webglcontextrestored",Mt,!1),t.removeEventListener("webglcontextcreationerror",qt,!1),Je.dispose(),Pe.dispose(),ut.dispose(),Z.dispose(),ge.dispose(),it.dispose(),rt.dispose(),Ce.dispose(),Qe.dispose(),nt.dispose(),nt.removeEventListener("sessionstart",kg),nt.removeEventListener("sessionend",zg),za.stop()};function Ge(W){W.preventDefault(),g_("WebGLRenderer: Context Lost."),L=!0}function Mt(){g_("WebGLRenderer: Context Restored."),L=!1;let W=ar.autoReset,ce=qe.enabled,Re=qe.autoUpdate,Se=qe.needsUpdate,Te=qe.type;ft(),ar.autoReset=W,qe.enabled=ce,qe.autoUpdate=Re,qe.needsUpdate=Se,qe.type=Te}function qt(W){Ht("WebGLRenderer: A WebGL context could not be created. Reason: ",W.statusMessage)}function Er(W){let ce=W.target;ce.removeEventListener("dispose",Er),_i(ce)}function _i(W){Gr(W),Z.remove(W)}function Gr(W){let ce=Z.get(W).programs;ce!==void 0&&(ce.forEach(function(Re){Qe.releaseProgram(Re)}),W.isShaderMaterial&&Qe.releaseShaderCache(W))}this.renderBufferDirect=function(W,ce,Re,Se,Te,St){ce===null&&(ce=Kt);let It=Te.isMesh&&Te.matrixWorld.determinant()<0,pt=Us(W,ce,Re,Se,Te);Ke.setMaterial(Se,It);let Lt=Re.index,Dt=1;if(Se.wireframe===!0){if(Lt=ke.getWireframeAttribute(Re),Lt===void 0)return;Dt=2}let oi=Re.drawRange,si=Re.attributes.position,Ft=oi.start*Dt,ji=(oi.start+oi.count)*Dt;St!==null&&(Ft=Math.max(Ft,St.start*Dt),ji=Math.min(ji,(St.start+St.count)*Dt)),Lt!==null?(Ft=Math.max(Ft,0),ji=Math.min(ji,Lt.count)):si!=null&&(Ft=Math.max(Ft,0),ji=Math.min(ji,si.count));let Nr=ji-Ft;if(Nr<0||Nr===1/0)return;rt.setup(Te,Se,pt,Re,Lt);let Pr,$i=Ut;if(Lt!==null&&(Pr=De.get(Lt),$i=yi,$i.setIndex(Pr)),Te.isMesh)Se.wireframe===!0?(Ke.setLineWidth(Se.wireframeLinewidth*wi()),$i.setMode(ae.LINES)):$i.setMode(ae.TRIANGLES);else if(Te.isLine){let dn=Se.linewidth;dn===void 0&&(dn=1),Ke.setLineWidth(dn*wi()),Te.isLineSegments?$i.setMode(ae.LINES):Te.isLineLoop?$i.setMode(ae.LINE_LOOP):$i.setMode(ae.LINE_STRIP)}else Te.isPoints?$i.setMode(ae.POINTS):Te.isSprite&&$i.setMode(ae.TRIANGLES);if(Te.isBatchedMesh)if(hi.get("WEBGL_multi_draw"))$i.renderMultiDraw(Te._multiDrawStarts,Te._multiDrawCounts,Te._multiDrawCount);else{let dn=Te._multiDrawStarts,yt=Te._multiDrawCounts,Hn=Te._multiDrawCount,Oi=Lt?De.get(Lt).bytesPerElement:1,X=Z.get(Se).currentProgram.getUniforms();for(let xe=0;xe<Hn;xe++)X.setValue(ae,"_gl_DrawID",xe),$i.render(dn[xe]/Oi,yt[xe])}else if(Te.isInstancedMesh)$i.renderInstances(Ft,Nr,Te.count);else if(Re.isInstancedBufferGeometry){let dn=Re._maxInstanceCount!==void 0?Re._maxInstanceCount:1/0,yt=Math.min(Re.instanceCount,dn);$i.renderInstances(Ft,Nr,yt)}else $i.render(Ft,Nr)};function cr(W,ce,Re){W.transparent===!0&&W.side===Xs&&W.forceSinglePass===!1?(W.side=On,W.needsUpdate=!0,Zd(W,ce,Re),W.side=va,W.needsUpdate=!0,Zd(W,ce,Re),W.side=Xs):Zd(W,ce,Re)}this.compile=function(W,ce,Re=null){Re===null&&(Re=W),A=ut.get(Re),A.init(ce),M.push(A),Re.traverseVisible(function(Te){Te.isLight&&Te.layers.test(ce.layers)&&(A.pushLight(Te),Te.castShadow&&A.pushShadow(Te))}),W!==Re&&W.traverseVisible(function(Te){Te.isLight&&Te.layers.test(ce.layers)&&(A.pushLight(Te),Te.castShadow&&A.pushShadow(Te))}),A.setupLights();let Se=new Set;return W.traverse(function(Te){if(!(Te.isMesh||Te.isPoints||Te.isLine||Te.isSprite))return;let St=Te.material;if(St)if(Array.isArray(St))for(let It=0;It<St.length;It++){let pt=St[It];cr(pt,Re,Te),Se.add(pt)}else cr(St,Re,Te),Se.add(St)}),A=M.pop(),Se},this.compileAsync=function(W,ce,Re=null){let Se=this.compile(W,ce,Re);return new Promise(Te=>{function St(){if(Se.forEach(function(It){Z.get(It).currentProgram.isReady()&&Se.delete(It)}),Se.size===0){Te(W);return}setTimeout(St,10)}hi.get("KHR_parallel_shader_compile")!==null?St():setTimeout(St,10)})};let Bs=null;function aS(W){Bs&&Bs(W)}function kg(){za.stop()}function zg(){za.start()}let za=new fU;za.setAnimationLoop(aS),typeof self!="undefined"&&za.setContext(self),this.setAnimationLoop=function(W){Bs=W,nt.setAnimationLoop(W),W===null?za.stop():za.start()},nt.addEventListener("sessionstart",kg),nt.addEventListener("sessionend",zg),this.render=function(W,ce){if(ce!==void 0&&ce.isCamera!==!0){Ht("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(L===!0)return;w!==null&&w.renderStart(W,ce);let Re=nt.enabled===!0&&nt.isPresenting===!0,Se=I!==null&&(N===null||Re)&&I.begin(C,N);if(W.matrixWorldAutoUpdate===!0&&W.updateMatrixWorld(),ce.parent===null&&ce.matrixWorldAutoUpdate===!0&&ce.updateMatrixWorld(),nt.enabled===!0&&nt.isPresenting===!0&&(I===null||I.isCompositing()===!1)&&(nt.cameraAutoUpdate===!0&&nt.updateCamera(ce),ce=nt.getCamera()),W.isScene===!0&&W.onBeforeRender(C,W,ce,N),A=ut.get(W,M.length),A.init(ce),A.state.textureUnits=U.getTextureUnits(),M.push(A),dt.multiplyMatrices(ce.projectionMatrix,ce.matrixWorldInverse),de.setFromProjectionMatrix(dt,xo,ce.reversedDepth),we=this.localClippingEnabled,be=bt.init(this.clippingPlanes,we),T=Pe.get(W,R.length),T.init(),R.push(T),nt.enabled===!0&&nt.isPresenting===!0){let It=C.xr.getDepthSensingMesh();It!==null&&ll(It,ce,-1/0,C.sortObjects)}ll(W,ce,0,C.sortObjects),T.finish(),C.sortObjects===!0&&T.sort(se,ve),Bt=nt.enabled===!1||nt.isPresenting===!1||nt.hasDepthSensing()===!1,Bt&&Je.addToRenderList(T,W),this.info.render.frame++,be===!0&&bt.beginShadows();let Te=A.state.shadowsArray;if(qe.render(Te,W,ce),be===!0&&bt.endShadows(),this.info.autoReset===!0&&this.info.reset(),(Se&&I.hasRenderPass())===!1){let It=T.opaque,pt=T.transmissive;if(A.setupLights(),ce.isArrayCamera){let Lt=ce.cameras;if(pt.length>0)for(let Dt=0,oi=Lt.length;Dt<oi;Dt++){let si=Lt[Dt];rc(It,pt,W,si)}Bt&&Je.render(W);for(let Dt=0,oi=Lt.length;Dt<oi;Dt++){let si=Lt[Dt];ic(T,W,si,si.viewport)}}else pt.length>0&&rc(It,pt,W,ce),Bt&&Je.render(W),ic(T,W,ce)}N!==null&&O===0&&(U.updateMultisampleRenderTarget(N),U.updateRenderTargetMipmap(N)),Se&&I.end(C),W.isScene===!0&&W.onAfterRender(C,W,ce),rt.resetDefaultState(),B=-1,V=null,M.pop(),M.length>0?(A=M[M.length-1],U.setTextureUnits(A.state.textureUnits),be===!0&&bt.setGlobalState(C.clippingPlanes,A.state.camera)):A=null,R.pop(),R.length>0?T=R[R.length-1]:T=null,w!==null&&w.renderEnd()};function ll(W,ce,Re,Se){if(W.visible===!1)return;if(W.layers.test(ce.layers)){if(W.isGroup)Re=W.renderOrder;else if(W.isLOD)W.autoUpdate===!0&&W.update(ce);else if(W.isLightProbeGrid)A.pushLightProbeGrid(W);else if(W.isLight)A.pushLight(W),W.castShadow&&A.pushShadow(W);else if(W.isSprite){if(!W.frustumCulled||de.intersectsSprite(W)){Se&&Ze.setFromMatrixPosition(W.matrixWorld).applyMatrix4(dt);let It=it.update(W),pt=W.material;pt.visible&&T.push(W,It,pt,Re,Ze.z,null)}}else if((W.isMesh||W.isLine||W.isPoints)&&(!W.frustumCulled||de.intersectsObject(W))){let It=it.update(W),pt=W.material;if(Se&&(W.boundingSphere!==void 0?(W.boundingSphere===null&&W.computeBoundingSphere(),Ze.copy(W.boundingSphere.center)):(It.boundingSphere===null&&It.computeBoundingSphere(),Ze.copy(It.boundingSphere.center)),Ze.applyMatrix4(W.matrixWorld).applyMatrix4(dt)),Array.isArray(pt)){let Lt=It.groups;for(let Dt=0,oi=Lt.length;Dt<oi;Dt++){let si=Lt[Dt],Ft=pt[si.materialIndex];Ft&&Ft.visible&&T.push(W,It,Ft,Re,Ze.z,si)}}else pt.visible&&T.push(W,It,pt,Re,Ze.z,null)}}let St=W.children;for(let It=0,pt=St.length;It<pt;It++)ll(St[It],ce,Re,Se)}function ic(W,ce,Re,Se){let{opaque:Te,transmissive:St,transparent:It}=W;A.setupLightsView(Re),be===!0&&bt.setGlobalState(C.clippingPlanes,Re),Se&&Ke.viewport(q.copy(Se)),Te.length>0&&Wg(Te,ce,Re),St.length>0&&Wg(St,ce,Re),It.length>0&&Wg(It,ce,Re),Ke.buffers.depth.setTest(!0),Ke.buffers.depth.setMask(!0),Ke.buffers.color.setMask(!0),Ke.setPolygonOffset(!1)}function rc(W,ce,Re,Se){if((Re.isScene===!0?Re.overrideMaterial:null)!==null)return;if(A.state.transmissionRenderTarget[Se.id]===void 0){let Ft=hi.has("EXT_color_buffer_half_float")||hi.has("EXT_color_buffer_float");A.state.transmissionRenderTarget[Se.id]=new Ea(1,1,{generateMipmaps:!0,type:Ft?Al:Ks,minFilter:Io,samples:Math.max(4,rr.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:mi.workingColorSpace})}let St=A.state.transmissionRenderTarget[Se.id],It=Se.viewport||q;St.setSize(It.z*C.transmissionResolutionScale,It.w*C.transmissionResolutionScale);let pt=C.getRenderTarget(),Lt=C.getActiveCubeFace(),Dt=C.getActiveMipmapLevel();C.setRenderTarget(St),C.getClearColor(Y),j=C.getClearAlpha(),j<1&&C.setClearColor(16777215,.5),C.clear(),Bt&&Je.render(Re);let oi=C.toneMapping;C.toneMapping=Ys;let si=Se.viewport;if(Se.viewport!==void 0&&(Se.viewport=void 0),A.setupLightsView(Se),be===!0&&bt.setGlobalState(C.clippingPlanes,Se),Wg(W,Re,Se),U.updateMultisampleRenderTarget(St),U.updateRenderTargetMipmap(St),hi.has("WEBGL_multisampled_render_to_texture")===!1){let Ft=!1;for(let ji=0,Nr=ce.length;ji<Nr;ji++){let Pr=ce[ji],{object:$i,geometry:dn,material:yt,group:Hn}=Pr;if(yt.side===Xs&&$i.layers.test(Se.layers)){let Oi=yt.side;yt.side=On,yt.needsUpdate=!0,Hg($i,Re,Se,dn,yt,Hn),yt.side=Oi,yt.needsUpdate=!0,Ft=!0}}Ft===!0&&(U.updateMultisampleRenderTarget(St),U.updateRenderTargetMipmap(St))}C.setRenderTarget(pt,Lt,Dt),C.setClearColor(Y,j),si!==void 0&&(Se.viewport=si),C.toneMapping=oi}function Wg(W,ce,Re){let Se=ce.isScene===!0?ce.overrideMaterial:null;for(let Te=0,St=W.length;Te<St;Te++){let It=W[Te],{object:pt,geometry:Lt,group:Dt}=It,oi=It.material;oi.allowOverride===!0&&Se!==null&&(oi=Se),pt.layers.test(Re.layers)&&Hg(pt,ce,Re,Lt,oi,Dt)}}function Hg(W,ce,Re,Se,Te,St){W.onBeforeRender(C,ce,Re,Se,Te,St),W.modelViewMatrix.multiplyMatrices(Re.matrixWorldInverse,W.matrixWorld),W.normalMatrix.getNormalMatrix(W.modelViewMatrix),Te.onBeforeRender(C,ce,Re,Se,W,St),Te.transparent===!0&&Te.side===Xs&&Te.forceSinglePass===!1?(Te.side=On,Te.needsUpdate=!0,C.renderBufferDirect(Re,ce,Se,Te,W,St),Te.side=va,Te.needsUpdate=!0,C.renderBufferDirect(Re,ce,Se,Te,W,St),Te.side=Xs):C.renderBufferDirect(Re,ce,Se,Te,W,St),W.onAfterRender(C,ce,Re,Se,Te,St)}function Zd(W,ce,Re){ce.isScene!==!0&&(ce=Kt);let Se=Z.get(W),Te=A.state.lights,St=A.state.shadowsArray,It=Te.state.version,pt=Qe.getParameters(W,Te.state,St,ce,Re,A.state.lightProbeGridArray),Lt=Qe.getProgramCacheKey(pt),Dt=Se.programs;Se.environment=W.isMeshStandardMaterial||W.isMeshLambertMaterial||W.isMeshPhongMaterial?ce.environment:null,Se.fog=ce.fog;let oi=W.isMeshStandardMaterial||W.isMeshLambertMaterial&&!W.envMap||W.isMeshPhongMaterial&&!W.envMap;Se.envMap=ge.get(W.envMap||Se.environment,oi),Se.envMapRotation=Se.environment!==null&&W.envMap===null?ce.environmentRotation:W.envMapRotation,Dt===void 0&&(W.addEventListener("dispose",Er),Dt=new Map,Se.programs=Dt);let si=Dt.get(Lt);if(si!==void 0){if(Se.currentProgram===si&&Se.lightsStateVersion===It)return Oh(W,pt),si}else pt.uniforms=Qe.getUniforms(W),w!==null&&W.isNodeMaterial&&w.build(W,Re,pt),W.onBeforeCompile(pt,C),si=Qe.acquireProgram(pt,Lt),Dt.set(Lt,si),Se.uniforms=pt.uniforms;let Ft=Se.uniforms;return(!W.isShaderMaterial&&!W.isRawShaderMaterial||W.clipping===!0)&&(Ft.clippingPlanes=bt.uniform),Oh(W,pt),Se.needsLights=I0(W),Se.lightsStateVersion=It,Se.needsLights&&(Ft.ambientLightColor.value=Te.state.ambient,Ft.lightProbe.value=Te.state.probe,Ft.directionalLights.value=Te.state.directional,Ft.directionalLightShadows.value=Te.state.directionalShadow,Ft.spotLights.value=Te.state.spot,Ft.spotLightShadows.value=Te.state.spotShadow,Ft.rectAreaLights.value=Te.state.rectArea,Ft.ltc_1.value=Te.state.rectAreaLTC1,Ft.ltc_2.value=Te.state.rectAreaLTC2,Ft.pointLights.value=Te.state.point,Ft.pointLightShadows.value=Te.state.pointShadow,Ft.hemisphereLights.value=Te.state.hemi,Ft.directionalShadowMatrix.value=Te.state.directionalShadowMatrix,Ft.spotLightMatrix.value=Te.state.spotLightMatrix,Ft.spotLightMap.value=Te.state.spotLightMap,Ft.pointShadowMatrix.value=Te.state.pointShadowMatrix),Se.lightProbeGrid=A.state.lightProbeGridArray.length>0,Se.currentProgram=si,Se.uniformsList=null,si}function Xg(W){if(W.uniformsList===null){let ce=W.currentProgram.getUniforms();W.uniformsList=ym.seqWithValue(ce.seq,W.uniforms)}return W.uniformsList}function Oh(W,ce){let Re=Z.get(W);Re.outputColorSpace=ce.outputColorSpace,Re.batching=ce.batching,Re.batchingColor=ce.batchingColor,Re.instancing=ce.instancing,Re.instancingColor=ce.instancingColor,Re.instancingMorph=ce.instancingMorph,Re.skinning=ce.skinning,Re.morphTargets=ce.morphTargets,Re.morphNormals=ce.morphNormals,Re.morphColors=ce.morphColors,Re.morphTargetsCount=ce.morphTargetsCount,Re.numClippingPlanes=ce.numClippingPlanes,Re.numIntersection=ce.numClipIntersection,Re.vertexAlphas=ce.vertexAlphas,Re.vertexTangents=ce.vertexTangents,Re.toneMapping=ce.toneMapping}function oS(W,ce){if(W.length===0)return null;if(W.length===1)return W[0].texture!==null?W[0]:null;S.setFromMatrixPosition(ce.matrixWorld);for(let Re=0,Se=W.length;Re<Se;Re++){let Te=W[Re];if(Te.texture!==null&&Te.boundingBox.containsPoint(S))return Te}return null}function Us(W,ce,Re,Se,Te){ce.isScene!==!0&&(ce=Kt),U.resetTextureUnits();let St=ce.fog,It=Se.isMeshStandardMaterial||Se.isMeshLambertMaterial||Se.isMeshPhongMaterial?ce.environment:null,pt=N===null?C.outputColorSpace:N.isXRRenderTarget===!0?N.texture.colorSpace:mi.workingColorSpace,Lt=Se.isMeshStandardMaterial||Se.isMeshLambertMaterial&&!Se.envMap||Se.isMeshPhongMaterial&&!Se.envMap,Dt=ge.get(Se.envMap||It,Lt),oi=Se.vertexColors===!0&&!!Re.attributes.color&&Re.attributes.color.itemSize===4,si=!!Re.attributes.tangent&&(!!Se.normalMap||Se.anisotropy>0),Ft=!!Re.morphAttributes.position,ji=!!Re.morphAttributes.normal,Nr=!!Re.morphAttributes.color,Pr=Ys;Se.toneMapped&&(N===null||N.isXRRenderTarget===!0)&&(Pr=C.toneMapping);let $i=Re.morphAttributes.position||Re.morphAttributes.normal||Re.morphAttributes.color,dn=$i!==void 0?$i.length:0,yt=Z.get(Se),Hn=A.state.lights;if(be===!0&&(we===!0||W!==V)){let Zi=W===V&&Se.id===B;bt.setState(Se,W,Zi)}let Oi=!1;Se.version===yt.__version?(yt.needsLights&&yt.lightsStateVersion!==Hn.state.version||yt.outputColorSpace!==pt||Te.isBatchedMesh&&yt.batching===!1||!Te.isBatchedMesh&&yt.batching===!0||Te.isBatchedMesh&&yt.batchingColor===!0&&Te.colorTexture===null||Te.isBatchedMesh&&yt.batchingColor===!1&&Te.colorTexture!==null||Te.isInstancedMesh&&yt.instancing===!1||!Te.isInstancedMesh&&yt.instancing===!0||Te.isSkinnedMesh&&yt.skinning===!1||!Te.isSkinnedMesh&&yt.skinning===!0||Te.isInstancedMesh&&yt.instancingColor===!0&&Te.instanceColor===null||Te.isInstancedMesh&&yt.instancingColor===!1&&Te.instanceColor!==null||Te.isInstancedMesh&&yt.instancingMorph===!0&&Te.morphTexture===null||Te.isInstancedMesh&&yt.instancingMorph===!1&&Te.morphTexture!==null||yt.envMap!==Dt||Se.fog===!0&&yt.fog!==St||yt.numClippingPlanes!==void 0&&(yt.numClippingPlanes!==bt.numPlanes||yt.numIntersection!==bt.numIntersection)||yt.vertexAlphas!==oi||yt.vertexTangents!==si||yt.morphTargets!==Ft||yt.morphNormals!==ji||yt.morphColors!==Nr||yt.toneMapping!==Pr||yt.morphTargetsCount!==dn||!!yt.lightProbeGrid!=A.state.lightProbeGridArray.length>0)&&(Oi=!0):(Oi=!0,yt.__version=Se.version);let X=yt.currentProgram;Oi===!0&&(X=Zd(Se,ce,Te),w&&Se.isNodeMaterial&&w.onUpdateProgram(Se,X,yt));let xe=!1,At=!1,kt=!1,st=X.getUniforms(),Qt=yt.uniforms;if(Ke.useProgram(X.program)&&(xe=!0,At=!0,kt=!0),Se.id!==B&&(B=Se.id,At=!0),yt.needsLights){let Zi=oS(A.state.lightProbeGridArray,Te);yt.lightProbeGrid!==Zi&&(yt.lightProbeGrid=Zi,At=!0)}if(xe||V!==W){Ke.buffers.depth.getReversed()&&W.reversedDepth!==!0&&(W._reversedDepth=!0,W.updateProjectionMatrix()),st.setValue(ae,"projectionMatrix",W.projectionMatrix),st.setValue(ae,"viewMatrix",W.matrixWorldInverse);let cl=st.map.cameraPosition;cl!==void 0&&cl.setValue(ae,Ve.setFromMatrixPosition(W.matrixWorld)),rr.logarithmicDepthBuffer&&st.setValue(ae,"logDepthBufFC",2/(Math.log(W.far+1)/Math.LN2)),(Se.isMeshPhongMaterial||Se.isMeshToonMaterial||Se.isMeshLambertMaterial||Se.isMeshBasicMaterial||Se.isMeshStandardMaterial||Se.isShaderMaterial)&&st.setValue(ae,"isOrthographic",W.isOrthographicCamera===!0),V!==W&&(V=W,At=!0,kt=!0)}if(yt.needsLights&&(Hn.state.directionalShadowMap.length>0&&st.setValue(ae,"directionalShadowMap",Hn.state.directionalShadowMap,U),Hn.state.spotShadowMap.length>0&&st.setValue(ae,"spotShadowMap",Hn.state.spotShadowMap,U),Hn.state.pointShadowMap.length>0&&st.setValue(ae,"pointShadowMap",Hn.state.pointShadowMap,U)),Te.isSkinnedMesh){st.setOptional(ae,Te,"bindMatrix"),st.setOptional(ae,Te,"bindMatrixInverse");let Zi=Te.skeleton;Zi&&(Zi.boneTexture===null&&Zi.computeBoneTexture(),st.setValue(ae,"boneTexture",Zi.boneTexture,U))}Te.isBatchedMesh&&(st.setOptional(ae,Te,"batchingTexture"),st.setValue(ae,"batchingTexture",Te._matricesTexture,U),st.setOptional(ae,Te,"batchingIdTexture"),st.setValue(ae,"batchingIdTexture",Te._indirectTexture,U),st.setOptional(ae,Te,"batchingColorTexture"),Te._colorsTexture!==null&&st.setValue(ae,"batchingColorTexture",Te._colorsTexture,U));let $r=Re.morphAttributes;if(($r.position!==void 0||$r.normal!==void 0||$r.color!==void 0)&&Wt.update(Te,Re,X),(At||yt.receiveShadow!==Te.receiveShadow)&&(yt.receiveShadow=Te.receiveShadow,st.setValue(ae,"receiveShadow",Te.receiveShadow)),(Se.isMeshStandardMaterial||Se.isMeshLambertMaterial||Se.isMeshPhongMaterial)&&Se.envMap===null&&ce.environment!==null&&(Qt.envMapIntensity.value=ce.environmentIntensity),Qt.dfgLUT!==void 0&&(Qt.dfgLUT.value=rle()),At){if(st.setValue(ae,"toneMappingExposure",C.toneMappingExposure),yt.needsLights&&lS(Qt,kt),St&&Se.fog===!0&&Me.refreshFogUniforms(Qt,St),Me.refreshMaterialUniforms(Qt,Se,Ue,Ee,A.state.transmissionRenderTarget[W.id]),yt.needsLights&&yt.lightProbeGrid){let Zi=yt.lightProbeGrid;Qt.probesSH.value=Zi.texture,Qt.probesMin.value.copy(Zi.boundingBox.min),Qt.probesMax.value.copy(Zi.boundingBox.max),Qt.probesResolution.value.copy(Zi.resolution)}ym.upload(ae,Xg(yt),Qt,U)}if(Se.isShaderMaterial&&Se.uniformsNeedUpdate===!0&&(ym.upload(ae,Xg(yt),Qt,U),Se.uniformsNeedUpdate=!1),Se.isSpriteMaterial&&st.setValue(ae,"center",Te.center),st.setValue(ae,"modelViewMatrix",Te.modelViewMatrix),st.setValue(ae,"normalMatrix",Te.normalMatrix),st.setValue(ae,"modelMatrix",Te.matrixWorld),Se.uniformsGroups!==void 0){let Zi=Se.uniformsGroups;for(let cl=0,nc=Zi.length;cl<nc;cl++){let cS=Zi[cl];Ce.update(cS,X),Ce.bind(cS,X)}}return X}function lS(W,ce){W.ambientLightColor.needsUpdate=ce,W.lightProbe.needsUpdate=ce,W.directionalLights.needsUpdate=ce,W.directionalLightShadows.needsUpdate=ce,W.pointLights.needsUpdate=ce,W.pointLightShadows.needsUpdate=ce,W.spotLights.needsUpdate=ce,W.spotLightShadows.needsUpdate=ce,W.rectAreaLights.needsUpdate=ce,W.hemisphereLights.needsUpdate=ce}function I0(W){return W.isMeshLambertMaterial||W.isMeshToonMaterial||W.isMeshPhongMaterial||W.isMeshStandardMaterial||W.isShadowMaterial||W.isShaderMaterial&&W.lights===!0}this.getActiveCubeFace=function(){return G},this.getActiveMipmapLevel=function(){return O},this.getRenderTarget=function(){return N},this.setRenderTargetTextures=function(W,ce,Re){let Se=Z.get(W);Se.__autoAllocateDepthBuffer=W.resolveDepthBuffer===!1,Se.__autoAllocateDepthBuffer===!1&&(Se.__useRenderToTexture=!1),Z.get(W.texture).__webglTexture=ce,Z.get(W.depthTexture).__webglTexture=Se.__autoAllocateDepthBuffer?void 0:Re,Se.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(W,ce){let Re=Z.get(W);Re.__webglFramebuffer=ce,Re.__useDefaultFramebuffer=ce===void 0};let C0=ae.createFramebuffer();this.setRenderTarget=function(W,ce=0,Re=0){N=W,G=ce,O=Re;let Se=null,Te=!1,St=!1;if(W){let pt=Z.get(W);if(pt.__useDefaultFramebuffer!==void 0){Ke.bindFramebuffer(ae.FRAMEBUFFER,pt.__webglFramebuffer),q.copy(W.viewport),K.copy(W.scissor),J=W.scissorTest,Ke.viewport(q),Ke.scissor(K),Ke.setScissorTest(J),B=-1;return}else if(pt.__webglFramebuffer===void 0)U.setupRenderTarget(W);else if(pt.__hasExternalTextures)U.rebindTextures(W,Z.get(W.texture).__webglTexture,Z.get(W.depthTexture).__webglTexture);else if(W.depthBuffer){let oi=W.depthTexture;if(pt.__boundDepthTexture!==oi){if(oi!==null&&Z.has(oi)&&(W.width!==oi.image.width||W.height!==oi.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");U.setupDepthRenderbuffer(W)}}let Lt=W.texture;(Lt.isData3DTexture||Lt.isDataArrayTexture||Lt.isCompressedArrayTexture)&&(St=!0);let Dt=Z.get(W).__webglFramebuffer;W.isWebGLCubeRenderTarget?(Array.isArray(Dt[ce])?Se=Dt[ce][Re]:Se=Dt[ce],Te=!0):W.samples>0&&U.useMultisampledRTT(W)===!1?Se=Z.get(W).__webglMultisampledFramebuffer:Array.isArray(Dt)?Se=Dt[Re]:Se=Dt,q.copy(W.viewport),K.copy(W.scissor),J=W.scissorTest}else q.copy(ne).multiplyScalar(Ue).floor(),K.copy(me).multiplyScalar(Ue).floor(),J=Le;if(Re!==0&&(Se=C0),Ke.bindFramebuffer(ae.FRAMEBUFFER,Se)&&Ke.drawBuffers(W,Se),Ke.viewport(q),Ke.scissor(K),Ke.setScissorTest(J),Te){let pt=Z.get(W.texture);ae.framebufferTexture2D(ae.FRAMEBUFFER,ae.COLOR_ATTACHMENT0,ae.TEXTURE_CUBE_MAP_POSITIVE_X+ce,pt.__webglTexture,Re)}else if(St){let pt=ce;for(let Lt=0;Lt<W.textures.length;Lt++){let Dt=Z.get(W.textures[Lt]);ae.framebufferTextureLayer(ae.FRAMEBUFFER,ae.COLOR_ATTACHMENT0+Lt,Dt.__webglTexture,Re,pt)}}else if(W!==null&&Re!==0){let pt=Z.get(W.texture);ae.framebufferTexture2D(ae.FRAMEBUFFER,ae.COLOR_ATTACHMENT0,ae.TEXTURE_2D,pt.__webglTexture,Re)}B=-1},this.readRenderTargetPixels=function(W,ce,Re,Se,Te,St,It,pt=0){if(!(W&&W.isWebGLRenderTarget)){Ht("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Lt=Z.get(W).__webglFramebuffer;if(W.isWebGLCubeRenderTarget&&It!==void 0&&(Lt=Lt[It]),Lt){Ke.bindFramebuffer(ae.FRAMEBUFFER,Lt);try{let Dt=W.textures[pt],oi=Dt.format,si=Dt.type;if(W.textures.length>1&&ae.readBuffer(ae.COLOR_ATTACHMENT0+pt),!rr.textureFormatReadable(oi)){Ht("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!rr.textureTypeReadable(si)){Ht("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}ce>=0&&ce<=W.width-Se&&Re>=0&&Re<=W.height-Te&&ae.readPixels(ce,Re,Se,Te,oe.convert(oi),oe.convert(si),St)}finally{let Dt=N!==null?Z.get(N).__webglFramebuffer:null;Ke.bindFramebuffer(ae.FRAMEBUFFER,Dt)}}},this.readRenderTargetPixelsAsync=async function(W,ce,Re,Se,Te,St,It,pt=0){if(!(W&&W.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Lt=Z.get(W).__webglFramebuffer;if(W.isWebGLCubeRenderTarget&&It!==void 0&&(Lt=Lt[It]),Lt)if(ce>=0&&ce<=W.width-Se&&Re>=0&&Re<=W.height-Te){Ke.bindFramebuffer(ae.FRAMEBUFFER,Lt);let Dt=W.textures[pt],oi=Dt.format,si=Dt.type;if(W.textures.length>1&&ae.readBuffer(ae.COLOR_ATTACHMENT0+pt),!rr.textureFormatReadable(oi))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!rr.textureTypeReadable(si))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let Ft=ae.createBuffer();ae.bindBuffer(ae.PIXEL_PACK_BUFFER,Ft),ae.bufferData(ae.PIXEL_PACK_BUFFER,St.byteLength,ae.STREAM_READ),ae.readPixels(ce,Re,Se,Te,oe.convert(oi),oe.convert(si),0);let ji=N!==null?Z.get(N).__webglFramebuffer:null;Ke.bindFramebuffer(ae.FRAMEBUFFER,ji);let Nr=ae.fenceSync(ae.SYNC_GPU_COMMANDS_COMPLETE,0);return ae.flush(),await F2(ae,Nr,4),ae.bindBuffer(ae.PIXEL_PACK_BUFFER,Ft),ae.getBufferSubData(ae.PIXEL_PACK_BUFFER,0,St),ae.deleteBuffer(Ft),ae.deleteSync(Nr),St}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(W,ce=null,Re=0){let Se=Math.pow(2,-Re),Te=Math.floor(W.image.width*Se),St=Math.floor(W.image.height*Se),It=ce!==null?ce.x:0,pt=ce!==null?ce.y:0;U.setTexture2D(W,0),ae.copyTexSubImage2D(ae.TEXTURE_2D,Re,0,0,It,pt,Te,St),Ke.unbindTexture()};let P0=ae.createFramebuffer(),L0=ae.createFramebuffer();this.copyTextureToTexture=function(W,ce,Re=null,Se=null,Te=0,St=0){let It,pt,Lt,Dt,oi,si,Ft,ji,Nr,Pr=W.isCompressedTexture?W.mipmaps[St]:W.image;if(Re!==null)It=Re.max.x-Re.min.x,pt=Re.max.y-Re.min.y,Lt=Re.isBox3?Re.max.z-Re.min.z:1,Dt=Re.min.x,oi=Re.min.y,si=Re.isBox3?Re.min.z:0;else{let Qt=Math.pow(2,-Te);It=Math.floor(Pr.width*Qt),pt=Math.floor(Pr.height*Qt),W.isDataArrayTexture?Lt=Pr.depth:W.isData3DTexture?Lt=Math.floor(Pr.depth*Qt):Lt=1,Dt=0,oi=0,si=0}Se!==null?(Ft=Se.x,ji=Se.y,Nr=Se.z):(Ft=0,ji=0,Nr=0);let $i=oe.convert(ce.format),dn=oe.convert(ce.type),yt;ce.isData3DTexture?(U.setTexture3D(ce,0),yt=ae.TEXTURE_3D):ce.isDataArrayTexture||ce.isCompressedArrayTexture?(U.setTexture2DArray(ce,0),yt=ae.TEXTURE_2D_ARRAY):(U.setTexture2D(ce,0),yt=ae.TEXTURE_2D),Ke.activeTexture(ae.TEXTURE0),Ke.pixelStorei(ae.UNPACK_FLIP_Y_WEBGL,ce.flipY),Ke.pixelStorei(ae.UNPACK_PREMULTIPLY_ALPHA_WEBGL,ce.premultiplyAlpha),Ke.pixelStorei(ae.UNPACK_ALIGNMENT,ce.unpackAlignment);let Hn=Ke.getParameter(ae.UNPACK_ROW_LENGTH),Oi=Ke.getParameter(ae.UNPACK_IMAGE_HEIGHT),X=Ke.getParameter(ae.UNPACK_SKIP_PIXELS),xe=Ke.getParameter(ae.UNPACK_SKIP_ROWS),At=Ke.getParameter(ae.UNPACK_SKIP_IMAGES);Ke.pixelStorei(ae.UNPACK_ROW_LENGTH,Pr.width),Ke.pixelStorei(ae.UNPACK_IMAGE_HEIGHT,Pr.height),Ke.pixelStorei(ae.UNPACK_SKIP_PIXELS,Dt),Ke.pixelStorei(ae.UNPACK_SKIP_ROWS,oi),Ke.pixelStorei(ae.UNPACK_SKIP_IMAGES,si);let kt=W.isDataArrayTexture||W.isData3DTexture,st=ce.isDataArrayTexture||ce.isData3DTexture;if(W.isDepthTexture){let Qt=Z.get(W),$r=Z.get(ce),Zi=Z.get(Qt.__renderTarget),cl=Z.get($r.__renderTarget);Ke.bindFramebuffer(ae.READ_FRAMEBUFFER,Zi.__webglFramebuffer),Ke.bindFramebuffer(ae.DRAW_FRAMEBUFFER,cl.__webglFramebuffer);for(let nc=0;nc<Lt;nc++)kt&&(ae.framebufferTextureLayer(ae.READ_FRAMEBUFFER,ae.COLOR_ATTACHMENT0,Z.get(W).__webglTexture,Te,si+nc),ae.framebufferTextureLayer(ae.DRAW_FRAMEBUFFER,ae.COLOR_ATTACHMENT0,Z.get(ce).__webglTexture,St,Nr+nc)),ae.blitFramebuffer(Dt,oi,It,pt,Ft,ji,It,pt,ae.DEPTH_BUFFER_BIT,ae.NEAREST);Ke.bindFramebuffer(ae.READ_FRAMEBUFFER,null),Ke.bindFramebuffer(ae.DRAW_FRAMEBUFFER,null)}else if(Te!==0||W.isRenderTargetTexture||Z.has(W)){let Qt=Z.get(W),$r=Z.get(ce);Ke.bindFramebuffer(ae.READ_FRAMEBUFFER,P0),Ke.bindFramebuffer(ae.DRAW_FRAMEBUFFER,L0);for(let Zi=0;Zi<Lt;Zi++)kt?ae.framebufferTextureLayer(ae.READ_FRAMEBUFFER,ae.COLOR_ATTACHMENT0,Qt.__webglTexture,Te,si+Zi):ae.framebufferTexture2D(ae.READ_FRAMEBUFFER,ae.COLOR_ATTACHMENT0,ae.TEXTURE_2D,Qt.__webglTexture,Te),st?ae.framebufferTextureLayer(ae.DRAW_FRAMEBUFFER,ae.COLOR_ATTACHMENT0,$r.__webglTexture,St,Nr+Zi):ae.framebufferTexture2D(ae.DRAW_FRAMEBUFFER,ae.COLOR_ATTACHMENT0,ae.TEXTURE_2D,$r.__webglTexture,St),Te!==0?ae.blitFramebuffer(Dt,oi,It,pt,Ft,ji,It,pt,ae.COLOR_BUFFER_BIT,ae.NEAREST):st?ae.copyTexSubImage3D(yt,St,Ft,ji,Nr+Zi,Dt,oi,It,pt):ae.copyTexSubImage2D(yt,St,Ft,ji,Dt,oi,It,pt);Ke.bindFramebuffer(ae.READ_FRAMEBUFFER,null),Ke.bindFramebuffer(ae.DRAW_FRAMEBUFFER,null)}else st?W.isDataTexture||W.isData3DTexture?ae.texSubImage3D(yt,St,Ft,ji,Nr,It,pt,Lt,$i,dn,Pr.data):ce.isCompressedArrayTexture?ae.compressedTexSubImage3D(yt,St,Ft,ji,Nr,It,pt,Lt,$i,Pr.data):ae.texSubImage3D(yt,St,Ft,ji,Nr,It,pt,Lt,$i,dn,Pr):W.isDataTexture?ae.texSubImage2D(ae.TEXTURE_2D,St,Ft,ji,It,pt,$i,dn,Pr.data):W.isCompressedTexture?ae.compressedTexSubImage2D(ae.TEXTURE_2D,St,Ft,ji,Pr.width,Pr.height,$i,Pr.data):ae.texSubImage2D(ae.TEXTURE_2D,St,Ft,ji,It,pt,$i,dn,Pr);Ke.pixelStorei(ae.UNPACK_ROW_LENGTH,Hn),Ke.pixelStorei(ae.UNPACK_IMAGE_HEIGHT,Oi),Ke.pixelStorei(ae.UNPACK_SKIP_PIXELS,X),Ke.pixelStorei(ae.UNPACK_SKIP_ROWS,xe),Ke.pixelStorei(ae.UNPACK_SKIP_IMAGES,At),St===0&&ce.generateMipmaps&&ae.generateMipmap(yt),Ke.unbindTexture()},this.initRenderTarget=function(W){Z.get(W).__webglFramebuffer===void 0&&U.setupRenderTarget(W)},this.initTexture=function(W){W.isCubeTexture?U.setTextureCube(W,0):W.isData3DTexture?U.setTexture3D(W,0):W.isDataArrayTexture||W.isCompressedArrayTexture?U.setTexture2DArray(W,0):U.setTexture2D(W,0),Ke.unbindTexture()},this.resetState=function(){G=0,O=0,N=null,Ke.reset(),rt.reset()},typeof __THREE_DEVTOOLS__!="undefined"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return xo}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=mi._getDrawingBufferColorSpace(e),t.unpackColorSpace=mi._getUnpackColorSpace()}}});function sle(n){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(n.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(n)&&(this._addPointer(n),n.pointerType==="touch"?this._onTouchStart(n):this._onMouseDown(n),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function ale(n){this.enabled!==!1&&(n.pointerType==="touch"?this._onTouchMove(n):this._onMouseMove(n))}function ole(n){switch(this._removePointer(n),this._pointers.length){case 0:this.domElement.releasePointerCapture(n.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(EU),this.state=ur.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:let e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function lle(n){let e;switch(n.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case Lf.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(n),this.state=ur.DOLLY;break;case Lf.ROTATE:if(n.ctrlKey||n.metaKey||n.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(n),this.state=ur.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(n),this.state=ur.ROTATE}break;case Lf.PAN:if(n.ctrlKey||n.metaKey||n.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(n),this.state=ur.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(n),this.state=ur.PAN}break;default:this.state=ur.NONE}this.state!==ur.NONE&&this.dispatchEvent(TC)}function cle(n){switch(this.state){case ur.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(n);break;case ur.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(n);break;case ur.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(n);break}}function fle(n){this.enabled===!1||this.enableZoom===!1||this.state!==ur.NONE||(n.preventDefault(),this.dispatchEvent(TC),this._handleMouseWheel(this._customWheelEvent(n)),this.dispatchEvent(EU))}function dle(n){this.enabled!==!1&&this._handleKeyDown(n)}function ule(n){switch(this._trackPointer(n),this._pointers.length){case 1:switch(this.touches.ONE){case Df.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(n),this.state=ur.TOUCH_ROTATE;break;case Df.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(n),this.state=ur.TOUCH_PAN;break;default:this.state=ur.NONE}break;case 2:switch(this.touches.TWO){case Df.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(n),this.state=ur.TOUCH_DOLLY_PAN;break;case Df.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(n),this.state=ur.TOUCH_DOLLY_ROTATE;break;default:this.state=ur.NONE}break;default:this.state=ur.NONE}this.state!==ur.NONE&&this.dispatchEvent(TC)}function hle(n){switch(this._trackPointer(n),this.state){case ur.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(n),this.update();break;case ur.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(n),this.update();break;case ur.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(n),this.update();break;case ur.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(n),this.update();break;default:this.state=ur.NONE}}function mle(n){this.enabled!==!1&&n.preventDefault()}function ple(n){n.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function gle(n){n.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}var _U,TC,EU,AA,vU,nle,pn,js,ur,SC,xA,SU=y(()=>{Es();_U={type:"change"},TC={type:"start"},EU={type:"end"},AA=new ml,vU=new ps,nle=Math.cos(70*K_.DEG2RAD),pn=new ie,js=2*Math.PI,ur={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},SC=1e-6,xA=class extends F_{constructor(e,t=null){super(e,t),this.state=ur.NONE,this.target=new ie,this.cursor=new ie,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Lf.ROTATE,MIDDLE:Lf.DOLLY,RIGHT:Lf.PAN},this.touches={ONE:Df.ROTATE,TWO:Df.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new ie,this._lastQuaternion=new un,this._lastTargetPosition=new ie,this._quat=new un().setFromUnitVectors(e.up,new ie(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new vm,this._sphericalDelta=new vm,this._scale=1,this._panOffset=new ie,this._rotateStart=new Ct,this._rotateEnd=new Ct,this._rotateDelta=new Ct,this._panStart=new Ct,this._panEnd=new Ct,this._panDelta=new Ct,this._dollyStart=new Ct,this._dollyEnd=new Ct,this._dollyDelta=new Ct,this._dollyDirection=new ie,this._mouse=new Ct,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=ale.bind(this),this._onPointerDown=sle.bind(this),this._onPointerUp=ole.bind(this),this._onContextMenu=mle.bind(this),this._onMouseWheel=fle.bind(this),this._onKeyDown=dle.bind(this),this._onTouchStart=ule.bind(this),this._onTouchMove=hle.bind(this),this._onMouseDown=lle.bind(this),this._onMouseMove=cle.bind(this),this._interceptControlDown=ple.bind(this),this._interceptControlUp=gle.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(_U),this.update(),this.state=ur.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){let t=this.object.position;pn.copy(t).sub(this.target),pn.applyQuaternion(this._quat),this._spherical.setFromVector3(pn),this.autoRotate&&this.state===ur.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let i=this.minAzimuthAngle,r=this.maxAzimuthAngle;isFinite(i)&&isFinite(r)&&(i<-Math.PI?i+=js:i>Math.PI&&(i-=js),r<-Math.PI?r+=js:r>Math.PI&&(r-=js),i<=r?this._spherical.theta=Math.max(i,Math.min(r,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+r)/2?Math.max(i,this._spherical.theta):Math.min(r,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let a=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=a!=this._spherical.radius}if(pn.setFromSpherical(this._spherical),pn.applyQuaternion(this._quatInverse),t.copy(this.target).add(pn),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let a=null;if(this.object.isPerspectiveCamera){let o=pn.length();a=this._clampDistance(o*this._scale);let l=o-a;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),s=!!l}else if(this.object.isOrthographicCamera){let o=new ie(this._mouse.x,this._mouse.y,0);o.unproject(this.object);let l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=l!==this.object.zoom;let c=new ie(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),a=pn.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;a!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(a).add(this.object.position):(AA.origin.copy(this.object.position),AA.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(AA.direction))<nle?this.object.lookAt(this.target):(vU.setFromNormalAndCoplanarPoint(this.object.up,this.target),AA.intersectPlane(vU,this.target))))}else if(this.object.isOrthographicCamera){let a=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),a!==this.object.zoom&&(this.object.updateProjectionMatrix(),s=!0)}return this._scale=1,this._performCursorZoom=!1,s||this._lastPosition.distanceToSquared(this.object.position)>SC||8*(1-this._lastQuaternion.dot(this.object.quaternion))>SC||this._lastTargetPosition.distanceToSquared(this.target)>SC?(this.dispatchEvent(_U),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?js/60*this.autoRotateSpeed*e:js/60/60*this.autoRotateSpeed}_getZoomScale(e){let t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){pn.setFromMatrixColumn(t,0),pn.multiplyScalar(-e),this._panOffset.add(pn)}_panUp(e,t){this.screenSpacePanning===!0?pn.setFromMatrixColumn(t,1):(pn.setFromMatrixColumn(t,0),pn.crossVectors(this.object.up,pn)),pn.multiplyScalar(e),this._panOffset.add(pn)}_pan(e,t){let i=this.domElement;if(this.object.isPerspectiveCamera){let r=this.object.position;pn.copy(r).sub(this.target);let s=pn.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/i.clientHeight,this.object.matrix),this._panUp(2*t*s/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let i=this.domElement.getBoundingClientRect(),r=e-i.left,s=t-i.top,a=i.width,o=i.height;this._mouse.x=r/a*2-1,this._mouse.y=-(s/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(js*this._rotateDelta.x/t.clientHeight),this._rotateUp(js*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(js*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-js*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(js*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-js*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._rotateStart.set(i,r)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panStart.set(i,r)}}_handleTouchStartDolly(e){let t=this._getSecondPointerPosition(e),i=e.pageX-t.x,r=e.pageY-t.y,s=Math.sqrt(i*i+r*r);this._dollyStart.set(0,s)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{let i=this._getSecondPointerPosition(e),r=.5*(e.pageX+i.x),s=.5*(e.pageY+i.y);this._rotateEnd.set(r,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(js*this._rotateDelta.x/t.clientHeight),this._rotateUp(js*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panEnd.set(i,r)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){let t=this._getSecondPointerPosition(e),i=e.pageX-t.x,r=e.pageY-t.y,s=Math.sqrt(i*i+r*r);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let a=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(a,o)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new Ct,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){let t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){let t=e.deltaMode,i={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:i.deltaY*=16;break;case 2:i.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(i.deltaY*=10),i}}});function Pm(n){return new I_({color:0,emissive:16777215,emissiveIntensity:n})}var RA,TU=y(()=>{Es();RA=class extends du{constructor(){super(),this.name="RoomEnvironment",this.position.y=-3.5;let e=new If;e.deleteAttribute("uv");let t=new Dn({side:On}),i=new Dn,r=new Mo(16777215,900,28,2);r.position.set(.418,16.199,.3),this.add(r);let s=new ci(e,t);s.position.set(-.757,13.219,.717),s.scale.set(31.713,28.305,28.591),this.add(s);let a=new hu(e,i,6),o=new sr;o.position.set(-10.906,2.009,1.846),o.rotation.set(0,-.195,0),o.scale.set(2.328,7.905,4.651),o.updateMatrix(),a.setMatrixAt(0,o.matrix),o.position.set(-5.607,-.754,-.758),o.rotation.set(0,.994,0),o.scale.set(1.97,1.534,3.955),o.updateMatrix(),a.setMatrixAt(1,o.matrix),o.position.set(6.167,.857,7.803),o.rotation.set(0,.561,0),o.scale.set(3.927,6.285,3.687),o.updateMatrix(),a.setMatrixAt(2,o.matrix),o.position.set(-2.017,.018,6.124),o.rotation.set(0,.333,0),o.scale.set(2.002,4.566,2.064),o.updateMatrix(),a.setMatrixAt(3,o.matrix),o.position.set(2.291,-.756,-2.621),o.rotation.set(0,-.286,0),o.scale.set(1.546,1.552,1.496),o.updateMatrix(),a.setMatrixAt(4,o.matrix),o.position.set(-2.193,-.369,-5.547),o.rotation.set(0,.516,0),o.scale.set(3.875,3.487,2.986),o.updateMatrix(),a.setMatrixAt(5,o.matrix),this.add(a);let l=new ci(e,Pm(50));l.position.set(-16.116,14.37,8.208),l.scale.set(.1,2.428,2.739),this.add(l);let c=new ci(e,Pm(50));c.position.set(-16.109,18.021,-8.207),c.scale.set(.1,2.425,2.751),this.add(c);let f=new ci(e,Pm(17));f.position.set(14.904,12.198,-1.832),f.scale.set(.15,4.265,6.331),this.add(f);let d=new ci(e,Pm(43));d.position.set(-.462,8.89,14.52),d.scale.set(4.38,5.441,.088),this.add(d);let u=new ci(e,Pm(20));u.position.set(3.235,11.486,-12.541),u.scale.set(2.5,2,.1),this.add(u);let h=new ci(e,Pm(100));h.position.set(0,20,0),h.scale.set(1,.1,1),this.add(h)}dispose(){let e=new Set;this.traverse(t=>{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(let t of e)t.dispose()}}});var bA,AC,AU=y(()=>{Es();bA=class extends bn{constructor(e){super(e)}load(e,t,i,r){let s=this,a=this.path===""?yo.extractUrlBase(e):this.path,o=new Hs(this.manager);o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(l){try{t(s.parse(l,a))}catch(c){r?r(c):console.error(c),s.manager.itemError(e)}},i,r)}setMaterialOptions(e){return this.materialOptions=e,this}parse(e,t){let i=e.split(`
`),r={},s=/\s+/,a={};for(let l=0;l<i.length;l++){let c=i[l];if(c=c.trim(),c.length===0||c.charAt(0)==="#")continue;let f=c.indexOf(" "),d=f>=0?c.substring(0,f):c;d=d.toLowerCase();let u=f>=0?c.substring(f+1):"";if(u=u.trim(),d==="newmtl")r={name:u},a[u]=r;else if(d==="ka"||d==="kd"||d==="ks"||d==="ke"){let h=u.split(s,3);r[d]=[parseFloat(h[0]),parseFloat(h[1]),parseFloat(h[2])]}else r[d]=u}let o=new AC(this.resourcePath||t,this.materialOptions);return o.setCrossOrigin(this.crossOrigin),o.setManager(this.manager),o.setMaterials(a),o}},AC=class{constructor(e="",t={}){this.baseUrl=e,this.options=t,this.materialsInfo={},this.materials={},this.materialsArray=[],this.nameLookup={},this.crossOrigin="anonymous",this.side=this.options.side!==void 0?this.options.side:va,this.wrap=this.options.wrap!==void 0?this.options.wrap:ul}setCrossOrigin(e){return this.crossOrigin=e,this}setManager(e){this.manager=e}setMaterials(e){this.materialsInfo=this.convert(e),this.materials={},this.materialsArray=[],this.nameLookup={}}convert(e){if(!this.options)return e;let t={};for(let i in e){let r=e[i],s={};t[i]=s;for(let a in r){let o=!0,l=r[a],c=a.toLowerCase();switch(c){case"kd":case"ka":case"ks":this.options&&this.options.normalizeRGB&&(l=[l[0]/255,l[1]/255,l[2]/255]),this.options&&this.options.ignoreZeroRGBs&&l[0]===0&&l[1]===0&&l[2]===0&&(o=!1);break;default:break}o&&(s[c]=l)}}return t}preload(){for(let e in this.materialsInfo)this.create(e)}getIndex(e){return this.nameLookup[e]}getAsArray(){let e=0;for(let t in this.materialsInfo)this.materialsArray[e]=this.create(t),this.nameLookup[t]=e,e++;return this.materialsArray}create(e){return this.materials[e]===void 0&&this.createMaterial_(e),this.materials[e]}createMaterial_(e){let t=this,i=this.materialsInfo[e],r={name:e,side:this.side};function s(o,l){return typeof l!="string"||l===""?"":/^https?:\/\//i.test(l)?l:o+l}function a(o,l){if(r[o])return;let c=t.getTextureParams(l,r),f=t.loadTexture(s(t.baseUrl,c.url));f.repeat.copy(c.scale),f.offset.copy(c.offset),f.wrapS=t.wrap,f.wrapT=t.wrap,(o==="map"||o==="emissiveMap")&&(f.colorSpace=Fi),r[o]=f}for(let o in i){let l=i[o],c;if(l!=="")switch(o.toLowerCase()){case"kd":r.color=mi.colorSpaceToWorking(new mt().fromArray(l),Fi);break;case"ks":r.specular=mi.colorSpaceToWorking(new mt().fromArray(l),Fi);break;case"ke":r.emissive=mi.colorSpaceToWorking(new mt().fromArray(l),Fi);break;case"map_kd":a("map",l);break;case"map_ks":a("specularMap",l);break;case"map_ke":a("emissiveMap",l);break;case"norm":a("normalMap",l);break;case"map_bump":case"bump":a("bumpMap",l);break;case"disp":a("displacementMap",l);break;case"map_d":a("alphaMap",l),r.transparent=!0;break;case"ns":r.shininess=parseFloat(l);break;case"d":c=parseFloat(l),c<1&&(r.opacity=c,r.transparent=!0);break;case"tr":c=parseFloat(l),this.options&&this.options.invertTrProperty&&(c=1-c),c>0&&(r.opacity=1-c,r.transparent=!0);break;default:break}}return this.materials[e]=new gu(r),this.materials[e]}getTextureParams(e,t){let i={scale:new Ct(1,1),offset:new Ct(0,0)},r=e.split(/\s+/),s;return s=r.indexOf("-bm"),s>=0&&(t.bumpScale=parseFloat(r[s+1]),r.splice(s,2)),s=r.indexOf("-mm"),s>=0&&(t.displacementBias=parseFloat(r[s+1]),t.displacementScale=parseFloat(r[s+2]),r.splice(s,3)),s=r.indexOf("-s"),s>=0&&(i.scale.set(parseFloat(r[s+1]),parseFloat(r[s+2])),r.splice(s,4)),s=r.indexOf("-o"),s>=0&&(i.offset.set(parseFloat(r[s+1]),parseFloat(r[s+2])),r.splice(s,4)),i.url=r.join(" ").trim(),i}loadTexture(e,t,i,r,s){let a=this.manager!==void 0?this.manager:pA,o=a.getHandler(e);o===null&&(o=new vu(a)),o.setCrossOrigin&&o.setCrossOrigin(this.crossOrigin);let l=o.load(e,i,r,s);return t!==void 0&&(l.mapping=t),l}}});function Tle(){let n={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(e,t){if(this.object&&this.object.fromDeclaration===!1){this.object.name=e,this.object.fromDeclaration=t!==!1;return}let i=this.object&&typeof this.object.currentMaterial=="function"?this.object.currentMaterial():void 0;if(this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0),this.object={name:e||"",fromDeclaration:t!==!1,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(r,s){let a=this._finalize(!1);a&&(a.inherited||a.groupCount<=0)&&this.materials.splice(a.index,1);let o={index:this.materials.length,name:r||"",mtllib:Array.isArray(s)&&s.length>0?s[s.length-1]:"",smooth:a!==void 0?a.smooth:this.smooth,groupStart:a!==void 0?a.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(l){let c={index:typeof l=="number"?l:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return c.clone=this.clone.bind(c),c}};return this.materials.push(o),o},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(r){let s=this.currentMaterial();if(s&&s.groupEnd===-1&&(s.groupEnd=this.geometry.vertices.length/3,s.groupCount=s.groupEnd-s.groupStart,s.inherited=!1),r&&this.materials.length>1)for(let a=this.materials.length-1;a>=0;a--)this.materials[a].groupCount<=0&&this.materials.splice(a,1);return r&&this.materials.length===0&&this.materials.push({name:"",smooth:this.smooth}),s}},i&&i.name&&typeof i.clone=="function"){let r=i.clone(0);r.inherited=!0,this.object.materials.push(r)}this.objects.push(this.object)},finalize:function(){this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0)},parseVertexIndex:function(e,t){let i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseNormalIndex:function(e,t){let i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseUVIndex:function(e,t){let i=parseInt(e,10);return(i>=0?i-1:i+t/2)*2},addVertex:function(e,t,i){let r=this.vertices,s=this.object.geometry.vertices;s.push(r[e+0],r[e+1],r[e+2]),s.push(r[t+0],r[t+1],r[t+2]),s.push(r[i+0],r[i+1],r[i+2])},addVertexPoint:function(e){let t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addVertexLine:function(e){let t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addNormal:function(e,t,i){let r=this.normals,s=this.object.geometry.normals;s.push(r[e+0],r[e+1],r[e+2]),s.push(r[t+0],r[t+1],r[t+2]),s.push(r[i+0],r[i+1],r[i+2])},addFaceNormal:function(e,t,i){let r=this.vertices,s=this.object.geometry.normals;RU.fromArray(r,e),xC.fromArray(r,t),bU.fromArray(r,i),Ka.subVectors(bU,xC),MU.subVectors(RU,xC),Ka.cross(MU),Ka.normalize(),s.push(Ka.x,Ka.y,Ka.z),s.push(Ka.x,Ka.y,Ka.z),s.push(Ka.x,Ka.y,Ka.z)},addColor:function(e,t,i){let r=this.colors,s=this.object.geometry.colors;r[e]!==void 0&&s.push(r[e+0],r[e+1],r[e+2]),r[t]!==void 0&&s.push(r[t+0],r[t+1],r[t+2]),r[i]!==void 0&&s.push(r[i+0],r[i+1],r[i+2])},addUV:function(e,t,i){let r=this.uvs,s=this.object.geometry.uvs;s.push(r[e+0],r[e+1]),s.push(r[t+0],r[t+1]),s.push(r[i+0],r[i+1])},addDefaultUV:function(){let e=this.object.geometry.uvs;e.push(0,0),e.push(0,0),e.push(0,0)},addUVLine:function(e){let t=this.uvs;this.object.geometry.uvs.push(t[e+0],t[e+1])},addFace:function(e,t,i,r,s,a,o,l,c){let f=this.vertices.length,d=this.parseVertexIndex(e,f),u=this.parseVertexIndex(t,f),h=this.parseVertexIndex(i,f);if(this.addVertex(d,u,h),this.addColor(d,u,h),o!==void 0&&o!==""){let m=this.normals.length;d=this.parseNormalIndex(o,m),u=this.parseNormalIndex(l,m),h=this.parseNormalIndex(c,m),this.addNormal(d,u,h)}else this.addFaceNormal(d,u,h);if(r!==void 0&&r!==""){let m=this.uvs.length;d=this.parseUVIndex(r,m),u=this.parseUVIndex(s,m),h=this.parseUVIndex(a,m),this.addUV(d,u,h),this.object.geometry.hasUVIndices=!0}else this.addDefaultUV()},addPointGeometry:function(e){this.object.geometry.type="Points";let t=this.vertices.length;for(let i=0,r=e.length;i<r;i++){let s=this.parseVertexIndex(e[i],t);this.addVertexPoint(s),this.addColor(s)}},addLineGeometry:function(e,t){this.object.geometry.type="Line";let i=this.vertices.length,r=this.uvs.length;for(let s=0,a=e.length;s<a;s++)this.addVertexLine(this.parseVertexIndex(e[s],i));for(let s=0,a=t.length;s<a;s++)this.addUVLine(this.parseUVIndex(t[s],r))}};return n.startObject("",!1),n}var _le,vle,Ele,Sle,xU,RU,xC,bU,MU,Ka,MA,yA,yU=y(()=>{Es();_le=/^[og]\s*(.+)?/,vle=/^mtllib /,Ele=/^usemtl /,Sle=/^usemap /,xU=/\s+/,RU=new ie,xC=new ie,bU=new ie,MU=new ie,Ka=new ie,MA=new mt;yA=class extends bn{constructor(e){super(e),this.materials=null}load(e,t,i,r){let s=this,a=new Hs(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){r?r(l):console.error(l),s.manager.itemError(e)}},i,r)}setMaterials(e){return this.materials=e,this}parse(e){let t=new Tle;e.indexOf(`\r
`)!==-1&&(e=e.replace(/\r\n/g,`
`)),e.indexOf(`\\
`)!==-1&&(e=e.replace(/\\\n/g,""));let i=e.split(`
`),r=[];for(let o=0,l=i.length;o<l;o++){let c=i[o].trimStart();if(c.length===0)continue;let f=c.charAt(0);if(f!=="#")if(f==="v"){let d=c.split(xU);switch(d[0]){case"v":t.vertices.push(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3])),d.length>=7?(MA.setRGB(parseFloat(d[4]),parseFloat(d[5]),parseFloat(d[6]),Fi),t.colors.push(MA.r,MA.g,MA.b)):t.colors.push(void 0,void 0,void 0);break;case"vn":t.normals.push(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));break;case"vt":t.uvs.push(parseFloat(d[1]),parseFloat(d[2]));break}}else if(f==="f"){let u=c.slice(1).trim().split(xU),h=[];for(let g=0,p=u.length;g<p;g++){let _=u[g];if(_.length>0){let v=_.split("/");h.push(v)}}let m=h[0];for(let g=1,p=h.length-1;g<p;g++){let _=h[g],v=h[g+1];t.addFace(m[0],_[0],v[0],m[1],_[1],v[1],m[2],_[2],v[2])}}else if(f==="l"){let d=c.substring(1).trim().split(" "),u=[],h=[];if(c.indexOf("/")===-1)u=d;else for(let m=0,g=d.length;m<g;m++){let p=d[m].split("/");p[0]!==""&&u.push(p[0]),p[1]!==""&&h.push(p[1])}t.addLineGeometry(u,h)}else if(f==="p"){let u=c.slice(1).trim().split(" ");t.addPointGeometry(u)}else if((r=_le.exec(c))!==null){let d=(" "+r[0].slice(1).trim()).slice(1);t.startObject(d)}else if(Ele.test(c))t.object.startMaterial(c.substring(7).trim(),t.materialLibraries);else if(vle.test(c))t.materialLibraries.push(c.substring(7).trim());else if(Sle.test(c))console.warn('THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.');else if(f==="s"){if(r=c.split(" "),r.length>1){let u=r[1].trim().toLowerCase();t.object.smooth=u!=="0"&&u!=="off"}else t.object.smooth=!0;let d=t.object.currentMaterial();d&&(d.smooth=t.object.smooth)}else{if(c==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+c+'"')}}t.finalize();let s=new _a;if(s.materialLibraries=[].concat(t.materialLibraries),!(t.objects.length===1&&t.objects[0].geometry.vertices.length===0)===!0)for(let o=0,l=t.objects.length;o<l;o++){let c=t.objects[o],f=c.geometry,d=c.materials,u=f.type==="Line",h=f.type==="Points",m=!1;if(f.vertices.length===0)continue;let g=new Bi;g.setAttribute("position",new gi(f.vertices,3)),f.normals.length>0&&g.setAttribute("normal",new gi(f.normals,3)),f.colors.length>0&&(m=!0,g.setAttribute("color",new gi(f.colors,3))),f.hasUVIndices===!0&&g.setAttribute("uv",new gi(f.uvs,2));let p=[];for(let v=0,E=d.length;v<E;v++){let S=d[v],T=S.name+"_"+S.smooth+"_"+m,A=t.materials[T];if(this.materials!==null){if(A=this.materials.create(S.name),u&&A&&!(A instanceof Ln)){let R=new Ln;Hr.prototype.copy.call(R,A),R.color.copy(A.color),A=R}else if(h&&A&&!(A instanceof Gs)){let R=new Gs({size:10,sizeAttenuation:!1});Hr.prototype.copy.call(R,A),R.color.copy(A.color),R.map=A.map,A=R}}A===void 0&&(u?A=new Ln:h?A=new Gs({size:1,sizeAttenuation:!1}):A=new gu,A.name=S.name,A.flatShading=!S.smooth,A.vertexColors=m,t.materials[T]=A),p.push(A)}let _;if(p.length>1){for(let v=0,E=d.length;v<E;v++){let S=d[v];g.addGroup(S.groupStart,S.groupCount,v)}u?_=new _s(g,p):h?_=new ks(g,p):_=new ci(g,p)}else u?_=new _s(g,p[0]):h?_=new ks(g,p[0]):_=new ci(g,p[0]);_.name=c.name,s.add(_)}else if(t.vertices.length>0){let o=new Gs({size:1,sizeAttenuation:!1}),l=new Bi;l.setAttribute("position",new gi(t.vertices,3)),t.colors.length>0&&t.colors[0]!==void 0&&(l.setAttribute("color",new gi(t.colors,3)),o.vertexColors=!0);let c=new ks(l,o);s.add(c)}return s}}});var Zs,IA,RC,IU=y(()=>{Es();Zs=new mt,IA=class extends bn{constructor(e){super(e),this.propertyNameMapping={},this.customPropertyMapping={}}load(e,t,i,r){let s=this,a=new Hs(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){r?r(l):console.error(l),s.manager.itemError(e)}},i,r)}setPropertyNameMapping(e){this.propertyNameMapping=e}setCustomPropertyNameMapping(e){this.customPropertyMapping=e}parse(e){function t(p,_=0){let v=/^ply([\s\S]*)end_header(\r\n|\r|\n)/,E="",S=v.exec(p);S!==null&&(E=S[1]);let T={comments:[],elements:[],headerLength:_,objInfo:""},A=E.split(/\r\n|\r|\n/),R;function M(I,C){let L={type:I[0]};return L.type==="list"?(L.name=I[3],L.countType=I[1],L.itemType=I[2]):L.name=I[1],L.name in C&&(L.name=C[L.name]),L}for(let I=0;I<A.length;I++){let C=A[I];if(C=C.trim(),C==="")continue;let L=C.split(/\s+/),w=L.shift();switch(C=L.join(" "),w){case"format":T.format=L[0],T.version=L[1];break;case"comment":T.comments.push(C);break;case"element":R!==void 0&&T.elements.push(R),R={},R.name=L[0],R.count=parseInt(L[1]),R.properties=[];break;case"property":R.properties.push(M(L,g.propertyNameMapping));break;case"obj_info":T.objInfo=C;break;default:console.log("unhandled",w,L)}}return R!==void 0&&T.elements.push(R),T}function i(p,_){switch(_){case"char":case"uchar":case"short":case"ushort":case"int":case"uint":case"int8":case"uint8":case"int16":case"uint16":case"int32":case"uint32":return parseInt(p);case"float":case"double":case"float32":case"float64":return parseFloat(p)}}function r(p,_){let v={};for(let E=0;E<p.length;E++){if(_.empty())return null;if(p[E].type==="list"){let S=[],T=i(_.next(),p[E].countType);for(let A=0;A<T;A++){if(_.empty())return null;S.push(i(_.next(),p[E].itemType))}v[p[E].name]=S}else v[p[E].name]=i(_.next(),p[E].type)}return v}function s(){let p={indices:[],vertices:[],normals:[],uvs:[],faceVertexUvs:[],colors:[],faceVertexColors:[]};for(let _ of Object.keys(g.customPropertyMapping))p[_]=[];return p}function a(p){let _=p.map(E=>E.name);function v(E){for(let S=0,T=E.length;S<T;S++){let A=E[S];if(_.includes(A))return A}return null}return{attrX:v(["x","px","posx"])||"x",attrY:v(["y","py","posy"])||"y",attrZ:v(["z","pz","posz"])||"z",attrNX:v(["nx","normalx"]),attrNY:v(["ny","normaly"]),attrNZ:v(["nz","normalz"]),attrS:v(["s","u","texture_u","tx"]),attrT:v(["t","v","texture_v","ty"]),attrR:v(["red","diffuse_red","r","diffuse_r"]),attrG:v(["green","diffuse_green","g","diffuse_g"]),attrB:v(["blue","diffuse_blue","b","diffuse_b"])}}function o(p,_){let v=s(),E=/end_header\s+(\S[\s\S]*\S|\S)\s*$/,S,T;(T=E.exec(p))!==null?S=T[1].split(/\s+/):S=[];let A=new RC(S);e:for(let R=0;R<_.elements.length;R++){let M=_.elements[R],I=a(M.properties);for(let C=0;C<M.count;C++){let L=r(M.properties,A);if(!L)break e;c(v,M.name,L,I)}}return l(v)}function l(p){let _=new Bi;p.indices.length>0&&_.setIndex(p.indices),_.setAttribute("position",new gi(p.vertices,3)),p.normals.length>0&&_.setAttribute("normal",new gi(p.normals,3)),p.uvs.length>0&&_.setAttribute("uv",new gi(p.uvs,2)),p.colors.length>0&&_.setAttribute("color",new gi(p.colors,3)),(p.faceVertexUvs.length>0||p.faceVertexColors.length>0)&&(_=_.toNonIndexed(),p.faceVertexUvs.length>0&&_.setAttribute("uv",new gi(p.faceVertexUvs,2)),p.faceVertexColors.length>0&&_.setAttribute("color",new gi(p.faceVertexColors,3)));for(let v of Object.keys(g.customPropertyMapping))p[v].length>0&&_.setAttribute(v,new gi(p[v],g.customPropertyMapping[v].length));return _.computeBoundingSphere(),_}function c(p,_,v,E){if(_==="vertex"){p.vertices.push(v[E.attrX],v[E.attrY],v[E.attrZ]),E.attrNX!==null&&E.attrNY!==null&&E.attrNZ!==null&&p.normals.push(v[E.attrNX],v[E.attrNY],v[E.attrNZ]),E.attrS!==null&&E.attrT!==null&&p.uvs.push(v[E.attrS],v[E.attrT]),E.attrR!==null&&E.attrG!==null&&E.attrB!==null&&(Zs.setRGB(v[E.attrR]/255,v[E.attrG]/255,v[E.attrB]/255,Fi),p.colors.push(Zs.r,Zs.g,Zs.b));for(let S of Object.keys(g.customPropertyMapping))for(let T of g.customPropertyMapping[S])p[S].push(v[T])}else if(_==="face"){let S=v.vertex_indices||v.vertex_index,T=v.texcoord;S.length===3?(p.indices.push(S[0],S[1],S[2]),T&&T.length===6&&(p.faceVertexUvs.push(T[0],T[1]),p.faceVertexUvs.push(T[2],T[3]),p.faceVertexUvs.push(T[4],T[5]))):S.length===4&&(p.indices.push(S[0],S[1],S[3]),p.indices.push(S[1],S[2],S[3])),E.attrR!==null&&E.attrG!==null&&E.attrB!==null&&(Zs.setRGB(v[E.attrR]/255,v[E.attrG]/255,v[E.attrB]/255,Fi),p.faceVertexColors.push(Zs.r,Zs.g,Zs.b),p.faceVertexColors.push(Zs.r,Zs.g,Zs.b),p.faceVertexColors.push(Zs.r,Zs.g,Zs.b))}}function f(p,_){let v={},E=0;for(let S=0;S<_.length;S++){let T=_[S],A=T.valueReader;if(T.type==="list"){let R=[],M=T.countReader.read(p+E);E+=T.countReader.size;for(let I=0;I<M;I++)R.push(A.read(p+E)),E+=A.size;v[T.name]=R}else v[T.name]=A.read(p+E),E+=A.size}return[v,E]}function d(p,_,v){function E(S,T,A){switch(T){case"int8":case"char":return{read:R=>S.getInt8(R),size:1};case"uint8":case"uchar":return{read:R=>S.getUint8(R),size:1};case"int16":case"short":return{read:R=>S.getInt16(R,A),size:2};case"uint16":case"ushort":return{read:R=>S.getUint16(R,A),size:2};case"int32":case"int":return{read:R=>S.getInt32(R,A),size:4};case"uint32":case"uint":return{read:R=>S.getUint32(R,A),size:4};case"float32":case"float":return{read:R=>S.getFloat32(R,A),size:4};case"float64":case"double":return{read:R=>S.getFloat64(R,A),size:8}}}for(let S=0,T=p.length;S<T;S++){let A=p[S];A.type==="list"?(A.countReader=E(_,A.countType,v),A.valueReader=E(_,A.itemType,v)):A.valueReader=E(_,A.type,v)}}function u(p,_){let v=s(),E=_.format==="binary_little_endian",S=new DataView(p,_.headerLength),T,A=0;for(let R=0;R<_.elements.length;R++){let M=_.elements[R],I=M.properties,C=a(I);d(I,S,E);for(let L=0;L<M.count;L++){T=f(A,I),A+=T[1];let w=T[0];c(v,M.name,w,C)}}return l(v)}function h(p){let _=0,v=!0,E="",S=[],T=new TextDecoder().decode(p.subarray(0,5)),A=/^ply\r\n/.test(T);do{let R=String.fromCharCode(p[_++]);R!==`
`&&R!=="\r"?E+=R:(E==="end_header"&&(v=!1),E!==""&&(S.push(E),E=""))}while(v&&_<p.length);return A===!0&&_++,{headerText:S.join("\r")+"\r",headerLength:_}}let m,g=this;if(e instanceof ArrayBuffer){let p=new Uint8Array(e),{headerText:_,headerLength:v}=h(p),E=t(_,v);if(E.format==="ascii"){let S=new TextDecoder().decode(p);m=o(S,E)}else m=u(e,E)}else m=o(e,t(e));return m}},RC=class{constructor(e){this.arr=e,this.i=0}empty(){return this.i>=this.arr.length}next(){return this.arr[this.i++]}}});var CA,CU=y(()=>{Es();CA=class extends bn{constructor(e){super(e)}load(e,t,i,r){let s=this,a=new Hs(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){r?r(l):console.error(l),s.manager.itemError(e)}},i,r)}parse(e){function t(c){let f=new DataView(c),d=32/8*3+32/8*3*3+16/8,u=f.getUint32(80,!0);if(80+32/8+u*d===f.byteLength)return!0;let m=[115,111,108,105,100];for(let g=0;g<5;g++)if(i(m,f,g))return!1;return!0}function i(c,f,d){for(let u=0,h=c.length;u<h;u++)if(c[u]!==f.getUint8(d+u))return!1;return!0}function r(c){let f=new DataView(c),d=f.getUint32(80,!0),u,h,m,g=!1,p,_,v,E,S;for(let L=0;L<70;L++)f.getUint32(L,!1)==1129270351&&f.getUint8(L+4)==82&&f.getUint8(L+5)==61&&(g=!0,p=new Float32Array(d*3*3),_=f.getUint8(L+6)/255,v=f.getUint8(L+7)/255,E=f.getUint8(L+8)/255,S=f.getUint8(L+9)/255);let T=84,A=50,R=new Bi,M=new Float32Array(d*3*3),I=new Float32Array(d*3*3),C=new mt;for(let L=0;L<d;L++){let w=T+L*A,G=f.getFloat32(w,!0),O=f.getFloat32(w+4,!0),N=f.getFloat32(w+8,!0);if(g){let B=f.getUint16(w+48,!0);(B&32768)===0?(u=(B&31)/31,h=(B>>5&31)/31,m=(B>>10&31)/31):(u=_,h=v,m=E)}for(let B=1;B<=3;B++){let V=w+B*12,q=L*3*3+(B-1)*3;M[q]=f.getFloat32(V,!0),M[q+1]=f.getFloat32(V+4,!0),M[q+2]=f.getFloat32(V+8,!0),I[q]=G,I[q+1]=O,I[q+2]=N,g&&(C.setRGB(u,h,m,Fi),p[q]=C.r,p[q+1]=C.g,p[q+2]=C.b)}}return R.setAttribute("position",new Tr(M,3)),R.setAttribute("normal",new Tr(I,3)),g&&(R.setAttribute("color",new Tr(p,3)),R.hasColors=!0,R.alpha=S),R}function s(c){let f=new Bi,d=/solid([\s\S]*?)endsolid/g,u=/facet([\s\S]*?)endfacet/g,h=/solid\s(.+)/,m=0,g=/[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source,p=new RegExp("vertex"+g+g+g,"g"),_=new RegExp("normal"+g+g+g,"g"),v=[],E=[],S=[],T=new ie,A,R=0,M=0,I=0;for(;(A=d.exec(c))!==null;){M=I;let C=A[0],L=(A=h.exec(C))!==null?A[1]:"";for(S.push(L);(A=u.exec(C))!==null;){let O=0,N=0,B=A[0];for(;(A=_.exec(B))!==null;)T.x=parseFloat(A[1]),T.y=parseFloat(A[2]),T.z=parseFloat(A[3]),N++;for(;(A=p.exec(B))!==null;)v.push(parseFloat(A[1]),parseFloat(A[2]),parseFloat(A[3])),E.push(T.x,T.y,T.z),O++,I++;N!==1&&console.error("THREE.STLLoader: Something isn't right with the normal of face number "+m),O!==3&&console.error("THREE.STLLoader: Something isn't right with the vertices of face number "+m),m++}let w=M,G=I-M;f.userData.groupNames=S,f.addGroup(w,G,R),R++}return f.setAttribute("position",new gi(v,3)),f.setAttribute("normal",new gi(E,3)),f}function a(c){return typeof c!="string"?new TextDecoder().decode(c):c}function o(c){if(typeof c=="string"){let f=new Uint8Array(c.length);for(let d=0;d<c.length;d++)f[d]=c.charCodeAt(d)&255;return f.buffer||f}else return c}let l=o(e);return t(l)?r(l):s(a(e))}}});function bC(n,e){if(e===YI)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===Rm||e===Y_){let t=n.getIndex();if(t===null){let a=[],o=n.getAttribute("position");if(o!==void 0){for(let l=0;l<o.count;l++)a.push(l);n.setIndex(a),t=n.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),n}let i=t.count-2,r=[];if(e===Rm)for(let a=1;a<=i;a++)r.push(t.getX(0)),r.push(t.getX(a)),r.push(t.getX(a+1));else for(let a=0;a<i;a++)a%2===0?(r.push(t.getX(a)),r.push(t.getX(a+1)),r.push(t.getX(a+2))):(r.push(t.getX(a+2)),r.push(t.getX(a+1)),r.push(t.getX(a)));r.length/3!==i&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");let s=n.clone();return s.setIndex(r),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),n}var PU=y(()=>{Es()});function LU(n){let e=new Map,t=new Map,i=n.clone();return DU(n,i,function(r,s){e.set(s,r),t.set(r,s)}),i.traverse(function(r){if(!r.isSkinnedMesh)return;let s=r,a=e.get(r),o=a.skeleton.bones;s.skeleton=a.skeleton.clone(),s.bindMatrix.copy(a.bindMatrix),s.skeleton.bones=o.map(function(l){return t.get(l)}),s.bind(s.skeleton,s.bindMatrix)}),i}function DU(n,e,t){t(n,e);for(let i=0;i<n.children.length;i++)DU(n.children[i],e.children[i],t)}var OU=y(()=>{});function Ale(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}function Xr(n,e,t){let i=n.json.materials[e];return i.extensions&&i.extensions[t]?i.extensions[t]:null}function ble(n){return n.DefaultMaterial===void 0&&(n.DefaultMaterial=new Dn({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:va})),n.DefaultMaterial}function xu(n,e,t){for(let i in t.extensions)n[i]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[i]=t.extensions[i])}function bl(n,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(n.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function Mle(n,e,t){let i=!1,r=!1,s=!1;for(let c=0,f=e.length;c<f;c++){let d=e[c];if(d.POSITION!==void 0&&(i=!0),d.NORMAL!==void 0&&(r=!0),d.COLOR_0!==void 0&&(s=!0),i&&r&&s)break}if(!i&&!r&&!s)return Promise.resolve(n);let a=[],o=[],l=[];for(let c=0,f=e.length;c<f;c++){let d=e[c];if(i){let u=d.POSITION!==void 0?t.getDependency("accessor",d.POSITION):n.attributes.position;a.push(u)}if(r){let u=d.NORMAL!==void 0?t.getDependency("accessor",d.NORMAL):n.attributes.normal;o.push(u)}if(s){let u=d.COLOR_0!==void 0?t.getDependency("accessor",d.COLOR_0):n.attributes.color;l.push(u)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l)]).then(function(c){let f=c[0],d=c[1],u=c[2];return i&&(n.morphAttributes.position=f),r&&(n.morphAttributes.normal=d),s&&(n.morphAttributes.color=u),n.morphTargetsRelative=!0,n})}function yle(n,e){if(n.updateMorphTargets(),e.weights!==void 0)for(let t=0,i=e.weights.length;t<i;t++)n.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){let t=e.extras.targetNames;if(n.morphTargetInfluences.length===t.length){n.morphTargetDictionary={};for(let i=0,r=t.length;i<r;i++)n.morphTargetDictionary[t[i]]=i}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Ile(n){let e,t=n.extensions&&n.extensions[Ii.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+IC(t.attributes):e=n.indices+":"+IC(n.attributes)+":"+n.mode,n.targets!==void 0)for(let i=0,r=n.targets.length;i<r;i++)e+=":"+IC(n.targets[i]);return e}function IC(n){let e="",t=Object.keys(n).sort();for(let i=0,r=t.length;i<r;i++)e+=t[i]+":"+n[t[i]]+";";return e}function $C(n){switch(n){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function Cle(n){return n.search(/\.jpe?g($|\?)/i)>0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}function Lle(n,e,t){let i=e.attributes,r=new Wr;if(i.POSITION!==void 0){let o=t.json.accessors[i.POSITION],l=o.min,c=o.max;if(l!==void 0&&c!==void 0){if(r.set(new ie(l[0],l[1],l[2]),new ie(c[0],c[1],c[2])),o.normalized){let f=$C(Lm[o.componentType]);r.min.multiplyScalar(f),r.max.multiplyScalar(f)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;let s=e.targets;if(s!==void 0){let o=new ie,l=new ie;for(let c=0,f=s.length;c<f;c++){let d=s[c];if(d.POSITION!==void 0){let u=t.json.accessors[d.POSITION],h=u.min,m=u.max;if(h!==void 0&&m!==void 0){if(l.setX(Math.max(Math.abs(h[0]),Math.abs(m[0]))),l.setY(Math.max(Math.abs(h[1]),Math.abs(m[1]))),l.setZ(Math.max(Math.abs(h[2]),Math.abs(m[2]))),u.normalized){let g=$C(Lm[u.componentType]);l.multiplyScalar(g)}o.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}r.expandByVector(o)}n.boundingBox=r;let a=new Vs;r.getCenter(a.center),a.radius=r.min.distanceTo(r.max)/2,n.boundingSphere=a}function BU(n,e,t){let i=e.attributes,r=[];function s(a,o){return t.getDependency("accessor",a).then(function(l){n.setAttribute(o,l)})}for(let a in i){let o=QC[a]||a.toLowerCase();o in n.attributes||r.push(s(i[a],o))}if(e.indices!==void 0&&!n.index){let a=t.getDependency("accessor",e.indices).then(function(o){n.setIndex(o)});r.push(a)}return mi.workingColorSpace!==gs&&"COLOR_0"in i&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${mi.workingColorSpace}" not supported.`),bl(n,e),Lle(n,e,t),Promise.all(r).then(function(){return e.targets!==void 0?Mle(n,e.targets,t):n})}var $_,Ii,CC,PC,LC,DC,OC,NC,wC,FC,BC,UC,VC,GC,kC,zC,WC,HC,PA,XC,UU,Q_,NU,YC,KC,jC,ZC,LA,xle,qC,ja,Lm,wU,FU,MC,QC,Bf,Rle,yC,Ple,JC,VU=y(()=>{Es();PU();OU();$_=class extends bn{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new DC(t)}),this.register(function(t){return new OC(t)}),this.register(function(t){return new zC(t)}),this.register(function(t){return new WC(t)}),this.register(function(t){return new HC(t)}),this.register(function(t){return new wC(t)}),this.register(function(t){return new FC(t)}),this.register(function(t){return new BC(t)}),this.register(function(t){return new UC(t)}),this.register(function(t){return new LC(t)}),this.register(function(t){return new VC(t)}),this.register(function(t){return new NC(t)}),this.register(function(t){return new kC(t)}),this.register(function(t){return new GC(t)}),this.register(function(t){return new CC(t)}),this.register(function(t){return new PA(t,Ii.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new PA(t,Ii.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new XC(t)})}load(e,t,i,r){let s=this,a;if(this.resourcePath!=="")a=this.resourcePath;else if(this.path!==""){let c=yo.extractUrlBase(e);a=yo.resolveURL(c,this.path)}else a=yo.extractUrlBase(e);this.manager.itemStart(e);let o=function(c){r?r(c):console.error(c),s.manager.itemError(e),s.manager.itemEnd(e)},l=new Hs(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(c){try{s.parse(c,a,function(f){t(f),s.manager.itemEnd(e)},o)}catch(f){o(f)}},i,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,i,r){let s,a={},o={},l=new TextDecoder;if(typeof e=="string")s=JSON.parse(e);else if(e instanceof ArrayBuffer)if(l.decode(new Uint8Array(e,0,4))===UU){try{a[Ii.KHR_BINARY_GLTF]=new YC(e)}catch(d){r&&r(d);return}s=JSON.parse(a[Ii.KHR_BINARY_GLTF].content)}else s=JSON.parse(l.decode(e));else s=e;if(s.asset===void 0||s.asset.version[0]<2){r&&r(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let c=new JC(s,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let f=0;f<this.pluginCallbacks.length;f++){let d=this.pluginCallbacks[f](c);d.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),o[d.name]=d,a[d.name]=!0}if(s.extensionsUsed)for(let f=0;f<s.extensionsUsed.length;++f){let d=s.extensionsUsed[f],u=s.extensionsRequired||[];switch(d){case Ii.KHR_MATERIALS_UNLIT:a[d]=new PC;break;case Ii.KHR_DRACO_MESH_COMPRESSION:a[d]=new KC(s,this.dracoLoader);break;case Ii.KHR_TEXTURE_TRANSFORM:a[d]=new jC;break;case Ii.KHR_MESH_QUANTIZATION:a[d]=new ZC;break;default:u.indexOf(d)>=0&&o[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}c.setExtensions(a),c.setPlugins(o),c.parse(i,r)}parseAsync(e,t){let i=this;return new Promise(function(r,s){i.parse(e,t,r,s)})}};Ii={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"},CC=class{constructor(e){this.parser=e,this.name=Ii.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let i=0,r=t.length;i<r;i++){let s=t[i];s.extensions&&s.extensions[this.name]&&s.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,s.extensions[this.name].light)}}_loadLight(e){let t=this.parser,i="light:"+e,r=t.cache.get(i);if(r)return r;let s=t.json,l=((s.extensions&&s.extensions[this.name]||{}).lights||[])[e],c,f=new mt(16777215);l.color!==void 0&&f.setRGB(l.color[0],l.color[1],l.color[2],gs);let d=l.range!==void 0?l.range:0;switch(l.type){case"directional":c=new El(f),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new Mo(f),c.distance=d;break;case"spot":c=new _c(f),c.distance=d,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,c.angle=l.spot.outerConeAngle,c.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return c.position.set(0,0,0),bl(c,l),l.intensity!==void 0&&(c.intensity=l.intensity),c.name=t.createUniqueName(l.name||"light_"+e),r=Promise.resolve(c),t.cache.add(i,r),r}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){let t=this,i=this.parser,s=i.json.nodes[e],o=(s.extensions&&s.extensions[this.name]||{}).light;return o===void 0?null:this._loadLight(o).then(function(l){return i._getNodeRef(t.cache,o,l)})}},PC=class{constructor(){this.name=Ii.KHR_MATERIALS_UNLIT}getMaterialType(){return Kn}extendParams(e,t,i){let r=[];e.color=new mt(1,1,1),e.opacity=1;let s=t.pbrMetallicRoughness;if(s){if(Array.isArray(s.baseColorFactor)){let a=s.baseColorFactor;e.color.setRGB(a[0],a[1],a[2],gs),e.opacity=a[3]}s.baseColorTexture!==void 0&&r.push(i.assignTexture(e,"map",s.baseColorTexture,Fi))}return Promise.all(r)}},LC=class{constructor(e){this.parser=e,this.name=Ii.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let i=Xr(this.parser,e,this.name);return i===null||i.emissiveStrength!==void 0&&(t.emissiveIntensity=i.emissiveStrength),Promise.resolve()}},DC=class{constructor(e){this.parser=e,this.name=Ii.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return Xr(this.parser,e,this.name)!==null?zs:null}extendMaterialParams(e,t){let i=Xr(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];if(i.clearcoatFactor!==void 0&&(t.clearcoat=i.clearcoatFactor),i.clearcoatTexture!==void 0&&r.push(this.parser.assignTexture(t,"clearcoatMap",i.clearcoatTexture)),i.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=i.clearcoatRoughnessFactor),i.clearcoatRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",i.clearcoatRoughnessTexture)),i.clearcoatNormalTexture!==void 0&&(r.push(this.parser.assignTexture(t,"clearcoatNormalMap",i.clearcoatNormalTexture)),i.clearcoatNormalTexture.scale!==void 0)){let s=i.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new Ct(s,s)}return Promise.all(r)}},OC=class{constructor(e){this.parser=e,this.name=Ii.KHR_MATERIALS_DISPERSION}getMaterialType(e){return Xr(this.parser,e,this.name)!==null?zs:null}extendMaterialParams(e,t){let i=Xr(this.parser,e,this.name);return i===null||(t.dispersion=i.dispersion!==void 0?i.dispersion:0),Promise.resolve()}},NC=class{constructor(e){this.parser=e,this.name=Ii.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return Xr(this.parser,e,this.name)!==null?zs:null}extendMaterialParams(e,t){let i=Xr(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];return i.iridescenceFactor!==void 0&&(t.iridescence=i.iridescenceFactor),i.iridescenceTexture!==void 0&&r.push(this.parser.assignTexture(t,"iridescenceMap",i.iridescenceTexture)),i.iridescenceIor!==void 0&&(t.iridescenceIOR=i.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),i.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=i.iridescenceThicknessMinimum),i.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=i.iridescenceThicknessMaximum),i.iridescenceThicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,"iridescenceThicknessMap",i.iridescenceThicknessTexture)),Promise.all(r)}},wC=class{constructor(e){this.parser=e,this.name=Ii.KHR_MATERIALS_SHEEN}getMaterialType(e){return Xr(this.parser,e,this.name)!==null?zs:null}extendMaterialParams(e,t){let i=Xr(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];if(t.sheenColor=new mt(0,0,0),t.sheenRoughness=0,t.sheen=1,i.sheenColorFactor!==void 0){let s=i.sheenColorFactor;t.sheenColor.setRGB(s[0],s[1],s[2],gs)}return i.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=i.sheenRoughnessFactor),i.sheenColorTexture!==void 0&&r.push(this.parser.assignTexture(t,"sheenColorMap",i.sheenColorTexture,Fi)),i.sheenRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,"sheenRoughnessMap",i.sheenRoughnessTexture)),Promise.all(r)}},FC=class{constructor(e){this.parser=e,this.name=Ii.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return Xr(this.parser,e,this.name)!==null?zs:null}extendMaterialParams(e,t){let i=Xr(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];return i.transmissionFactor!==void 0&&(t.transmission=i.transmissionFactor),i.transmissionTexture!==void 0&&r.push(this.parser.assignTexture(t,"transmissionMap",i.transmissionTexture)),Promise.all(r)}},BC=class{constructor(e){this.parser=e,this.name=Ii.KHR_MATERIALS_VOLUME}getMaterialType(e){return Xr(this.parser,e,this.name)!==null?zs:null}extendMaterialParams(e,t){let i=Xr(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];t.thickness=i.thicknessFactor!==void 0?i.thicknessFactor:0,i.thicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,"thicknessMap",i.thicknessTexture)),t.attenuationDistance=i.attenuationDistance||1/0;let s=i.attenuationColor||[1,1,1];return t.attenuationColor=new mt().setRGB(s[0],s[1],s[2],gs),Promise.all(r)}},UC=class{constructor(e){this.parser=e,this.name=Ii.KHR_MATERIALS_IOR}getMaterialType(e){return Xr(this.parser,e,this.name)!==null?zs:null}extendMaterialParams(e,t){let i=Xr(this.parser,e,this.name);return i===null||(t.ior=i.ior!==void 0?i.ior:1.5,t.ior===0&&(t.ior=1e3)),Promise.resolve()}},VC=class{constructor(e){this.parser=e,this.name=Ii.KHR_MATERIALS_SPECULAR}getMaterialType(e){return Xr(this.parser,e,this.name)!==null?zs:null}extendMaterialParams(e,t){let i=Xr(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];t.specularIntensity=i.specularFactor!==void 0?i.specularFactor:1,i.specularTexture!==void 0&&r.push(this.parser.assignTexture(t,"specularIntensityMap",i.specularTexture));let s=i.specularColorFactor||[1,1,1];return t.specularColor=new mt().setRGB(s[0],s[1],s[2],gs),i.specularColorTexture!==void 0&&r.push(this.parser.assignTexture(t,"specularColorMap",i.specularColorTexture,Fi)),Promise.all(r)}},GC=class{constructor(e){this.parser=e,this.name=Ii.EXT_MATERIALS_BUMP}getMaterialType(e){return Xr(this.parser,e,this.name)!==null?zs:null}extendMaterialParams(e,t){let i=Xr(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];return t.bumpScale=i.bumpFactor!==void 0?i.bumpFactor:1,i.bumpTexture!==void 0&&r.push(this.parser.assignTexture(t,"bumpMap",i.bumpTexture)),Promise.all(r)}},kC=class{constructor(e){this.parser=e,this.name=Ii.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return Xr(this.parser,e,this.name)!==null?zs:null}extendMaterialParams(e,t){let i=Xr(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];return i.anisotropyStrength!==void 0&&(t.anisotropy=i.anisotropyStrength),i.anisotropyRotation!==void 0&&(t.anisotropyRotation=i.anisotropyRotation),i.anisotropyTexture!==void 0&&r.push(this.parser.assignTexture(t,"anisotropyMap",i.anisotropyTexture)),Promise.all(r)}},zC=class{constructor(e){this.parser=e,this.name=Ii.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,i=t.json,r=i.textures[e];if(!r.extensions||!r.extensions[this.name])return null;let s=r.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(i.extensionsRequired&&i.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,a)}},WC=class{constructor(e){this.parser=e,this.name=Ii.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,i=this.parser,r=i.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;let a=s.extensions[t],o=r.images[a.source],l=i.textureLoader;if(o.uri){let c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,a.source,l)}},HC=class{constructor(e){this.parser=e,this.name=Ii.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,i=this.parser,r=i.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;let a=s.extensions[t],o=r.images[a.source],l=i.textureLoader;if(o.uri){let c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,a.source,l)}},PA=class{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){let t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){let r=i.extensions[this.name],s=this.parser.getDependency("buffer",r.buffer),a=this.parser.options.meshoptDecoder;if(!a||!a.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return s.then(function(o){let l=r.byteOffset||0,c=r.byteLength||0,f=r.count,d=r.byteStride,u=new Uint8Array(o,l,c);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(f,d,u,r.mode,r.filter).then(function(h){return h.buffer}):a.ready.then(function(){let h=new ArrayBuffer(f*d);return a.decodeGltfBuffer(new Uint8Array(h),f,d,u,r.mode,r.filter),h})})}else return null}},XC=class{constructor(e){this.name=Ii.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;let r=t.meshes[i.mesh];for(let c of r.primitives)if(c.mode!==ja.TRIANGLES&&c.mode!==ja.TRIANGLE_STRIP&&c.mode!==ja.TRIANGLE_FAN&&c.mode!==void 0)return null;let a=i.extensions[this.name].attributes,o=[],l={};for(let c in a)o.push(this.parser.getDependency("accessor",a[c]).then(f=>(l[c]=f,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{let f=c.pop(),d=f.isGroup?f.children:[f],u=c[0].count,h=[];for(let m of d){let g=new pi,p=new ie,_=new un,v=new ie(1,1,1),E=new hu(m.geometry,m.material,u);for(let S=0;S<u;S++)l.TRANSLATION&&p.fromBufferAttribute(l.TRANSLATION,S),l.ROTATION&&_.fromBufferAttribute(l.ROTATION,S),l.SCALE&&v.fromBufferAttribute(l.SCALE,S),E.setMatrixAt(S,g.compose(p,_,v));for(let S in l)if(S==="_COLOR_0"){let T=l[S];E.instanceColor=new yf(T.array,T.itemSize,T.normalized)}else S!=="TRANSLATION"&&S!=="ROTATION"&&S!=="SCALE"&&m.geometry.setAttribute(S,l[S]);sr.prototype.copy.call(E,m),this.parser.assignFinalMaterial(E),h.push(E)}return f.isGroup?(f.clear(),f.add(...h),f):h[0]}))}},UU="glTF",Q_=12,NU={JSON:1313821514,BIN:5130562},YC=class{constructor(e){this.name=Ii.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,Q_),i=new TextDecoder;if(this.header={magic:i.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==UU)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");let r=this.header.length-Q_,s=new DataView(e,Q_),a=0;for(;a<r;){let o=s.getUint32(a,!0);a+=4;let l=s.getUint32(a,!0);if(a+=4,l===NU.JSON){let c=new Uint8Array(e,Q_+a,o);this.content=i.decode(c)}else if(l===NU.BIN){let c=Q_+a;this.body=e.slice(c,c+o)}a+=o}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}},KC=class{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Ii.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let i=this.json,r=this.dracoLoader,s=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},l={},c={};for(let f in a){let d=QC[f]||f.toLowerCase();o[d]=a[f]}for(let f in e.attributes){let d=QC[f]||f.toLowerCase();if(a[f]!==void 0){let u=i.accessors[e.attributes[f]],h=Lm[u.componentType];c[d]=h.name,l[d]=u.normalized===!0}}return t.getDependency("bufferView",s).then(function(f){return new Promise(function(d,u){r.decodeDracoFile(f,function(h){for(let m in h.attributes){let g=h.attributes[m],p=l[m];p!==void 0&&(g.normalized=p)}d(h)},o,c,gs,u)})})}},jC=class{constructor(){this.name=Ii.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}},ZC=class{constructor(){this.name=Ii.KHR_MESH_QUANTIZATION}},LA=class extends pl{constructor(e,t,i,r){super(e,t,i,r)}copySampleValue_(e){let t=this.resultBuffer,i=this.sampleValues,r=this.valueSize,s=e*r*3+r;for(let a=0;a!==r;a++)t[a]=i[s+a];return t}interpolate_(e,t,i,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=o*2,c=o*3,f=r-t,d=(i-t)/f,u=d*d,h=u*d,m=e*c,g=m-c,p=-2*h+3*u,_=h-u,v=1-p,E=_-u+d;for(let S=0;S!==o;S++){let T=a[g+S+o],A=a[g+S+l]*f,R=a[m+S+o],M=a[m+S]*f;s[S]=v*T+E*A+p*R+_*M}return s}},xle=new un,qC=class extends LA{interpolate_(e,t,i,r){let s=super.interpolate_(e,t,i,r);return xle.fromArray(s).normalize().toArray(s),s}},ja={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},Lm={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},wU={9728:kr,9729:zr,9984:IT,9985:Tm,9986:Su,9987:Io},FU={33071:Xa,33648:rm,10497:ul},MC={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},QC={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Bf={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Rle={CUBICSPLINE:void 0,LINEAR:cu,STEP:lu},yC={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};Ple=new pi,JC=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new Ale,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,r=-1,s=!1,a=-1;if(typeof navigator!="undefined"&&typeof navigator.userAgent!="undefined"){let o=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(o)===!0;let l=o.match(/Version\/(\d+)/);r=i&&l?parseInt(l[1],10):-1,s=o.indexOf("Firefox")>-1,a=s?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap=="undefined"||i&&r<17||s&&a<98?this.textureLoader=new vu(this.options.manager):this.textureLoader=new O_(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Hs(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let i=this,r=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(a){let o={scene:a[0][r.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:r.asset,parser:i,userData:{}};return xu(s,o,r),bl(o,r),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(let l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let r=0,s=t.length;r<s;r++){let a=t[r].joints;for(let o=0,l=a.length;o<l;o++)e[a[o]].isBone=!0}for(let r=0,s=e.length;r<s;r++){let a=e[r];a.mesh!==void 0&&(this._addNodeRef(this.meshCache,a.mesh),a.skin!==void 0&&(i[a.mesh].isSkinnedMesh=!0)),a.camera!==void 0&&this._addNodeRef(this.cameraCache,a.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,i){if(e.refs[t]<=1)return i;let r=i.clone(),s=(a,o)=>{let l=this.associations.get(a);l!=null&&this.associations.set(o,l);for(let[c,f]of a.children.entries())s(f,o.children[c])};return s(i,r),r.name+="_instance_"+e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let i=0;i<t.length;i++){let r=e(t[i]);if(r)return r}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let i=[];for(let r=0;r<t.length;r++){let s=e(t[r]);s&&i.push(s)}return i}getDependency(e,t){let i=e+":"+t,r=this.cache.get(i);if(!r){switch(e){case"scene":r=this.loadScene(t);break;case"node":r=this._invokeOne(function(s){return s.loadNode&&s.loadNode(t)});break;case"mesh":r=this._invokeOne(function(s){return s.loadMesh&&s.loadMesh(t)});break;case"accessor":r=this.loadAccessor(t);break;case"bufferView":r=this._invokeOne(function(s){return s.loadBufferView&&s.loadBufferView(t)});break;case"buffer":r=this.loadBuffer(t);break;case"material":r=this._invokeOne(function(s){return s.loadMaterial&&s.loadMaterial(t)});break;case"texture":r=this._invokeOne(function(s){return s.loadTexture&&s.loadTexture(t)});break;case"skin":r=this.loadSkin(t);break;case"animation":r=this._invokeOne(function(s){return s.loadAnimation&&s.loadAnimation(t)});break;case"camera":r=this.loadCamera(t);break;default:if(r=this._invokeOne(function(s){return s!=this&&s.getDependency&&s.getDependency(e,t)}),!r)throw new Error("Unknown type: "+e);break}this.cache.add(i,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){let i=this,r=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(r.map(function(s,a){return i.getDependency(e,a)})),this.cache.add(e,t)}return t}loadBuffer(e){let t=this.json.buffers[e],i=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[Ii.KHR_BINARY_GLTF].body);let r=this.options;return new Promise(function(s,a){i.load(yo.resolveURL(t.uri,r.path),s,void 0,function(){a(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(i){let r=t.byteLength||0,s=t.byteOffset||0;return i.slice(s,s+r)})}loadAccessor(e){let t=this,i=this.json,r=this.json.accessors[e];if(r.bufferView===void 0&&r.sparse===void 0){let a=MC[r.type],o=Lm[r.componentType],l=r.normalized===!0,c=new o(r.count*a);return Promise.resolve(new Tr(c,a,l))}let s=[];return r.bufferView!==void 0?s.push(this.getDependency("bufferView",r.bufferView)):s.push(null),r.sparse!==void 0&&(s.push(this.getDependency("bufferView",r.sparse.indices.bufferView)),s.push(this.getDependency("bufferView",r.sparse.values.bufferView))),Promise.all(s).then(function(a){let o=a[0],l=MC[r.type],c=Lm[r.componentType],f=c.BYTES_PER_ELEMENT,d=f*l,u=r.byteOffset||0,h=r.bufferView!==void 0?i.bufferViews[r.bufferView].byteStride:void 0,m=r.normalized===!0,g,p;if(h&&h!==d){let _=Math.floor(u/h),v="InterleavedBuffer:"+r.bufferView+":"+r.componentType+":"+_+":"+r.count,E=t.cache.get(v);E||(g=new c(o,_*h,r.count*h/f),E=new uu(g,h/f),t.cache.add(v,E)),p=new Mf(E,l,u%h/f,m)}else o===null?g=new c(r.count*l):g=new c(o,u,r.count*l),p=new Tr(g,l,m);if(r.sparse!==void 0){let _=MC.SCALAR,v=Lm[r.sparse.indices.componentType],E=r.sparse.indices.byteOffset||0,S=r.sparse.values.byteOffset||0,T=new v(a[1],E,r.sparse.count*_),A=new c(a[2],S,r.sparse.count*l);o!==null&&(p=new Tr(p.array.slice(),p.itemSize,p.normalized)),p.normalized=!1;for(let R=0,M=T.length;R<M;R++){let I=T[R];if(p.setX(I,A[R*l]),l>=2&&p.setY(I,A[R*l+1]),l>=3&&p.setZ(I,A[R*l+2]),l>=4&&p.setW(I,A[R*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}p.normalized=m}return p})}loadTexture(e){let t=this.json,i=this.options,s=t.textures[e].source,a=t.images[s],o=this.textureLoader;if(a.uri){let l=i.manager.getHandler(a.uri);l!==null&&(o=l)}return this.loadTextureImage(e,s,o)}loadTextureImage(e,t,i){let r=this,s=this.json,a=s.textures[e],o=s.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];let c=this.loadImageSource(t,i).then(function(f){f.flipY=!1,f.name=a.name||o.name||"",f.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(f.name=o.uri);let u=(s.samplers||{})[a.sampler]||{};return f.magFilter=wU[u.magFilter]||zr,f.minFilter=wU[u.minFilter]||Io,f.wrapS=FU[u.wrapS]||ul,f.wrapT=FU[u.wrapT]||ul,f.generateMipmaps=!f.isCompressedTexture&&f.minFilter!==kr&&f.minFilter!==zr,r.associations.set(f,{textures:e}),f}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){let i=this,r=this.json,s=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());let a=r.images[e],o=self.URL||self.webkitURL,l=a.uri||"",c=!1;if(a.bufferView!==void 0)l=i.getDependency("bufferView",a.bufferView).then(function(d){c=!0;let u=new Blob([d],{type:a.mimeType});return l=o.createObjectURL(u),l});else if(a.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let f=Promise.resolve(l).then(function(d){return new Promise(function(u,h){let m=u;t.isImageBitmapLoader===!0&&(m=function(g){let p=new Lr(g);p.needsUpdate=!0,u(p)}),t.load(yo.resolveURL(d,s.path),m,void 0,h)})}).then(function(d){return c===!0&&o.revokeObjectURL(l),bl(d,a),d.userData.mimeType=a.mimeType||Cle(a.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=f,f}assignTexture(e,t,i,r){let s=this;return this.getDependency("texture",i.index).then(function(a){if(!a)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(a=a.clone(),a.channel=i.texCoord),s.extensions[Ii.KHR_TEXTURE_TRANSFORM]){let o=i.extensions!==void 0?i.extensions[Ii.KHR_TEXTURE_TRANSFORM]:void 0;if(o){let l=s.associations.get(a);a=s.extensions[Ii.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),s.associations.set(a,l)}}return r!==void 0&&(a.colorSpace=r),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,i=e.material,r=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let o="PointsMaterial:"+i.uuid,l=this.cache.get(o);l||(l=new Gs,Hr.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,l.sizeAttenuation=!1,this.cache.add(o,l)),i=l}else if(e.isLine){let o="LineBasicMaterial:"+i.uuid,l=this.cache.get(o);l||(l=new Ln,Hr.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(o,l)),i=l}if(r||s||a){let o="ClonedMaterial:"+i.uuid+":";r&&(o+="derivative-tangents:"),s&&(o+="vertex-colors:"),a&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=i.clone(),s&&(l.vertexColors=!0),a&&(l.flatShading=!0),r&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(i))),i=l}e.material=i}getMaterialType(){return Dn}loadMaterial(e){let t=this,i=this.json,r=this.extensions,s=i.materials[e],a,o={},l=s.extensions||{},c=[];if(l[Ii.KHR_MATERIALS_UNLIT]){let d=r[Ii.KHR_MATERIALS_UNLIT];a=d.getMaterialType(),c.push(d.extendParams(o,s,t))}else{let d=s.pbrMetallicRoughness||{};if(o.color=new mt(1,1,1),o.opacity=1,Array.isArray(d.baseColorFactor)){let u=d.baseColorFactor;o.color.setRGB(u[0],u[1],u[2],gs),o.opacity=u[3]}d.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",d.baseColorTexture,Fi)),o.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,o.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",d.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",d.metallicRoughnessTexture))),a=this._invokeOne(function(u){return u.getMaterialType&&u.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(u){return u.extendMaterialParams&&u.extendMaterialParams(e,o)})))}s.doubleSided===!0&&(o.side=Xs);let f=s.alphaMode||yC.OPAQUE;if(f===yC.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,f===yC.MASK&&(o.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&a!==Kn&&(c.push(t.assignTexture(o,"normalMap",s.normalTexture)),o.normalScale=new Ct(1,1),s.normalTexture.scale!==void 0)){let d=s.normalTexture.scale;o.normalScale.set(d,d)}if(s.occlusionTexture!==void 0&&a!==Kn&&(c.push(t.assignTexture(o,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&a!==Kn){let d=s.emissiveFactor;o.emissive=new mt().setRGB(d[0],d[1],d[2],gs)}return s.emissiveTexture!==void 0&&a!==Kn&&c.push(t.assignTexture(o,"emissiveMap",s.emissiveTexture,Fi)),Promise.all(c).then(function(){let d=new a(o);return s.name&&(d.name=s.name),bl(d,s),t.associations.set(d,{materials:e}),s.extensions&&xu(r,d,s),d})}createUniqueName(e){let t=fr.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,i=this.extensions,r=this.primitiveCache;function s(o){return i[Ii.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return BU(l,o,t)})}let a=[];for(let o=0,l=e.length;o<l;o++){let c=e[o],f=Ile(c),d=r[f];if(d)a.push(d.promise);else{let u;c.extensions&&c.extensions[Ii.KHR_DRACO_MESH_COMPRESSION]?u=s(c):u=BU(new Bi,c,t),r[f]={primitive:c,promise:u},a.push(u)}}return Promise.all(a)}loadMesh(e){let t=this,i=this.json,r=this.extensions,s=i.meshes[e],a=s.primitives,o=[];for(let l=0,c=a.length;l<c;l++){let f=a[l].material===void 0?ble(this.cache):this.getDependency("material",a[l].material);o.push(f)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(l){let c=l.slice(0,l.length-1),f=l[l.length-1],d=[];for(let h=0,m=f.length;h<m;h++){let g=f[h],p=a[h],_,v=c[h];if(p.mode===ja.TRIANGLES||p.mode===ja.TRIANGLE_STRIP||p.mode===ja.TRIANGLE_FAN||p.mode===void 0)_=s.isSkinnedMesh===!0?new T_(g,v):new ci(g,v),_.isSkinnedMesh===!0&&_.normalizeSkinWeights(),p.mode===ja.TRIANGLE_STRIP?_.geometry=bC(_.geometry,Y_):p.mode===ja.TRIANGLE_FAN&&(_.geometry=bC(_.geometry,Rm));else if(p.mode===ja.LINES)_=new _s(g,v);else if(p.mode===ja.LINE_STRIP)_=new mu(g,v);else if(p.mode===ja.LINE_LOOP)_=new x_(g,v);else if(p.mode===ja.POINTS)_=new ks(g,v);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+p.mode);Object.keys(_.geometry.morphAttributes).length>0&&yle(_,s),_.name=t.createUniqueName(s.name||"mesh_"+e),bl(_,s),p.extensions&&xu(r,_,p),t.assignFinalMaterial(_),d.push(_)}for(let h=0,m=d.length;h<m;h++)t.associations.set(d[h],{meshes:e,primitives:h});if(d.length===1)return s.extensions&&xu(r,d[0],s),d[0];let u=new _a;s.extensions&&xu(r,u,s),t.associations.set(u,{meshes:e});for(let h=0,m=d.length;h<m;h++)u.add(d[h]);return u})}loadCamera(e){let t,i=this.json.cameras[e],r=i[i.type];if(!r){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return i.type==="perspective"?t=new Sr(K_.radToDeg(r.yfov),r.aspectRatio||1,r.znear||1,r.zfar||2e6):i.type==="orthographic"&&(t=new vs(-r.xmag,r.xmag,r.ymag,-r.ymag,r.znear,r.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),bl(t,i),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],i=[];for(let r=0,s=t.joints.length;r<s;r++)i.push(this._loadNodeShallow(t.joints[r]));return t.inverseBindMatrices!==void 0?i.push(this.getDependency("accessor",t.inverseBindMatrices)):i.push(null),Promise.all(i).then(function(r){let s=r.pop(),a=r,o=[],l=[];for(let c=0,f=a.length;c<f;c++){let d=a[c];if(d){o.push(d);let u=new pi;s!==null&&u.fromArray(s.array,c*16),l.push(u)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new A_(o,l)})}loadAnimation(e){let t=this.json,i=this,r=t.animations[e],s=r.name?r.name:"animation_"+e,a=[],o=[],l=[],c=[],f=[];for(let d=0,u=r.channels.length;d<u;d++){let h=r.channels[d],m=r.samplers[h.sampler],g=h.target,p=g.node,_=r.parameters!==void 0?r.parameters[m.input]:m.input,v=r.parameters!==void 0?r.parameters[m.output]:m.output;g.node!==void 0&&(a.push(this.getDependency("node",p)),o.push(this.getDependency("accessor",_)),l.push(this.getDependency("accessor",v)),c.push(m),f.push(g))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(f)]).then(function(d){let u=d[0],h=d[1],m=d[2],g=d[3],p=d[4],_=[];for(let E=0,S=u.length;E<S;E++){let T=u[E],A=h[E],R=m[E],M=g[E],I=p[E];if(T===void 0)continue;T.updateMatrix&&T.updateMatrix();let C=i._createAnimationTracks(T,A,R,M,I);if(C)for(let L=0;L<C.length;L++)_.push(C[L])}let v=new _u(s,void 0,_);return bl(v,r),v})}createNodeMesh(e){let t=this.json,i=this,r=t.nodes[e];return r.mesh===void 0?null:i.getDependency("mesh",r.mesh).then(function(s){let a=i._getNodeRef(i.meshCache,r.mesh,s);return r.weights!==void 0&&a.traverse(function(o){if(o.isMesh)for(let l=0,c=r.weights.length;l<c;l++)o.morphTargetInfluences[l]=r.weights[l]}),a})}loadNode(e){let t=this.json,i=this,r=t.nodes[e],s=i._loadNodeShallow(e),a=[],o=r.children||[];for(let c=0,f=o.length;c<f;c++)a.push(i.getDependency("node",o[c]));let l=r.skin===void 0?Promise.resolve(null):i.getDependency("skin",r.skin);return Promise.all([s,Promise.all(a),l]).then(function(c){let f=c[0],d=c[1],u=c[2];u!==null&&f.traverse(function(h){h.isSkinnedMesh&&h.bind(u,Ple)});for(let h=0,m=d.length;h<m;h++)f.add(d[h]);if(f.userData.pivot!==void 0&&d.length>0){let h=f.userData.pivot,m=d[0];f.pivot=new ie().fromArray(h),f.position.x-=h[0],f.position.y-=h[1],f.position.z-=h[2],m.position.set(0,0,0),delete f.userData.pivot}return f})}_loadNodeShallow(e){let t=this.json,i=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let s=t.nodes[e],a=s.name?r.createUniqueName(s.name):"",o=[],l=r._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&o.push(l),s.camera!==void 0&&o.push(r.getDependency("camera",s.camera).then(function(c){return r._getNodeRef(r.cameraCache,s.camera,c)})),r._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(e)}).forEach(function(c){o.push(c)}),this.nodeCache[e]=Promise.all(o).then(function(c){let f;if(s.isBone===!0?f=new dm:c.length>1?f=new _a:c.length===1?f=c[0]:f=new sr,f!==c[0])for(let d=0,u=c.length;d<u;d++)f.add(c[d]);if(s.name&&(f.userData.name=s.name,f.name=a),bl(f,s),s.extensions&&xu(i,f,s),s.matrix!==void 0){let d=new pi;d.fromArray(s.matrix),f.applyMatrix4(d)}else s.translation!==void 0&&f.position.fromArray(s.translation),s.rotation!==void 0&&f.quaternion.fromArray(s.rotation),s.scale!==void 0&&f.scale.fromArray(s.scale);if(!r.associations.has(f))r.associations.set(f,{});else if(s.mesh!==void 0&&r.meshCache.refs[s.mesh]>1){let d=r.associations.get(f);r.associations.set(f,{...d})}return r.associations.get(f).nodes=e,f}),this.nodeCache[e]}loadScene(e){let t=this.extensions,i=this.json.scenes[e],r=this,s=new _a;i.name&&(s.name=r.createUniqueName(i.name)),bl(s,i),i.extensions&&xu(t,s,i);let a=i.nodes||[],o=[];for(let l=0,c=a.length;l<c;l++)o.push(r.getDependency("node",a[l]));return Promise.all(o).then(function(l){for(let f=0,d=l.length;f<d;f++){let u=l[f];u.parent!==null?s.add(LU(u)):s.add(u)}let c=f=>{let d=new Map;for(let[u,h]of r.associations)(u instanceof Hr||u instanceof Lr)&&d.set(u,h);return f.traverse(u=>{let h=r.associations.get(u);h!=null&&d.set(u,h)}),d};return r.associations=c(s),s})}_createAnimationTracks(e,t,i,r,s){let a=[],o=e.name?e.name:e.uuid,l=[];function c(h){h.morphTargetInfluences&&l.push(h.name?h.name:h.uuid)}Bf[s.path]===Bf.weights?(c(e),e.isGroup&&e.children.forEach(c)):l.push(o);let f;switch(Bf[s.path]){case Bf.weights:f=gl;break;case Bf.rotation:f=_l;break;case Bf.translation:case Bf.scale:f=vl;break;default:i.itemSize===1?f=gl:f=vl;break}let d=r.interpolation!==void 0?Rle[r.interpolation]:cu,u=this._getArrayFromAccessor(i);for(let h=0,m=l.length;h<m;h++){let g=new f(l[h]+"."+Bf[s.path],t.array,u,d);r.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(g),a.push(g)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let i=$C(t.constructor),r=new Float32Array(t.length);for(let s=0,a=t.length;s<a;s++)r[s]=t[s]*i;t=r}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(i){let r=this instanceof _l?qC:LA;return new r(this.times,this.values,this.getValueSize()/3,i)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}});var OA={};Be(OA,{F_OK:()=>Ts,X_OK:()=>nP,access:()=>Ss,execFile:()=>ba,getRuntimeProcess:()=>Dm,mkdir:()=>Zn,osTmpdir:()=>yu,pathBasename:()=>Qn,pathDelimiter:()=>sP,pathDirname:()=>qn,pathExtname:()=>$n,pathIsAbsolute:()=>Ra,pathJoin:()=>tr,pathNormalize:()=>wle,readFile:()=>xa,rm:()=>bu,stat:()=>Mu,writeFile:()=>Ru});function kU(){return typeof activeWindow=="undefined"?void 0:activeWindow}function Dle(){let n=kU();if(!(!n||!("require"in n)))return n.require}function Dm(){let n=kU();if(!(!n||!("process"in n)))return n.process}function DA(n){let e=Dle();if(!e)return null;try{return e(n)}catch(t){return null}}function Om(){return eP===void 0&&(eP=DA("node:fs/promises")),eP}function Nm(){return tP===void 0&&(tP=DA("node:path")),tP}function Ole(){return iP===void 0&&(iP=DA("node:child_process")),iP}function Nle(){return rP===void 0&&(rP=DA("node:os")),rP}function qs(n,e){if(n===null)throw new Error(`${e} is not available in this environment (mobile or web).`);return n}function Ss(n,e){return qs(Om(),"node:fs/promises").access(n,e)}function xa(n,e){return qs(Om(),"node:fs/promises").readFile(n,e)}function Ru(n,e,t){return qs(Om(),"node:fs/promises").writeFile(n,e,{encoding:t})}function Zn(n,e){return qs(Om(),"node:fs/promises").mkdir(n,e)}function bu(n,e){return qs(Om(),"node:fs/promises").rm(n,e)}function Mu(n){return qs(Om(),"node:fs/promises").stat(n)}function tr(...n){return qs(Nm(),"node:path").join(...n)}function qn(n){return qs(Nm(),"node:path").dirname(n)}function Qn(n,e){return qs(Nm(),"node:path").basename(n,e)}function $n(n){return qs(Nm(),"node:path").extname(n)}function wle(n){return qs(Nm(),"node:path").normalize(n)}function Ra(n){return qs(Nm(),"node:path").isAbsolute(n)}function ba(n,e,t,i){qs(Ole(),"node:child_process").execFile(n,e,t,i)}function yu(){return qs(Nle(),"node:os").tmpdir()}var eP,tP,iP,rP,Ts,nP,GU,sP,hr=y(()=>{"use strict";Ts=0,nP=1;sP=((GU=Dm())==null?void 0:GU.platform)==="win32"?";":":"});function zU(n){return n.startsWith("/")||n.startsWith("\\")||/^[A-Za-z]:[\\/]/.test(n)}function Fle(n,e){let t=n.includes("\\")?"\\":"/",i=n.replace(/[\\/]+$/,""),r=e.replace(/^[\\/]+/,"").replace(/[\\/]/g,t);return`${i}${t}${r}`}function aP(n){return n.replace(/\\/g,"/")}function wA(n){let e=aP(n),t=[];for(let i of e.split("/"))if(!(!i||i===".")){if(i===".."){t.pop();continue}t.push(i)}return t.join("/")}function WU(n){try{return decodeURIComponent(n)}catch(e){return n}}function Nn(n,e){var i;let t=WU((i=e.split(/[?#]/,1)[0])!=null?i:e);return wA(n?`${n}/${t}`:t)}function HU(n,e){return Nn(n.vault.configDir,e)}function J_(n){let e=aP(n).replace(/\/+$/,""),t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Qs(n){let e=aP(n).replace(/\/+$/,""),t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function gn(n){return Qs(n).replace(/\.[^.]+$/,"")}async function Ble(n,e){let t=wA(e);if(!t)return null;let i=t.split("/"),r="",s=n.vault.getRoot().children;for(let a of i){let o=s.find(c=>c.name===a),l=o!=null?o:s.find(c=>c.name.toLowerCase()===a.toLowerCase());if(!l)return null;if(r=r?`${r}/${l.name}`:l.name,l instanceof wm.TFile)return r;if(!(l instanceof wm.TFolder))return null;s=l.children}return null}function Ule(n){let e=n.buffer;if(e instanceof ArrayBuffer&&n.byteOffset===0&&n.byteLength===e.byteLength)return e;let t=new Uint8Array(n.byteLength);return t.set(n),t.buffer}function Vle(){let n=new Error("File read aborted");return n.name="AbortError",n}function NA(n){if(n!=null&&n.aborted)throw n.reason instanceof Error?n.reason:Vle()}function Gle(n){let e=n.vault.adapter;return e?typeof e.getBasePath=="function"?e.getBasePath():typeof e.basePath=="string"&&e.basePath.length>0?e.basePath:null:null}function Uf(n,e){var r,s;let t=n.vault.getAbstractFileByPath(e);if(t)return t.path;let i=(s=(r=n.metadataCache)==null?void 0:r.getFirstLinkpathDest)==null?void 0:s.call(r,e,"");return i?i.path:null}function Ec(n,e){if(zU(e))return e;let t=Gle(n);return t?Fle(t,e):null}async function Po(n,e,t={}){if(NA(t.signal),zU(e)){let a=await xa(e,t.signal?{signal:t.signal}:void 0);return NA(t.signal),Ule(a)}let i=wA(WU(e)),r=n.vault.getAbstractFileByPath(i);if(!(r instanceof wm.TFile)){let a=await Ble(n,i);if(a){let o=n.vault.getAbstractFileByPath(a);if(o instanceof wm.TFile){let l=await n.vault.readBinary(o);return NA(t.signal),l}}throw new Error(`File not found: ${i}`)}let s=await n.vault.readBinary(r);return NA(t.signal),s}var wm,As=y(()=>{"use strict";wm=require("obsidian");hr()});function Iu(n){let e=new Uint8Array(n),t=32768,i=[];for(let r=0;r<e.length;r+=t)i.push(String.fromCharCode.apply(null,e.subarray(r,r+t)));return btoa(i.join(""))}var FA=y(()=>{"use strict"});function zle(n){return kle.has(n)}function XU(n,e){let t=Number.isFinite(n)&&n>0?Math.floor(n):1;return e==="low"?1:e==="medium"?Math.min(t,4):t}function BA(n,e){let t=n,i={textureCount:0,colorTextureCount:0,srgbColorTextureCount:0};for(let[r,s]of Object.entries(t))s instanceof Lr&&(i.textureCount++,s.anisotropy=Math.max(s.anisotropy,e),zle(r)&&(i.colorTextureCount++,s.colorSpace=Fi,i.srgbColorTextureCount++),s.needsUpdate=!0);return n.needsUpdate=!0,i}function oP(n){n.boundingBox||n.computeBoundingBox();let e=n.boundingBox;if(!e)return .02;let t=e.getSize(new ie),i=Math.max(t.x,t.y,t.z);return!Number.isFinite(i)||i<=0?.02:Math.min(Math.max(i/180,5e-4),.05)}var kle,lP=y(()=>{"use strict";Es();kle=new Set(["map","emissiveMap","specularMap","specularColorMap","sheenColorMap","clearcoatColorMap"])});function Wle(n){var e,t;return n?((e=n.signal)==null?void 0:e.aborted)===!0||((t=n.isCurrent)==null?void 0:t.call(n))===!1:!1}function xi(n){if(Wle(n))throw new UA}function Vf(n){return n instanceof UA||n instanceof Error&&n.name==="AbortError"}var UA,ev=y(()=>{"use strict";UA=class extends Error{constructor(e="Preview load interrupted"){super(e),this.name="PreviewLoadInterruptedError"}}});function KU(n){var t,i,r;let e=(i=(t=n.split(".").pop())==null?void 0:t.toLowerCase())!=null?i:"png";return(r=Hle[e])!=null?r:`image/${e}`}function Kle(n){var e;return(e=n.split(/[?#]/,1)[0])!=null?e:n}function cP(n){return Nn("",n)}function VA(n,e,t){e&&n.set(cP(e),t)}function jle(n,e,t,i,r){let s=Kle(t);VA(n,s,r),VA(n,Nn("",s),r),VA(n,i,r),e&&VA(n,`${e}/${s}`,r)}function Zle(n){var i,r;let e=new Map,t=(s,a)=>{var c;if(!s||s.startsWith("data:"))return;let o=cP(s);if(!o)return;let l=e.get(o);if(l){l.aliases.push(s),(c=l.mimeType)!=null||(l.mimeType=a);return}e.set(o,{uri:s,mimeType:a,aliases:[s]})};for(let s of(i=n.buffers)!=null?i:[])t(s.uri,"application/octet-stream");for(let s of(r=n.images)!=null?r:[])t(s.uri);return[...e.values()]}async function qle(n,e,t,i){let r=0,s=Math.max(1,Math.min(e,n.length));await Promise.all(Array.from({length:s},async()=>{for(;r<n.length;){xi(i);let a=n[r++];await t(a),xi(i)}}))}async function Qle(n,e,t,i){let r=new Map,s=[],a=new pm,o=async l=>{var d;xi(i);let c=await ece(n,e,l.uri);xi(i);let f=URL.createObjectURL(new Blob([c.data],{type:(d=l.mimeType)!=null?d:KU(c.path)}));s.push(f);for(let u of l.aliases)jle(r,e,u,c.path,f)};try{await qle(Zle(t),Yle,o,i)}catch(l){for(let c of s)URL.revokeObjectURL(c);throw l}return a.setURLModifier(l=>{var f,d;let c=cP(l);return(d=(f=r.get(c))!=null?f:r.get(Nn("",c)))!=null?d:l}),{manager:a,dispose:()=>{for(let l of s)URL.revokeObjectURL(l)}}}function $le(n){let e=n.replace(/\s+#.*$/,"").trim();if(e.startsWith('"')){let t=e.indexOf('"',1);if(t>1)return e.slice(1,t)}return e}function Jle(n){let e=n.trim().split(/\s+/),t=e.findIndex(i=>!i.startsWith("-")&&!/^[-+]?\d*\.?\d+$/.test(i));return e.slice(Math.max(0,t)).join(" ").replace(/^"|"$/g,"")}async function ece(n,e,t){let i=Nn(e,t);try{return{data:await n(i),path:i}}catch(r){throw new Error(`Missing external model resource: ${i}`)}}function tce(n,e,t){let i=Qs(e),r=i.replace(/\.[^.]+$/,""),s=gn(t),a=[Nn(n,e),Nn(n,i)];if(s)for(let o of YU)a.push(Nn(n,`${s}.${o}`));for(let o of YU){let l=`${r}.${o}`;l!==i&&a.push(Nn(n,l))}return a}async function jU(n,e,t,i,r){var c,f;let s=[];if(xi(r),e==="gltf"&&t&&i){let d=new TextDecoder().decode(new Uint8Array(n)),u=JSON.parse(d),h=J_(i),m=await Qle(t,h,u,r);xi(r);let g=new $_(m.manager);try{xi(r);let p=await g.parseAsync(n,h?`${h}/`:""),_=p.scene||((c=p.scenes)==null?void 0:c[0]);if(!_)throw new Error("GLTF did not contain a scene");return{scene:_,animations:p.animations,warnings:s}}finally{m.dispose()}}xi(r);let o=await new $_().parseAsync(n,""),l=o.scene||((f=o.scenes)==null?void 0:f[0]);if(!l)throw new Error("GLB did not contain a scene");return{scene:l,animations:o.animations,warnings:s}}async function ZU(n){let t=new CA().parse(n),i=t.hasAttribute("color")?new Dn({color:16777215,vertexColors:!0}):new Dn({color:13421772}),r=new ci(t,i);return r.name=Qs("")||"stl-model",r}async function qU(n){let t=new IA().parse(n),i=!!t.index||t.hasAttribute("normal");if(t.hasAttribute("color")){if(i){t.hasAttribute("normal")||t.computeVertexNormals();let a=new Dn({vertexColors:!0});return new ci(t,a)}let s=new Gs({size:oP(t),vertexColors:!0});return new ks(t,s)}if(i){t.hasAttribute("normal")||t.computeVertexNormals();let s=new Dn({color:13421772});return new ci(t,s)}let r=new Gs({size:oP(t),color:13421772});return new ks(t,r)}function ice(n){return n?Array.isArray(n)?n:[n]:[]}function rce(n){n.traverse(e=>{if(!(e instanceof ci))return;let t=e;for(let i of ice(t.material))BA(i,1)})}async function QU(n,e,t){let i=new TextDecoder().decode(new Uint8Array(n)),r=[],s=null,a=i.match(/mtllib\s+(.+)/);if(a&&e&&t){let c=$le(a[1]),f=J_(t),d=Nn(f,c);try{let u=await e(d),m=new TextDecoder().decode(new Uint8Array(u)).split(`
`),g=new Map;for(let S=0;S<m.length;S++){let T=m[S].match(Xle);if(!T)continue;let A=Jle(T[2]),R=tce(f,A,t),M=!1;for(let I of R){if(g.has(I)){m[S]=`${T[1]} ${g.get(I)}`,M=!0;break}try{let C=await e(I),L=`data:${KU(I)};base64,${Iu(C)}`;g.set(I,L),m[S]=`${T[1]} ${L}`,M=!0;break}catch(C){}}M||(r.push(`OBJ material texture not found: ${A}`),m[S]="")}let p=m.filter(S=>S!=="");if(!p.some(S=>/^\s*Kd\s+/i.test(S))){let S=p.findIndex(T=>/^\s*newmtl\s+/i.test(T));p.splice(S>=0?S+1:0,0,"Kd 0.80 0.80 0.80")}let E=new bA().parse(p.join(`
`),f?`${f}/`:"");E.preload(),s=E}catch(u){r.push(`OBJ material library not found: ${d}`)}}else a&&(!e||!t)&&r.push("OBJ material library could not be resolved without a model path.");let o=new yA;s&&o.setMaterials(s);let l=o.parse(i);return rce(l),{object:l,warnings:r}}var Hle,YU,Xle,Yle,$U=y(()=>{"use strict";AU();yU();IU();CU();VU();Es();As();FA();lP();ev();Hle={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",tga:"image/x-tga",webp:"image/webp",tif:"image/tiff",tiff:"image/tiff"},YU=["jpg","jpeg","png","bmp","tga","webp","tif","tiff"],Xle=/^\s*(map_Kd|map_Ka|map_Ks|map_Ns|map_d|map_bump|bump|disp|decal)\s+(.+)/i,Yle=4});function Rr(){return JU.Platform.isMobile}var JU,Ma=y(()=>{"use strict";JU=require("obsidian")});function sce(){return typeof activeDocument=="undefined"?window.document:activeDocument}function eV(n){return sce().createElementNS(nce,n)}function Ml(n){let e=eV("div");return n&&(e.className=n),e}function Cu(n,e){let t=eV(n);return e&&(t.className=e),t}var nce,Fm=y(()=>{"use strict";nce="http://www.w3.org/1999/xhtml"});function ct(n){return{x:n.x,y:n.y,z:n.z}}function _n(n){return{x:n.x,y:n.y,z:n.z}}function Bm(n,e){return{x:n.x-e.x,y:n.y-e.y,z:n.z-e.z}}function en(n,e){return{x:n.x*e,y:n.y*e,z:n.z*e}}function iV(n,e){let t=Bm(n,e);return Math.hypot(t.x,t.y,t.z)}function wn(n){let e=Math.hypot(n.x,n.y,n.z);return e<=Number.EPSILON?null:en(n,1/e)}function tn(n,e){return{x:n.x+e.x,y:n.y+e.y,z:n.z+e.z}}function $s(n,e){return n.x*e.x+n.y*e.y+n.z*e.z}function rV(n,e,t){return{x:e==="x"?n.x+t:n.x,y:e==="y"?n.y+t:n.y,z:e==="z"?n.z+t:n.z}}function nV(n){return Math.max(n*.01,.01)}function Gf(n,e,t=nV(e)){return n<e-t}function kf(n,e){let t=Bm(e,n),i=Math.hypot(t.x,t.y,t.z),r=wn(t);return r?{direction:r,distance:i,epsilon:nV(i)}:null}function Um(n,e){let t=wn(e);return t?{point:_n(n),normal:t}:null}function kA(n,e){let t=$s(n.direction,e.normal);if(Math.abs(t)<=Number.EPSILON)return null;let i=Bm(e.point,n.origin),r=$s(i,e.normal)/t;return Number.isFinite(r)?tn(n.origin,en(n.direction,r)):null}function zA(n){return{x:n.x,y:n.y,z:n.z,w:n.w}}function GA(n,e){return{x:n.w*e.x+n.x*e.w+n.y*e.z-n.z*e.y,y:n.w*e.y-n.x*e.z+n.y*e.w+n.z*e.x,z:n.w*e.z+n.x*e.y-n.y*e.x+n.z*e.w,w:n.w*e.w-n.x*e.x-n.y*e.y-n.z*e.z}}function ace(n){return{x:-n.x,y:-n.y,z:-n.z,w:n.w}}function tV(n,e){let t=wn(n);if(!t)return null;let i=e/2,r=Math.sin(i);return{x:t.x*r,y:t.y*r,z:t.z*r,w:Math.cos(i)}}function oce(n,e){let t={x:n.x,y:n.y,z:n.z,w:0},i=GA(GA(e,t),ace(e));return{x:i.x,y:i.y,z:i.z}}function WA(n){let e=tV(n.yawAxis,n.deltaX*n.sensitivity),t=tV(n.pitchAxis,n.deltaY*n.sensitivity);if(!e||!t)return null;let i=GA(e,t),r=Bm(n.startPosition,n.pivot),s=oce(r,i);return{position:tn(n.pivot,s),rotationQuaternion:GA(i,n.startRotationQuaternion)}}var xs=y(()=>{"use strict"});function Za(n,e){return{min:_n(n),max:_n(e)}}function Pu(n,e){return n?{min:{x:Math.min(n.min.x,e.min.x),y:Math.min(n.min.y,e.min.y),z:Math.min(n.min.z,e.min.z)},max:{x:Math.max(n.max.x,e.max.x),y:Math.max(n.max.y,e.max.y),z:Math.max(n.max.z,e.max.z)}}:Za(e.min,e.max)}function Ui(n){return Bm(n.max,n.min)}function mr(n){return tn(n.min,en(Ui(n),.5))}function sV(n){return iV(n.min,n.max)}function Rs(n){return sV(n)/2}function aV(n){let e=Ui(n);return Math.max(e.x,e.y,e.z)}function fP(n){let e=Ui(n),t=sV(n);return{center:tn(n.min,en(e,.5)),size:e,diagonalLength:t,radius:t/2,maxSpan:Math.max(e.x,e.y,e.z)}}var Lo=y(()=>{"use strict";xs()});function dP(n,e,t={}){var s,a,o,l,c;let i=Math.max(e,Number.EPSILON),r=(s=t.radiusMultiplier)!=null?s:2.5;return{target:_n(n),radius:i*r,lowerRadiusLimit:i*((a=t.lowerRadiusFactor)!=null?a:.05),upperRadiusLimit:i*((o=t.upperRadiusFactor)!=null?o:10),near:i*((l=t.nearFactor)!=null?l:.001),far:i*((c=t.farFactor)!=null?c:20)}}function tv(n,e={}){let t=fP(n);return dP(t.center,t.radius,e)}function oV(n,e={}){var o,l,c,f,d,u;let t=fP(n),i=Math.max(t.maxSpan,t.radius,Number.EPSILON),r=i*((o=e.distanceMultiplier)!=null?o:1.8),s=Math.max((l=e.minNear)!=null?l:Math.max(i/1e4,1e-5),i/((c=e.nearDivisor)!=null?c:1e3)),a=Math.max((d=e.minFar)!=null?d:Math.max(i*((f=e.farMultiplier)!=null?f:20),1),r+t.radius*4);return{target:_n(t.center),position:tn(t.center,{x:r,y:r*((u=e.elevationFactor)!=null?u:.65),z:r}),near:s,far:a}}var HA=y(()=>{"use strict";Lo();xs()});function Hi(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var XA=y(()=>{"use strict"});function YA(n){var s;let e=new Set,t=0,i=0;for(let a of n.meshes){t+=a.triangleCount,i+=a.vertexCount;for(let o of(s=a.materialKeys)!=null?s:[])o!=null&&e.add(o)}let r=lce({triangleCount:t,splatCount:n.splatCount,meshCount:n.meshes.length,materialCount:e.size});return{meshCount:n.meshes.length,triangleCount:t,splatCount:n.splatCount,vertexCount:i,materialCount:e.size,performanceTier:r,performanceHint:cce(r,{triangleCount:t,splatCount:n.splatCount,materialCount:e.size}),resourceWarnings:n.resourceWarnings?[...n.resourceWarnings]:void 0,boundingSize:_n(n.boundingSize),rootName:n.rootName}}function lce(n){var e,t,i;return((e=n.splatCount)!=null?e:0)>=15e5||n.triangleCount>=12e5||n.materialCount>=96||n.meshCount>=240?"extreme":((t=n.splatCount)!=null?t:0)>=65e4||n.triangleCount>=45e4||n.materialCount>=48||n.meshCount>=120?"heavy":((i=n.splatCount)!=null?i:0)>=18e4||n.triangleCount>=12e4||n.materialCount>=18||n.meshCount>=48?"medium":"light"}function cce(n,e){var r;let t=((r=e.splatCount)!=null?r:e.triangleCount).toLocaleString(),i=e.splatCount!==void 0?"splats":"triangles";return n==="extreme"?`${t} ${i}, ${e.materialCount.toLocaleString()} materials. Expect automatic quality throttling while interacting.`:n==="heavy"?`${t} ${i}, ${e.materialCount.toLocaleString()} materials. Interaction may lower shadows and resolution temporarily.`:n==="medium"?`${t} ${i}, ${e.materialCount.toLocaleString()} materials. Performance should be steady on most desktop GPUs.`:`${t} ${i}, ${e.materialCount.toLocaleString()} materials. Performance tier: light.`}function Sc(n){var e;return{name:n.name,triangleCount:n.triangleCount,vertexCount:n.vertexCount,materialName:(e=n.materialName)!=null?e:null,boundingSize:_n(n.boundingSize),center:_n(n.center),source:n.source,meshNames:n.meshNames?[...n.meshNames]:void 0,childCount:n.childCount,componentId:n.componentId,occurrenceId:n.occurrenceId,partNumber:n.partNumber,componentPath:n.componentPath}}function lV(n){return n.splatCount!==void 0?"Splats":"Triangles"}function cV(n){var e;return(e=n.splatCount)!=null?e:n.triangleCount}var KA=y(()=>{"use strict";xs()});function Vm(n,e="-"){if(typeof n!="string")return e;let t=n.trim();return t.length>0?t:e}function fce(n){return n?n==="detail-cluster"?"Detail cluster":n.charAt(0).toUpperCase()+n.slice(1):null}function dce(n){var r,s,a,o;if(!n.sourceFormat&&!n.effectiveFormat&&!n.loadStrategy)return null;let e=(s=(r=n.sourceFormat)!=null?r:n.effectiveFormat)!=null?s:"unknown",t=(a=n.effectiveFormat)!=null?a:e,i=(o=n.loadStrategy)!=null?o:e!==t?"convert":"direct";return`${e.toUpperCase()}${t!==e?` -> ${t.toUpperCase()}`:""} (${i})`}function uce(n,e=8){if(!(n!=null&&n.length))return null;let t=n.slice(0,e).join(", "),i=n.length-e;return i>0?`${t}, +${i} more`:t}function fV(n,e={}){var r,s;let t=(r=e.countLabel)!=null?r:lV(n),i=(s=e.decimals)!=null?s:3;return[`| Meshes | ${n.meshCount} |`,`| ${t} | ${cV(n).toLocaleString()} |`,`| Vertices | ${n.vertexCount.toLocaleString()} |`,`| Materials | ${n.materialCount} |`,...n.performanceTier?[`| Performance Tier | ${n.performanceTier} |`]:[],`| Bounding Size | ${uP(n.boundingSize,{decimals:i})} |`]}function Do(n){return Hi(n).replace(/\|/g,"\\|").replace(/\r?\n/g," ")}function uP(n,e={}){var r,s;let t=(r=e.decimals)!=null?r:3,i=(s=e.separator)!=null?s:" x ";return`${n.x.toFixed(t)}${i}${n.y.toFixed(t)}${i}${n.z.toFixed(t)}`}function dV(n,e={}){return["| Metric | Value |","|--------|-------|",...fV(n,e)]}function hce(n,e,t={}){return["| Property | Value |","|----------|-------|",`| Format | ${n} |`,...fV(e,t)]}function jA(n){var r,s;let e=[];e.push(`## ${n.title} - Model Info`),e.push(""),e.push(...hce(n.format,n.summary,{countLabel:n.countLabel})),e.push("");let t=(r=n.meshBreakdown)!=null?r:[];t.length>1&&t.length<=50&&(e.push("### Mesh Breakdown"),e.push(""),e.push("| # | Name | Triangles | Vertices | Material |"),e.push("|---|------|-----------|----------|----------|"),t.forEach((a,o)=>{let l=a.triangleCount===null?"-":a.triangleCount.toLocaleString();e.push(`| ${o+1} | ${Do(Vm(a.name,`mesh-${o+1}`))} | ${l} | ${a.vertexCount.toLocaleString()} | ${Do(Vm(a.materialName))} |`)}),e.push(""));let i=Array.from((s=n.materialNames)!=null?s:[]).map(a=>Vm(a,"")).filter(a=>a.length>0);if(i.length>0){let a=Array.from(new Set(i));e.push("### Materials"),e.push("");for(let o of a)e.push(`- ${Hi(o)}`);e.push("")}return e.join(`
`)}function ZA(n,e={}){var o;let t=Hi(Vm((o=e.title)!=null?o:n.name,"Selected Part")),i=[];i.push(`## ${t} - Part Info`),i.push(""),i.push("| Property | Value |"),i.push("|----------|-------|"),i.push(`| Mesh | ${Do(Vm(n.name))} |`);let r=fce(n.source);r&&i.push(`| Source | ${Do(r)} |`),n.childCount!==void 0&&n.childCount>1&&i.push(`| Child Meshes | ${n.childCount.toLocaleString()} |`),n.componentId&&i.push(`| Component ID | ${Do(n.componentId)} |`),n.occurrenceId&&i.push(`| Occurrence ID | ${Do(n.occurrenceId)} |`),n.partNumber&&i.push(`| Part Number | ${Do(n.partNumber)} |`),n.componentPath&&i.push(`| Component Path | ${Do(n.componentPath)} |`);let s=dce(n);s&&i.push(`| Format Lineage | ${Do(s)} |`),i.push(`| Triangles | ${n.triangleCount.toLocaleString()} |`),i.push(`| Vertices | ${n.vertexCount.toLocaleString()} |`),i.push(`| Material | ${Do(Vm(n.materialName))} |`),i.push(`| Bounding Size | ${uP(n.boundingSize)} |`),i.push(`| Center | ${uP(n.center,{separator:", "})} |`);let a=uce(n.meshNames);return a&&n.childCount!==1&&i.push(`| Mesh Refs | ${Do(a)} |`),i.push(""),i.join(`
`)}var qA=y(()=>{"use strict";XA();KA()});function QA(n){return{canvas:n.canvas,observeRender:n.observeRender,getCameraStateKey:n.getCameraStateKey,projectWorldPoint:n.projectWorldPoint,isWorldPointOccluded:n.isWorldPointOccluded}}function $A(n){return n.map(e=>e.value.toFixed(e.digits)).join("_")}function uV(n){return Number.isFinite(n.x)&&Number.isFinite(n.y)&&Number.isFinite(n.z)}function hV(n,e,t){return!uV(n)||e.clientWidth===0||e.clientHeight===0?!1:(t.screenX=(n.x+1)/2*e.clientWidth,t.screenY=(1-n.y)/2*e.clientHeight,t.depth=(n.z+1)/2,!0)}function mV(n,e,t,i,r){return!uV(n)||e===0||t===0||i.clientWidth===0||i.clientHeight===0?!1:(r.screenX=n.x*(i.clientWidth/e),r.screenY=n.y*(i.clientHeight/t),r.depth=n.z,!0)}var hP=y(()=>{"use strict"});function Lu(n){var e;return n.size===0?null:n.size===1?(e=Array.from(n)[0])!=null?e:null:`${n.size} materials`}function mce(n){return Math.max(n.boundingSize.x,n.boundingSize.y,n.boundingSize.z)}function pce(n){return Math.max(n.boundingSize.x,n.boundingSize.y,n.boundingSize.z)}function gce(n){let e=n.trim().toLowerCase();return/^(mesh|node|object|primitive|points|pointcloud|geometry)[-_\s.]?\d+$/i.test(e)||/^(mesh|node|object|primitive|points|pointcloud|geometry)$/i.test(e)}function _ce(n){let e={x:n.boundingSize.x/2,y:n.boundingSize.y/2,z:n.boundingSize.z/2};return{min:{x:n.center.x-e.x,y:n.center.y-e.y,z:n.center.z-e.z},max:{x:n.center.x+e.x,y:n.center.y+e.y,z:n.center.z+e.z}}}function vce(n,e){if(n.source&&n.source!=="mesh"||!Number.isFinite(e)||e<=0||!gce(n.name))return!1;let t=mce(n);return Number.isFinite(t)&&t>0&&t<=e*.04}function Ece(n){var o;let e=null,t=0,i=0,r=new Set,s=[];for(let l of n)e=Pu(e,_ce(l)),t+=l.triangleCount,i+=l.vertexCount,l.materialName&&r.add(l.materialName),s.push(...(o=l.meshNames)!=null&&o.length?l.meshNames:[l.name]);let a=e!=null?e:{min:{x:0,y:0,z:0},max:{x:0,y:0,z:0}};return{name:"Small detail cluster",triangleCount:t,vertexCount:i,materialName:Lu(r),boundingSize:Ui(a),center:mr(a),source:"detail-cluster",meshNames:s,childCount:n.length}}function Sce(n,e,t){let i=pce(n),r=t.filter(o=>vce(o,i));if(r.length<2)return e.length>0?[...e,...t]:[...t];let s=new Set(r),a=t.filter(o=>!s.has(o));return[...e,Ece(r),...a]}function JA(n){var e;return{summary:n.summary,parts:Tce(n),materialNames:Ace(n.renderableMeshes,n.getMeshMaterialNames),resourceWarnings:n.resourceWarnings?[...n.resourceWarnings]:[],capturedAt:(e=n.capturedAt)!=null?e:new Date().toISOString()}}function Tce(n){let e=n.renderableMeshes.filter(t=>!n.groupedPartCandidates.groupedMeshes.has(t)).map(t=>n.createMeshPart(t));return Sce(n.summary,n.groupedPartCandidates.parts,e)}function Ace(n,e){let t=new Set;for(let i of n)for(let r of e(i))r&&t.add(r);return Array.from(t).sort((i,r)=>i.localeCompare(r))}var iv=y(()=>{"use strict";Lo()});function rv(n){switch(n){case"\xB5m":case"\u03BCm":return"um";case"um":case"mm":case"cm":case"m":return n;default:return"mm"}}function Ms(n){return{x:Number.isFinite(n.x)&&n.x>0?n.x:1,y:Number.isFinite(n.y)&&n.y>0?n.y:1,z:Number.isFinite(n.z)&&n.z>0?n.z:1}}function No(n){let e=Math.abs(n),t=e>=100?1:e>=10?2:3;return zm(n,t)}function vV(n,e,t){if(!Number.isFinite(e)||e<=Js||!Number.isFinite(t)||t<=Js)return null;let i=Ms(n),r=t/e;return Ms({x:i.x*r,y:i.y*r,z:i.z*r})}function rx(n,e,t){let i=Ms(t);return{x:e.x+(n.x-e.x)*i.x,y:e.y+(n.y-e.y)*i.y,z:e.z+(n.z-e.z)*i.z}}function nx(n,e,t){let i=Ms(t);return{x:e.x+(n.x-e.x)/i.x,y:e.y+(n.y-e.y)/i.y,z:e.z+(n.z-e.z)/i.z}}function sx(n,e){var a,o,l,c;if(!yl(n))return null;let t=null;for(let f of e.vertices)yl(f.point)&&(t=gV(t,{point:f.point,kind:"vertex",distance:tx(n,f.point),targetId:(a=f.targetId)!=null?a:e.targetId}));let i=null;for(let f of e.edges){if(!yl(f.start)||!yl(f.end))continue;let d=Oce(n,f.start,f.end);d&&(i=gV(i,{point:d,kind:"edge",distance:tx(n,d),targetId:(o=f.targetId)!=null?o:e.targetId}))}let r=Math.max((l=e.vertexRadius)!=null?l:0,0),s=t&&t.distance<=r?t:i!=null?i:t;return!s||Number.isFinite(e.maxDistance)&&s.distance>((c=e.maxDistance)!=null?c:0)?null:{point:{...s.point},kind:s.kind,distance:s.distance,targetId:s.targetId}}function ax(n,e){let i=Math.max(n.x,n.y,n.z,.001)*Mce,r=e.map(a=>tx(a.start,a.end)).filter(a=>Number.isFinite(a)&&a>Js).sort((a,o)=>a-o);if(r.length===0)return i;let s=r[Math.floor(r.length/2)];return Math.max(Math.min(i,s*yce),Js)}function ox(n,e,t){let i=new Map;for(let[r,s,a]of e){let o=[n[r],n[s],n[a]];if(o.some(c=>!c||!yl(c)))continue;let l=Pce(o[0],o[1],o[2]);for(let[c,f]of[[r,s],[s,a],[a,r]]){let d=n[c],u=n[f];if(!d||!u||!yl(d)||!yl(u)||tx(d,u)<=Js)continue;let h=Cce(d,u),m=i.get(h);m?l&&m.normals.push(l):i.set(h,{start:d,end:u,normals:l?[l]:[],targetId:t})}}return Array.from(i.values()).filter(r=>!Lce(r.normals)).map(r=>({start:r.start,end:r.end,targetId:r.targetId}))}function lx(n,e){let t=[];if(e&&e.length>=3){for(let i=0;i+2<e.length;i+=3){let r=e[i],s=e[i+1],a=e[i+2];gP(r,n)&&gP(s,n)&&gP(a,n)&&t.push([r,s,a])}return t}for(let i=0;i+2<n;i+=3)t.push([i,i+1,i+2]);return t}function cx(n,e,t={}){var w,G,O,N,B,V,q,K,J,Y,j,ue;if(!yl(n)||!yl(e))return null;let i=Gm(e,n),r=SV(i);if(r<=Js)return null;let s=bs(i,1/r),a=bs(ya(n,e),.5),o=(w=t.viewPosition)!=null?w:{x:a.x,y:a.y,z:a.z+1},l=(G=km(Gm(o,a)))!=null?G:{x:0,y:0,z:1},c=(N=km((O=t.viewUp)!=null?O:{x:0,y:1,z:0}))!=null?N:{x:0,y:1,z:0},f=(V=(B=km(ix(l,s)))!=null?B:km(ix(c,s)))!=null?V:Dce(s);TV(f,c)<0&&(f=bs(f,-1));let d=(q=t.offset)!=null?q:Math.max(r*.08,Js*1e3),u=Math.max(d,Js*1e3),h=Math.max((K=t.extensionGap)!=null?K:u*.16,0),m=Math.max((J=t.extensionOvershoot)!=null?J:u*.22,0),g=Math.min(Math.max((Y=t.arrowLength)!=null?Y:u*.62,u*.2),r*.42),p=Math.max((j=t.arrowWidth)!=null?j:g*.34,u*.08),_=Math.max((ue=t.labelGap)!=null?ue:p*1.18,0),v=ya(n,bs(f,u)),E=ya(e,bs(f,u)),S=ya(n,bs(f,h)),T=ya(e,bs(f,h)),A=ya(v,bs(f,m)),R=ya(E,bs(f,m)),M=ya(v,bs(s,g)),I=ya(E,bs(s,-g)),C=bs(f,p),L=ya(bs(ya(v,E),.5),bs(f,_));return{lineSegments:[[S,A],[T,R],[v,E],[v,ya(M,C)],[v,Gm(M,C)],[E,ya(I,C)],[E,Gm(I,C)]],labelPoint:L}}function EV(n,e,t,i){var l;let r=Ms(t),s=["x","y","z"];if(i){let c=s.find(d=>{var u;return Number.isFinite(e[d])&&((u=e[d])!=null?u:0)>Js&&n[d]>Js});if(!c)return null;let f=((l=e[c])!=null?l:0)/n[c];return Ms({x:f,y:f,z:f})}let a=!1,o={...r};for(let c of s){let f=e[c];Number.isFinite(f)&&(f!=null?f:0)>Js&&n[c]>Js&&(o[c]=(f!=null?f:0)/n[c],a=!0)}return a?Ms(o):null}function fx(n){var t,i;let e=n.active?n.pending?"picking-end":n.targetLocked?"ready":"select-target":n.records.length>0?"reviewing":"inactive";return{active:n.active,phase:e,records:n.records,unit:rv(n.unit),scale:Ms(n.scale),bounds:n.bounds,targetLocked:!!n.targetLocked,targetName:(t=n.targetName)!=null?t:null,targetScope:n.targetScope,snapKind:(i=n.snapKind)!=null?i:null}}function dx(n){let e=n.getMeasurementState();return e.active?(e.phase==="picking-end"?n.cancelMeasurement():n.toggleMeasurement(),!0):!1}function Wf(n,e){if(!n)return;if(n.classList.toggle(xce,e),!e){n.classList.remove(ex),delete n.dataset.ai3dMeasurementFocusToken;return}let t=`${Date.now()}-${Math.random().toString(36).slice(2)}`;n.dataset.ai3dMeasurementFocusToken=t,n.classList.remove(ex),n.getBoundingClientRect(),n.classList.add(ex),window.setTimeout(()=>{n.dataset.ai3dMeasurementFocusToken===t&&(n.classList.remove(ex),delete n.dataset.ai3dMeasurementFocusToken)},Rce)}function ux(n,e,t,i){let r=Ms(t),s={x:(e.x-n.x)*r.x,y:(e.y-n.y)*r.y,z:(e.z-n.z)*r.z},a={x:Math.abs(s.x),y:Math.abs(s.y),z:Math.abs(s.z)};return{distance:Math.sqrt(s.x*s.x+s.y*s.y+s.z*s.z),delta:s,absDelta:a,unit:i}}function zm(n,e){return n.toFixed(e).replace(/\.?0+$/,"")}function yl(n){return Number.isFinite(n.x)&&Number.isFinite(n.y)&&Number.isFinite(n.z)}function pV(n){return[Math.round(n.x*pP),Math.round(n.y*pP),Math.round(n.z*pP)].join(",")}function Cce(n,e){let t=pV(n),i=pV(e);return t<i?`${t}|${i}`:`${i}|${t}`}function Pce(n,e,t){return km(ix(Gm(e,n),Gm(t,n)))}function Lce(n){if(n.length<2)return!1;for(let e=0;e<n.length;e++)for(let t=e+1;t<n.length;t++)if(Math.abs(TV(n[e],n[t]))<bce)return!1;return!0}function tx(n,e){return Math.hypot(n.x-e.x,n.y-e.y,n.z-e.z)}function ya(n,e){return{x:n.x+e.x,y:n.y+e.y,z:n.z+e.z}}function Gm(n,e){return{x:n.x-e.x,y:n.y-e.y,z:n.z-e.z}}function bs(n,e){return{x:n.x*e,y:n.y*e,z:n.z*e}}function SV(n){return Math.hypot(n.x,n.y,n.z)}function km(n){if(!n||!yl(n))return null;let e=SV(n);return e<=Js?null:bs(n,1/e)}function TV(n,e){return n.x*e.x+n.y*e.y+n.z*e.z}function ix(n,e){return{x:n.y*e.z-n.z*e.y,y:n.z*e.x-n.x*e.z,z:n.x*e.y-n.y*e.x}}function Dce(n){var t;let e=Math.abs(n.y)<.8?{x:0,y:1,z:0}:{x:1,y:0,z:0};return(t=km(ix(e,n)))!=null?t:{x:0,y:0,z:1}}function gV(n,e){return n?e&&(e.distance<n.distance||e.distance===n.distance&&e.kind==="vertex"&&n.kind!=="vertex")?e:n:e}function Oce(n,e,t){let i={x:t.x-e.x,y:t.y-e.y,z:t.z-e.z},r=i.x*i.x+i.y*i.y+i.z*i.z;if(r<=Js)return null;let s={x:n.x-e.x,y:n.y-e.y,z:n.z-e.z},a=Math.max(0,Math.min(1,(s.x*i.x+s.y*i.y+s.z*i.z)/r));return{x:e.x+i.x*a,y:e.y+i.y*a,z:e.z+i.z*a}}function gP(n,e){return typeof n=="number"&&Number.isInteger(n)&&n>=0&&n<e}function Nce(n,e){if(n===0)return e;let t=Math.abs(n)*vP[e];return t<.001?"um":t<.1?"mm":t<1?"cm":"m"}function AV(n){return n==="um"?"um":Ice[n]}function zf(n,e,t=!0){let i=t?Nce(n,e):e,r=n*vP[e]/vP[i],s=Math.abs(r),a=s>=100?1:s>=10?2:3;return`${zm(r,a)} ${AV(i)}`}function _P(n){let e=Math.abs(n),t=e>=100?1:e>=10?2:3;return zm(e,t)}function Wm(n){return{primary:zf(n.distance,n.unit),secondary:[`X ${_P(n.absDelta.x)}`,`Y ${_P(n.absDelta.y)}`,`Z ${_P(n.absDelta.z)}`,AV(n.unit)].join(" ")}}function nv(n,e,t=Oo.width,i=Oo.height){n.clearRect(0,0,t,i);let r=t/2,s=i/2,a=Math.min(t-120,Math.max(250,e.primary.length*24+92)),o=78,l=(t-a)/2,c=(i-o)/2,f=s;wce(n,l,c,a,o,4),n.fillStyle=mP.labelPlate,n.fill(),n.lineWidth=2,n.strokeStyle=mP.labelPlateBorder,n.stroke(),n.textAlign="center",n.textBaseline="middle",n.lineJoin="round",n.fillStyle=mP.labelText,n.font="700 38px 'Segoe UI', Arial, sans-serif",n.fillText(e.primary,r,f,a-72)}function wce(n,e,t,i,r,s){if(typeof n.roundRect=="function"){n.beginPath(),n.roundRect(e,t,i,r,s);return}let a=Math.min(s,i/2,r/2);n.beginPath(),n.moveTo(e+a,t),n.lineTo(e+i-a,t),n.quadraticCurveTo(e+i,t,e+i,t+a),n.lineTo(e+i,t+r-a),n.quadraticCurveTo(e+i,t+r,e+i-a,t+r),n.lineTo(e+a,t+r),n.quadraticCurveTo(e,t+r,e,t+r-a),n.lineTo(e,t+a),n.quadraticCurveTo(e,t,e+a,t),n.closePath()}function hx(n){if(n.length===0)return"";let e=["## Measurements","","| # | Distance | Delta X | Delta Y | Delta Z | Start | End |","|---|----------|---------|---------|---------|-------|-----|"];for(let t of n){let i=t.reading.unit,r=_V(t.start),s=_V(t.end);e.push([t.index,zf(t.reading.distance,i),zf(t.reading.absDelta.x,i,!1),zf(t.reading.absDelta.y,i,!1),zf(t.reading.absDelta.z,i,!1),r,s].join(" | ").replace(/^/,"| ").replace(/$/," |"))}return e.join(`
`)}function _V(n){return`${zm(n.x,3)}, ${zm(n.y,3)}, ${zm(n.z,3)}`}var mP,Oo,xce,ex,Rce,vP,Js,pP,bce,Mce,yce,Ice,sv=y(()=>{"use strict";mP={line:"#f8fafc",marker:"#f8fafc",pending:"#f59e0b",hover:"#ffffff",preview:"#e5e7eb",labelPlate:"rgba(248, 250, 252, 0.94)",labelPlateBorder:"rgba(15, 23, 42, 0.58)",labelText:"#111827",labelSecondary:"rgba(51, 65, 85, 0.82)",labelOutline:"rgba(248, 250, 252, 0.22)"},Oo={width:760,height:220},xce="ai3d-measurement-active",ex="ai3d-measurement-focus-aggregation",Rce=1100,vP={um:1e-6,mm:.001,cm:.01,m:1},Js=1e-9,pP=1e6,bce=.9995,Mce=.045,yce=.1,Ice={um:"\u03BCm",mm:"mm",cm:"cm",m:"m"}});function av(n){return n==="x"||n==="y"||n==="z"?n:Fce}function wo(n){var t;let e={x:Number.isFinite(n==null?void 0:n.x)?Number(n==null?void 0:n.x):0,y:Number.isFinite(n==null?void 0:n.y)?Number(n==null?void 0:n.y):0,z:Number.isFinite(n==null?void 0:n.z)?Number(n==null?void 0:n.z):0};return(t=wn(e))!=null?t:{...Dr}}function Ia(n){return Number.isFinite(n)?Math.max(0,Math.min(n,1)):Il}function ov(n){return n==="rotate"?"rotate":Xf}function lv(n){return Number.isFinite(n)?Math.max(Bce,Math.min(n,Uce)):Hm}function px(n,e,t,i,r=!1,s=Hm,a=Xf,o=Dr){let l=wo(e),c=Ia(t),f=Du(i,{normal:l,offset:c});return{active:n,normal:l,offset:c,point:f?{...f.point}:null,dragging:r,interactionMode:ov(a),tiltDegrees:Gce(l,o),bounds:i?Ui(i):null,axis:kce(l),position:c,thickness:lv(s)}}function Xm(n,e,t){if(!n)return Il;let i=wo(e),r=MV(n,i),s=r.max-r.min;if(!Number.isFinite(s)||s<=Number.EPSILON)return Il;let a=$s(t,i);return Ia((a-r.min)/s)}function Yf(n,e,t){var s,a;let i=wo(n),r=(s=wn({x:Number(e==null?void 0:e.x),y:Number(e==null?void 0:e.y),z:Number(e==null?void 0:e.z)}))!=null?s:{x:0,y:1,z:0};return(a=wn(Wce(i,r,Ax(t))))!=null?a:i}function cv(n){let e=Math.PI*2,t=((Ax(n)+Math.PI)%e+e)%e-Math.PI;return t===-Math.PI?Math.PI:t}function EP(n){if(!Number.isFinite(n))return 0;let e=((n+180)%360+360)%360-180;return e===-180?180:e}function RV(n){return{x:EP(Number(n==null?void 0:n.x)),y:EP(Number(n==null?void 0:n.y)),z:EP(Number(n==null?void 0:n.z))}}function gx(n){let e=RV(n),t=e.x*Math.PI/180,i=e.y*Math.PI/180,r=e.z*Math.PI/180,s=Math.cos(t),a=Math.sin(t),o=Math.cos(i),l=Math.sin(i),c=Math.cos(r),f=Math.sin(r),d={m11:o*c,m12:-o*f,m13:l,m21:s*f+a*l*c,m22:s*c-a*l*f,m23:-a*o,m31:a*f-s*l*c,m32:a*c+s*l*f,m33:s*o};return{x:{x:d.m11,y:d.m21,z:d.m31},y:{x:-d.m13,y:-d.m23,z:-d.m33},z:{x:d.m12,y:d.m22,z:d.m32}}}function _x(n){let e=RP(n,n.z),t=e.x.x,i=e.z.x,r=-e.y.x,s=e.z.y,a=-e.y.y,o=e.z.z,l=-e.y.z,c=Math.asin(Math.max(-1,Math.min(1,r))),f=Math.abs(r)<.9999999?Math.atan2(-a,l):Math.atan2(o,s),d=Math.abs(r)<.9999999?Math.atan2(-i,t):0;return RV({x:f*180/Math.PI,y:c*180/Math.PI,z:d*180/Math.PI})}function Ym(n,e="free"){let t=Number.isFinite(n)?Math.abs(n):1;return e==="coarse"&&t>=.26&&t<=.74?"coarse":e==="fine"&&t>=.82&&t<=1.32?"fine":t>=.3&&t<=.68?"coarse":t>=.88&&t<=1.24?"fine":"free"}function vx(n,e){let t=cv(n),i=e==="coarse"?Math.PI/4:e==="fine"?Math.PI/36:0;return i>0?Math.round(t/i)*i:t}function Ex(n){return!Number.isFinite(n)||Math.abs(n)<Vce}function RP(n,e){var l,c,f,d,u;let t=wo((l=n==null?void 0:n.z)!=null?l:e),i=Hce(t),r=(f=wn((c=n==null?void 0:n.x)!=null?c:i.u))!=null?f:i.u,s={x:r.x-t.x*$s(r,t),y:r.y-t.y*$s(r,t),z:r.z-t.z*$s(r,t)},a=(d=wn(s))!=null?d:i.u,o=(u=wn(mx(t,a)))!=null?u:i.v;return n!=null&&n.y&&$s(o,n.y)<0&&(o=en(o,-1)),{x:a,y:o,z:t}}function Gce(n,e){let t=wo(n),i=wo(e),r=Math.max(-1,Math.min(1,$s(t,i)));return Math.acos(r)*(180/Math.PI)}function Du(n,e){var f;if(!n)return null;let t=e.normal?wo(e.normal):zce(av(e.axis),1),i=MV(n,t),r=i.max-i.min;if(!Number.isFinite(r)||r<=Number.EPSILON)return null;let s=Ia(typeof e.offset=="number"?e.offset:(f=e.position)!=null?f:Il),a=i.min+r*s,o=mr(n),l=$s(o,t),c=tn(o,en(t,a-l));return{normal:t,offset:s,min:i.min,max:i.max,distance:a,span:r,point:c}}function Sx(n,e,t=.12,i){let r=RP(i,e.normal),s=e.point,a=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY,l=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY;for(let p of bV(n)){let _={x:p.x-s.x,y:p.y-s.y,z:p.z-s.z},v=$s(_,r.x),E=$s(_,r.y);a=Math.min(a,v),o=Math.max(o,v),l=Math.min(l,E),c=Math.max(c,E)}let f=Math.max(.1,Number.isFinite(t)?t:.12),d=Math.max(Rs(n)*.04,Number.EPSILON),u=Math.max((o-a)*f,d),h=Math.max((c-l)*f,d);a-=u,o+=u,l-=h,c+=h;let m=(p,_)=>tn(tn(s,en(r.x,p)),en(r.y,_)),g=[m(a,l),m(o,l),m(o,c),m(a,c)];return{coordinate:e.distance,normal:{...e.normal},center:{...s},corners:g,segments:Yce(g)}}function Km(n,e,t=64,i,r){var _,v,E,S,T,A;let s=Math.max(Rs(n)*.62,e.span*.16,Number.EPSILON),a=e.point,o=RP(i,e.normal),l=o.z,c=s*.92,f=s*.16,d=s*.085,u=tn(a,en(l,-c*.52)),h=tn(a,en(l,c)),m=tn(h,en(l,-f)),g=tn(m,en(o.x,d)),p=tn(m,en(o.x,-d));return{rotationRings:{x:SP(a,"x",s,t,o),y:SP(a,"y",s,t,o),z:SP(a,"z",s,t,o)},rotationTicks:{x:TP(a,"x",s,36,o),y:TP(a,"y",s,36,o),z:TP(a,"z",s,36,o)},rotationArcs:{x:AP(a,"x",s*1.12,(_=r==null?void 0:r.x)!=null?_:0,o),y:AP(a,"y",s*1.12,(v=r==null?void 0:r.y)!=null?v:0,o),z:AP(a,"z",s*1.12,(E=r==null?void 0:r.z)!=null?E:0,o)},rotationArrowheads:{x:xP(a,"x",s*1.12,(S=r==null?void 0:r.x)!=null?S:0,o),y:xP(a,"y",s*1.12,(T=r==null?void 0:r.y)!=null?T:0,o),z:xP(a,"z",s*1.12,(A=r==null?void 0:r.z)!=null?A:0,o)},moveGuide:[[u,h],[h,g],[h,p]]}}function Tx(n,e){return n?e==="babylon"?[{normal:en(n.normal,-1),constant:n.distance}]:[{normal:{...n.normal},constant:-n.distance}]:null}function kce(n){let e=Math.abs(n.x),t=Math.abs(n.y),i=Math.abs(n.z);return e>=t&&e>=i?"x":t>=e&&t>=i?"y":"z"}function zce(n,e){return{x:n==="x"?e:0,y:n==="y"?e:0,z:n==="z"?e:0}}function mx(n,e){return{x:n.y*e.z-n.z*e.y,y:n.z*e.x-n.x*e.z,z:n.x*e.y-n.y*e.x}}function Ax(n){return Number.isFinite(n)?n:0}function Wce(n,e,t){if(Math.abs(t)<=Number.EPSILON)return{...n};let i=Math.cos(t),r=Math.sin(t),s=mx(e,n),a=$s(e,n)*(1-i);return{x:n.x*i+s.x*r+e.x*a,y:n.y*i+s.y*r+e.y*a,z:n.z*i+s.z*r+e.z*a}}function Hce(n){var r,s;let e=Math.abs(n.y)<.92?{x:0,y:1,z:0}:{x:1,y:0,z:0},t=(r=wn(mx(e,n)))!=null?r:{x:1,y:0,z:0},i=(s=wn(mx(n,t)))!=null?s:{x:0,y:1,z:0};return{u:t,v:i}}function SP(n,e,t,i,r){let s=Math.max(16,Math.round(i)),a=[];for(let o=0;o<s;o+=1){let l=o/s*Math.PI*2,c=(o+1)/s*Math.PI*2;a.push([Hf(n,e,t,l,r),Hf(n,e,t,c,r)])}return a}function Hf(n,e,t,i,r){let s=Math.cos(i)*t,a=Math.sin(i)*t,o=e==="x"?r.y:e==="y"?r.z:r.x,l=e==="x"?r.z:e==="y"?r.x:r.y;return tn(tn(n,en(o,s)),en(l,a))}function TP(n,e,t,i,r){let s=Math.max(12,Math.round(i)),a=[];for(let o=0;o<s;o+=1){let l=o/s*Math.PI*2,c=o%3===0;a.push([Hf(n,e,t*(c?.93:.96),l,r),Hf(n,e,t*1.06,l,r)])}return a}function Xce(n,e,t,i,r,s,a){let o=[],l=i*Math.PI*2,c=r*Math.PI*2;for(let f=0;f<s;f+=1){let d=f/s,u=(f+1)/s;o.push([Hf(n,e,t,l+(c-l)*d,a),Hf(n,e,t,l+(c-l)*u,a)])}return o}function AP(n,e,t,i,r){let s=(Ax(i)%(Math.PI*2)+Math.PI*2)%(Math.PI*2);return Xce(n,e,t,0,s/(Math.PI*2),52,r)}function xP(n,e,t,i,r){let s=(Ax(i)%(Math.PI*2)+Math.PI*2)%(Math.PI*2),a=t*.12,o=t*.055;return[...xV(n,e,t,s,1,a,o,r),...xV(n,e,t,s,-1,a,o,r)]}function xV(n,e,t,i,r,s,a,o){var h;let l=Hf(n,e,t,i,o),c=Hf(n,e,t,i-r*(s/t),o),f=(h=wn({x:c.x-n.x,y:c.y-n.y,z:c.z-n.z}))!=null?h:{x:1,y:0,z:0},d=tn(c,en(f,a)),u=tn(c,en(f,-a));return[[l,d],[l,u],[d,u]]}function bV(n){return[{x:n.min.x,y:n.min.y,z:n.min.z},{x:n.max.x,y:n.min.y,z:n.min.z},{x:n.min.x,y:n.max.y,z:n.min.z},{x:n.max.x,y:n.max.y,z:n.min.z},{x:n.min.x,y:n.min.y,z:n.max.z},{x:n.max.x,y:n.min.y,z:n.max.z},{x:n.min.x,y:n.max.y,z:n.max.z},{x:n.max.x,y:n.max.y,z:n.max.z}]}function MV(n,e){let t=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let r of bV(n)){let s=$s(r,e);t=Math.min(t,s),i=Math.max(i,s)}return{min:t,max:i}}function Yce(n){return[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]]}var Fce,Dr,Il,Xf,Hm,Bce,Uce,Vce,bP=y(()=>{"use strict";Lo();xs();Fce="y",Dr={x:0,y:1,z:0},Il=.5,Xf="move",Hm=.08,Bce=.002,Uce=1,Vce=.08});function Kce(n){let e=typeof activeWindow=="undefined"?window:activeWindow;return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(n):e.setTimeout(()=>n(e.performance.now()),16)}function jce(n){let e=typeof activeWindow=="undefined"?window:activeWindow;if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(n);return}e.clearTimeout(n)}function Rx(n){return new MP(n)}var xx,MP,yP=y(()=>{"use strict";xx=class xx{constructor(e){this.originals=new Map;this.unsubscribe=null;this.active=!1;this.drag=null;this.pendingDrag=null;this.selected=null;this.activePointerId=null;this.frameCount=0;this.pendingDragEvent=null;this.dragUpdateFrame=null;this.adapter=e}isEnabled(){return this.active}setEnabled(e){var t,i,r;return this.active===e?this.active:(this.active=e,this.finishDrag(),this.setSelected(null),this.activePointerId=null,e?this.unsubscribe=this.adapter.subscribe({onPointerDown:(s,a)=>this.handlePointerDown(s,a),onPointerMove:s=>this.handlePointerMove(s),onPointerUp:s=>this.handlePointerUp(s),onRender:()=>this.handleRender()}):((t=this.unsubscribe)==null||t.call(this),this.unsubscribe=null),(r=(i=this.adapter).requestRender)==null||r.call(i),this.active)}toggle(){return this.setEnabled(!this.active)}reset(){var e,t;this.finishDrag(),this.setSelected(null);for(let{part:i,transform:r}of this.originals.values())this.adapter.isDisposed(i)||this.adapter.restoreTransform(i,r);this.activePointerId=null,(t=(e=this.adapter).requestRender)==null||t.call(e)}dispose(){this.setEnabled(!1),this.originals.clear()}handlePointerDown(e,t){if(t.button!==0||t.isPrimary===!1)return;let i=this.adapter.resolvePart(e);if(!i){this.drag=null,this.pendingDrag=null,this.activePointerId=null,this.setSelected(null);return}this.activePointerId=t.pointerId,this.setSelected(i),this.pendingDrag={part:i,event:t,x:t.clientX,y:t.clientY}}handlePointerMove(e){if(!(this.activePointerId!==null&&e.pointerId!==this.activePointerId)){if(!this.drag&&this.pendingDrag){if(e.pointerType==="mouse"&&(e.buttons&1)===0){this.pendingDrag=null,this.activePointerId=null;return}if(Math.hypot(e.clientX-this.pendingDrag.x,e.clientY-this.pendingDrag.y)<xx.DRAG_START_DISTANCE)return;let i=this.pendingDrag;if(this.pendingDrag=null,this.adapter.isDisposed(i.part))return;this.captureOriginalTransform(i.part),this.drag=this.adapter.beginDrag(i.part,i.event),this.drag&&this.adapter.updateDrag(this.drag,e);return}this.drag&&this.scheduleDragUpdate(e)}}handlePointerUp(e){this.activePointerId!==null&&e.pointerId!==this.activePointerId||(this.pendingDrag=null,this.flushDragUpdate(),this.finishDrag(),this.activePointerId=null)}handleRender(){!this.selected||this.adapter.isDisposed(this.selected)||this.drag||this.pendingDrag||(this.frameCount++,this.frameCount%6===0&&this.adapter.updateSelectionOcclusion(this.selected))}finishDrag(){var e,t;this.pendingDrag=null,this.flushDragUpdate(),this.adapter.endDrag(this.drag),this.drag=null,(t=(e=this.adapter).requestRender)==null||t.call(e)}scheduleDragUpdate(e){this.pendingDragEvent=e,this.dragUpdateFrame===null&&(this.dragUpdateFrame=Kce(()=>{this.dragUpdateFrame=null,this.flushDragUpdate()}))}flushDragUpdate(){this.dragUpdateFrame!==null&&(jce(this.dragUpdateFrame),this.dragUpdateFrame=null);let e=this.pendingDragEvent;this.pendingDragEvent=null,!(!this.drag||!e)&&this.adapter.updateDrag(this.drag,e)}setSelected(e){this.selected=e,this.frameCount=0,this.adapter.setSelected(e)}captureOriginalTransform(e){let t=this.adapter.getPartId(e);this.originals.has(t)||this.originals.set(t,{part:e,transform:this.adapter.captureTransform(e)})}};xx.DRAG_START_DISTANCE=4;MP=xx});function tfe(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function bx(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"")}function ife(n){if(typeof n=="string"){let e=n.trim();return e.length>0?e:void 0}if(typeof n=="number"&&Number.isFinite(n))return String(n)}function yV(n,e=0){if(!tfe(n)||e>2)return[];let t=[];for(let i of efe)for(let[r,s]of Object.entries(n))bx(r)===bx(i)&&t.push(...yV(s,e+1));return t.push(n),t}function fv(n,e){let t=new Set(e.map(bx));for(let i of n)for(let[r,s]of Object.entries(i)){if(!t.has(bx(r)))continue;let a=ife(s);if(a)return a}}function Ca(n,e={}){var c,f;let t=yV(n),i=fv(t,Zce),r=fv(t,qce),s=fv(t,Qce),a=(c=fv(t,Jce))!=null?c:e.path,o=(f=fv(t,$ce))!=null?f:e.name;return{componentId:i,occurrenceId:r,partNumber:s,componentPath:a,displayName:o,hasExplicitIdentity:!!(i||r||s)}}var Zce,qce,Qce,$ce,Jce,efe,IP=y(()=>{"use strict";Zce=["ai3dPartId","partId","componentId","componentIdentifier","cadId","persistentId","externalId","id"],qce=["ai3dOccurrenceId","occurrenceId","instanceId","occurrencePath","assemblyPath","pathId"],Qce=["ai3dPartNumber","partNumber","partNo","partNum","swPartNumber","solidworksPartNumber","part_number"],$ce=["displayName","partName","componentName","cadName","name"],Jce=["componentPath","cadPath","assemblyPath","occurrencePath"],efe=["ai3d","cad","solidworks","sw","metadata","properties","extras","gltf","userData"]});function La(n){return n instanceof ci}function dv(n){return n instanceof ks}function Kf(n){return La(n)||dv(n)}function Fn(n){return n?Array.isArray(n)?n:[n]:[]}function uv(n){var r,s,a,o;if(dv(n))return 0;let e=n.geometry,t=(s=(r=e.getIndex())==null?void 0:r.count)!=null?s:0;if(t>0)return Math.floor(t/3);let i=(o=(a=e.getAttribute("position"))==null?void 0:a.count)!=null?o:0;return Math.floor(i/3)}function Zm(n){var e,t;return(t=(e=n.geometry.getAttribute("position"))==null?void 0:e.count)!=null?t:0}function qm(n){return n?n.name||n.type||`material-${n.uuid}`:null}function Pa(n,e){var i;let t=(i=n.userData)==null?void 0:i.name;return typeof t=="string"&&t.trim().length>0?t:n.name||e}function jm(n,e){let t=[],i=e;for(;i&&i!==n;)t.push(Pa(i,i.type||`object-${i.id}`)),i=i.parent;return t.reverse().join("/")}function rn(n){let e=new Wr().setFromObject(n);return Za(ct(e.min),ct(e.max))}function IV(n){let e=new Map;for(let t of n)t.updateWorldMatrix(!0,!1),e.set(t,rn(t));return e}function CV(n){return Fn(n.material).map(e=>qm(e))}function PV(n){return{name:Pa(n,dv(n)?`points-${n.id}`:`mesh-${n.id}`),triangleCount:dv(n)?null:uv(n),vertexCount:Zm(n),materialName:qm(Fn(n.material)[0])}}function rfe(n,e,t){var a;n.updateWorldMatrix(!0,!1);let i=(a=t==null?void 0:t.get(n))!=null?a:rn(n),r=Pa(n,`mesh-${n.id}`),s=Ca(n.userData,{name:r,path:e?jm(e,n):r});return Sc({name:Ix(s,r),triangleCount:uv(n),vertexCount:Zm(n),materialName:qm(Fn(n.material)[0]),boundingSize:Ui(i),center:mr(i),source:s.hasExplicitIdentity?"component":"mesh",meshNames:[r],childCount:1,componentId:s.componentId,occurrenceId:s.occurrenceId,partNumber:s.partNumber,componentPath:s.componentPath})}function CP(n,e,t){var a;if(La(n))return rfe(n,e,t);n.updateWorldMatrix(!0,!1);let i=(a=t==null?void 0:t.get(n))!=null?a:rn(n),r=Pa(n,`points-${n.id}`),s=Ca(n.userData,{name:r,path:e?jm(e,n):r});return Sc({name:Ix(s,r),triangleCount:0,vertexCount:Zm(n),materialName:qm(Fn(n.material)[0]),boundingSize:Ui(i),center:mr(i),source:s.hasExplicitIdentity?"component":"mesh",meshNames:[r],childCount:1,componentId:s.componentId,occurrenceId:s.occurrenceId,partNumber:s.partNumber,componentPath:s.componentPath})}function nfe(n,e){let t=[];return n.traverse(i=>{La(i)&&e.has(i)&&t.push(i)}),t}function Qm(n,e){let t=new Map;for(let i of e){let r=i.parent;for(;r&&r!==n;){let s=t.get(r);s||(s=[],t.set(r,s)),s.push(i),r=r.parent}}return t}function LV(n,e,t){var i;return(i=t==null?void 0:t.get(n))!=null?i:nfe(n,e)}function sfe(n){let e=n.trim().toLowerCase();return/^(scene|root|model|group|node|object|assembly|component)[-_\s.]?\d*$/i.test(e)||e==="__root__"}function afe(n){return/->\d+(?:[_\s.-]*primitive\d*)?$/i.test(n.trim())}function DV(n,e,t,i,r){var m;if(Kf(n))return CP(n,e,r);n.updateWorldMatrix(!0,!0);let s=new Set(t!=null?t:[]);s.size===0&&n.traverse(g=>{La(g)&&s.add(g)});let a=LV(n,s,i),o=null,l=new Set,c=0,f=0;for(let g of a){g.updateWorldMatrix(!0,!1),o=Pu(o,(m=r==null?void 0:r.get(g))!=null?m:rn(g)),c+=uv(g),f+=Zm(g);for(let p of Fn(g.material)){let _=qm(p);_&&l.add(_)}}a.length===0&&(o=rn(n));let d=o!=null?o:Za({x:0,y:0,z:0},{x:0,y:0,z:0}),u=Pa(n,`group-${n.id}`),h=Ca(n.userData,{name:u,path:e?jm(e,n):u});return Sc({name:Ix(h,u),triangleCount:c,vertexCount:f,materialName:Lu(l),boundingSize:Ui(d),center:mr(d),source:h.hasExplicitIdentity?"component":"group",meshNames:a.map(g=>Pa(g,`mesh-${g.id}`)),childCount:a.length,componentId:h.componentId,occurrenceId:h.occurrenceId,partNumber:h.partNumber,componentPath:h.componentPath})}function Mx(n,e,t,i){var l,c;let r=new Set(t),s=null,a=null,o=e.parent;for(;o&&o!==n;){let f=LV(o,r,i);if(f.length>0&&f.length<t.length){let d=(l=o.name)!=null?l:"",u=Pa(o,`group-${o.id}`);if(Ca(o.userData,{name:u,path:jm(n,o)}).hasExplicitIdentity){if(!afe(d))return o;a!=null||(a=o)}!s&&f.length>1&&u.trim()&&!sfe(u)&&(s=o)}o=o.parent}return(c=s!=null?s:a)!=null?c:e}function OV(n,e,t=Qm(n,e),i){let r=[],s=new Set,a=[];return n.updateWorldMatrix(!0,!0),n.traverse(o=>{var f;if(o===n||La(o))return;let l=(f=t.get(o))!=null?f:[];if(l.length<2||l.length===e.length){let d=Ca(o.userData,{name:Pa(o,`component-${o.id}`),path:jm(n,o)});if(!d.hasExplicitIdentity||l.length<1||l.length===e.length)return;a.push({object:o,childMeshes:l,identity:d});return}let c=Ca(o.userData,{name:Pa(o,`group-${o.id}`),path:jm(n,o)});!c.hasExplicitIdentity&&!o.name.trim()||a.push({object:o,childMeshes:l,identity:c})}),a.sort((o,l)=>o.childMeshes.length-l.childMeshes.length).forEach(({object:o,childMeshes:l,identity:c})=>{var p;let f=l.filter(_=>!s.has(_));if(f.length<1||!c.hasExplicitIdentity&&f.length<2)return;for(let _ of f)s.add(_);let d=null;for(let _ of f)_.updateWorldMatrix(!0,!1),d=Pu(d,(p=i==null?void 0:i.get(_))!=null?p:rn(_));let u=new Set,h=0,m=0;for(let _ of f){h+=uv(_),m+=Zm(_);for(let v of Fn(_.material)){let E=qm(v);E&&u.add(E)}}let g=d!=null?d:Za({x:0,y:0,z:0},{x:0,y:0,z:0});r.push(Sc({name:Ix(c,Pa(o,`group-${o.id}`)),triangleCount:h,vertexCount:m,materialName:Lu(u),boundingSize:Ui(g),center:mr(g),source:c.hasExplicitIdentity?"component":"group",meshNames:f.map(_=>Pa(_,`mesh-${_.id}`)),childCount:f.length,componentId:c.componentId,occurrenceId:c.occurrenceId,partNumber:c.partNumber,componentPath:c.componentPath}))}),{parts:r,groupedMeshes:s}}function yx(n,e,t=[],i){return YA({rootName:n.name||"__root__",boundingSize:Ui(i!=null?i:rn(n)),meshes:e.map(r=>({triangleCount:uv(r),vertexCount:Zm(r),materialKeys:Fn(r.material).map(s=>s.uuid)})),resourceWarnings:t})}function NV(n,e,t,i){var f;if(!n)return{meshCount:0,pointCloudCount:0,smallPartCount:0,smallestPartSpan:null,modelSpan:null};let r=Ui(t!=null?t:rn(n)),s=Math.max(r.x,r.y,r.z),a=Math.max(s*.04,Number.EPSILON),o=0,l=0,c=Number.POSITIVE_INFINITY;for(let d of e){dv(d)&&o++;let u=Ui((f=i==null?void 0:i.get(d))!=null?f:rn(d)),h=Math.max(u.x,u.y,u.z);Number.isFinite(h)&&h>0&&(c=Math.min(c,h),La(d)&&h<=a&&h<s&&l++)}return{meshCount:e.length,pointCloudCount:o,smallPartCount:l,smallestPartSpan:Number.isFinite(c)?Number(c.toPrecision(6)):null,modelSpan:Number.isFinite(s)&&s>0?Number(s.toPrecision(6)):null}}function Ix(n,e){var t;return((t=n.displayName)==null?void 0:t.trim())||n.partNumber||n.componentId||e}var PP=y(()=>{"use strict";Es();Lo();IP();iv();xs();KA()});function ofe(n){return!!n&&typeof n=="object"&&"object"in n&&"meshes"in n}function lfe(n,e,t=Qm(n,e)){let i=new Map;for(let r of e){let s=Mx(n,r,e,t),a=i.get(s);a||(a={id:s.id,object:s,meshes:[]},i.set(s,a)),a.meshes.push(r)}return Array.from(i.values())}function cfe(n,e){var t;n.updateMatrixWorld(!0),(t=e.parent)==null||t.updateMatrixWorld(!0),e.updateMatrixWorld(!0),n.attach(e),e.updateMatrixWorld(!0)}function FV(n,e,t,i,r,s,a,o){return Rx(new LP(n,e,t,i,r,s,a,o))}var wV,ffe,LP,BV=y(()=>{"use strict";Es();xs();yP();PP();wV=new mt(4890367),ffe=new mt(1722990),LP=class{constructor(e,t,i,r,s,a,o,l=Qm(r,s)){this.meshToPart=new Map;this.raycaster=new Pf;this.pointer=new Ct;this.tempBox=new Wr;this.tempCenter=new ie;this.tempDirection=new ie;this.tempCameraForward=new ie;this.tempCameraRight=new ie;this.tempCameraUp=new ie;this.tempDragOffset=new ie;this.tempNextPosition=new ie;this.tempHelperDelta=new ie;this.partCenterCache=new Map;this.selectionHelper=null;this.lastOccluded=!1;this.selected=null;this.lastPointerDown=null;this.partPointerActive=!1;this.activePointerId=null;this.scene=e,this.camera=t,this.canvas=i,this.meshes=s,this.parts=lfe(r,s,l);for(let c of this.parts)for(let f of c.meshes)this.meshToPart.set(f.id,c);this.controls=a,this.invalidate=o}requestRender(){this.invalidate()}getParts(){return this.parts}getPartId(e){return e.id}isDisposed(e){return!e.object.parent&&!this.scene.children.includes(e.object)}captureTransform(e){return{parent:e.object.parent,position:e.object.position.clone(),quaternion:e.object.quaternion.clone(),scale:e.object.scale.clone()}}restoreTransform(e,t){t.parent?t.parent.add(e.object):this.scene.add(e.object),e.object.position.copy(t.position),e.object.quaternion.copy(t.quaternion),e.object.scale.copy(t.scale),e.object.updateMatrixWorld(!0),this.invalidatePartCenter(e),this.requestRender()}subscribe(e){this.canvas.classList.add("ai3d-disassembly-active");let t=s=>{var o,l;if(s.button!==0||s.isPrimary===!1)return;this.lastPointerDown={x:s.clientX,y:s.clientY};let a=this.resolvePickTarget(s);if(this.partPointerActive=!!a,this.partPointerActive){s.preventDefault(),s.stopPropagation(),this.controls.enabled=!1,this.activePointerId=s.pointerId;try{(l=(o=this.canvas).setPointerCapture)==null||l.call(o,s.pointerId)}catch(c){}}e.onPointerDown(a,s)},i=s=>{this.activePointerId!==null&&s.pointerId!==this.activePointerId||(this.partPointerActive&&(s.preventDefault(),s.stopPropagation()),e.onPointerMove(s))},r=s=>{var a,o;if(!(this.activePointerId!==null&&s.pointerId!==this.activePointerId)){if(this.partPointerActive&&(s.preventDefault(),s.stopPropagation()),this.lastPointerDown=null,e.onPointerUp(s),this.partPointerActive=!1,this.activePointerId!==null&&((o=(a=this.canvas).hasPointerCapture)!=null&&o.call(a,this.activePointerId)))try{this.canvas.releasePointerCapture(this.activePointerId)}catch(l){}this.activePointerId=null,this.controls.enabled=!0}};return this.canvas.addEventListener("pointerdown",t),window.addEventListener("pointermove",i),window.addEventListener("pointerup",r),()=>{var s,a;if(this.canvas.removeEventListener("pointerdown",t),window.removeEventListener("pointermove",i),window.removeEventListener("pointerup",r),this.canvas.classList.remove("ai3d-disassembly-active","ai3d-disassembly-dragging"),this.partPointerActive=!1,this.activePointerId!==null&&((a=(s=this.canvas).hasPointerCapture)!=null&&a.call(s,this.activePointerId)))try{this.canvas.releasePointerCapture(this.activePointerId)}catch(o){}this.activePointerId=null,this.controls.enabled=!0}}resolvePart(e){var t;return ofe(e)?this.parts.includes(e)?e:null:e&&(t=this.meshToPart.get(e.id))!=null?t:null}setSelected(e){var t;(t=this.selectionHelper)==null||t.removeFromParent(),this.selectionHelper=null,this.selected=e,this.lastOccluded=!1,e&&!this.isDisposed(e)&&(this.selectionHelper=new Sl(e.object,wV),this.scene.add(this.selectionHelper)),this.requestRender()}beginDrag(e,t){let i=this.getPartWorldCenter(e,this.tempCenter).clone(),r=this.getPointOnDragPlane(i,t);if(!r)return null;t.preventDefault(),t.stopPropagation(),cfe(this.scene,e.object),this.canvas.classList.add("ai3d-disassembly-dragging");let s="move";t.shiftKey&&(s="rotate");let a=this.tempCameraForward;this.camera.getWorldDirection(a);let o=Um(ct(r),ct(a));return o?(this.controls.enabled=!1,this.requestRender(),{part:e,mode:s,plane:o,startPoint:r.clone(),startPosition:e.object.position.clone(),startQuaternion:e.object.quaternion.clone(),pivot:i,pointerX:t.clientX,pointerY:t.clientY}):null}updateDrag(e,t){if(t.preventDefault(),t.stopPropagation(),e.mode==="rotate"){this.updateRotation(e,t);return}let i=this.getRayPlanePoint(t,e.plane);if(!i)return;let r=this.tempDragOffset.copy(i).sub(e.startPoint),s=this.tempNextPosition.copy(e.startPosition).add(r),a=this.tempHelperDelta.copy(s).sub(e.part.object.position);e.part.object.position.copy(s),e.part.object.updateMatrixWorld(!0),this.invalidatePartCenter(e.part),this.translateSelectionHelper(a),this.requestRender()}endDrag(e){var t;this.controls.enabled=!0,this.canvas.classList.remove("ai3d-disassembly-dragging"),(t=this.selectionHelper)==null||t.update(),this.requestRender()}updateSelectionOcclusion(e){let t=this.getPartWorldCenter(e,this.tempCenter),i=this.camera.position,r=kf(ct(i),ct(t));if(!r)return;let s=this.tempDirection.set(r.direction.x,r.direction.y,r.direction.z);this.raycaster.set(i,s),this.raycaster.far=r.distance;let a=this.raycaster.intersectObjects(this.meshes,!1)[0],o=!!a&&Gf(a.distance,r.distance,r.epsilon);o!==this.lastOccluded&&(this.lastOccluded=o,this.selectionHelper&&(this.selectionHelper.material.color.set(o?ffe:wV),this.requestRender()))}updateRotation(e,t){var c;let i=t.clientX-e.pointerX,r=t.clientY-e.pointerY,s=this.tempCameraForward;this.camera.getWorldDirection(s);let a=this.tempCameraUp.copy(this.camera.up).normalize(),o=this.tempCameraRight.crossVectors(a,s).normalize(),l=WA({startPosition:ct(e.startPosition),pivot:ct(e.pivot),startRotationQuaternion:zA(e.startQuaternion),yawAxis:ct(a),pitchAxis:ct(o),deltaX:i,deltaY:r,sensitivity:.01});l&&(e.part.object.position.set(l.position.x,l.position.y,l.position.z),e.part.object.quaternion.set(l.rotationQuaternion.x,l.rotationQuaternion.y,l.rotationQuaternion.z,l.rotationQuaternion.w),e.part.object.updateMatrixWorld(!0),this.invalidatePartCenter(e.part),(c=this.selectionHelper)==null||c.update(),this.requestRender())}resolvePickTarget(e){let t=this.canvas.getBoundingClientRect();this.pointer.x=(e.clientX-t.left)/t.width*2-1,this.pointer.y=-((e.clientY-t.top)/t.height)*2+1,this.raycaster.setFromCamera(this.pointer,this.camera);let i=this.raycaster.intersectObjects(this.meshes,!1)[0];return(i==null?void 0:i.object)instanceof ci?i.object:null}getPointOnDragPlane(e,t){var s;let i=this.tempCameraForward;this.camera.getWorldDirection(i);let r=Um(ct(e),ct(i));return r&&(s=this.getRayPlanePoint(t,r))!=null?s:e}getRayPlanePoint(e,t){let i=this.canvas.getBoundingClientRect(),r=e.clientX-i.left,s=e.clientY-i.top;this.pointer.set(r/i.width*2-1,-(s/i.height)*2+1),this.raycaster.setFromCamera(this.pointer,this.camera);let a=kA({origin:ct(this.raycaster.ray.origin),direction:ct(this.raycaster.ray.direction)},t);return a?new ie(a.x,a.y,a.z):null}getPartWorldCenter(e,t){let i=this.partCenterCache.get(e.id);return i?t.copy(i):(this.tempBox.setFromObject(e.object).getCenter(t),this.partCenterCache.set(e.id,t.clone()),t)}invalidatePartCenter(e){this.partCenterCache.delete(e.id)}translateSelectionHelper(e){if(!this.selectionHelper||e.lengthSq()<=Number.EPSILON)return;let t=this.selectionHelper.geometry.getAttribute("position");for(let i=0;i<t.count;i++)t.setXYZ(i,t.getX(i)+e.x,t.getY(i)+e.y,t.getZ(i)+e.z);t.needsUpdate=!0,this.selectionHelper.geometry.computeBoundingSphere()}}});function UV(n){let e=n.clone();return e.transparent=!0,e.opacity=Math.max(0,Math.min(1,n.opacity))*dfe,e.depthWrite=!1,e.needsUpdate=!0,e}function ufe(n){return Array.isArray(n)?n.map(UV):UV(n)}function hfe(n){return Array.isArray(n)?n.map(e=>e.uuid).join("|"):n.uuid}function mfe(n){if(n)for(let e of Array.isArray(n)?n:[n])e.dispose()}var dfe,Cx,VV=y(()=>{"use strict";dfe=.242;Cx=class{constructor(){this.materials=new Map}get(e){let t=hfe(e),i=this.materials.get(t);if(i)return i;let r=ufe(e);return this.materials.set(t,r),r}clear(){for(let e of this.materials.values())mfe(e);this.materials.clear()}get size(){return this.materials.size}}});function GV(n){return _n(n)}function pfe(n,e){return{originalPosition:GV(n),originalCenter:GV(e)}}function Px(n,e,t){let i=n.getRootCenter();for(let r of n.getParts()){let s=n.getPartState(r);s||(s=pfe(n.getPartPosition(r),n.getPartCenter(r)),n.setPartState(r,s));let a=(s.originalCenter[t]-i[t])*e;n.setPartPosition(r,rV(s.originalPosition,t,a))}}function Lx(n){for(let e of n.getParts()){let t=n.getPartState(e);t&&n.setPartPosition(e,t.originalPosition)}}var DP=y(()=>{"use strict";xs()});function Dx(n){return _n(n)}function gfe(n){return n instanceof ci}function _fe(n){let e=[];return n.traverse(t=>{gfe(t)&&t.geometry&&e.push(t)}),e}function kV(n,e,t){Px(new Ox(n),e,t)}function OP(n){Lx(new Ox(n))}var Ox,zV=y(()=>{"use strict";Es();xs();Lo();DP();Ox=class{constructor(e){this.root=e}getParts(){return _fe(this.root)}getRootCenter(){let e=new Wr().setFromObject(this.root);return mr({min:ct(e.min),max:ct(e.max)})}getPartPosition(e){return ct(e.position)}getPartCenter(e){let i=new Wr().setFromObject(e).getCenter(new ie);return ct(i)}setPartPosition(e,t){e.position.set(t.x,t.y,t.z)}getPartState(e){var i;let t=(i=e.userData)!=null?i:{};return t._previewExplodeState?{originalPosition:Dx(t._previewExplodeState.originalPosition),originalCenter:Dx(t._previewExplodeState.originalCenter)}:null}setPartState(e,t){e.userData._previewExplodeState={originalPosition:Dx(t.originalPosition),originalCenter:Dx(t.originalCenter)}}}});function WV(n){return n.cameraMoved||n.animating||n.renderDirty||n.renderObserverCount>0&&n.renderObserverSettleFrames>0}var Nx,HV=y(()=>{"use strict";Nx=class{constructor(e=120){this.maxSamples=e;this.samples=[];this.renderedFrameCount=0;this.idleFrameSkipCount=0;this.slowFrameCount=0;this.maxRenderMs=0;this.adaptiveScaleChangeCount=0}recordRenderedFrame(e,t){!Number.isFinite(e)||e<0||(this.renderedFrameCount++,e>=t&&this.slowFrameCount++,this.maxRenderMs=Math.max(this.maxRenderMs,e),this.samples.push(e),this.samples.length>this.maxSamples&&this.samples.shift())}recordIdleFrameSkip(){this.idleFrameSkipCount++}recordAdaptiveScaleChange(){this.adaptiveScaleChangeCount++}snapshot(){let e=[...this.samples].sort((r,s)=>r-s),t=this.samples.reduce((r,s)=>r+s,0),i=e.length===0?-1:Math.min(e.length-1,Math.ceil(e.length*.95)-1);return{renderedFrameCount:this.renderedFrameCount,idleFrameSkipCount:this.idleFrameSkipCount,slowFrameCount:this.slowFrameCount,averageRenderMs:e.length?Number((t/e.length).toFixed(2)):0,p95RenderMs:i>=0?Number(e[i].toFixed(2)):0,maxRenderMs:Number(this.maxRenderMs.toFixed(2)),adaptiveScaleChangeCount:this.adaptiveScaleChangeCount}}}});var QV={};Be(QV,{ThreeModelPreview:()=>Fx,createThreeModelPreview:()=>jfe});function KV(n,e,t){let i=t.x-e.x,r=t.y-e.y,s=i*i+r*r;if(s<=Number.EPSILON)return Math.hypot(n.x-e.x,n.y-e.y);let a=Math.max(0,Math.min(1,((n.x-e.x)*i+(n.y-e.y)*r)/s));return Math.hypot(n.x-(e.x+i*a),n.y-(e.y+r*a))}function jV(){return{textureCount:0,colorTextureCount:0,srgbColorTextureCount:0}}function Yfe(n,e){n.textureCount+=e.textureCount,n.colorTextureCount+=e.colorTextureCount,n.srgbColorTextureCount+=e.srgbColorTextureCount}function BP(n){return n instanceof El||n instanceof Mo||n instanceof _c}function ZV(n){return n instanceof sr}function qV(n){return Number.isFinite(n)?Math.max(0,Math.min(n,1)):0}function Kfe(n){return Number.isFinite(n)?n.toPrecision(10):String(n)}function jfe(n){return new Fx(n)}var wx,vfe,Efe,Sfe,Tfe,Afe,XV,xfe,YV,Rfe,bfe,Mfe,yfe,Ife,Cfe,Pfe,Lfe,Dfe,Ofe,hv,Nfe,wfe,Ffe,Bfe,Ufe,Vfe,Gfe,kfe,NP,wP,FP,zfe,Wfe,Hfe,Xfe,Fx,$V=y(()=>{"use strict";Es();SU();TU();$U();Ma();Fm();Lo();HA();qA();ev();hP();xs();iv();sv();bP();BV();VV();zV();As();lP();HV();PP();wx=new mt("#20242e"),vfe=.28,Efe=2.5,Sfe=1.5,Tfe=1.15,Afe=260,XV=30,xfe=8,YV=28,Rfe=18,bfe=2,Mfe=28,yfe=.86,Ife=1.08,Cfe=.62,Pfe=.86,Lfe=4,Dfe=120,Ofe=16317180,hv=16317180,Nfe=16096779,wfe=16777215,Ffe=15067115,Bfe=3718648,Ufe=9684477,Vfe=14742270,Gfe=16096779,kfe=16569165,NP=15680580,wP=2278750,FP=3900150,zfe=16317180,Wfe=16436245,Hfe=.32,Xfe=.84;Fx=class{constructor(e){this.raycaster=new Pf;this.occlusionRaycaster=new Pf;this.renderObservers=new Set;this.cameraZoomObservers=new Set;this.pointer=new Ct;this.annotationProjection=new ie;this.annotationDirection=new ie;this.clock={last:performance.now()};this.defaultLights=[];this.configLights=[];this.environmentTarget=null;this.environmentInstallHandle=0;this.rootObject=null;this.loadedExt="";this.resourceWarnings=[];this.textureAudit=jV();this.renderHandle=0;this.contextLost=!1;this.quality="high";this.renderScale=1;this.interactivePixelRatioActive=!1;this.interactionPixelRatioDeadline=0;this.renderObserverSettleFrames=0;this.frameBudgetPixelRatioScale=1;this.frameBudgetSlowStreak=0;this.frameBudgetFastStreak=0;this.frameBudgetObserverStride=1;this.frameBudgetObserverCursor=0;this.frameBudgetShadowDeferred=!1;this.lastFrameDurationMs=0;this.smoothness=new Nx;this.viewportVisible=!0;this.viewportObserver=null;this.lastDisposalAudit={reason:"initial",meshCount:0,geometryCount:0,materialCount:0,textureCount:0,objectCount:0,timestamp:performance.now()};this.axesHelper=null;this.bboxHelper=null;this.groundShadowMesh=null;this.meshShadowFlagsPrepared=!1;this.gridHelper=null;this.bboxEnabled=!1;this.wireframeEnabled=!1;this.wireframeOriginalMaterials=new Map;this.sliceActive=!1;this.sliceNormal=new ie(Dr.x,Dr.y,Dr.z);this.slicePlaneX=new ie(1,0,0);this.slicePlaneY=new ie(0,0,-1);this.sliceCenter=null;this.sliceReferenceNormal=new ie(Dr.x,Dr.y,Dr.z);this.sliceOffset=Il;this.sliceInteractionMode=Xf;this.sliceThickness=Hm;this.slicePlanes=[];this.sliceOverlayPlanes=[];this.sliceOverlayLines=[];this.sliceOverlayLabels=[];this.sliceDragState=null;this.sliceObservers=new Set;this.sliceOriginalMaterialClipping=new Map;this.sliceOriginalLocalClippingEnabled=null;this.sceneConfig={};this.focusSelectionEnabled=!1;this.explodeStateActive=!1;this.focusedObject=null;this.highlightedObject=null;this.selectionHelper=null;this.focusHelper=null;this.mixer=null;this.animationPlaying=!1;this.initialTarget=new ie;this.initialPosition=new ie(3,2,3);this.initialFov=45;this.initialZoom=1;this.initialCameraMode="perspective";this.cameraMode="perspective";this.lastPointerDown=null;this.measurementActive=!1;this.measurementScale={x:1,y:1,z:1};this.measurementBaseRootScale=new ie(1,1,1);this.measurementBaseBounds=null;this.measurementUnit="mm";this.measurementSegments=[];this.measurementMarkers=[];this.measurementMarkerPoints=[];this.measurementTargetObject=null;this.measurementTargetHelper=null;this.measurementSnapInputCache=null;this.measurementSnapInputCacheTarget=null;this.measurementSnapInputCacheSignature=null;this.measurementSnapKind=null;this.measurementObservers=new Set;this.pendingPoint=null;this.pendingMarker=null;this.hoveredMarkerIndex=-1;this.lastPointerClient={x:0,y:0,altKey:!1};this.previewLine=null;this.previewLineUpdateHandle=0;this.originalMaterials=new Map;this.focusedSelectedMeshes=new Map;this.focusDimMaterialCache=new Cx;this._lastPickResult={mesh:null,pickedPoint:null,screenX:0,screenY:0};this._onPickCallbacks=[];this.disassembly=null;this.disassemblySetup=!1;this.renderDirty=!0;this.stlMaterial=null;this.cachedMeshes=null;this.cachedMeshRoot=null;this.cachedRenderables=null;this.cachedRenderableRoot=null;this.cachedRenderableObjectCount=null;this.cachedChildMeshMap=null;this.cachedChildMeshMapRoot=null;this.cachedRenderableBoundsMap=null;this.cachedRenderableBoundsMapRoot=null;this.cachedRootPreviewBounds=null;this.cachedRootPreviewBoundsObject=null;this.cachedGeometryQualityStats=null;this.cameraAnimHandle=0;this.preventCanvasWheelScroll=e=>{this.prepareInteractiveFrameBudget(),e.preventDefault(),e.stopPropagation(),this.markDirty()};this.handleControlsChange=()=>{this.prepareInteractiveFrameBudget(),this.measurementSegments.length>0&&this.updateMeasurementOverlayPositions(),this.markDirty(),this.notifyCameraZoomChanged()};this.handleViewportIntersection=e=>{let t=e[e.length-1];if(!t)return;let i=t.isIntersecting&&t.intersectionRatio>0;i!==this.viewportVisible&&(this.viewportVisible=i,i?(this.clock.last=performance.now(),this.markDirty(),this.markShadowDirty(),this.startRenderLoop()):(cancelAnimationFrame(this.renderHandle),this.renderHandle=0))};this.handlePointerDown=e=>{e.button!==0||e.isPrimary===!1||this.sliceActive&&this.beginSliceDrag(e)||(this.lastPointerDown={x:e.clientX,y:e.clientY},this.prepareInteractiveFrameBudget())};this.handlePointerUp=e=>{var i;if(e.button!==0||e.isPrimary===!1||this.endSliceDrag(e))return;this.lastPointerClient={x:e.clientX,y:e.clientY,altKey:e.altKey};let t=this.lastPointerDown;this.lastPointerDown=null,t&&(Math.hypot(e.clientX-t.x,e.clientY-t.y)>4||(i=this.disassembly)!=null&&i.isEnabled()||this.sliceActive||this.dispatchPick(e))};this.handlePointerMove=e=>{if(this.lastPointerClient={x:e.clientX,y:e.clientY,altKey:e.altKey},this.updateSliceDrag(e)||(e.buttons&1&&this.prepareInteractiveFrameBudget(),!this.measurementActive)||(this.pendingPoint&&this.schedulePreviewLineUpdate(),this.measurementMarkers.length===0))return;let t=this.renderer.domElement.getBoundingClientRect();this.pointer.x=(e.clientX-t.left)/t.width*2-1,this.pointer.y=-((e.clientY-t.top)/t.height)*2+1,this.raycaster.setFromCamera(this.pointer,this.camera);let i=this.raycaster.intersectObjects(this.measurementMarkers,!1),r=i.length>0?this.measurementMarkers.indexOf(i[0].object):-1;if(r!==this.hoveredMarkerIndex){if(this.hoveredMarkerIndex>=0&&this.hoveredMarkerIndex<this.measurementMarkers.length){let s=this.measurementMarkers[this.hoveredMarkerIndex];s!==this.pendingMarker&&(s.scale.setScalar(1),s.material.color.setHex(hv))}if(r>=0&&r<this.measurementMarkers.length){let s=this.measurementMarkers[r];s.scale.setScalar(1.6),s.material.color.setHex(wfe)}this.hoveredMarkerIndex=r,this.markDirty()}};this.handlePointerCancel=e=>{this.endSliceDrag(e,!0)};this.handleMeasurementModifierKey=e=>{e.key==="Alt"&&this.updateMeasurementModifierAltKey(e.type==="keydown")};this.handleMeasurementModifierBlur=()=>{this.updateMeasurementModifierAltKey(!1)};this.handleContextLost=e=>{e.preventDefault(),this.contextLost=!0,this.renderHandle&&(cancelAnimationFrame(this.renderHandle),this.renderHandle=0)};this.handleContextRestored=()=>{this.contextLost=!1,this.markDirty(),this.startRenderLoop()};this.renderer=new EA({canvas:e,antialias:!0,alpha:!0,preserveDrawingBuffer:!0,powerPreference:"high-performance"}),this.renderer.outputColorSpace=Fi,this.renderer.toneMapping=Ys,this.renderer.toneMappingExposure=1,this.renderer.shadowMap.enabled=!1,this.renderer.shadowMap.type=bT,this.renderer.shadowMap.autoUpdate=!1,this.renderer.shadowMap.needsUpdate=!1,this.renderer.setClearColor(wx,1),this.scene=new du,this.camera=new Sr(this.initialFov,1,.01,2e3),this.camera.position.copy(this.initialPosition),this.camera.lookAt(this.initialTarget),this.scene.add(this.camera),this.controls=new xA(this.camera,e),this.controls.enableDamping=!0,this.controls.dampingFactor=.08,this.controls.zoomSpeed=.65,this.controls.screenSpacePanning=!0,this.controls.target.copy(this.initialTarget),this.controls.addEventListener("change",this.handleControlsChange),this.installDefaultLighting(),this.resizeObs=new ResizeObserver(()=>this.resizeRenderer()),this.resizeObs.observe(e),typeof IntersectionObserver!="undefined"&&(this.viewportObserver=new IntersectionObserver(this.handleViewportIntersection,{root:null,threshold:[0,.01]}),this.viewportObserver.observe(e)),e.addEventListener("wheel",this.preventCanvasWheelScroll,{passive:!1}),e.addEventListener("pointerdown",this.handlePointerDown,!0),e.addEventListener("pointerup",this.handlePointerUp,!0),e.addEventListener("pointermove",this.handlePointerMove,!0),e.addEventListener("pointercancel",this.handlePointerCancel,!0),e.addEventListener("webglcontextlost",this.handleContextLost),e.addEventListener("webglcontextrestored",this.handleContextRestored),window.addEventListener("keydown",this.handleMeasurementModifierKey),window.addEventListener("keyup",this.handleMeasurementModifierKey),window.addEventListener("blur",this.handleMeasurementModifierBlur),this.resizeRenderer(),this.startRenderLoop()}async loadModel(e,t,i,r,s){var l;xi(s),this.clearLoadedModel("model-switch"),xi(s),this.loadedExt=t.toLowerCase(),this.resourceWarnings=[],this.textureAudit=jV();let a=null,o=[];try{if(this.loadedExt==="glb"||this.loadedExt==="gltf"){let u=await jU(e,this.loadedExt,i,r,s);a=u.scene,o=u.animations,this.resourceWarnings=u.warnings}else if(this.loadedExt==="stl")a=await ZU(e),this.stlMaterial=La(a)?a.material:null;else if(this.loadedExt==="ply")a=await qU(e);else if(this.loadedExt==="obj"){let u=await QU(e,i,r);a=u.object,this.resourceWarnings=u.warnings}else throw new Error(`Three preview does not support .${this.loadedExt} format`);xi(s),this.rootObject=a,this.scene.add(a),this.invalidateMeshCache();let c=this.getRenderableObjects(a);this.prepareModelForQuality(c),xi(s),this.syncShadowFeatures();let f=this.getRootPreviewBounds(a);if(this.captureMeasurementBaseState(a,f),this.updateShadowFraming(f),this.syncSceneHelpers(),this.syncSliceClipping(),this.notifySliceChanged(),this.markDirty(),o.length>0){this.mixer=new N_(a);for(let u of o)this.mixer.clipAction(u).play();this.animationPlaying=!0}let d=yx(a,c,this.resourceWarnings,f!=null?f:void 0);return this.cachedGeometryQualityStats=null,this.fitCameraToObject(a,f!=null?f:void 0),this.bboxEnabled&&this.ensureBoundingBoxHelper(),this.scheduleGlobalEnvironmentInstall(),this.disassemblySetup=!1,(l=this.disassembly)==null||l.dispose(),this.disassembly=null,d}catch(c){throw a&&(a.removeFromParent(),this.rootObject===a&&(this.rootObject=null),this.lastDisposalAudit=this.disposeObjectGraph(a,"model-switch"),this.invalidateMeshCache()),c}}applyConfig(e){e.camera&&this.applyCameraConfig(e.camera),e.lights&&this.applyLightConfig(e.lights),e.scene&&this.applySceneConfig(e.scene),e.stl&&this.applySTLConfig(e.stl)}applySTLConfig(e){let t=this.stlMaterial;t&&(e.color!==void 0&&t.color.set(e.color),e.wireframe!==void 0&&(t.wireframe=e.wireframe,t.needsUpdate=!0),this.markDirty())}destroy(){var t,i;cancelAnimationFrame(this.renderHandle),cancelAnimationFrame(this.cameraAnimHandle),this._onPickCallbacks=[],this.renderObservers.clear(),this.cameraZoomObservers.clear(),this.measurementObservers.clear(),this.sliceObservers.clear(),(t=this.disassembly)==null||t.dispose(),this.disassembly=null,this.disassemblySetup=!1,this.clearFocusedMesh(),this.clearSelectionHighlight(),this.clearLoadedModel("destroy");for(let r of this.configLights)this.disposeConfiguredLight(r);this.configLights.length=0;for(let r of this.defaultLights)this.disposeConfiguredLight(r);this.defaultLights.length=0,this.disposeGlobalEnvironment(),this.controls.removeEventListener("change",this.handleControlsChange),this.controls.dispose();let e=this.renderer.domElement;e.classList.remove("ai3d-slice-active","ai3d-slice-dragging","ai3d-slice-rotate"),e.removeEventListener("wheel",this.preventCanvasWheelScroll),e.removeEventListener("pointerdown",this.handlePointerDown,!0),e.removeEventListener("pointerup",this.handlePointerUp,!0),e.removeEventListener("pointermove",this.handlePointerMove,!0),e.removeEventListener("pointercancel",this.handlePointerCancel,!0),e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),window.removeEventListener("keydown",this.handleMeasurementModifierKey),window.removeEventListener("keyup",this.handleMeasurementModifierKey),window.removeEventListener("blur",this.handleMeasurementModifierBlur),this.resizeObs.disconnect(),(i=this.viewportObserver)==null||i.disconnect(),this.viewportObserver=null,this.renderer.dispose()}getCanvas(){return this.renderer.domElement}captureSnapshot(){return this.renderNow(0),this.renderer.domElement.toDataURL("image/png")}getAnnotationProvider(){let e=this.renderer.domElement;return QA({canvas:e,observeRender:t=>(this.renderObservers.add(t),this.setRenderObserverSettleFrames(),this.markDirty(),{remove:()=>{this.renderObservers.delete(t),this.renderObservers.size===0&&this.setRenderObserverSettleFrames(0)}}),getCameraStateKey:()=>this.getAnnotationCameraStateKey(),projectWorldPoint:(t,i)=>this.projectAnnotationWorldPoint(t,i),isWorldPointOccluded:t=>this.isAnnotationWorldPointOccluded(t)})}exportModelInfo(e){var s;if(!this.rootObject)return"";let t=this.getRenderableObjects(this.rootObject),i=yx(this.rootObject,t,this.resourceWarnings,(s=this.getRootPreviewBounds())!=null?s:void 0),r=e&&Qs(e)||i.rootName;return jA({title:r,format:this.loadedExt.toUpperCase(),summary:i,meshBreakdown:t.map(PV)})}getModelEvidence(){var o;if(!this.rootObject)return null;let e=this.getRenderableObjects(this.rootObject),t=this.getRenderableMeshes(this.rootObject),i=this.getChildRenderableMeshMap(this.rootObject),r=this.getRenderableBoundsMap(this.rootObject),s=OV(this.rootObject,t,i,r),a={parts:s.parts,groupedMeshes:new Set(s.groupedMeshes)};return JA({summary:yx(this.rootObject,e,this.resourceWarnings,(o=this.getRootPreviewBounds())!=null?o:void 0),renderableMeshes:e,groupedPartCandidates:a,createMeshPart:l=>CP(l,this.rootObject,r),getMeshMaterialNames:CV,resourceWarnings:this.resourceWarnings})}getSelectedPartInfo(){var r;let e=(r=this.focusedObject)!=null?r:ZV(this._lastPickResult.mesh)?this._lastPickResult.mesh:null;if(!e)return null;let t=this.rootObject?this.getRenderableMeshes(this.rootObject):[],i=this.rootObject?this.getChildRenderableMeshMap(this.rootObject):void 0;return DV(e,this.rootObject,t,i)}exportSelectedPartInfo(){let e=this.getSelectedPartInfo();return e?ZA(e):""}getPickWorldPoint(e){return e.pickedPoint&&typeof e.pickedPoint=="object"?ct(e.pickedPoint):ZV(e.mesh)?mr(rn(e.mesh)):null}onPick(e){return this._onPickCallbacks.push(e),()=>{this._onPickCallbacks=this._onPickCallbacks.filter(t=>t!==e)}}resetView(){this.rootObject&&this.explodeStateActive&&(OP(this.rootObject),this.explodeStateActive=!1,this.invalidateRootBoundsCache(),this.markShadowDirty()),this.resetDisassembly(),this.clearFocusedMesh(),this.clearSelectionHighlight(),this.switchCameraMode(this.initialCameraMode),this.camera.position.copy(this.initialPosition),this.controls.target.copy(this.initialTarget),this.camera.lookAt(this.controls.target),this.camera instanceof Sr&&(this.camera.fov=this.initialFov),this.camera.zoom=this.initialZoom,this.camera.updateProjectionMatrix(),this.controls.update(),this.markDirty(),this.renderNow(performance.now()),this.notifyCameraZoomChanged()}toggleFocusSelection(){var t;let e=!this.focusSelectionEnabled;return e&&((t=this.disassembly)!=null&&t.isEnabled())&&this.disableDisassemblyAndReset(),e&&(this.deactivateMeasurementMode(),this.deactivateSliceMode()),this.focusSelectionEnabled=e,this.focusSelectionEnabled?(this.clearSelectionHighlight(),this._lastPickResult.mesh instanceof sr&&this.setFocusedObject(this._lastPickResult.mesh)):this.clearFocusedMesh(),this.markDirty(),this.focusSelectionEnabled}isFocusSelectionEnabled(){return this.focusSelectionEnabled}setWireframe(e){e!==this.wireframeEnabled&&(this.wireframeEnabled=e,this.applyWireframe(e),this.syncSliceClipping(),this.markDirty())}toggleWireframe(){return this.setWireframe(!this.wireframeEnabled),this.wireframeEnabled}applyWireframe(e){if(this.rootObject)for(let t of this.getRenderableMeshes(this.rootObject))if(e){this.wireframeOriginalMaterials.set(t.id,t.material);let r=Fn(t.material).map(s=>{if(s instanceof Dn){let a=new Kn({color:s.color,transparent:s.transparent,opacity:s.opacity,side:s.side,visible:s.visible});return a.wireframe=!0,a}if("wireframe"in s){let a=s.clone();return a.wireframe=!0,a}return s});t.material=Array.isArray(t.material)?r:r[0]}else{let i=this.wireframeOriginalMaterials.get(t.id);i&&(t.material=i),this.wireframeOriginalMaterials.delete(t.id)}}toggleOrientationGizmo(){if(!this.axesHelper){this.axesHelper=new Em(1.2),this.axesHelper.visible=!1;let e=this.axesHelper.material;e.depthTest=!1,e.depthWrite=!1,this.axesHelper.renderOrder=999,this.scene.add(this.axesHelper)}return this.axesHelper.visible=!this.axesHelper.visible,this.axesHelper.position.copy(this.controls.target),this.markDirty(),this.axesHelper.visible}isOrientationGizmoEnabled(){var e;return!!((e=this.axesHelper)!=null&&e.visible)}toggleBoundingBox(){var e;return this.bboxEnabled=!this.bboxEnabled,this.bboxEnabled?(this.ensureBoundingBoxHelper(),this.markDirty(),!!this.bboxHelper):((e=this.bboxHelper)==null||e.removeFromParent(),this.bboxHelper=null,this.markDirty(),!1)}toggleSlice(){var e;return this.sliceActive?(this.deactivateSliceMode(),!1):((e=this.disassembly)!=null&&e.isEnabled()&&this.disableDisassemblyAndReset(),this.deactivateMeasurementMode(),this.focusSelectionEnabled&&(this.focusSelectionEnabled=!1,this.clearFocusedMesh(),this.clearSelectionHighlight()),this.alignSlicePlaneToWorld(),this.sliceInteractionMode=Xf,this.sliceActive=!0,this.syncSliceClipping(),this.notifySliceChanged(),this.sliceActive)}isSliceActive(){return this.sliceActive}setSlicePlane(e,t=this.sliceOffset){let i=wo(e);return this.sliceNormal.set(i.x,i.y,i.z),this.rebuildSlicePlaneAxes(),this.sliceOffset=Ia(t),this.setSliceCenterFromOffset(this.sliceOffset),this.syncSliceClipping(),this.notifySliceChanged(),this.getSliceState()}setSliceOffset(e){return this.sliceOffset=Ia(e),this.setSliceCenterFromOffset(this.sliceOffset),this.syncSliceClipping(),this.notifySliceChanged(),this.getSliceState()}setSliceRotation(e){var a,o;let t=this.getRootPreviewBounds(),i=this.getSliceRange(),r=(o=(a=this.sliceCenter)==null?void 0:a.clone())!=null?o:i?new ie(i.point.x,i.point.y,i.point.z):null,s=gx(e);return this.slicePlaneX.set(s.x.x,s.x.y,s.x.z),this.slicePlaneY.set(s.y.x,s.y.y,s.y.z),this.sliceNormal.set(s.z.x,s.z.y,s.z.z),r?(this.sliceCenter=r,this.sliceOffset=Xm(t,s.z,ct(r))):this.setSliceCenterFromOffset(this.sliceOffset),this.syncSliceClipping(),this.notifySliceChanged(),this.getSliceState()}setSliceInteractionMode(e){let t=ov(e);return t===this.sliceInteractionMode?this.getSliceState():(this.endSliceDrag(null,!0),this.sliceInteractionMode=t,this.syncSliceClipping(),this.notifySliceChanged(),this.getSliceState())}resetSlicePlane(){return this.alignSlicePlaneToWorld(),this.sliceOffset=Il,this.setSliceCenterFromOffset(this.sliceOffset),this.syncSliceClipping(),this.notifySliceChanged(),this.getSliceState()}setSliceAxis(e){let t=av(e);return this.setSlicePlane({x:t==="x"?1:0,y:t==="y"?1:0,z:t==="z"?1:0})}setSlicePosition(e){return this.setSliceOffset(e)}setSliceThickness(e){return this.sliceThickness=lv(e),this.notifySliceChanged(),this.getSliceState()}getSliceState(){let e=px(this.sliceActive,ct(this.sliceNormal),this.sliceOffset,this.getRootPreviewBounds(),!!this.sliceDragState,this.sliceThickness,this.sliceInteractionMode,ct(this.sliceReferenceNormal)),t=this.getSliceRange(),i=_x({x:ct(this.slicePlaneX),y:ct(this.slicePlaneY),z:ct(this.sliceNormal)});return t?{...e,rotationDegrees:i,offset:t.offset,position:t.offset,point:{...t.point}}:{...e,rotationDegrees:i}}observeSlice(e){return this.sliceObservers.add(e),e(),()=>{this.sliceObservers.delete(e)}}hasAnimations(){return this.mixer!==null}toggleAnimation(){return this.mixer?(this.animationPlaying=!this.animationPlaying,this.mixer.timeScale=this.animationPlaying?1:0,this.markDirty(),this.animationPlaying):!1}toggleMeasurement(){var t;if(this.measurementActive)return this.deactivateMeasurementMode(),!1;(t=this.disassembly)!=null&&t.isEnabled()&&this.disableDisassemblyAndReset(),this.deactivateSliceMode();let e=this.getCurrentMeasurementTargetObject();return this.clearSelectionHighlight(),this.focusSelectionEnabled&&(this.focusSelectionEnabled=!1,this.clearFocusedMesh()),this.measurementActive=!0,this.setMeasurementTargetObject(e,!1),Wf(this.renderer.domElement,this.measurementActive),this.notifyMeasurementsChanged(),this.measurementActive}isMeasurementActive(){return this.measurementActive}clearMeasurements(){this.disposeMeasurementOverlays(!1)}cancelMeasurement(){let e=!!this.pendingPoint;this.cancelPendingMeasurement(),e&&this.notifyMeasurementsChanged()}deactivateMeasurementMode(){return this.measurementActive?(this.measurementActive=!1,Wf(this.renderer.domElement,!1),this.setMeasurementTargetObject(null,!1),this.cancelPendingMeasurement(),this.notifyMeasurementsChanged(),!0):!1}disposeMeasurementOverlays(e){var t;e&&(this.measurementActive=!1,Wf(this.renderer.domElement,!1),this.setMeasurementTargetObject(null,!1)),this.cancelPendingMeasurement(!1);for(let i of this.measurementSegments){i.line.removeFromParent(),i.line.geometry.dispose(),i.line.material.dispose(),i.label.removeFromParent();let r=i.label.material;(t=r.map)==null||t.dispose(),r.dispose()}this.measurementSegments=[];for(let i of this.measurementMarkers){i.removeFromParent(),i.geometry.dispose();let r=i.material;if(Array.isArray(r))for(let s of r)s.dispose();else r.dispose()}this.measurementMarkers=[],this.measurementMarkerPoints=[],this.setMeasurementSnapKind(null,!1),this.markDirty(),this.notifyMeasurementsChanged()}setMeasurementScale(e){var t,i;this.measurementScale=Ms(e),this.invalidateMeasurementSnapInputCache(),this.applyMeasurementModelScale(),this.sliceActive&&(this.setSliceCenterFromOffset(this.sliceOffset),this.syncSliceClipping()),(t=this.selectionHelper)==null||t.update(),(i=this.focusHelper)==null||i.update(),this.updateMeasurementOverlayPositions(),this.updateMeasurementLabels(),this.notifyMeasurementsChanged()}getMeasurementScale(){return{...this.measurementScale}}setMeasurementUnit(e){this.measurementUnit=rv(e),this.updateMeasurementLabels(),this.notifyMeasurementsChanged()}getMeasurementUnit(){return this.measurementUnit}getMeasurementBounds(){var i;if(!this.rootObject)return null;let e=(i=this.measurementBaseBounds)!=null?i:rn(this.rootObject);return Ui(e)}getMeasurementRecords(){return this.createMeasurementRecords()}getMeasurementState(){return fx({active:this.measurementActive,pending:!!this.pendingPoint,records:this.createMeasurementRecords(),unit:this.measurementUnit,scale:this.getMeasurementScale(),bounds:this.getMeasurementBounds(),targetLocked:!!this.measurementTargetObject,targetName:this.getMeasurementTargetName(),targetScope:this.measurementTargetObject===this.rootObject?"model":"part",snapKind:this.measurementSnapKind})}exportMeasurements(){return hx(this.createMeasurementRecords())}observeMeasurements(e){return this.measurementObservers.add(e),e(),()=>{this.measurementObservers.delete(e)}}updateMeasurementLabels(){var t,i;if(this.measurementSegments.length===0)return;let e=this.getMeasurementMarkerSize()*3.2;for(let r of this.measurementSegments){this.updateMeasurementLineGeometry(r);let s=Wm(this.createMeasurementReading(r.start,r.end));r.label.removeFromParent();let a=r.label.material;(t=a.map)==null||t.dispose(),a.dispose();let o=this.createThreeMeasurementDraftingLayout(r.start,r.end),l=(i=o==null?void 0:o.labelPosition)!=null?i:new ie().addVectors(this.toMeasurementDisplayPoint(r.start),this.toMeasurementDisplayPoint(r.end)).multiplyScalar(.5);r.label=this.createMeasurementLabelSprite(s,l,e),this.scene.add(r.label)}this.markDirty()}captureMeasurementBaseState(e,t){this.measurementBaseRootScale.copy(e.scale),this.measurementBaseBounds=t?Za(t.min,t.max):null,this.measurementScale={x:1,y:1,z:1}}resetMeasurementCalibrationState(){this.measurementScale={x:1,y:1,z:1},this.measurementBaseRootScale.set(1,1,1),this.measurementBaseBounds=null,this.measurementMarkerPoints=[],this.invalidateMeasurementSnapInputCache()}applyMeasurementModelScale(){var t;if(!this.rootObject)return;this.applyRootMeasurementScale(),this.invalidateRootBoundsCache();let e=(t=this.getRootPreviewBounds())!=null?t:rn(this.rootObject);this.updateShadowFraming(e),this.bboxEnabled&&this.ensureBoundingBoxHelper(),this.removeGroundShadow(),this.removeGrid(),this.syncSceneHelpers(),this.fitCameraToObject(this.rootObject,e),this.applyRootMeasurementScale(),this.invalidateRootBoundsCache()}applyRootMeasurementScale(){if(!this.rootObject)return;let e=Ms(this.measurementScale);this.rootObject.scale.set(this.measurementBaseRootScale.x*e.x,this.measurementBaseRootScale.y*e.y,this.measurementBaseRootScale.z*e.z),this.rootObject.updateMatrixWorld(!0)}getMeasurementPivot(){return this.rootObject?this.rootObject.getWorldPosition(new ie):new ie}toMeasurementDisplayPoint(e){let t=rx(e,this.getMeasurementPivot(),this.measurementScale);return new ie(t.x,t.y,t.z)}toMeasurementBasePoint(e){let t=nx(e,this.getMeasurementPivot(),this.measurementScale);return new ie(t.x,t.y,t.z)}updateMeasurementOverlayPositions(){this.updateMeasurementTargetHelper();for(let e=0;e<this.measurementMarkers.length;e++){let t=this.measurementMarkerPoints[e];t&&this.measurementMarkers[e].position.copy(this.toMeasurementDisplayPoint(t))}for(let e of this.measurementSegments)this.updateMeasurementLineGeometry(e);this.pendingPoint&&this.previewLine&&this.schedulePreviewLineUpdate()}updateMeasurementLineGeometry(e){var s;let t=this.createThreeMeasurementDraftingLayout(e.start,e.end),i=(s=t==null?void 0:t.linePoints)!=null?s:[this.toMeasurementDisplayPoint(e.start),this.toMeasurementDisplayPoint(e.end)],r=e.line.geometry.getAttribute("position");if(r.count!==i.length)e.line.geometry.dispose(),e.line.geometry=new Bi().setFromPoints(i);else{for(let a=0;a<i.length;a++){let o=i[a];r.setXYZ(a,o.x,o.y,o.z)}r.needsUpdate=!0}t&&e.label.position.copy(t.labelPosition),e.line.geometry.computeBoundingSphere()}setRenderQuality(e,t=this.renderScale){this.quality=e,this.renderScale=t,this.syncGlobalEnvironmentForQuality(),this.applyShadowQuality(),this.resizeRenderer()}setRenderScale(e){return this.renderScale=Math.min(2,Math.max(.25,e)),this.resizeRenderer(),Number(this.renderScale.toFixed(2))}getRenderScale(){return Number(this.renderScale.toFixed(2))}getCameraZoomState(){let e=this.getCameraZoomRange();if(!e)return null;let t=e.mode==="distance"?(e.max-e.current)/(e.max-e.min):(e.current-e.min)/(e.max-e.min),i=qV(t);return{value:i,percentage:Math.round(i*100)}}setCameraZoom(e){let t=this.getCameraZoomRange();if(!t)return null;let i=qV(e);if(t.mode==="distance"){let r=t.max-i*(t.max-t.min),s=this.camera.position.clone().sub(this.controls.target);s.lengthSq()<Number.EPSILON&&s.copy(this.initialPosition).sub(this.initialTarget),s.normalize(),this.camera.position.copy(this.controls.target).addScaledVector(s,r),this.camera.lookAt(this.controls.target)}else this.camera.zoom=t.min+i*(t.max-t.min),this.camera.updateProjectionMatrix();return this.controls.update(),this.prepareInteractiveFrameBudget(),this.markDirty(),this.notifyCameraZoomChanged(),this.getCameraZoomState()}observeCameraZoom(e){return this.cameraZoomObservers.add(e),e(this.getCameraZoomState()),()=>{this.cameraZoomObservers.delete(e)}}getPerformanceSnapshot(){let e=this.smoothness.snapshot(),t=this.getQualitySnapshot();return{backend:"three",renderScale:Number(this.renderScale.toFixed(2)),quality:this.quality,pixelRatio:Number(this.renderer.getPixelRatio().toFixed(2)),interactivePixelRatioActive:this.interactivePixelRatioActive,renderDirty:this.renderDirty,renderObserverCount:this.renderObservers.size,renderObserverSettleFrames:this.renderObserverSettleFrames,frameBudgetPixelRatioScale:Number(this.frameBudgetPixelRatioScale.toFixed(2)),frameBudgetObserverStride:this.frameBudgetObserverStride,frameBudgetShadowDeferred:this.frameBudgetShadowDeferred,lastFrameDurationMs:Number(this.lastFrameDurationMs.toFixed(2)),averageRenderMs:e.averageRenderMs,p95RenderMs:e.p95RenderMs,maxRenderMs:e.maxRenderMs,renderedFrameCount:e.renderedFrameCount,slowFrameCount:e.slowFrameCount,idleFrameSkipCount:e.idleFrameSkipCount,adaptiveScaleChangeCount:e.adaptiveScaleChangeCount,viewportVisible:this.viewportVisible,disposalAudit:{...this.lastDisposalAudit},meshCount:t.geometry.meshCount,qualitySnapshot:t}}getQualitySnapshot(){let e=this.getGeometryQualityStats(),t=this.smoothness.snapshot();return{backend:"three",supportedFormats:["glb","gltf","stl","ply","obj"],colorPipeline:{outputColorSpace:String(this.renderer.outputColorSpace),toneMapping:this.renderer.toneMapping===Ys?"NoToneMapping":String(this.renderer.toneMapping),textureCount:this.textureAudit.textureCount,colorTextureCount:this.textureAudit.colorTextureCount,srgbColorTextureCount:this.textureAudit.srgbColorTextureCount},geometry:e,camera:{near:Number(this.camera.near.toPrecision(6)),far:Number(this.camera.far.toPrecision(6)),nearFarRatio:Number((this.camera.far/Math.max(this.camera.near,Number.EPSILON)).toPrecision(6))},performance:{renderScale:Number(this.renderScale.toFixed(2)),pixelRatio:Number(this.renderer.getPixelRatio().toFixed(2)),frameBudgetPixelRatioScale:Number(this.frameBudgetPixelRatioScale.toFixed(2)),frameBudgetObserverStride:this.frameBudgetObserverStride,viewportVisible:this.viewportVisible,renderedFrameCount:t.renderedFrameCount,idleFrameSkipCount:t.idleFrameSkipCount,slowFrameCount:t.slowFrameCount,averageRenderMs:t.averageRenderMs,p95RenderMs:t.p95RenderMs,maxRenderMs:t.maxRenderMs,adaptiveScaleChangeCount:t.adaptiveScaleChangeCount}}}setExplode(e,t){if(!this.rootObject)return;let i=Math.abs(e)>Number.EPSILON;!i&&!this.explodeStateActive||(kV(this.rootObject,e,t),this.explodeStateActive=i,this.invalidateRootBoundsCache(),this.markShadowDirty(),this.markDirty())}resetExplode(){this.rootObject&&this.explodeStateActive&&(OP(this.rootObject),this.explodeStateActive=!1,this.invalidateRootBoundsCache(),this.markShadowDirty(),this.markDirty())}focusWorldPoint(e){let t=new ie(e.x,e.y,e.z),i=this.camera.position.distanceTo(this.controls.target),r=t.clone().sub(this.camera.position).normalize(),s=t.clone().sub(r.multiplyScalar(i));this.animateCamera(s,t)}toggleDisassembly(){if(this.ensureDisassembly(),!this.disassembly)return!1;let e=!this.disassembly.isEnabled();e&&(this.focusSelectionEnabled=!1,this.clearFocusedMesh(),this.clearSelectionHighlight(),this.deactivateMeasurementMode(),this.deactivateSliceMode());let t=this.disassembly.setEnabled(e);return t||this.disassembly.reset(),t}resetDisassembly(){this.disassembly&&(this.disassembly.reset(),this.invalidateRootBoundsCache())}disableDisassemblyAndReset(){var e;(e=this.disassembly)!=null&&e.isEnabled()&&(this.disassembly.setEnabled(!1),this.resetDisassembly())}isDisassemblyEnabled(){var e,t;return(t=(e=this.disassembly)==null?void 0:e.isEnabled())!=null?t:!1}ensureDisassembly(){if(this.disassemblySetup||(this.disassemblySetup=!0,!this.rootObject))return;let e=this.getRenderableMeshes(this.rootObject);e.length!==0&&(this.disassembly=FV(this.scene,this.camera,this.renderer.domElement,this.rootObject,e,this.controls,()=>{this.invalidateRootBoundsCache(),this.markShadowDirty(),this.markDirty()},this.getChildRenderableMeshMap(this.rootObject)))}animateCamera(e,t){cancelAnimationFrame(this.cameraAnimHandle);let i=this.camera.position.clone(),r=this.controls.target.clone(),s=500,a=performance.now(),o=()=>{let l=performance.now()-a,c=Math.min(1,l/s),f=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2;this.camera.position.lerpVectors(i,e,f),this.controls.target.lerpVectors(r,t,f),this.controls.update(),this.markDirty(),c<1&&(this.cameraAnimHandle=window.requestAnimationFrame(o))};this.cameraAnimHandle=window.requestAnimationFrame(o)}startRenderLoop(){if(this.renderHandle||!this.viewportVisible||this.contextLost)return;let e=()=>{if(!this.viewportVisible||this.contextLost){this.renderHandle=0;return}let t=this.renderNow(performance.now());this.renderHandle=t?window.requestAnimationFrame(e):0};this.renderHandle=window.requestAnimationFrame(e)}renderNow(e){var l,c,f;let t=this.renderer.domElement;if(!this.viewportVisible||!t.isConnected||t.clientWidth<=0||t.clientHeight<=0)return!1;let i=Math.max(0,(e-this.clock.last)/1e3);this.clock.last=e;let r=this.controls.update(),s=!!this.mixer&&this.animationPlaying;if(s&&this.mixer&&(this.mixer.update(i),this.markShadowDirty()),this.restoreInteractivePixelRatioIfIdle(e,r),!r&&!s&&!this.renderDirty)return this.smoothness.recordIdleFrameSkip(),this.renderObserverSettleFrames>0&&(this.renderObserverSettleFrames--,this.notifyRenderObservers()),this.shouldContinueRenderLoop(r,s);this.renderDirty=!1,this.setRenderObserverSettleFrames(),(l=this.bboxHelper)==null||l.update(),(c=this.selectionHelper)==null||c.update(),(f=this.focusHelper)==null||f.update(),this.axesHelper&&this.axesHelper.visible&&this.axesHelper.position.copy(this.controls.target);let a=performance.now();this.renderer.render(this.scene,this.camera);let o=performance.now()-a;return this.smoothness.recordRenderedFrame(o,YV),this.updateFrameBudget(o),this.notifyRenderObservers(),this.shouldContinueRenderLoop(r,s)}shouldContinueRenderLoop(e,t){return WV({cameraMoved:e,animating:t,renderDirty:this.renderDirty,renderObserverCount:this.renderObservers.size,renderObserverSettleFrames:this.renderObserverSettleFrames})}notifyRenderObservers(){if(!(this.frameBudgetObserverStride>1&&(this.frameBudgetObserverCursor=(this.frameBudgetObserverCursor+1)%this.frameBudgetObserverStride,this.frameBudgetObserverCursor!==0)))for(let e of this.renderObservers)e()}markDirty(){this.renderDirty=!0,this.startRenderLoop()}markShadowDirty(){if(!this.renderer.shadowMap.enabled){this.frameBudgetShadowDeferred=!1,this.renderer.shadowMap.needsUpdate=!1;return}if(this.shouldDeferShadowRefresh()){this.frameBudgetShadowDeferred=!0;return}this.frameBudgetShadowDeferred=!1,this.renderer.shadowMap.needsUpdate=!0}prepareInteractiveFrameBudget(){let e=performance.now();this.interactionPixelRatioDeadline=e+Afe,this.activateInteractivePixelRatio()&&this.resizeRenderer()}activateInteractivePixelRatio(){if(this.interactivePixelRatioActive)return!1;let e=this.computePixelRatio(!1);return this.computePixelRatio(!0)>=e?!1:(this.interactivePixelRatioActive=!0,!0)}restoreInteractivePixelRatioIfIdle(e,t){!this.interactivePixelRatioActive||t||e<this.interactionPixelRatioDeadline||(this.interactivePixelRatioActive=!1,this.resetFrameBudget(),this.renderer.shadowMap.enabled&&this.frameBudgetShadowDeferred&&(this.frameBudgetShadowDeferred=!1,this.renderer.shadowMap.needsUpdate=!0),this.resizeRenderer())}computePixelRatio(e=this.interactivePixelRatioActive){let t=this.quality==="low"?.5:this.quality==="medium"?.75:1,i=Rr(),r=i?.85:1,s=Math.min(Efe,window.devicePixelRatio*t*r*this.renderScale);return e?Math.min(s,i?Tfe:Sfe)*this.frameBudgetPixelRatioScale:s}updateFrameBudget(e){if(this.lastFrameDurationMs=e,!!this.interactivePixelRatioActive){if(e>=YV?(this.frameBudgetSlowStreak++,this.frameBudgetFastStreak=0):e<=Rfe?(this.frameBudgetFastStreak++,this.frameBudgetSlowStreak=0):(this.frameBudgetSlowStreak=0,this.frameBudgetFastStreak=0),this.frameBudgetSlowStreak>=bfe){this.frameBudgetSlowStreak=0;let t=Math.max(Cfe,this.frameBudgetPixelRatioScale*yfe);t<this.frameBudgetPixelRatioScale-.01&&(this.frameBudgetPixelRatioScale=t,this.frameBudgetObserverStride=Math.min(Lfe,this.frameBudgetObserverStride+1),this.setRenderObserverSettleFrames(Math.max(xfe,Math.floor(XV/this.frameBudgetObserverStride))),this.smoothness.recordAdaptiveScaleChange(),this.resizeRenderer());return}this.frameBudgetFastStreak>=Mfe&&this.frameBudgetPixelRatioScale<1&&(this.frameBudgetFastStreak=0,this.frameBudgetPixelRatioScale=Math.min(1,this.frameBudgetPixelRatioScale*Ife),this.frameBudgetObserverStride=Math.max(1,this.frameBudgetObserverStride-1),this.setRenderObserverSettleFrames(),this.smoothness.recordAdaptiveScaleChange(),this.resizeRenderer())}}resetFrameBudget(){let e=this.frameBudgetPixelRatioScale!==1||this.frameBudgetObserverStride!==1;this.frameBudgetPixelRatioScale=1,this.frameBudgetSlowStreak=0,this.frameBudgetFastStreak=0,this.frameBudgetObserverStride=1,this.frameBudgetObserverCursor=0,this.setRenderObserverSettleFrames(),e&&this.markDirty()}setRenderObserverSettleFrames(e=XV){this.renderObserverSettleFrames=this.renderObservers.size>0?e:0}shouldDeferShadowRefresh(){return this.interactivePixelRatioActive&&this.frameBudgetPixelRatioScale<=Pfe}resizeRenderer(){let e=this.renderer.domElement,t=Math.max(1,Math.round(e.clientWidth||e.width||1)),i=Math.max(1,Math.round(e.clientHeight||e.height||1));this.renderer.setPixelRatio(this.computePixelRatio()),this.renderer.setSize(t,i,!1),this.camera instanceof vs?this.updateOrthographicFrustum(t/i):this.camera.aspect=t/i,this.camera.updateProjectionMatrix(),this.markDirty()}getCameraZoomRange(){if(!this.rootObject)return null;if(this.camera instanceof vs){let s=Math.max(this.initialZoom*.25,.05),a=Math.max(this.initialZoom*6,s*2),o=Number.isFinite(this.controls.minZoom)&&this.controls.minZoom>0?this.controls.minZoom:s,l=Number.isFinite(this.controls.maxZoom)&&this.controls.maxZoom>o?this.controls.maxZoom:a;return{mode:"zoom",current:Math.max(o,Math.min(this.camera.zoom,l)),min:o,max:l}}let e=this.camera.position.distanceTo(this.controls.target),t=Math.max(e*.08,1e-5),i=Number.isFinite(this.controls.minDistance)&&this.controls.minDistance>0?this.controls.minDistance:t,r=Number.isFinite(this.controls.maxDistance)&&this.controls.maxDistance>i?this.controls.maxDistance:Math.max(e*8,i*10);return{mode:"distance",current:Math.max(i,Math.min(e,r)),min:i,max:r}}notifyCameraZoomChanged(){if(this.cameraZoomObservers.size===0)return;let e=this.getCameraZoomState();for(let t of this.cameraZoomObservers)t(e)}computeOrthographicViewSpan(){var i;if(!this.rootObject)return 2;let e=(i=this.getRootPreviewBounds())!=null?i:rn(this.rootObject),t=Ui(e);return Math.max(Math.max(t.x,t.y,t.z,Number.EPSILON)*1.2,.001)}updateOrthographicFrustum(e){if(!(this.camera instanceof vs))return;let i=this.computeOrthographicViewSpan()/2,r=i*e;this.camera.left=-r,this.camera.right=r,this.camera.top=i,this.camera.bottom=-i}updateOrthographicFrustumForCamera(e,t){let r=this.computeOrthographicViewSpan()/2,s=r*t;e.left=-s,e.right=s,e.top=r,e.bottom=-r,e.updateProjectionMatrix()}switchCameraMode(e){if(this.cameraMode===e&&(e==="perspective"&&this.camera instanceof Sr||e==="orthographic"&&this.camera instanceof vs))return;let t=this.renderer.domElement,i=Math.max(1,Math.round(t.clientWidth||t.width||1)),r=Math.max(1,Math.round(t.clientHeight||t.height||1)),s=i/r,a=this.camera,o=a.position.clone(),l=this.controls.target.clone(),c=a.zoom||1,f=a.near,d=a.far;if(this.scene.remove(a),e==="orthographic"){let u=new vs(-1,1,1,-1,f,d);u.position.copy(o),u.zoom=c,u.lookAt(l),this.updateOrthographicFrustumForCamera(u,s),this.camera=u}else{let u=new Sr(this.initialFov,s,f,d);u.position.copy(o),u.zoom=c,u.lookAt(l),this.camera=u}this.scene.add(this.camera),this.controls.object=this.camera,this.controls.target.copy(l),this.controls.update(),this.cameraMode=e}applyCameraConfig(e){var i;let t=(i=e.mode)!=null?i:this.cameraMode;e.mode&&(this.initialCameraMode=e.mode),this.switchCameraMode(t),this.camera instanceof Sr&&typeof e.fov=="number"&&Number.isFinite(e.fov)&&(this.camera.fov=e.fov,this.initialFov=e.fov),e.position&&(this.camera.position.set(...e.position),this.initialPosition.set(...e.position)),e.lookAt&&(this.controls.target.set(...e.lookAt),this.camera.lookAt(this.controls.target),this.initialTarget.set(...e.lookAt)),typeof e.near=="number"&&Number.isFinite(e.near)&&(this.camera.near=e.near),typeof e.far=="number"&&Number.isFinite(e.far)&&(this.camera.far=e.far),typeof e.zoom=="number"&&Number.isFinite(e.zoom)&&(this.camera.zoom=e.zoom,this.initialZoom=e.zoom),this.camera.updateProjectionMatrix(),this.controls.update(),this.markDirty(),this.notifyCameraZoomChanged()}applyLightConfig(e){for(let i of this.configLights)this.disposeConfiguredLight(i);this.configLights.length=0;let t=e.length>0;for(let i of this.defaultLights)i.visible=!t;for(let i of e){let r=this.createConfiguredLight(i);r&&(this.configLights.push(r),r.parent!==this.camera&&this.scene.add(r))}this.syncShadowFeatures(),this.updateShadowFraming(),this.markShadowDirty(),this.markDirty()}applySceneConfig(e){if(this.sceneConfig={...this.sceneConfig,...e},e.transparent!==void 0||e.background!==void 0)if(this.sceneConfig.transparent)this.scene.background=null,this.renderer.setClearColor(wx,0);else if(this.sceneConfig.background){let t=new mt(this.sceneConfig.background);this.scene.background=t,this.renderer.setClearColor(t,1)}else this.scene.background=wx,this.renderer.setClearColor(wx,1);typeof e.autoRotate=="boolean"&&(this.controls.autoRotate=e.autoRotate),typeof e.autoRotateSpeed=="number"&&(this.controls.autoRotateSpeed=e.autoRotateSpeed),typeof e.axis=="boolean"&&this.syncAxisHelper(e.axis),this.syncSceneHelpers(),this.syncShadowFeatures(),this.markDirty()}installDefaultLighting(){let e=new _m(16777215,.96);e.name="default-global-ambient";let t=new gm(16777215,7172736,.34);t.name="default-hemi",this.defaultLights.push(e,t);for(let i of this.defaultLights)this.scene.add(i)}installGlobalEnvironment(){this.disposeGlobalEnvironment();let e=new Im(this.renderer),t=new RA;this.environmentTarget=e.fromScene(t,.04),this.scene.environment=this.environmentTarget.texture,this.scene.environmentIntensity=.48,t.dispose(),e.dispose()}syncGlobalEnvironmentForQuality(){if(this.quality==="low"){this.cancelGlobalEnvironmentInstall(),this.disposeGlobalEnvironment(),this.markDirty();return}this.rootObject&&!this.environmentTarget&&this.scheduleGlobalEnvironmentInstall()}scheduleGlobalEnvironmentInstall(){this.quality==="low"||this.environmentTarget||this.environmentInstallHandle||(this.environmentInstallHandle=window.setTimeout(()=>{this.environmentInstallHandle=0,!(this.quality==="low"||this.contextLost||!this.rootObject)&&(this.installGlobalEnvironment(),this.markDirty())},Dfe))}cancelGlobalEnvironmentInstall(){this.environmentInstallHandle&&(window.clearTimeout(this.environmentInstallHandle),this.environmentInstallHandle=0)}disposeGlobalEnvironment(){var e;this.cancelGlobalEnvironmentInstall(),this.scene.environment=null,(e=this.environmentTarget)==null||e.dispose(),this.environmentTarget=null}createConfiguredLight(e){var r,s,a,o,l,c,f;let t=e.color?new mt(e.color):new mt(16777215),i=(r=e.intensity)!=null?r:1;switch(e.type){case"ambient":return new _m(t,i);case"hemisphere":{let d=e.groundColor?new mt(e.groundColor):new mt(4473924);return new gm(t,d,i)}case"directional":{let d=new El(t,i),u=(s=e.position)!=null?s:[-1,2,1],h=(a=e.target)!=null?a:[0,0,0];return d.position.set(...u),d.target.position.set(...h),this.scene.add(d.target),d.castShadow=!!e.castShadow,d}case"point":{let d=new Mo(t,i),u=(o=e.position)!=null?o:[0,5,0];return d.position.set(...u),d.castShadow=!!e.castShadow,typeof e.decay=="number"&&(d.decay=e.decay),d}case"spot":{let d=new _c(t,i),u=(l=e.position)!=null?l:[0,5,0],h=(c=e.target)!=null?c:[0,0,0];return d.position.set(...u),d.target.position.set(...h),this.scene.add(d.target),d.angle=e.angle?e.angle*Math.PI/180:Math.PI/4,d.penumbra=(f=e.penumbra)!=null?f:.5,typeof e.decay=="number"&&(d.decay=e.decay),d.castShadow=!!e.castShadow,d}case"attachToCam":{let d=new Mo(t,i);return this.camera.add(d),d}default:return null}}disposeConfiguredLight(e){(e instanceof El||e instanceof _c)&&e.target.removeFromParent(),e.removeFromParent(),e.dispose()}prepareModelForQuality(e){let t=XU(this.renderer.capabilities.getMaxAnisotropy(),this.quality),i=new Set;for(let r of e)for(let s of Fn(r.material))i.has(s.uuid)||(i.add(s.uuid),this.prepareMaterialForQuality(s,t))}prepareMaterialForQuality(e,t){Yfe(this.textureAudit,BA(e,t))}applyShadowQuality(){let e=this.shadowMapSize(),t=!1;for(let i of this.allLights())!BP(i)||!i.castShadow||(i.shadow.mapSize.set(e,e),i.shadow.bias=-12e-5,i.shadow.normalBias=.018,i.shadow.needsUpdate=!0,t=!0);t&&(this.syncShadowFeatures(),this.markShadowDirty(),this.markDirty())}updateShadowFraming(e=this.getRootPreviewBounds()){if(!this.rootObject||!e)return;let t=mr(e),i=Ui(e),r=Math.max(i.x,i.y,i.z,Number.EPSILON),s=Math.max(r*1.8,.001),a=new ie(t.x,t.y,t.z),o=!1;for(let l of this.allLights())if(!(!BP(l)||!l.castShadow)){if(this.ensureMeshShadowFlags(),l.shadow.mapSize.set(this.shadowMapSize(),this.shadowMapSize()),l.shadow.bias=-12e-5,l.shadow.normalBias=.018,l instanceof El){let c=l.position.clone().sub(l.target.position);if(c.lengthSq()<.001&&c.set(4,7,5),l.target.position.copy(a),l.target.parent||this.scene.add(l.target),l.position.copy(a).add(c.normalize().multiplyScalar(s*2.4)),l.shadow.camera instanceof vs){let f=l.shadow.camera;f.left=-s,f.right=s,f.top=s,f.bottom=-s,f.near=.1,f.far=s*5,f.updateProjectionMatrix()}}l.shadow.needsUpdate=!0,o=!0}o&&this.markShadowDirty()}shadowMapSize(){return this.quality==="low"?512:this.quality==="medium"?1024:2048}allLights(){return[...this.defaultLights,...this.configLights]}hasActiveShadowFeatures(){return!!this.sceneConfig.groundShadow||this.allLights().some(e=>BP(e)&&e.castShadow)}syncShadowFeatures(){let e=this.hasActiveShadowFeatures();if(this.renderer.shadowMap.enabled!==e&&(this.renderer.shadowMap.enabled=e),!e){this.frameBudgetShadowDeferred=!1,this.renderer.shadowMap.needsUpdate=!1;return}this.ensureMeshShadowFlags(),this.renderer.shadowMap.needsUpdate=!0}ensureMeshShadowFlags(){if(!(!this.rootObject||this.meshShadowFlagsPrepared)){for(let e of this.getRenderableObjects(this.rootObject))La(e)&&(e.castShadow=!0,e.receiveShadow=!0);this.meshShadowFlagsPrepared=!0}}syncSceneHelpers(){this.sceneConfig.groundShadow?this.createGroundShadow():this.removeGroundShadow(),this.sceneConfig.grid?this.createGrid():this.removeGrid(),typeof this.sceneConfig.axis=="boolean"&&this.syncAxisHelper(this.sceneConfig.axis)}syncAxisHelper(e){if(!this.axesHelper){this.axesHelper=new Em(1.2);let t=this.axesHelper.material;t.depthTest=!1,t.depthWrite=!1,this.axesHelper.renderOrder=999,this.scene.add(this.axesHelper)}this.axesHelper.visible=e,this.axesHelper.position.copy(this.controls.target)}createGroundShadow(){var l;if(!this.rootObject||this.groundShadowMesh)return;this.ensureMeshShadowFlags();let e=(l=this.getRootPreviewBounds())!=null?l:rn(this.rootObject),t=mr(e),i=Ui(e),r=Math.max(i.x,i.z,Number.EPSILON),s=Math.max(r*3,.001),a=e.min.y-Math.max(s*.002,1e-5),o=new ci(new pu(s,s),new y_({color:0,opacity:vfe,transparent:!0}));o.name="ai3d-ground-shadow",o.rotation.x=-Math.PI/2,o.position.set(t.x,a,t.z),o.receiveShadow=!0,o.renderOrder=-1,this.scene.add(o),this.groundShadowMesh=o}removeGroundShadow(){if(this.groundShadowMesh){this.groundShadowMesh.removeFromParent(),this.groundShadowMesh.geometry.dispose();for(let e of Fn(this.groundShadowMesh.material))e.dispose();this.groundShadowMesh=null}}createGrid(){var o;if(!this.rootObject||this.gridHelper)return;let e=(o=this.getRootPreviewBounds())!=null?o:rn(this.rootObject),t=mr(e),i=Ui(e),r=Math.max(i.x,i.z,Number.EPSILON),s=Math.max(r*2,.001),a=new w_(s,20,7305093,3423046);a.name="ai3d-grid",a.position.set(t.x,e.min.y-Math.max(s*.003,1e-5),t.z);for(let l of Fn(a.material))l.transparent=!0,l.opacity=.42;this.scene.add(a),this.gridHelper=a}removeGrid(){if(this.gridHelper){this.gridHelper.removeFromParent(),this.gridHelper.geometry.dispose();for(let e of Fn(this.gridHelper.material))e.dispose();this.gridHelper=null}}dispatchPick(e){var c,f,d;if(!this.rootObject||(c=this.disassembly)!=null&&c.isEnabled())return;let t=this.renderer.domElement.getBoundingClientRect();this.pointer.x=(e.clientX-t.left)/t.width*2-1,this.pointer.y=-((e.clientY-t.top)/t.height)*2+1,this.raycaster.setFromCamera(this.pointer,this.camera);let i=this.raycaster.intersectObjects(this.getRenderableObjects(this.rootObject),!1)[0],r=Kf(i==null?void 0:i.object)?i.object:null,s=this.getRenderableMeshes(this.rootObject),a=this.getChildRenderableMeshMap(this.rootObject),o=r?Mx(this.rootObject,r,s,a):null,l={mesh:o,pickedPoint:(d=(f=i==null?void 0:i.point)==null?void 0:f.clone())!=null?d:null,screenX:e.clientX,screenY:e.clientY,modifiers:{altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,shiftKey:e.shiftKey}};if(this._lastPickResult=l,this.measurementActive){if(e.altKey){if(!(i!=null&&i.point))return;this.setMeasurementSnapKind("free"),this.addMeasurementPoint(i.point.clone());return}if(!this.measurementTargetObject){o&&this.setMeasurementTargetObject(o);return}let u=this.getMeasurementTargetRaycastPoint(i);if(!u){this.setMeasurementSnapKind(null);return}this.addMeasurementPoint(this.resolveMeasurementPickPoint(u,!1));return}this.focusSelectionEnabled&&o?(this.clearSelectionHighlight(),this.focusedObject!==o&&this.setFocusedObject(o)):this.focusSelectionEnabled?this.clearSelectionHighlight():this.updateSelectionHighlight(o),this._onPickCallbacks.forEach(u=>u(l))}clearLoadedModel(e="model-switch"){var t,i;if(this.cancelGlobalEnvironmentInstall(),(t=this.disassembly)==null||t.dispose(),this.disassembly=null,this.disassemblySetup=!1,this.explodeStateActive=!1,this.meshShadowFlagsPrepared=!1,this.invalidateMeshCache(),this.markDirty(),this.clearFocusedMesh(),this.renderer.domElement.classList.remove("ai3d-slice-active","ai3d-slice-dragging","ai3d-slice-rotate"),this.restoreSliceMaterialClipping(),this.restoreSliceLocalClippingEnabled(),this.disposeSliceOverlay(!1),this.clearSelectionHighlight(),this.disposeMeasurementOverlays(!0),this.resetMeasurementCalibrationState(),this.wireframeEnabled=!1,this.wireframeOriginalMaterials.clear(),this.stlMaterial=null,this.notifyCameraZoomChanged(),(i=this.bboxHelper)==null||i.removeFromParent(),this.bboxHelper=null,this.bboxEnabled=!1,this.removeGroundShadow(),this.removeGrid(),this.mixer=null,this.animationPlaying=!1,!this.rootObject){this.lastDisposalAudit={reason:e,meshCount:0,geometryCount:0,materialCount:0,textureCount:0,objectCount:0,timestamp:performance.now()};return}this.scene.remove(this.rootObject),this.lastDisposalAudit=this.disposeObjectGraph(this.rootObject,e),this.rootObject=null,this.invalidateMeshCache(),this.markShadowDirty()}disposeObjectGraph(e,t){var c;let i=new Set,r=new Set,s=new Set,a=0,o=0,l=f=>{La(f)&&a++;let d=f.geometry;d&&!i.has(d.uuid)&&(d.dispose(),i.add(d.uuid));for(let u of Fn(f.material))this.disposeMaterialWithTextures(u,r,s)};if(this.cachedRenderables&&this.cachedRenderableRoot===e){o=(c=this.cachedRenderableObjectCount)!=null?c:this.cachedRenderables.length;for(let f of this.cachedRenderables)l(f)}else e.traverse(f=>{o++,Kf(f)&&l(f)});return{reason:t,meshCount:a,geometryCount:i.size,materialCount:r.size,textureCount:s.size,objectCount:o,timestamp:performance.now()}}disposeMaterialWithTextures(e,t,i){if(t.has(e.uuid))return;let r=e;for(let s of Object.values(r))if(s instanceof Lr&&!i.has(s.uuid))s.dispose(),i.add(s.uuid);else if(Array.isArray(s))for(let a of s)a instanceof Lr&&!i.has(a.uuid)&&(a.dispose(),i.add(a.uuid));e.dispose(),t.add(e.uuid)}fitCameraToObject(e,t){var l;let i=(l=t!=null?t:this.getRootPreviewBounds(e))!=null?l:rn(e),r=oV(i);this.initialTarget.set(r.target.x,r.target.y,r.target.z),this.initialPosition.set(r.position.x,r.position.y,r.position.z),this.initialFov=45;let s=Ui(i),a=Math.max(s.x,s.y,s.z,Number.EPSILON),o=this.initialPosition.distanceTo(this.initialTarget);this.controls.minDistance=Math.max(r.near*4,a*.02,1e-5),this.controls.maxDistance=Math.max(o*8,this.controls.minDistance*10),this.controls.minZoom=.25,this.controls.maxZoom=8,this.raycaster.params.Points={threshold:Math.max(a*.01,1e-5)},this.raycaster.params.Line={threshold:Math.max(a*.002,1e-5)},this.occlusionRaycaster.params.Points={threshold:Math.max(a*.006,1e-5)},this.occlusionRaycaster.params.Line={threshold:Math.max(a*.001,1e-5)},this.resetView(),this.axesHelper&&(this.axesHelper.position.copy(this.controls.target),this.axesHelper.scale.setScalar(Math.max(a*.25,5e-4))),this.camera.near=r.near,this.camera.far=r.far,this.camera.updateProjectionMatrix(),this.markDirty(),this.notifyCameraZoomChanged()}getAnnotationCameraStateKey(){return $A([{value:this.camera.position.x,digits:3},{value:this.camera.position.y,digits:3},{value:this.camera.position.z,digits:3},{value:this.controls.target.x,digits:2},{value:this.controls.target.y,digits:2},{value:this.controls.target.z,digits:2},{value:this.camera instanceof Sr?this.camera.fov:this.camera.zoom,digits:this.camera instanceof Sr?2:3}])}projectAnnotationWorldPoint(e,t){let i=this.renderer.domElement;return!i.isConnected||i.clientWidth===0||i.clientHeight===0?!1:(this.scene.updateMatrixWorld(),this.camera.updateMatrixWorld(),this.annotationProjection.set(e.x,e.y,e.z).project(this.camera),hV(this.annotationProjection,i,t))}isAnnotationWorldPointOccluded(e){if(!this.rootObject)return!1;let t=kf(ct(this.camera.position),e);if(!t)return!1;this.rootObject.updateWorldMatrix(!0,!0),this.annotationDirection.set(t.direction.x,t.direction.y,t.direction.z),this.occlusionRaycaster.set(this.camera.position,this.annotationDirection),this.occlusionRaycaster.far=t.distance;let i=this.occlusionRaycaster.intersectObjects(this.getRenderableObjects(this.rootObject),!1)[0];return!!i&&Gf(i.distance,t.distance,t.epsilon)}getRenderableMeshes(e){if(this.cachedMeshes&&this.cachedMeshRoot===e)return this.cachedMeshes;let t=[];return e.traverse(i=>{La(i)&&i.geometry&&t.push(i)}),this.cachedMeshes=t,this.cachedMeshRoot=e,t}getRenderableObjects(e){if(this.cachedRenderables&&this.cachedRenderableRoot===e)return this.cachedRenderables;let t=[],i=0;return e.traverse(r=>{i++,Kf(r)&&r.geometry&&t.push(r)}),this.cachedRenderables=t,this.cachedRenderableRoot=e,this.cachedRenderableObjectCount=i,t}getChildRenderableMeshMap(e){return this.cachedChildMeshMap&&this.cachedChildMeshMapRoot===e?this.cachedChildMeshMap:(this.cachedChildMeshMap=Qm(e,this.getRenderableMeshes(e)),this.cachedChildMeshMapRoot=e,this.cachedChildMeshMap)}getRenderableBoundsMap(e){return this.cachedRenderableBoundsMap&&this.cachedRenderableBoundsMapRoot===e?this.cachedRenderableBoundsMap:(this.cachedRenderableBoundsMap=IV(this.getRenderableObjects(e)),this.cachedRenderableBoundsMapRoot=e,this.cachedRenderableBoundsMap)}getGeometryQualityStats(){var e;return this.rootObject?(this.cachedGeometryQualityStats||(this.cachedGeometryQualityStats=NV(this.rootObject,this.getRenderableObjects(this.rootObject),(e=this.getRootPreviewBounds())!=null?e:void 0,this.getRenderableBoundsMap(this.rootObject))),this.cachedGeometryQualityStats):{meshCount:0,pointCloudCount:0,smallPartCount:0,smallestPartSpan:null,modelSpan:null}}invalidateMeshCache(){this.cachedMeshes=null,this.cachedMeshRoot=null,this.cachedRenderables=null,this.cachedRenderableRoot=null,this.cachedRenderableObjectCount=null,this.cachedChildMeshMap=null,this.cachedChildMeshMapRoot=null,this.cachedRenderableBoundsMap=null,this.cachedRenderableBoundsMapRoot=null,this.invalidateRootBoundsCache()}invalidateRootBoundsCache(){this.cachedRootPreviewBounds=null,this.cachedRootPreviewBoundsObject=null,this.cachedRenderableBoundsMap=null,this.cachedRenderableBoundsMapRoot=null,this.cachedGeometryQualityStats=null}getRootPreviewBounds(e=this.rootObject){return e?this.cachedRootPreviewBounds&&this.cachedRootPreviewBoundsObject===e?this.cachedRootPreviewBounds:(this.cachedRootPreviewBounds=rn(e),this.cachedRootPreviewBoundsObject=e,this.cachedRootPreviewBounds):null}getSliceRange(){let e=Du(this.getRootPreviewBounds(),{normal:ct(this.sliceNormal),offset:this.sliceOffset});if(!e||!this.sliceCenter)return e;let t=this.sliceCenter.dot(this.sliceNormal),i=Ia((t-e.min)/e.span);return this.sliceOffset=i,{...e,offset:i,distance:t,point:ct(this.sliceCenter)}}setSliceCenterFromOffset(e){let t=Du(this.getRootPreviewBounds(),{normal:ct(this.sliceNormal),offset:e});t&&(this.sliceCenter=new ie(t.point.x,t.point.y,t.point.z))}alignSlicePlaneToWorld(){this.sliceNormal.set(Dr.x,Dr.y,Dr.z),this.rebuildSlicePlaneAxes(new ie(1,0,0)),this.sliceReferenceNormal.copy(this.sliceNormal),this.sliceCenter=null,this.setSliceCenterFromOffset(this.sliceOffset)}rebuildSlicePlaneAxes(e=this.slicePlaneX){let t=this.sliceNormal.clone().normalize(),i=e.clone().addScaledVector(t,-e.dot(t));i.lengthSq()<=1e-6&&(i.copy(Math.abs(t.y)<.92?new ie(0,1,0):new ie(1,0,0)),i.addScaledVector(t,-i.dot(t))),i.normalize(),this.slicePlaneX.copy(i),this.slicePlaneY.crossVectors(t,i).normalize()}deactivateSliceMode(){return!this.sliceActive&&!this.sliceDragState?!1:(this.endSliceDrag(null,!0),this.sliceActive=!1,this.syncSliceClipping(),this.notifySliceChanged(),!0)}beginSliceDrag(e){if(!this.rootObject||!this.sliceActive)return!1;let t=this.getSlicePointerTarget(e);if(!t)return!1;let i=this.renderer.domElement.getBoundingClientRect(),r=t.mode;this.sliceInteractionMode=r;let s={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,mode:r,moved:!1};if(r==="rotate"){let a=this.getSliceRange();if(!a)return!1;let o=this.getSlicePointerPolar(e,t.axis);if(!o)return!1;this.sliceDragState={...s,mode:r,axis:t.axis,startNormal:ct(this.sliceNormal),anchorPoint:{...a.point},rotationAxis:ct(t.axis==="x"?this.slicePlaneX:t.axis==="y"?this.slicePlaneY:this.sliceNormal),startPlaneX:ct(this.slicePlaneX),startPlaneY:ct(this.slicePlaneY),screenTangent:t.screenTangent,radiansPerPixel:t.radiansPerPixel,rotationRadians:0,startPointerAngle:o.angle,currentPointerAngle:o.angle,snapMode:Ym(o.radiusRatio),useScreenRotation:Ex(o.rayPlaneAlignment),labelPoint:t.labelPoint}}else this.sliceDragState={...s,mode:r,startOffset:this.sliceOffset,screenAxis:this.getSliceScreenAxis(),pixelsToOffset:1/Math.max(Math.min(i.width,i.height)*.72,1)};this.syncSliceClipping(),this.lastPointerDown=null,this.controls.enabled=!1,this.renderer.domElement.classList.add("ai3d-slice-dragging");try{this.renderer.domElement.setPointerCapture(e.pointerId)}catch(a){}return e.preventDefault(),e.stopImmediatePropagation(),this.prepareInteractiveFrameBudget(),this.notifySliceChanged(),!0}getSlicePointerPolar(e,t,i,r){let s=this.getSliceRange(),a=this.getRootPreviewBounds();if(!s||!a)return null;let o=this.renderer.domElement.getBoundingClientRect();if(o.width<=0||o.height<=0)return null;this.pointer.x=(e.clientX-o.left)/o.width*2-1,this.pointer.y=-((e.clientY-o.top)/o.height)*2+1,this.raycaster.setFromCamera(this.pointer,this.camera);let l=r!=null?r:s.point,c=new ie(l.x,l.y,l.z),f=i?{x:new ie(i.x.x,i.x.y,i.x.z),y:new ie(i.y.x,i.y.y,i.y.z),z:new ie(i.z.x,i.z.y,i.z.z)}:{x:this.slicePlaneX,y:this.slicePlaneY,z:this.sliceNormal},d=(t==="x"?f.x:t==="y"?f.y:f.z).clone().normalize(),u=(t==="x"?f.y:t==="y"?f.z:f.x).clone().normalize(),h=(t==="x"?f.z:t==="y"?f.x:f.y).clone().normalize(),m=new ps(d,-d.dot(c)),g=this.raycaster.ray.intersectPlane(m,new ie);if(!g)return null;let p=g.sub(c),_=Math.max(Rs(a)*.62,s.span*.16,Number.EPSILON);return{angle:Math.atan2(p.dot(h),p.dot(u)),radiusRatio:p.length()/_,rayPlaneAlignment:Math.abs(this.raycaster.ray.direction.dot(d))}}getSlicePointerTarget(e){if(e.altKey)return null;let t=this.getRootPreviewBounds(),i=this.getSliceRange();if(!t||!i)return null;let r=this.renderer.domElement.getBoundingClientRect();if(r.width<=0||r.height<=0)return null;let s=u=>{let h=new ie(u.x,u.y,u.z).project(this.camera);return{x:r.left+(h.x+1)*r.width*.5,y:r.top+(1-h.y)*r.height*.5}},a={x:e.clientX,y:e.clientY},o=e.pointerType==="touch"?28:14,l=s(i.point);if(Math.hypot(a.x-l.x,a.y-l.y)<=o*1.35)return{mode:"move"};let c=Km(t,i,64,{x:ct(this.slicePlaneX),y:ct(this.slicePlaneY),z:ct(this.sliceNormal)});if(c.moveGuide.some(([u,h])=>{let m=s(u),g=s(h);return KV(a,m,g)<=o}))return{mode:"move"};let f=null,d=Number.POSITIVE_INFINITY;for(let u of["x","y","z"]){let h=c.rotationRings[u].map(([g,p])=>[s(g),s(p)]),m=h.reduce((g,[p,_])=>g+Math.hypot(_.x-p.x,_.y-p.y),0);for(let[g,p]of h){let _=KV(a,g,p);if(_>o||_>=d)continue;let v=new Ct(p.x-g.x,p.y-g.y);v.lengthSq()<=Number.EPSILON||(d=_,f={mode:"rotate",axis:u,screenTangent:v.normalize(),radiansPerPixel:Math.PI*2/Math.max(m,80),labelPoint:{...i.point}})}}return f}updateSliceDrag(e){let t=this.sliceDragState;if(!t||t.pointerId!==e.pointerId)return!1;let i=e.clientX-t.startX,r=e.clientY-t.startY,s=Math.hypot(i,r)>2;if(t.moved=t.moved||s,e.preventDefault(),e.stopImmediatePropagation(),this.prepareInteractiveFrameBudget(),t.mode==="rotate"){let l=this.getSlicePointerPolar(e,t.axis,{x:t.startPlaneX,y:t.startPlaneY,z:t.startNormal},t.anchorPoint);if(!l)return!0;let c=(i*t.screenTangent.x+r*t.screenTangent.y)*t.radiansPerPixel,f=cv(t.useScreenRotation?c:l.angle-t.startPointerAngle);t.useScreenRotation||(t.snapMode=Ym(l.radiusRatio,t.snapMode)),t.rotationRadians=vx(f,t.snapMode),t.currentPointerAngle=t.startPointerAngle+t.rotationRadians;let d=Yf(t.startNormal,t.rotationAxis,t.rotationRadians),u=Yf(t.startPlaneX,t.rotationAxis,t.rotationRadians),h=Yf(t.startPlaneY,t.rotationAxis,t.rotationRadians),m=this.sliceNormal.distanceToSquared(new ie(d.x,d.y,d.z)),g=this.slicePlaneX.distanceToSquared(new ie(u.x,u.y,u.z))+this.slicePlaneY.distanceToSquared(new ie(h.x,h.y,h.z));if(m<=1e-6&&g<=1e-6)return!0;if(m>1e-6){let p=this.getRootPreviewBounds();this.sliceNormal.set(d.x,d.y,d.z),this.sliceCenter=new ie(t.anchorPoint.x,t.anchorPoint.y,t.anchorPoint.z),this.sliceOffset=Xm(p,d,t.anchorPoint)}return this.slicePlaneX.set(u.x,u.y,u.z),this.slicePlaneY.set(h.x,h.y,h.z),this.syncSliceClipping(),this.notifySliceChanged(),!0}let a=i*t.screenAxis.x+r*t.screenAxis.y,o=Ia(t.startOffset+a*t.pixelsToOffset);return Math.abs(o-this.sliceOffset)<=5e-4||(this.sliceOffset=o,this.setSliceCenterFromOffset(o),this.syncSliceClipping(),this.notifySliceChanged()),!0}endSliceDrag(e,t=!1){let i=this.sliceDragState;if(!i||e&&i.pointerId!==e.pointerId)return!1;if(this.sliceDragState=null,this.controls.enabled=!0,this.renderer.domElement.classList.remove("ai3d-slice-dragging"),this.syncSliceClipping(),e){try{this.renderer.domElement.releasePointerCapture(e.pointerId)}catch(r){}e.preventDefault(),e.stopImmediatePropagation()}return(!t||i.moved)&&this.notifySliceChanged(),this.markDirty(),!0}getSliceScreenAxis(){let e=this.getSliceRange(),t=this.getRootPreviewBounds();if(!e||!t)return new Ct(0,-1);let i=Math.max(Rs(t),e.span*.25,Number.EPSILON),r=new ie(e.point.x,e.point.y,e.point.z),s=new ie(e.normal.x,e.normal.y,e.normal.z).normalize(),a=r.clone().project(this.camera),o=r.clone().add(s.multiplyScalar(i*.35)).project(this.camera),l=new Ct(o.x-a.x,-(o.y-a.y));return!Number.isFinite(l.lengthSq())||l.lengthSq()<=1e-6?new Ct(0,-1):l.normalize()}updateThreeSlicePlanes(e){let t=Tx(e,"three");if(!(t!=null&&t.length))return!1;let i=t[0];return this.slicePlanes.length===1?(this.slicePlanes[0].normal.set(i.normal.x,i.normal.y,i.normal.z),this.slicePlanes[0].constant=i.constant):this.slicePlanes=[new ps(new ie(i.normal.x,i.normal.y,i.normal.z),i.constant)],!0}syncSliceClipping(){if(this.renderer.domElement.classList.toggle("ai3d-slice-active",this.sliceActive),this.renderer.domElement.classList.toggle("ai3d-slice-rotate",this.sliceActive&&this.sliceInteractionMode==="rotate"),!this.rootObject||!this.sliceActive){this.restoreSliceMaterialClipping(),this.disposeSliceOverlay(),this.slicePlanes=[],this.restoreSliceLocalClippingEnabled(),this.renderer.domElement.classList.remove("ai3d-slice-dragging"),this.renderer.domElement.classList.remove("ai3d-slice-rotate"),this.markDirty();return}let e=this.getSliceRange();if(!this.updateThreeSlicePlanes(e)){this.restoreSliceMaterialClipping(),this.disposeSliceOverlay(),this.restoreSliceLocalClippingEnabled(),this.markDirty();return}this.syncSliceOverlay(e),this.sliceOriginalLocalClippingEnabled===null&&(this.sliceOriginalLocalClippingEnabled=this.renderer.localClippingEnabled),this.renderer.localClippingEnabled=!0;let t=new Set;for(let i of this.getRenderableMeshes(this.rootObject))for(let r of Fn(i.material)){t.add(r.uuid);let s=!this.sliceOriginalMaterialClipping.has(r.uuid);s&&this.sliceOriginalMaterialClipping.set(r.uuid,{material:r,clippingPlanes:r.clippingPlanes,clipIntersection:r.clipIntersection,clipShadows:r.clipShadows}),(s||r.clippingPlanes!==this.slicePlanes)&&(r.clippingPlanes=this.slicePlanes,r.clipIntersection=!1,r.clipShadows=!0,r.needsUpdate=!0)}for(let[i,r]of Array.from(this.sliceOriginalMaterialClipping.entries()))t.has(i)||(r.material.clippingPlanes=r.clippingPlanes,r.material.clipIntersection=r.clipIntersection,r.material.clipShadows=r.clipShadows,r.material.needsUpdate=!0,this.sliceOriginalMaterialClipping.delete(i));this.markDirty()}restoreSliceMaterialClipping(){for(let e of this.sliceOriginalMaterialClipping.values())e.material.clippingPlanes=e.clippingPlanes,e.material.clipIntersection=e.clipIntersection,e.material.clipShadows=e.clipShadows,e.material.needsUpdate=!0;this.sliceOriginalMaterialClipping.clear()}restoreSliceLocalClippingEnabled(){this.sliceOriginalLocalClippingEnabled!==null&&(this.renderer.localClippingEnabled=this.sliceOriginalLocalClippingEnabled,this.sliceOriginalLocalClippingEnabled=null)}syncSliceOverlay(e){var L,w,G,O,N,B;this.disposeSliceOverlay(!1);let t=this.getRootPreviewBounds();if(!t||!e)return;let i={x:ct(this.slicePlaneX),y:ct(this.slicePlaneY),z:ct(this.sliceNormal)},r=Sx(t,e,.12,i),s=this.createSliceOverlayPlane(r),a=this.sliceInteractionMode==="rotate"?kfe:Ufe,o=this.createSliceOverlayLines(r.segments,a,Xfe),l=this.createSliceOverlayLines(this.createSliceNormalGuide(t,e),Vfe,.92),c=((L=this.sliceDragState)==null?void 0:L.mode)==="rotate"?{[this.sliceDragState.axis]:this.sliceDragState.currentPointerAngle}:void 0,f=((w=this.sliceDragState)==null?void 0:w.mode)==="rotate"?{x:this.sliceDragState.startPlaneX,y:this.sliceDragState.startPlaneY,z:this.sliceDragState.startNormal}:i,d=Km(t,e,64,f,c),u=((G=this.sliceDragState)==null?void 0:G.mode)==="rotate"?this.sliceDragState.axis:null,h=((O=this.sliceDragState)==null?void 0:O.mode)==="move",m=(V,q)=>({color:u===V?zfe:q,opacity:u?u===V?.98:0:h?.1:.34,tickOpacity:u?u===V?.82:0:h?.04:.14}),g=m("x",NP),p=m("y",wP),_=m("z",FP),v=this.createSliceOverlayLines(d.rotationRings.x,g.color,g.opacity),E=this.createSliceOverlayLines(d.rotationRings.y,p.color,p.opacity),S=this.createSliceOverlayLines(d.rotationRings.z,_.color,_.opacity),T=this.createSliceOverlayLines(d.rotationTicks.x,g.color,g.tickOpacity),A=this.createSliceOverlayLines(d.rotationTicks.y,p.color,p.tickOpacity),R=this.createSliceOverlayLines(d.rotationTicks.z,_.color,_.tickOpacity),M=this.createSliceOverlayLines(d.moveGuide,Wfe,u?.22:.96),I=u?this.createSliceOverlayLines(d.rotationArcs[u],u==="x"?NP:u==="y"?wP:FP,1):null,C=u?this.createSliceOverlayLines(d.rotationArrowheads[u],u==="x"?NP:u==="y"?wP:FP,1):null;if(this.sliceOverlayPlanes.push(s),this.sliceOverlayLines.push(o,l,v,E,S,T,A,R,M),this.scene.add(s,o,l,v,E,S,T,A,R,M),u&&I&&C){this.sliceOverlayLines.push(I,C),this.scene.add(I,C);let V=this.sliceDragState;if((V==null?void 0:V.mode)==="rotate"){let q=(V.currentPointerAngle*180/Math.PI%360+360)%360,K=d.rotationArcs[u],J=(B=(N=K[K.length-1])==null?void 0:N[1])!=null?B:V.labelPoint,Y=this.createMeasurementLabelSprite({primary:`${u.toUpperCase()}: ${q.toFixed(1)}\xB0`,secondary:""},new ie(J.x,J.y,J.z),this.getMeasurementMarkerSize()*2.5);this.sliceOverlayLabels.push(Y),this.scene.add(Y)}}}createSliceOverlayPlane(e){let t=new Bi,i=e.corners;t.setAttribute("position",new gi([i[0].x,i[0].y,i[0].z,i[1].x,i[1].y,i[1].z,i[2].x,i[2].y,i[2].z,i[0].x,i[0].y,i[0].z,i[2].x,i[2].y,i[2].z,i[3].x,i[3].y,i[3].z],3)),t.computeVertexNormals();let r=new Kn({color:this.sliceInteractionMode==="rotate"?Gfe:Bfe,transparent:!0,opacity:Hfe,side:Xs,depthWrite:!1,depthTest:!1}),s=new ci(t,r);return s.name="ai3d-slice-plane",s.renderOrder=995,s}createSliceOverlayLines(e,t,i){let r=new Bi,s=[];for(let[l,c]of e)s.push(l.x,l.y,l.z,c.x,c.y,c.z);r.setAttribute("position",new gi(s,3));let a=new Ln({color:t,transparent:!0,opacity:i,depthWrite:!1,depthTest:!1}),o=new _s(r,a);return o.name="ai3d-slice-frame",o.renderOrder=996,o}createSliceNormalGuide(e,t){var o;let i=Math.max(Rs(e),t.span*.25,Number.EPSILON),r=(o=wn(t.normal))!=null?o:Dr,s=t.point,a={x:s.x+r.x*i*.26,y:s.y+r.y*i*.26,z:s.z+r.z*i*.26};return[[s,a]]}disposeSliceOverlay(e=!0){var t;for(let i of this.sliceOverlayPlanes){i.removeFromParent(),i.geometry.dispose();for(let r of Fn(i.material))r.dispose()}for(let i of this.sliceOverlayLines){i.removeFromParent(),i.geometry.dispose();for(let r of Fn(i.material))r.dispose()}for(let i of this.sliceOverlayLabels)i.removeFromParent(),(t=i.material.map)==null||t.dispose(),i.material.dispose();this.sliceOverlayPlanes=[],this.sliceOverlayLines=[],this.sliceOverlayLabels=[],e&&this.markDirty()}notifySliceChanged(){for(let e of this.sliceObservers)e()}ensureBoundingBoxHelper(){var e;this.rootObject&&((e=this.bboxHelper)==null||e.removeFromParent(),this.bboxHelper=new Sl(this.rootObject,16436245),this.scene.add(this.bboxHelper))}updateSelectionHighlight(e){var t;if(!this.rootObject||!e){this.clearSelectionHighlight();return}this.highlightedObject===e&&this.selectionHelper||((t=this.selectionHelper)==null||t.removeFromParent(),this.selectionHelper=new Sl(e,4890367),this.scene.add(this.selectionHelper),this.highlightedObject=e,this.markDirty())}setFocusedObject(e){var r,s;if(!this.rootObject||!e){this.clearFocusedMesh();return}if(this.focusedObject===e)return;let t=this.getRenderableMeshes(this.rootObject),i=La(e)?[e]:(r=this.getChildRenderableMeshMap(this.rootObject).get(e))!=null?r:[];if(i.length===0&&!Kf(e)){this.clearFocusedMesh();return}this.originalMaterials.size===0?this.applyInitialFocusMaterials(t,i):this.applyFocusSelectionDelta(i),(s=this.focusHelper)==null||s.removeFromParent(),this.focusHelper=new Sl(e,3065087),this.scene.add(this.focusHelper),this.focusedObject=e,this.focusedSelectedMeshes.clear();for(let a of i)this.focusedSelectedMeshes.set(a.id,a);this.syncSliceClipping(),this.markDirty()}clearFocusedMesh(){var e;this.restoreFocusedMaterials(),this.disposeFocusDimMaterials(),this.originalMaterials.clear(),this.focusedSelectedMeshes.clear(),(e=this.focusHelper)==null||e.removeFromParent(),this.focusHelper=null,this.focusedObject=null,this.syncSliceClipping(),this.markDirty()}restoreFocusedMaterials(){if(this.rootObject)for(let e of this.getRenderableMeshes(this.rootObject)){let t=this.originalMaterials.get(e.id);t&&(e.material=t)}}applyInitialFocusMaterials(e,t){let i=new Set(t.map(r=>r.id));for(let r of e)this.originalMaterials.set(r.id,r.material),!i.has(r.id)&&(r.material=this.focusDimMaterialCache.get(r.material))}applyFocusSelectionDelta(e){var i,r;let t=new Set(e.map(s=>s.id));for(let[s,a]of this.focusedSelectedMeshes){if(t.has(s))continue;let o=(i=this.originalMaterials.get(s))!=null?i:a.material;this.originalMaterials.has(s)||this.originalMaterials.set(s,o),a.material=this.focusDimMaterialCache.get(o)}for(let s of e){let a=(r=this.originalMaterials.get(s.id))!=null?r:s.material;this.originalMaterials.has(s.id)||this.originalMaterials.set(s.id,a),s.material=a}}disposeFocusDimMaterials(){this.focusDimMaterialCache.clear()}clearSelectionHighlight(){var e;(e=this.selectionHelper)==null||e.removeFromParent(),this.selectionHelper=null,this.highlightedObject=null,this.markDirty()}setMeasurementTargetObject(e,t=!0){this.clearMeasurementTargetHelper(!1),this.invalidateMeasurementSnapInputCache();let i=e&&this.isObjectInLoadedRoot(e)?e:null;this.measurementTargetObject=i,this.setMeasurementSnapKind(null,!1),i&&(this.measurementTargetHelper=new Sl(i,6333946),this.scene.add(this.measurementTargetHelper)),this.markDirty(),t&&this.notifyMeasurementsChanged()}clearMeasurementTargetHelper(e=!0){var t;(t=this.measurementTargetHelper)==null||t.removeFromParent(),this.measurementTargetHelper=null,e&&this.markDirty()}updateMeasurementTargetHelper(){!this.measurementTargetHelper||!this.measurementTargetObject||this.measurementTargetHelper.update()}invalidateMeasurementSnapInputCache(){this.measurementSnapInputCache=null,this.measurementSnapInputCacheTarget=null,this.measurementSnapInputCacheSignature=null}setMeasurementSnapKind(e,t=!0){this.measurementSnapKind!==e&&(this.measurementSnapKind=e,t&&this.notifyMeasurementsChanged())}updateMeasurementModifierAltKey(e){this.lastPointerClient.altKey!==e&&(this.lastPointerClient={...this.lastPointerClient,altKey:e},this.measurementActive&&this.pendingPoint&&this.schedulePreviewLineUpdate())}getCurrentMeasurementTargetObject(){return this.rootObject?this.focusSelectionEnabled&&this.focusedObject&&this.isObjectInLoadedRoot(this.focusedObject)?this.focusedObject:this.rootObject:null}isObjectInLoadedRoot(e){if(!this.rootObject)return!1;let t=e;for(;t;){if(t===this.rootObject)return!0;t=t.parent}return!1}getMeasurementTargetName(){let e=this.measurementTargetObject;return!e||!this.isObjectInLoadedRoot(e)?null:Pa(e,e.type||`object-${e.id}`)}getMeasurementTargetBounds(){let e=this.measurementTargetObject;return!e||!this.isObjectInLoadedRoot(e)?null:(e.updateWorldMatrix(!0,!0),rn(e))}resolveMeasurementPickPoint(e,t){if(t)return this.setMeasurementSnapKind("free"),e;let i=this.createMeasurementGeometrySnapInput();if(!i)return this.setMeasurementSnapKind("free"),e;let r=sx(this.toMeasurementPoint(e),i);return r?(this.setMeasurementSnapKind(r.kind),new ie(r.point.x,r.point.y,r.point.z)):(this.setMeasurementSnapKind("free"),e)}createMeasurementGeometrySnapInput(){var f,d;let e=this.measurementTargetObject;if(!e||!this.isObjectInLoadedRoot(e))return null;let t=this.getMeasurementTargetRenderables();if(t.length===0)return null;let i=this.createMeasurementSnapInputSignature(t);if(this.measurementSnapInputCache&&this.measurementSnapInputCacheTarget===e&&this.measurementSnapInputCacheSignature===i)return this.measurementSnapInputCache;let r=[],s=[],a=`three:${e.id}`;for(let u of t){let h=u.geometry.getAttribute("position");if(!h||h.count<=0)continue;u.updateWorldMatrix(!0,!1);let m=[];for(let g=0;g<h.count;g++){let p=new ie().fromBufferAttribute(h,g).applyMatrix4(u.matrixWorld),_=this.toMeasurementPoint(p);m.push(_),r.push({point:_,targetId:a})}if(La(u)){let g=lx(h.count,(d=(f=u.geometry.getIndex())==null?void 0:f.array)!=null?d:null);s.push(...ox(m,g,a))}}if(r.length===0&&s.length===0)return null;let o=this.getMeasurementTargetBounds(),l=o?Ui(o):{x:1,y:1,z:1},c={vertices:r,edges:s,targetId:a,vertexRadius:ax(l,s)};return this.measurementSnapInputCache=c,this.measurementSnapInputCacheTarget=e,this.measurementSnapInputCacheSignature=i,c}createMeasurementSnapInputSignature(e){return e.map(t=>{var o,l,c,f;let i=t.geometry,r=i.getAttribute("position"),s=i.getIndex(),a=r&&"version"in r&&(o=r.version)!=null?o:0;return t.updateWorldMatrix(!0,!1),[t.id,i.id,(l=r==null?void 0:r.count)!=null?l:0,a,(c=s==null?void 0:s.count)!=null?c:0,(f=s==null?void 0:s.version)!=null?f:0,t.matrixWorld.elements.map(Kfe).join(",")].join(":")}).join("|")}getMeasurementTargetRenderables(){let e=this.measurementTargetObject;if(!this.rootObject||!e||!this.isObjectInLoadedRoot(e))return[];let t=new Set(this.getRenderableObjects(this.rootObject));if(Kf(e)&&t.has(e))return[e];let i=[];return e.traverse(r=>{Kf(r)&&r.geometry&&t.has(r)&&i.push(r)}),i}getMeasurementTargetRaycastPoint(e){let t=this.getMeasurementTargetRenderables();if(t.length===0)return null;let i=e!=null?e:this.raycaster.intersectObjects(this.rootObject?this.getRenderableObjects(this.rootObject):[],!1)[0];return i!=null&&i.point&&t.includes(i.object)?i.point.clone():null}createThreeMeasurementDraftingLayout(e,t){let i=this.toMeasurementDisplayPoint(e),r=this.toMeasurementDisplayPoint(t),s=this.getMeasurementMarkerSize(),a=this.camera.getWorldPosition(new ie),o=new ie(0,1,0).applyQuaternion(this.camera.quaternion).normalize(),l=cx(this.toMeasurementPoint(i),this.toMeasurementPoint(r),{viewPosition:this.toMeasurementPoint(a),viewUp:this.toMeasurementPoint(o),offset:s*4.2,extensionGap:s*.55,extensionOvershoot:s*.8,arrowLength:s*2.35,arrowWidth:s*.78,labelGap:s*1.05});return l?{linePoints:l.lineSegments.flatMap(([f,d])=>[new ie(f.x,f.y,f.z),new ie(d.x,d.y,d.z)]),labelPosition:new ie(l.labelPoint.x,l.labelPoint.y,l.labelPoint.z)}:null}getMeasurementMarkerSize(){var r;if(!this.rootObject)return .02;let e=(r=this.getRootPreviewBounds())!=null?r:rn(this.rootObject),t=Ui(e);return Math.max(t.x,t.y,t.z,.001)*.018}cancelPendingMeasurement(e=!0){var r,s;let t=this.pendingMarker,i=(s=(r=this.pendingPoint)==null?void 0:r.clone())!=null?s:null;if(this.pendingPoint=null,this.pendingMarker=null,this.hoveredMarkerIndex=-1,i&&this.setMeasurementSnapKind(null,!1),this.removePreviewLine(),t&&i&&!this.isMeasurementPointUsed(i)){let a=this.measurementMarkers.indexOf(t);a>=0&&(this.measurementMarkers.splice(a,1),this.measurementMarkerPoints.splice(a,1)),this.disposeMeasurementMarker(t)}else t&&(t.scale.setScalar(1),t.material.color.setHex(hv));e&&this.markDirty()}isMeasurementPointUsed(e){return this.measurementSegments.some(t=>t.start.distanceTo(e)<1e-4||t.end.distanceTo(e)<1e-4)}disposeMeasurementMarker(e){e.removeFromParent(),e.geometry.dispose();let t=e.material;if(Array.isArray(t))for(let i of t)i.dispose();else t.dispose()}findNearestMarkerIndex(e){let t=this.getMeasurementMarkerSize()*2.5,i=this.toMeasurementDisplayPoint(e);for(let r=0;r<this.measurementMarkers.length;r++)if((this.measurementMarkerPoints[r]?this.toMeasurementDisplayPoint(this.measurementMarkerPoints[r]):this.measurementMarkers[r].position).distanceTo(i)<t)return r;return-1}addMeasurementPoint(e){let t=this.toMeasurementBasePoint(e),i=this.findNearestMarkerIndex(t),r=i>=0?this.measurementMarkerPoints[i].clone():t;if(this.pendingPoint){if(r.distanceTo(this.pendingPoint)<1e-4)return;if(i<0){let s=this.getMeasurementMarkerSize(),a=new mm(s*.38,12,12),o=new Kn({color:hv,depthTest:!1,transparent:!0,opacity:.48}),l=new ci(a,o);l.position.copy(this.toMeasurementDisplayPoint(r)),l.renderOrder=999,this.scene.add(l),this.measurementMarkers.push(l),this.measurementMarkerPoints.push(r.clone())}this.createMeasurementSegment(this.pendingPoint,r),this.pendingMarker&&(this.pendingMarker.scale.setScalar(1),this.pendingMarker.material.color.setHex(hv)),this.pendingPoint=null,this.pendingMarker=null,this.removePreviewLine()}else{if(i<0){let s=this.getMeasurementMarkerSize(),a=new mm(s*.38,12,12),o=new Kn({color:hv,depthTest:!1,transparent:!0,opacity:.48}),l=new ci(a,o);l.position.copy(this.toMeasurementDisplayPoint(r)),l.renderOrder=999,this.scene.add(l),this.measurementMarkers.push(l),this.measurementMarkerPoints.push(r.clone()),this.pendingMarker=l}else this.pendingMarker=this.measurementMarkers[i];this.pendingMarker.scale.setScalar(1.6),this.pendingMarker.material.color.setHex(Nfe),this.pendingPoint=r,this.ensurePreviewLine()}this.markDirty(),this.notifyMeasurementsChanged()}createMeasurementSegment(e,t){var u,h;let i=this.createThreeMeasurementDraftingLayout(e,t),r=this.toMeasurementDisplayPoint(e),s=this.toMeasurementDisplayPoint(t),a=(u=i==null?void 0:i.linePoints)!=null?u:[r,s],o=new Bi().setFromPoints(a),l=new _s(o,new Ln({color:Ofe,transparent:!0,opacity:1,depthTest:!1,depthWrite:!1}));l.renderOrder=998,this.scene.add(l);let c=Wm(this.createMeasurementReading(e,t)),f=(h=i==null?void 0:i.labelPosition)!=null?h:new ie().addVectors(r,s).multiplyScalar(.5),d=this.createMeasurementLabelSprite(c,f,this.getMeasurementMarkerSize()*3.2);this.scene.add(d),this.measurementSegments.push({start:e.clone(),end:t.clone(),line:l,label:d})}createMeasurementLabelSprite(e,t,i){let r=Cu("canvas"),s=r.getContext("2d");r.width=Oo.width,r.height=Oo.height,nv(s,e,r.width,r.height);let a=new b_(r),o=new fm({map:a,depthTest:!1,depthWrite:!1,transparent:!0}),l=new S_(o);return l.position.copy(t),l.scale.set(i*3.7,i*1.08,1),l.renderOrder=1e3,l}ensurePreviewLine(){if(this.previewLine)return;let e=new Bi().setFromPoints(Array.from({length:14},()=>new ie));this.previewLine=new _s(e,new Ln({color:Ffe,transparent:!0,opacity:.82,depthTest:!1,depthWrite:!1})),this.previewLine.renderOrder=997,this.scene.add(this.previewLine)}updatePreviewLine(){if(this.previewLineUpdateHandle=0,!this.pendingPoint||!this.previewLine||!this.rootObject)return;let e=this.toMeasurementDisplayPoint(this.pendingPoint),t=this.renderer.domElement.getBoundingClientRect();this.pointer.x=(this.lastPointerClient.x-t.left)/t.width*2-1,this.pointer.y=-((this.lastPointerClient.y-t.top)/t.height)*2+1,this.raycaster.setFromCamera(this.pointer,this.camera);let i=null;if(this.lastPointerClient.altKey){this.setMeasurementSnapKind("free");let o=this.raycaster.intersectObjects(this.getRenderableObjects(this.rootObject),!1)[0];i=o!=null&&o.point?this.resolveMeasurementPickPoint(o.point.clone(),!0):e.clone().add(this.raycaster.ray.direction.clone().multiplyScalar(5))}else{let o=this.getMeasurementTargetRaycastPoint();o?i=this.resolveMeasurementPickPoint(o,!1):this.setMeasurementSnapKind(null)}let r=i?this.createThreeMeasurementDraftingLayout(this.pendingPoint,this.toMeasurementBasePoint(i)):null,s=i&&r?r.linePoints:[e,e],a=this.previewLine.geometry.getAttribute("position");if(a.count!==s.length)this.previewLine.geometry.dispose(),this.previewLine.geometry=new Bi().setFromPoints(s);else{for(let o=0;o<s.length;o++){let l=s[o];a.setXYZ(o,l.x,l.y,l.z)}a.needsUpdate=!0}this.previewLine.geometry.computeBoundingSphere(),this.markDirty()}schedulePreviewLineUpdate(){this.previewLineUpdateHandle||(this.previewLineUpdateHandle=window.requestAnimationFrame(()=>this.updatePreviewLine()))}cancelPreviewLineUpdate(){this.previewLineUpdateHandle&&(window.cancelAnimationFrame(this.previewLineUpdateHandle),this.previewLineUpdateHandle=0)}removePreviewLine(){this.cancelPreviewLineUpdate(),this.previewLine&&(this.previewLine.removeFromParent(),this.previewLine.geometry.dispose(),this.previewLine.material.dispose(),this.previewLine=null)}createMeasurementReading(e,t){return ux(this.toMeasurementPoint(e),this.toMeasurementPoint(t),this.measurementScale,this.measurementUnit)}createMeasurementRecords(){return this.measurementSegments.map((e,t)=>({index:t+1,start:this.toMeasurementPoint(e.start),end:this.toMeasurementPoint(e.end),reading:this.createMeasurementReading(e.start,e.end)}))}toMeasurementPoint(e){return{x:e.x,y:e.y,z:e.z}}notifyMeasurementsChanged(){for(let e of Array.from(this.measurementObservers))e()}}});var Zfe,UP,VP,re,Si=y(()=>{Zfe=typeof WeakRef!="undefined",UP=class{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}},VP=class{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(e=!1){this._remove&&this._remove(e)}},re=class n{static FromPromise(e,t){let i=new n;return e.then(r=>{i.notifyObservers(r)}).catch(r=>{if(t)t.notifyObservers(r);else throw r}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new UP(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,s=!1){if(!e)return null;let a=new VP(e,t,r);a.unregisterOnNextCall=s,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),this._hasNotified&&this.notifyIfTriggered&&this._lastNotifiedValue!==void 0&&this.notifyObserver(a,this._lastNotifiedValue);let o=Zfe?new WeakRef(this):{deref:()=>this};return a._remove=(l=!1)=>{let c=o.deref();c&&(l?c.remove(a):c._remove(a))},a}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return e?(e._remove=null,this._observers.indexOf(e)!==-1?(this._deferUnregister(e),!0):!1):!1}removeCallback(e,t){for(let i=0;i<this._observers.length;i++){let r=this._observers[i];if(!r._willBeUnregistered&&r.callback===e&&(!t||t===r.scope))return this._deferUnregister(r),!0}return!1}_deferUnregister(e){e._willBeUnregistered||(this._numObserversMarkedAsDeleted++,e.unregisterOnNextCall=!1,e._willBeUnregistered=!0,setTimeout(()=>{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;let i=this._observers.indexOf(e);return i!==-1?(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0):!1}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,r,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;let a=this._eventState;a.mask=t,a.target=i,a.currentTarget=r,a.skipNextObservers=!1,a.lastReturnValue=e,a.userInfo=s;for(let o of this._observers)if(!o._willBeUnregistered&&(o.mask&t&&(o.unregisterOnNextCall&&this._deferUnregister(o),o.scope?a.lastReturnValue=o.callback.apply(o.scope,[e,a]):a.lastReturnValue=o.callback(e,a)),a.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;let r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){let e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){let e=new n;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(let t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}});var Bx,JV=y(()=>{Bx=class{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,r=1,s=2,a=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=r,this.samplingMode=s,this._comparisonFunction=a,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}});var eG,Xi,ea=y(()=>{Si();JV();(function(n){n[n.Unknown=0]="Unknown",n[n.Url=1]="Url",n[n.Temp=2]="Temp",n[n.Raw=3]="Raw",n[n.Dynamic=4]="Dynamic",n[n.RenderTarget=5]="RenderTarget",n[n.MultiRenderTarget=6]="MultiRenderTarget",n[n.Cube=7]="Cube",n[n.CubeRaw=8]="CubeRaw",n[n.CubePrefiltered=9]="CubePrefiltered",n[n.Raw3D=10]="Raw3D",n[n.Raw2DArray=11]="Raw2DArray",n[n.DepthStencil=12]="DepthStencil",n[n.CubeRawRGBD=13]="CubeRawRGBD",n[n.Depth=14]="Depth"})(eG||(eG={}));Xi=class n extends Bx{get useMipMaps(){return this._useMipMaps===null?this.generateMipMaps:this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this._useMipMaps=null,this.mipLevelCount=1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new re,this.onErrorObservable=new re,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=0,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._creationFlags=0,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._premulAlpha=!1,this._dynamicTextureSource=null,this._autoMSAAManagement=!1,this._engine=e,this._source=t,this._uniqueId=n._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){var t,i;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){let r=this.onRebuildCallback(this),s=a=>{a._swapAndDie(this,!1),this.isReady=r.isReady};r.isAsync?r.proxy.then(s):s(r.proxy);return}let e;switch(this.source){case 2:break;case 1:e=this._engine.createTexture((t=this._originalUrl)!=null?t:this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,r=>{r._swapAndDie(this,!1),this.isReady=!0},null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer);return;case 3:if(e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer,this.mipLevelCount),e._swapAndDie(this,!1),this._bufferViewArray)for(let r=0;r<this._bufferViewArray.length;r++){let s=this._bufferViewArray[r];s&&this._engine.updateRawTexture(this,s,this.format,this.invertY,this._compression,this.type,this._useSRGBBuffer,r)}this.isReady=!0;break;case 10:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 11:if(e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this.mipLevelCount),e._swapAndDie(this,!1),this._bufferViewArray)for(let r=0;r<this._bufferViewArray.length;r++){let s=this._bufferViewArray[r];s&&this._engine.updateRawTexture2DArray(this,s,this.format,this.invertY,this._compression,this.type,r)}this.isReady=!0;break;case 4:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case 7:e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer,ArrayBuffer.isView(this._buffer)?this._buffer:null);return;case 8:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,(i=this._originalFormat)!=null?i:this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case 13:return;case 9:e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,r=>{r&&r._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension),e._sphericalPolynomial=this._sphericalPolynomial;return;case 12:case 14:break}}_swapAndDie(e,t=!0){var s;(s=this._hardwareTexture)==null||s.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);let i=this._engine.getLoadedTexturesCache(),r=i.indexOf(this);r!==-1&&i.splice(r,1),r=i.indexOf(e),r===-1&&i.push(e)}dispose(){this._references--,this._references===0&&(this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}};Xi._Counter=0});var Oe,Yi=y(()=>{Si();Oe=class{static get LastCreatedEngine(){return this.Instances.length===0?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}};Oe.Instances=[];Oe.OnEnginesDisposedObservable=new re;Oe._LastCreatedScene=null;Oe.UseFallbackTexture=!0;Oe.FallbackTexture=""});var te,wt=y(()=>{te=class n{static _CheckLimit(e,t){let i=n._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},n._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){var s;let i=n._LogLimitOutputs[e];if(!i||!n.MessageLimitReached)return;let r=this._Levels[t];i.current===i.limit&&n[r.name](n.MessageLimitReached.replace(/%LIMIT%/g,""+i.limit).replace(/%TYPE%/g,(s=r.name)!=null?s:""))}static _AddLogEntry(e){n._LogCache=e+n._LogCache,n.OnNewCacheEntry&&n.OnNewCacheEntry(e)}static _FormatMessage(e){let t=r=>r<10?"0"+r:""+r,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){let r=Array.isArray(t)?t[0]:t;if(i!==void 0&&!n._CheckLimit(r,i))return;let s=n._FormatMessage(r),a=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];a.logFunc&&a.logFunc("BJS - "+s,...o);let l=`<div style='color:${a.color}'>${s}</div><br>`;n._AddLogEntry(l),n._GenerateLimitMessage(r,e)}static get LogCache(){return n._LogCache}static ClearLogCache(){n._LogCache="",n._LogLimitOutputs={},n.errorsCount=0}static set LogLevels(e){n.Log=n._LogDisabled,n.Warn=n._LogDisabled,n.Error=n._LogDisabled;let t=[n.MessageLogLevel,n.WarningLogLevel,n.ErrorLogLevel];for(let i of t)if((e&i)===i){let r=this._Levels[i];n[r.name]=n._LogEnabled.bind(n,i)}}};te.NoneLogLevel=0;te.MessageLogLevel=1;te.WarningLogLevel=2;te.ErrorLogLevel=4;te.AllLogLevel=7;te.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";te._LogCache="";te._LogLimitOutputs={};te._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];te.errorsCount=0;te.Log=te._LogEnabled.bind(te,te.MessageLogLevel);te.Warn=te._LogEnabled.bind(te,te.WarningLogLevel);te.Error=te._LogEnabled.bind(te,te.ErrorLogLevel)});var x,k=y(()=>{x=class n{static GetShadersRepository(e=0){return e===0?n.ShadersRepository:n.ShadersRepositoryWGSL}static GetShadersStore(e=0){return e===0?n.ShadersStore:n.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return e===0?n.IncludesShadersStore:n.IncludesShadersStoreWGSL}};x.ShadersRepository="src/Shaders/";x.ShadersStore={};x.IncludesShadersStore={};x.ShadersRepositoryWGSL="src/ShadersWGSL/";x.ShadersStoreWGSL={};x.IncludesShadersStoreWGSL={}});function Ar(){return typeof window!="undefined"}function Tc(){return typeof navigator!="undefined"}function jf(){return typeof document!="undefined"}function Ux(n){let e="",t=n.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}var qa=y(()=>{});var Vx,tG=y(()=>{Vx=class{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return this.program?this.isParallelCompiled?this.engine._isRenderingStateCompiled(this):!0:!1}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,r,s,a,o,l){let c=this.engine;if(c.supportsUniformBuffers)for(let u in t)e.bindUniformBlock(u,t[u]);this.engine.getUniforms(this,i).forEach((u,h)=>{r[i[h]]=u}),this._uniforms=r;let d;for(d=0;d<s.length;d++)e.getUniform(s[d])==null&&(s.splice(d,1),d--);s.forEach((u,h)=>{a[u]=h});for(let u of c.getAttributes(this,o))l.push(u)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return i!==void 0&&i===r?!1:(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||r.length!==2)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s||s.length!==3)return s=[t,i,r],this._valueCache[e]=s,!0;let a=!1;return s[0]!==t&&(s[0]=t,a=!0),s[1]!==i&&(s[1]=i,a=!0),s[2]!==r&&(s[2]=r,a=!0),a}_cacheFloat4(e,t,i,r,s){let a=this._valueCache[e];if(!a||a.length!==4)return a=[t,i,r,s],this._valueCache[e]=a,!0;let o=!1;return a[0]!==t&&(a[0]=t,o=!0),a[1]!==i&&(a[1]=i,o=!0),a[2]!==r&&(a[2]=r,o=!0),a[3]!==s&&(a[3]=s,o=!0),o}setInt(e,t){let i=this._valueCache[e];i!==void 0&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){let i=this._valueCache[e];i!==void 0&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setUInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setUInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){let i=this._valueCache[e];i!==void 0&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setFloat3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setFloat4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}});function $e(n,e=!1){if(!(e&&iG[n]))return iG[n]=!0,`${n} needs to be imported before as it contains a side-effect required by your code.`}var iG,Mn=y(()=>{iG={}});function Gx(n,e,t=""){return t+(e?e+`
`:"")+n}function kx(n,e,t,i,r,s,a){let o=a||$m.loadFile;if(o)return o(n,e,t,i,r,s);throw $e("FileTools")}function zx(n,e,t,i){if(n){e?n.IS_NDC_HALF_ZRANGE="":delete n.IS_NDC_HALF_ZRANGE,t?n.USE_REVERSE_DEPTHBUFFER="":delete n.USE_REVERSE_DEPTHBUFFER,i?n.USE_EXACT_SRGB_CONVERSIONS="":delete n.USE_EXACT_SRGB_CONVERSIONS;return}else{let r="";return e&&(r+="#define IS_NDC_HALF_ZRANGE"),t&&(r&&(r+=`
`),r+="#define USE_REVERSE_DEPTHBUFFER"),i&&(r&&(r+=`
`),r+="#define USE_EXACT_SRGB_CONVERSIONS"),r}}function rG(n,e,t=!1,i){switch(n){case 3:{let s=new Int8Array(e);return i&&s.set(new Int8Array(i)),s}case 0:{let s=new Uint8Array(e);return i&&s.set(new Uint8Array(i)),s}case 4:{let s=typeof e!="number"?new Int16Array(e):new Int16Array(t?e/2:e);return i&&s.set(new Int16Array(i)),s}case 5:case 8:case 9:case 10:case 2:{let s=typeof e!="number"?new Uint16Array(e):new Uint16Array(t?e/2:e);return i&&s.set(new Uint16Array(i)),s}case 6:{let s=typeof e!="number"?new Int32Array(e):new Int32Array(t?e/4:e);return i&&s.set(new Int32Array(i)),s}case 7:case 11:case 12:case 13:case 14:case 15:{let s=typeof e!="number"?new Uint32Array(e):new Uint32Array(t?e/4:e);return i&&s.set(new Uint32Array(i)),s}case 1:{let s=typeof e!="number"?new Float32Array(e):new Float32Array(t?e/4:e);return i&&s.set(new Float32Array(i)),s}}let r=new Uint8Array(e);return i&&r.set(new Uint8Array(i)),r}var $m,Zf=y(()=>{Mn();qa();$m={}});function Jn(n){let e=GP.get(n);if(!e){if(!n)return qfe;e={_webGLVersion:n.TEXTURE_BINDING_3D?2:1,_context:n,parallelShaderCompile:n.getExtension("KHR_parallel_shader_compile")||void 0,cachedPipelines:{}},GP.set(n,e)}return e}function Wx(n){GP.delete(n)}function zP(n,e,t,i,r,s){var c;let a=Jn(i);s||(s=(c=a._createShaderProgramInjection)!=null?c:Hx);let o=kP(e,"vertex",i,a._contextWasLost),l=kP(t,"fragment",i,a._contextWasLost);return s(n,o,l,i,r,a.validateShaderPrograms)}function WP(n,e,t,i,r,s=null,a){var d;let o=Jn(r);a||(a=(d=o._createShaderProgramInjection)!=null?d:Hx);let l=o._webGLVersion>1?`#version 300 es
#define WEBGL2
`:"",c=nG(e,"vertex",i,l,r,o._contextWasLost),f=nG(t,"fragment",i,l,r,o._contextWasLost);return a(n,c,f,r,s,o.validateShaderPrograms)}function sG(n,e){let t=new Vx,i=Jn(n);return i.parallelShaderCompile&&!i.disableParallelShaderCompile&&(t.isParallelCompiled=!0),t.context=i._context,t}function Hx(n,e,t,i,r=null,s){let a=i.createProgram();if(n.program=a,!a)throw new Error("Unable to create program");return i.attachShader(a,e),i.attachShader(a,t),i.linkProgram(a),n.context=i,n.vertexShader=e,n.fragmentShader=t,n.isParallelCompiled||Xx(n,i,s),a}function aG(n,e,t){let i=n;if(i._isDisposed)return!1;let r=Jn(e);return r&&r.parallelShaderCompile&&r.parallelShaderCompile.COMPLETION_STATUS_KHR&&i.program&&e.getProgramParameter(i.program,r.parallelShaderCompile.COMPLETION_STATUS_KHR)?(Xx(i,e,t),!0):!1}function Xx(n,e,t){let i=n.context,r=n.vertexShader,s=n.fragmentShader,a=n.program;if(!i.getProgramParameter(a,i.LINK_STATUS)){if(!e.getShaderParameter(r,e.COMPILE_STATUS)){let c=e.getShaderInfoLog(r);if(c)throw n.vertexCompilationError=c,new Error("VERTEX SHADER "+c)}if(!e.getShaderParameter(s,e.COMPILE_STATUS)){let c=e.getShaderInfoLog(s);if(c)throw n.fragmentCompilationError=c,new Error("FRAGMENT SHADER "+c)}let l=i.getProgramInfoLog(a);if(l)throw n.programLinkError=l,new Error(l)}if(t&&(i.validateProgram(a),!i.getProgramParameter(a,i.VALIDATE_STATUS))){let c=i.getProgramInfoLog(a);if(c)throw n.programValidationError=c,new Error(c)}i.deleteShader(r),i.deleteShader(s),n.vertexShader=void 0,n.fragmentShader=void 0,n.onCompiled&&(n.onCompiled(),n.onCompiled=void 0)}function oG(n,e,t,i,r,s,a,o,l,c="",f,d,u){var g,p;let h=Jn(n.context);d||(d=(g=h.createRawShaderProgramInjection)!=null?g:zP),u||(u=(p=h.createShaderProgramInjection)!=null?p:WP);let m=n;i?m.program=d(m,e,t,m.context,l):m.program=u(m,e,t,o,m.context,l),m.program.__SPECTOR_rebuildProgram=a,f()}function nG(n,e,t,i,r,s){return kP(Gx(n,t,i),e,r,s)}function kP(n,e,t,i){let r=t.createShader(e==="vertex"?t.VERTEX_SHADER:t.FRAGMENT_SHADER);if(!r){let s=t.NO_ERROR,a;for(;(a=t.getError())!==t.NO_ERROR;)s=a;throw new Error(`Something went wrong while creating a gl ${e} shader object. gl error=${s}, gl isContextLost=${t.isContextLost()}, _contextWasLost=${i}`)}return t.shaderSource(r,n),t.compileShader(r),r}function lG(n,e){e.useProgram(n)}function cG(n,e){let t=n;if(!t.isParallelCompiled){e(n);return}let i=t.onCompiled;t.onCompiled=()=>{i==null||i(),e(n)}}var GP,qfe,HP=y(()=>{tG();Zf();GP=new WeakMap,qfe={_webGLVersion:2,cachedPipelines:{}}});var Qfe,$fe,Cl,Yx=y(()=>{Qfe="attribute",$fe="varying",Cl=class{constructor(){this.children=[]}isValid(e){return!0}process(e,t,i){var s,a,o,l,c,f,d;let r="";if(this.line){let u=this.line,h=t.processor;if(h){h.lineProcessor&&(u=h.lineProcessor(u,t.isFragment,t.processingContext));let m=(a=(s=t.processor)==null?void 0:s.attributeKeywordName)!=null?a:Qfe,g=t.isFragment&&((o=t.processor)!=null&&o.varyingFragmentKeywordName)?(l=t.processor)==null?void 0:l.varyingFragmentKeywordName:!t.isFragment&&((c=t.processor)!=null&&c.varyingVertexKeywordName)?(f=t.processor)==null?void 0:f.varyingVertexKeywordName:$fe;!t.isFragment&&h.attributeProcessor&&this.line.startsWith(m)?u=h.attributeProcessor(this.line,e,t.processingContext):h.varyingProcessor&&((d=h.varyingCheck)!=null&&d.call(h,this.line,t.isFragment)||!h.varyingCheck&&this.line.startsWith(g))?u=h.varyingProcessor(this.line,t.isFragment,e,t.processingContext):h.uniformProcessor&&h.uniformRegexp&&h.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=h.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):h.uniformBufferProcessor&&h.uniformBufferRegexp&&h.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=h.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):h.textureProcessor&&h.textureRegexp&&h.textureRegexp.test(this.line)?u=h.textureProcessor(this.line,t.isFragment,e,t.processingContext):(h.uniformProcessor||h.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?h.uniformProcessor&&(u=h.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):h.uniformBufferProcessor&&(u=h.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&this.line.indexOf("}")!==-1&&(t.lookForClosingBracketForUniformBuffer=!1,h.endOfUniformBufferProcessor&&(u=h.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}r+=u+`
`}for(let u of this.children)r+=u.process(e,t,i);return this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true",i[this.additionalDefineKey]=e[this.additionalDefineKey]),r}}});var Kx,fG=y(()=>{Kx=class{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex<this._lines.length-1}set lines(e){this._lines.length=0;for(let t of e){if(!t||t==="\r")continue;if(t[0]==="#"){this._lines.push(t);continue}let i=t.trim();if(!i)continue;if(i.startsWith("//")){this._lines.push(t);continue}let r=i.indexOf(";");if(r===-1)this._lines.push(i);else if(r===i.length-1)i.length>1&&this._lines.push(i);else{let s=t.split(";");for(let a=0;a<s.length;a++){let o=s[a];o&&(o=o.trim(),o&&this._lines.push(o+(a!==s.length-1?";":"")))}}}}}});var Jm,dG=y(()=>{Yx();Jm=class extends Cl{process(e,t,i){for(let r=0;r<this.children.length;r++){let s=this.children[r];if(s.isValid(e))return s.process(e,t,i)}return""}}});var jx,uG=y(()=>{Yx();jx=class extends Cl{isValid(e){return this.testExpression.isTrue(e)}}});var Bn,ep=y(()=>{Bn=class n{isTrue(e){return!0}static postfixToInfix(e){let t=[];for(let i of e)if(n._OperatorPriority[i]===void 0)t.push(i);else{let r=t[t.length-1],s=t[t.length-2];t.length-=2,t.push(`(${s}${i}${r})`)}return t[t.length-1]}static infixToPostfix(e){let t=n._InfixToPostfixCache.get(e);if(t)return t.accessTime=Date.now(),t.result;if(!e.includes("&&")&&!e.includes("||")&&!e.includes(")")&&!e.includes("("))return[e];let i=[],r=-1,s=()=>{f=f.trim(),f!==""&&(i.push(f),f="")},a=d=>{r<n._Stack.length-1&&(n._Stack[++r]=d)},o=()=>n._Stack[r],l=()=>r===-1?"!!INVALID EXPRESSION!!":n._Stack[r--],c=0,f="";for(;c<e.length;){let d=e.charAt(c),u=c<e.length-1?e.substring(c,2+c):"";if(d==="(")f="",a(d);else if(d===")"){for(s();r!==-1&&o()!=="(";)i.push(l());l()}else if(n._OperatorPriority[u]>1){for(s();r!==-1&&n._OperatorPriority[o()]>=n._OperatorPriority[u];)i.push(l());a(u),c++}else f+=d;c++}for(s();r!==-1;)o()==="("?l():i.push(l());return n._InfixToPostfixCache.size>=n.InfixToPostfixCacheLimitSize&&n.ClearCache(),n._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){let e=Array.from(n._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t<n.InfixToPostfixCacheCleanupSize;t++)n._InfixToPostfixCache.delete(e[t][0])}};Bn.InfixToPostfixCacheLimitSize=5e4;Bn.InfixToPostfixCacheCleanupSize=25e3;Bn._InfixToPostfixCache=new Map;Bn._OperatorPriority={")":0,"(":1,"||":2,"&&":3};Bn._Stack=["","","","","","","","","","","","","","","","","","","",""]});var Ou,hG=y(()=>{ep();Ou=class extends Bn{constructor(e,t=!1){super(),this.define=e,this.not=t}isTrue(e){let t=e[this.define]!==void 0;return this.not&&(t=!t),t}}});var Zx,mG=y(()=>{ep();Zx=class extends Bn{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}});var qx,pG=y(()=>{ep();qx=class extends Bn{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}});var Qx,gG=y(()=>{ep();Qx=class extends Bn{constructor(e,t,i){super(),this.define=e,this.operand=t,this.testValue=i}toString(){return`${this.define} ${this.operand} ${this.testValue}`}isTrue(e){let t=!1,i=parseInt(e[this.define]!=null?e[this.define]:this.define),r=parseInt(e[this.testValue]!=null?e[this.testValue]:this.testValue);if(isNaN(i)||isNaN(r))return!1;switch(this.operand){case">":t=i>r;break;case"<":t=i<r;break;case"<=":t=i<=r;break;case">=":t=i>=r;break;case"==":t=i===r;break;case"!=":t=i!==r;break}return t}}});function EG(n){n.processor&&n.processor.initializeShaders&&n.processor.initializeShaders(n.processingContext)}function ZP(n,e,t,i){var r;(r=e.processor)!=null&&r.preProcessShaderCode&&(n=e.processor.preProcessShaderCode(n,e.isFragment)),mv(n,e,s=>{e.processCodeAfterIncludes&&(s=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",s,e.defines));let a=ode(s,e,i);t(a,s)})}function SG(n,e,t){return!t.processor||!t.processor.finalizeShaders?{vertexCode:n,fragmentCode:e}:t.processor.finalizeShaders(n,e,t.processingContext)}function rde(n,e){var i;if((i=e.processor)!=null&&i.noPrecision)return n;let t=e.shouldUseHighPrecisionShader;return n.indexOf("precision highp float")===-1?t?n=`precision highp float;
`+n:n=`precision mediump float;
`+n:t||(n=n.replace("precision highp float","precision mediump float")),n}function YP(n){let t=/defined\((.+)\)/.exec(n);if(t&&t.length)return new Ou(t[1].trim(),n[0]==="!");let i=["==","!=",">=","<=","<",">"],r="",s=0;for(r of i)if(s=n.indexOf(r),s>-1)break;if(s===-1)return new Ou(n);let a=n.substring(0,s).trim(),o=n.substring(s+r.length).trim();return new Qx(a,r,o)}function nde(n){n=n.replace(Jfe,"defined[$1]");let e=Bn.infixToPostfix(n),t=[];for(let r of e)if(r!=="||"&&r!=="&&")t.push(r);else if(t.length>=2){let s=t[t.length-1],a=t[t.length-2];t.length-=2;let o=r=="&&"?new qx:new Zx;typeof s=="string"&&(s=s.replace(XP,"defined($1)")),typeof a=="string"&&(a=a.replace(XP,"defined($1)")),o.leftOperand=typeof a=="string"?YP(a):a,o.rightOperand=typeof s=="string"?YP(s):s,t.push(o)}let i=t[t.length-1];return typeof i=="string"&&(i=i.replace(XP,"defined($1)")),typeof i=="string"?YP(i):i}function Jx(n,e){let t=new jx,i=n.substring(0,e),r=n.substring(e);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i==="#ifdef"?t.testExpression=new Ou(r):i==="#ifndef"?t.testExpression=new Ou(r,!0):t.testExpression=nde(r),t}function KP(n,e,t,i){let r;for(;jP(n,t,i);){r=n.currentLine;let s=r.substring(0,5).toLowerCase();if(s==="#else"){let a=new Cl;e.children.push(a),jP(n,a,i);return}else if(s==="#elif"){let a=Jx(r,5);e.children.push(a),t=a}}}function jP(n,e,t){for(;n.canRead;){n.lineIndex++;let i=n.currentLine;if(i.indexOf("#")>=0){let s=ide.exec(i);if(s&&s.length){switch(s[0]){case"#ifdef":{let o=new Jm;e.children.push(o);let l=Jx(i,6);o.children.push(l),KP(n,o,l,t);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{let o=new Jm;e.children.push(o);let l=Jx(i,7);o.children.push(l),KP(n,o,l,t);break}case"#if":{let o=new Jm,l=Jx(i,3);e.children.push(o),o.children.push(l),KP(n,o,l,t);break}}continue}}let r=new Cl;if(r.line=i,e.children.push(r),i[0]==="#"&&i[1]==="d"){let s=i.replace(";","").split(" ");r.additionalDefineKey=s[1],s.length===3&&(r.additionalDefineValue=s[2])}}return!1}function sde(n,e,t,i){let r=new Cl,s=new Kx;return s.lineIndex=-1,s.lines=n.split(`
`),jP(s,r,i),r.process(e,t,i)}function ade(n,e){var r;let t=n.defines,i={};for(let s of t){let o=s.replace("#define","").replace(";","").trim().split(" ");i[o[0]]=o.length>1?o[1]:""}return((r=n.processor)==null?void 0:r.shaderLanguage)===0&&(i.GL_ES="true"),i.__VERSION__=n.version,i[n.platformName]="true",zx(i,e==null?void 0:e.isNDCHalfZRange,e==null?void 0:e.useReverseDepthBuffer,e==null?void 0:e.useExactSrgbConversions),i}function ode(n,e,t){let i=rde(n,e);if(!e.processor||e.processor.shaderLanguage===0&&i.indexOf("#version 3")!==-1&&(i=i.replace("#version 300 es",""),!e.processor.parseGLES3))return i;let r=e.defines,s=ade(e,t);e.processor.preProcessor&&(i=e.processor.preProcessor(i,r,s,e.isFragment,e.processingContext));let a={};return i=sde(i,s,e,a),e.processor.postProcessor&&(i=e.processor.postProcessor(i,r,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{},s,a)),t!=null&&t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function mv(n,e,t){$x.length=0;let i;for(;(i=ede.exec(n))!==null;)$x.push(i);let r=[n],s=!1;for(let o of $x){let l=o[1];if(l.indexOf("__decl__")!==-1&&(l=l.replace(tde,""),e.supportsUniformBuffers&&(l=l.replace("Vertex","Ubo").replace("Fragment","Ubo")),l=l+"Declaration"),e.includesShadersStore[l]){let c=e.includesShadersStore[l];if(o[2]){let d=o[3].split(",");for(let u=0;u<d.length;u+=2){let h=new RegExp(d[u],"g"),m=d[u+1];c=c.replace(h,m)}}if(o[4]){let d=o[5];if(d.indexOf("..")!==-1){let u=d.split(".."),h=parseInt(u[0]),m=parseInt(u[1]),g=c.slice(0);c="",isNaN(m)&&(m=e.indexParameters[u[1]]);for(let p=h;p<m;p++)e.supportsUniformBuffers||(g=g.replace(_G,(_,v)=>v+"{X}")),c+=g.replace(vG,p.toString())+`
`}else e.supportsUniformBuffers||(c=c.replace(_G,(u,h)=>h+"{X}")),c=c.replace(vG,d)}let f=[];for(let d of r){let u=d.split(o[0]);for(let h=0;h<u.length-1;h++)f.push(u[h]),f.push(c);f.push(u[u.length-1])}r=f,s=s||c.indexOf("#include<")>=0||c.indexOf("#include <")>=0}else{let c=e.shadersRepository+"ShadersInclude/"+l+".fx";qP.loadFile(c,f=>{e.includesShadersStore[l]=f,mv(r.join(""),e,t)});return}}$x.length=0;let a=r.join("");s?mv(a.toString(),e,t):t(a)}var Jfe,XP,ede,tde,_G,vG,$x,ide,qP,eR=y(()=>{Yx();fG();dG();uG();hG();mG();pG();ep();gG();Mn();Zf();Jfe=/defined\s*?\((.+?)\)/g,XP=/defined\s*?\[(.+?)\]/g,ede=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,tde=/__decl__/,_G=/light\{X\}.(\w*)/g,vG=/\{X\}/g,$x=[],ide=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;qP={loadFile:(n,e,t,i,r,s)=>{throw $e("FileTools")}}});function AG(n,e){return Jn(e).cachedPipelines[n]}function tR(n){let e=n._name,t=n.context;if(e&&t){let i=Jn(t),r=i.cachedPipelines[e];r==null||r.dispose(),delete i.cachedPipelines[e]}}function xG(n,e,t,i,r,s,a){let o,l,c=Ar()?s==null?void 0:s.getHostDocument():null;typeof e=="string"?o=e:typeof e.vertexSource=="string"?o="source:"+e.vertexSource:typeof e.vertexElement=="string"?o=(c==null?void 0:c.getElementById(e.vertexElement))||e.vertexElement:o=e.vertex||e,typeof e=="string"?l=e:typeof e.fragmentSource=="string"?l="source:"+e.fragmentSource:typeof e.fragmentElement=="string"?l=(c==null?void 0:c.getElementById(e.fragmentElement))||e.fragmentElement:l=e.fragment||e;let f=[void 0,void 0],d=()=>{if(f[0]&&f[1]){let[u,h]=f;EG(n),ZP(u,n,(m,g)=>{a&&(a._vertexSourceCodeBeforeMigration=g),t&&(m=t("vertex",m)),n.isFragment=!0,ZP(h,n,(p,_)=>{a&&(a._fragmentSourceCodeBeforeMigration=_),t&&(p=t("fragment",p));let v=SG(m,p,n);n=null;let E=lde(v.vertexCode,v.fragmentCode,e,r);i==null||i(E.vertexSourceCode,E.fragmentSourceCode)},s)},s)}};TG(o,"Vertex","",u=>{a&&(a._rawVertexSourceCode=u),f[0]=u,d()},r),TG(l,"Fragment","Pixel",u=>{a&&(a._rawFragmentSourceCode=u),f[1]=u,d()},r)}function TG(n,e,t,i,r,s){if(typeof HTMLElement!="undefined"&&n instanceof HTMLElement){let l=Ux(n);i(l);return}if(n.substring(0,7)==="source:"){i(n.substring(7));return}if(n.substring(0,7)==="base64:"){let l=window.atob(n.substring(7));i(l);return}let a=x.GetShadersStore(r);if(a[n+e+"Shader"]){i(a[n+e+"Shader"]);return}if(t&&a[n+t+"Shader"]){i(a[n+t+"Shader"]);return}let o;if(n[0]==="."||n[0]==="/"||n.indexOf("http")>-1?o=n:o=x.GetShadersRepository(r)+n,s=s||kx,!s)throw new Error("loadFileInjection is not defined");s(o+"."+e.toLowerCase()+".fx",i)}function lde(n,e,t,i){if(t){let r=t.vertexElement||t.vertex||t.spectorName||t,s=t.fragmentElement||t.fragment||t.spectorName||t;return{vertexSourceCode:(i===1?"//":"")+"#define SHADER_NAME vertex:"+r+`
`+n,fragmentSourceCode:(i===1?"//":"")+"#define SHADER_NAME fragment:"+s+`
`+e}}else return{vertexSourceCode:n,fragmentSourceCode:e}}var RG,QP=y(()=>{qa();HP();k();wt();eR();Zf();RG=(n,e,t,i)=>{try{let r=n.context?Jn(n.context):null;r&&(r.disableParallelShaderCompile=n.disableParallelCompilation);let s=n.existingPipelineContext||e(n.shaderProcessingContext);return s._name=n.name,n.name&&r&&(r.cachedPipelines[n.name]=s),t(s,n.vertex,n.fragment,!!n.createAsRaw,"","",n.rebuildRebind,n.defines,n.transformFeedbackVaryings,"",()=>{i(s,()=>{var a;(a=n.onRenderingStateCompiled)==null||a.call(n,s)})}),s}catch(r){throw te.Error("Error compiling effect"),r}}});function bG(n,e,t){try{if(n())return e(),!0}catch(i){return t==null||t(i),!0}return!1}var iR,Fo,Pl,Ll=y(()=>{iR=[],Fo=class{static SetImmediate(e){iR.length===0&&setTimeout(()=>{let t=iR;iR=[];for(let i of t)i()},1),iR.push(e)}};Pl=(n,e,t,i=16,r=3e4,s=!0,a)=>{if(s&&bG(n,e,t))return null;let o=!1,l=null,c=()=>{if(!o&&!bG(n,e,t)){if(r-=i,r<0){t==null||t(new Error("Operation timed out after maximum retries. "+(a||"")),!0);return}l=setTimeout(c,i)}};return l=setTimeout(c,i),()=>{o=!0,l!==null&&clearTimeout(l)}}});var pr,Nu=y(()=>{Si();wt();k();QP();Ll();pr=class n{static get ShadersRepository(){return x.ShadersRepository}static set ShadersRepository(e){x.ShadersRepository=e}get isDisposed(){return this._isDisposed}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new re),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r=null,s,a=null,o=null,l=null,c=null,f,d="",u=0,h){var p,_,v,E;this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new re,this.onErrorObservable=new re,this._onBindObservable=null,this._isDisposed=!1,this._refCount=1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._disableParallelShaderCompilation=!1,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this._onReleaseEffectsObserver=null,this.name=e,this._key=d;let m=this._key.replace(/\r/g,"").replace(/\n/g,"|"),g;if(t.attributes){let S=t;if(this._engine=i,this._attributesNames=S.attributes,this._uniformsNames=S.uniformsNames.concat(S.samplers),this._samplerList=S.samplers.slice(),this.defines=S.defines,this.onError=S.onError,this.onCompiled=S.onCompiled,this._fallbacks=S.fallbacks,this._indexParameters=S.indexParameters,this._transformFeedbackVaryings=S.transformFeedbackVaryings||null,this._multiTarget=!!S.multiTarget,this._shaderLanguage=(p=S.shaderLanguage)!=null?p:0,this._disableParallelShaderCompilation=!!S.disableParallelShaderCompilation,S.uniformBuffersNames){this._uniformBuffersNamesList=S.uniformBuffersNames.slice();for(let T=0;T<S.uniformBuffersNames.length;T++)this._uniformBuffersNames[S.uniformBuffersNames[T]]=T}this._processFinalCode=(_=S.processFinalCode)!=null?_:null,this._processCodeAfterIncludes=(v=S.processCodeAfterIncludes)!=null?v:void 0,h=S.extraInitializationsAsync,g=S.existingPipelineContext}else this._engine=s,this.defines=a==null?"":a,this._uniformsNames=i.concat(r),this._samplerList=r?r.slice():[],this._attributesNames=t,this._uniformBuffersNamesList=[],this._shaderLanguage=u,this.onError=c,this.onCompiled=l,this._indexParameters=f,this._fallbacks=o;this._engine.shaderPlatformName==="WEBGL2"&&(g=(E=AG(m,this._engine._gl))!=null?E:g),this._attributeLocationByName={},this.uniqueId=n._UniqueIdSeed++,g?(this._pipelineContext=g,this._pipelineContext.setEngine(this._engine),this._onRenderingStateCompiled(this._pipelineContext),this._pipelineContext.program&&(this._pipelineContext.program.__SPECTOR_rebuildProgram=this._rebuildProgram.bind(this))):this._processShaderCodeAsync(null,!1,null,h),this._onReleaseEffectsObserver=this._engine.onReleaseEffectsObservable.addOnce(()=>{this._onReleaseEffectsObserver=null,!this.isDisposed&&this.dispose(!0)})}async _processShaderCodeAsync(e=null,t=!1,i=null,r){r&&await r(),this._processingContext=i||this._engine._getShaderProcessingContext(this._shaderLanguage,!1);let s={defines:this.defines.split(`
`),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:e!=null?e:this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:x.GetShadersRepository(this._shaderLanguage),includesShadersStore:x.GetIncludesShadersStore(this._shaderLanguage),version:(this._engine.version*100).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes};xG(s,this.name,this._processFinalCode,(a,o)=>{this._vertexSourceCode=a,this._fragmentSourceCode=o,this._prepareEffect(t)},this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){return!1}}_isReadyInternal(){return this._engine.isDisposed||this._isReady?!0:this._pipelineContext?this._pipelineContext.isReady:!1}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}async whenCompiledAsync(){return await new Promise(e=>{this.executeWhenCompiled(e)})}executeWhenCompiled(e){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&this._checkIsReady(null)}_checkIsReady(e){Pl(()=>this._isReadyInternal()||this._isDisposed,()=>{},t=>{this._processCompilationErrors(t,e)},16,12e4,!0,` - Effect: ${typeof this.name=="string"?this.name:this.key}`)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:(t=(e=this._pipelineContext)==null?void 0:e._getVertexShaderCode())!=null?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:(t=(e=this._pipelineContext)==null?void 0:e._getFragmentShaderCode())!=null?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}getPipelineGenerationOptions(){return{platformName:this._engine.shaderPlatformName,shaderLanguage:this._shaderLanguage,shaderNameOrContent:this.name,key:this._key,defines:this.defines.split(`
`),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!!(this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,i,r){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(s,a)=>{r&&r(a)},this.onCompiled=()=>{var a,o;let s=this.getEngine().scenes;if(s)for(let l=0;l<s.length;l++)s[l].markAllMaterialsAsDirty(127);(o=(a=this._pipelineContext)._handlesSpectorRebuildCallback)==null||o.call(a,i)},this._fallbacks=null,this._prepareEffect()}_onRenderingStateCompiled(e){if(this._pipelineContext=e,this._pipelineContext.setEngine(this._engine),this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,this._attributesNames,this._attributes),this._attributesNames)for(let t=0;t<this._attributesNames.length;t++){let i=this._attributesNames[t];this._attributeLocationByName[i]=this._attributes[t]}this._engine.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh(),n.AutomaticallyClearCodeCache&&this.clearCodeCache()}_prepareEffect(e=!1){let t=this._pipelineContext;this._isReady=!1;try{let i=!!(this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride),r=i?null:this.defines,s=i?this._vertexSourceCodeOverride:this._vertexSourceCode,a=i?this._fragmentSourceCodeOverride:this._fragmentSourceCode,o=this._engine;this._pipelineContext=RG({existingPipelineContext:e?t:null,vertex:s,fragment:a,context:o.shaderPlatformName==="WEBGL2"||o.shaderPlatformName==="WEBGL1"?o._gl:void 0,rebuildRebind:(l,c,f,d)=>this._rebuildProgram(l,c,f,d),defines:r,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,disableParallelCompilation:this._disableParallelShaderCompilation,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:l=>{t&&!e&&this._engine._deletePipelineContext(t),l&&this._onRenderingStateCompiled(l)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContextAsync.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(i){this._processCompilationErrors(i,t)}}_getShaderCodeAndErrorLine(e,t,i){let r=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/,s=null;if(t&&e){let a=t.match(r);if(a&&a.length===2){let o=parseInt(a[1]),l=e.split(`
`,-1);l.length>=o&&(s=`Offending line [${o}] in ${i?"fragment":"vertex"} code: ${l[o-1]}`)}}return[e,s]}_processCompilationErrors(e,t=null){var a,o,l;this._compilationError=e.message;let i=this._attributesNames,r=this._fallbacks;if(te.Error("Unable to compile effect:"),te.Error(`Uniforms: ${this._uniformsNames.join(" ")}`),te.Error(`Attributes: ${i.join(" ")}`),te.Error(`Defines:
`+this.defines),n.LogShaderCodeOnCompilationError){let c=null,f=null,d;(a=this._pipelineContext)!=null&&a._getVertexShaderCode()&&([d,c]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),d&&(te.Error("Vertex code:"),te.Error(d))),(o=this._pipelineContext)!=null&&o._getFragmentShaderCode()&&([d,f]=this._getShaderCodeAndErrorLine((l=this._pipelineContext)==null?void 0:l._getFragmentShaderCode(),this._compilationError,!0),d&&(te.Error("Fragment code:"),te.Error(d))),c&&te.Error(c),f&&te.Error(f)}te.Error("Error: "+this._compilationError);let s=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this),this._engine.onEffectErrorObservable.notifyObservers({effect:this,errors:this._compilationError})};t&&(this._pipelineContext=t,this._isReady=!0,s()),r?(this._pipelineContext=null,r.hasMoreFallbacks?(this._allFallbacksProcessed=!1,te.Error("Trying next fallback."),this.defines=r.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,s(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||s())}get isSupported(){return this._compilationError===""}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){let i=e+"Ex";if(this._samplerList.indexOf(i+"0")===-1){let r=this._samplerList.indexOf(e);for(let a=1;a<t.length;a++){let o=i+(a-1).toString();this._samplerList.splice(r+a,0,o)}let s=0;for(let a of this._samplerList)this._samplers[a]=s,s+=1}this._engine.setTextureArray(this._samplers[e],this._uniforms[e],t,e)}bindUniformBuffer(e,t){let i=this._uniformBuffersNames[t];i===void 0||n._BaseCache[i]===e&&this._engine._features.useUBOBindingCache||(n._BaseCache[i]=e,this._engine.bindUniformBufferBase(e,i,t))}bindUniformBlock(e,t){this._engine.bindUniformBlock(this._pipelineContext,e,t)}setInt(e,t){return this._pipelineContext.setInt(e,t),this}setInt2(e,t,i){return this._pipelineContext.setInt2(e,t,i),this}setInt3(e,t,i,r){return this._pipelineContext.setInt3(e,t,i,r),this}setInt4(e,t,i,r,s){return this._pipelineContext.setInt4(e,t,i,r,s),this}setIntArray(e,t){return this._pipelineContext.setIntArray(e,t),this}setIntArray2(e,t){return this._pipelineContext.setIntArray2(e,t),this}setIntArray3(e,t){return this._pipelineContext.setIntArray3(e,t),this}setIntArray4(e,t){return this._pipelineContext.setIntArray4(e,t),this}setUInt(e,t){return this._pipelineContext.setUInt(e,t),this}setUInt2(e,t,i){return this._pipelineContext.setUInt2(e,t,i),this}setUInt3(e,t,i,r){return this._pipelineContext.setUInt3(e,t,i,r),this}setUInt4(e,t,i,r,s){return this._pipelineContext.setUInt4(e,t,i,r,s),this}setUIntArray(e,t){return this._pipelineContext.setUIntArray(e,t),this}setUIntArray2(e,t){return this._pipelineContext.setUIntArray2(e,t),this}setUIntArray3(e,t){return this._pipelineContext.setUIntArray3(e,t),this}setUIntArray4(e,t){return this._pipelineContext.setUIntArray4(e,t),this}setFloatArray(e,t){return this._pipelineContext.setArray(e,t),this}setFloatArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setFloatArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setFloatArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setArray(e,t){return this._pipelineContext.setArray(e,t),this}setArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setMatrices(e,t){return this._pipelineContext.setMatrices(e,t),this}setMatrix(e,t){return this._pipelineContext.setMatrix(e,t),this}setMatrix3x3(e,t){return this._pipelineContext.setMatrix3x3(e,t),this}setMatrix2x2(e,t){return this._pipelineContext.setMatrix2x2(e,t),this}setFloat(e,t){return this._pipelineContext.setFloat(e,t),this}setBool(e,t){return this._pipelineContext.setInt(e,t?1:0),this}setVector2(e,t){return this._pipelineContext.setVector2(e,t),this}setFloat2(e,t,i){return this._pipelineContext.setFloat2(e,t,i),this}setVector3(e,t){return this._pipelineContext.setVector3(e,t),this}setFloat3(e,t,i,r){return this._pipelineContext.setFloat3(e,t,i,r),this}setVector4(e,t){return this._pipelineContext.setVector4(e,t),this}setQuaternion(e,t){return this._pipelineContext.setQuaternion(e,t),this}setFloat4(e,t,i,r,s){return this._pipelineContext.setFloat4(e,t,i,r,s),this}setColor3(e,t){return this._pipelineContext.setColor3(e,t),this}setColor4(e,t,i){return this._pipelineContext.setColor4(e,t,i),this}setDirectColor4(e,t){return this._pipelineContext.setDirectColor4(e,t),this}clearCodeCache(){this._vertexSourceCode="",this._fragmentSourceCode="",this._fragmentSourceCodeBeforeMigration="",this._vertexSourceCodeBeforeMigration=""}dispose(e=!1){if(e)this._refCount=0;else{if(n.PersistentMode)return;this._refCount--}this._refCount>0||this._isDisposed||(this._onReleaseEffectsObserver&&(this._engine.onReleaseEffectsObservable.remove(this._onReleaseEffectsObserver),this._onReleaseEffectsObserver=null),this._pipelineContext&&tR(this._pipelineContext),this._engine._releaseEffect(this),this.clearCodeCache(),this._isDisposed=!0)}static RegisterShader(e,t,i,r=0){t&&(x.GetShadersStore(r)[`${e}PixelShader`]=t),i&&(x.GetShadersStore(r)[`${e}VertexShader`]=i)}static ResetCache(){n._BaseCache={}}};pr.LogShaderCodeOnCompilationError=!0;pr.PersistentMode=!1;pr.AutomaticallyClearCodeCache=!1;pr._UniqueIdSeed=0;pr._BaseCache={};pr.ShadersStore=x.ShadersStore;pr.IncludesShadersStore=x.IncludesShadersStore});var ys,$P=y(()=>{ys=class n{static SetMatrixPrecision(e){if(n.MatrixTrackPrecisionChange=!1,e&&!n.MatrixUse64Bits&&n.MatrixTrackedMatrices)for(let t=0;t<n.MatrixTrackedMatrices.length;++t){let i=n.MatrixTrackedMatrices[t],r=i._m;i._m=new Array(16);for(let s=0;s<16;++s)i._m[s]=r[s]}n.MatrixUse64Bits=e,n.MatrixCurrentType=n.MatrixUse64Bits?Array:Float32Array,n.MatrixTrackedMatrices=null}};ys.MatrixUse64Bits=!1;ys.MatrixTrackPrecisionChange=!0;ys.MatrixCurrentType=Float32Array;ys.MatrixTrackedMatrices=[]});var br,Ac=y(()=>{qa();br=class{static get Now(){return Ar()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}});var rR,MG=y(()=>{rR=class{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}});var nR,yG=y(()=>{nR=class{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get backFunc(){return this._func}set backFunc(e){this._backFunc!==e&&(this._backFunc=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get backOpStencilFail(){return this._backOpStencilFail}set backOpStencilFail(e){this._backOpStencilFail!==e&&(this._backOpStencilFail=e,this._isStencilOpDirty=!0)}get backOpDepthFail(){return this._backOpDepthFail}set backOpDepthFail(e){this._backOpDepthFail!==e&&(this._backOpDepthFail=e,this._isStencilOpDirty=!0)}get backOpStencilDepthPass(){return this._backOpStencilDepthPass}set backOpStencilDepthPass(e){this._backOpStencilDepthPass!==e&&(this._backOpStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){var e;this.stencilMaterial=void 0,(e=this.stencilGlobal)==null||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){var i;if(!e)return;let t=!this.useStencilGlobalOnly&&!!((i=this.stencilMaterial)!=null&&i.enabled);this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.backFunc=t?this.stencilMaterial.backFunc:this.stencilGlobal.backFunc,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.backOpStencilFail=t?this.stencilMaterial.backOpStencilFail:this.stencilGlobal.backOpStencilFail,this.backOpDepthFail=t?this.stencilMaterial.backOpDepthFail:this.stencilGlobal.backOpDepthFail,this.backOpStencilDepthPass=t?this.stencilMaterial.backOpStencilDepthPass:this.stencilGlobal.backOpStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFuncSeparate(e.FRONT,this.func,this.funcRef,this.funcMask),e.stencilFuncSeparate(e.BACK,this.backFunc,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOpSeparate(e.FRONT,this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),e.stencilOpSeparate(e.BACK,this.backOpStencilFail,this.backOpDepthFail,this.backOpStencilDepthPass),this._isStencilOpDirty=!1))}}});var wu,IG=y(()=>{wu=class n{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.funcRef=1,this.funcMask=255,this.func=n.ALWAYS,this.opStencilFail=n.KEEP,this.opDepthFail=n.KEEP,this.opStencilDepthPass=n.REPLACE,this.backFunc=n.ALWAYS,this.backOpStencilFail=n.KEEP,this.backOpDepthFail=n.KEEP,this.backOpStencilDepthPass=n.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilBackFunc(){return this.backFunc}set stencilBackFunc(e){this.backFunc=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilBackOpStencilFail(){return this.backOpStencilFail}set stencilBackOpStencilFail(e){this.backOpStencilFail=e}get stencilBackOpDepthFail(){return this.backOpDepthFail}set stencilBackOpDepthFail(e){this.backOpDepthFail=e}get stencilBackOpStencilDepthPass(){return this.backOpStencilDepthPass}set stencilBackOpStencilDepthPass(e){this.backOpStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}};wu.ALWAYS=519;wu.KEEP=7680;wu.REPLACE=7681});var tp,JP=y(()=>{tp=class{constructor(e){this._supportBlendParametersPerTarget=e,this._blendFunctionParameters=new Array(32),this._blendEquationParameters=new Array(16),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=Array(8).fill(!1),this._numTargetEnabled=0,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._numTargetEnabled>0}set alphaBlend(e){this.setAlphaBlend(e)}setAlphaBlend(e,t=0){this._alphaBlend[t]!==e&&(e?this._numTargetEnabled++:this._numTargetEnabled--,this._alphaBlend[t]=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,r){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===r||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=r,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,r,s=0){let a=s*4;this._blendFunctionParameters[a+0]===e&&this._blendFunctionParameters[a+1]===t&&this._blendFunctionParameters[a+2]===i&&this._blendFunctionParameters[a+3]===r||(this._blendFunctionParameters[a+0]=e,this._blendFunctionParameters[a+1]=t,this._blendFunctionParameters[a+2]=i,this._blendFunctionParameters[a+3]=r,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t,i=0){let r=i*2;this._blendEquationParameters[r+0]===e&&this._blendEquationParameters[r+1]===t||(this._blendEquationParameters[r+0]=e,this._blendEquationParameters[r+1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend.fill(!1),this._numTargetEnabled=0,this._blendFunctionParameters.fill(null),this._blendEquationParameters.fill(null),this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e,t=1){if(!this.isDirty)return;if(this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1),t===1||!this._supportBlendParametersPerTarget){this._isAlphaBlendDirty&&(this._alphaBlend[0]?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1);return}let i=e;if(this._isAlphaBlendDirty){for(let r=0;r<t;r++){let s=r<this._numTargetEnabled?r:0;this._alphaBlend[s]?i.enableIndexed(e.BLEND,r):i.disableIndexed(e.BLEND,r)}this._isAlphaBlendDirty=!1}if(this._isBlendFunctionParametersDirty){for(let r=0;r<t;r++){let s=r<this._numTargetEnabled?r*4:0;i.blendFuncSeparateIndexed(r,this._blendFunctionParameters[s+0],this._blendFunctionParameters[s+1],this._blendFunctionParameters[s+2],this._blendFunctionParameters[s+3])}this._isBlendFunctionParametersDirty=!1}if(this._isBlendEquationParametersDirty){for(let r=0;r<t;r++){let s=r<this._numTargetEnabled?r*2:0;i.blendEquationSeparateIndexed(r,this._blendEquationParameters[s+0],this._blendEquationParameters[s+1])}this._isBlendEquationParametersDirty=!1}}setAlphaMode(e,t){let i=32774;switch(e){case 0:break;case 7:this.setAlphaBlendFunctionParameters(1,771,1,1,t);break;case 8:this.setAlphaBlendFunctionParameters(1,771,1,771,t);break;case 2:this.setAlphaBlendFunctionParameters(770,771,1,1,t);break;case 6:this.setAlphaBlendFunctionParameters(1,1,0,1,t);break;case 1:this.setAlphaBlendFunctionParameters(770,1,0,1,t);break;case 3:this.setAlphaBlendFunctionParameters(0,769,1,1,t);break;case 4:this.setAlphaBlendFunctionParameters(774,0,1,1,t);break;case 5:this.setAlphaBlendFunctionParameters(770,769,1,1,t);break;case 9:this.setAlphaBlendFunctionParameters(32769,32770,32771,32772,t);break;case 10:this.setAlphaBlendFunctionParameters(1,769,1,771,t);break;case 11:this.setAlphaBlendFunctionParameters(1,1,1,1,t);break;case 12:this.setAlphaBlendFunctionParameters(772,1,0,0,t);break;case 13:this.setAlphaBlendFunctionParameters(775,769,773,771,t);break;case 14:this.setAlphaBlendFunctionParameters(1,771,1,771,t);break;case 15:this.setAlphaBlendFunctionParameters(1,1,1,0,t);break;case 16:this.setAlphaBlendFunctionParameters(775,769,0,1,t);break;case 17:this.setAlphaBlendFunctionParameters(770,771,1,771,t);break;case 18:this.setAlphaBlendFunctionParameters(1,1,1,1,t),i=32775;break;case 19:this.setAlphaBlendFunctionParameters(1,1,1,1,t),i=32776;break;case 20:this.setAlphaBlendFunctionParameters(1,35065,0,1,t);break}this.setAlphaEquationParameters(i,i,t)}}});function CG(n,e){if(Ar()){let{requestAnimationFrame:t}=e||window;if(typeof t=="function")return t(n)}else if(typeof requestAnimationFrame=="function")return requestAnimationFrame(n);return setTimeout(n,16)}var ye,Yr=y(()=>{Si();Nu();Yi();wt();$P();Ac();MG();yG();IG();JP();Mn();ea();qa();Zf();ye=class n{get frameId(){return this._frameId}get isWebGPU(){return this._isWebGPU}_getShaderProcessor(e){return this._shaderProcessor}_resetAlphaMode(){this._alphaMode.fill(-1),this._alphaEquation.fill(-1)}get shaderPlatformName(){return this._shaderPlatformName}_clearEmptyResources(){this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}_getGlobalDefines(e){if(e){this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS;return}else{let t="";return this.isNDCHalfZRange&&(t+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(t&&(t+=`
`),t+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(t&&(t+=`
`),t+="#define USE_EXACT_SRGB_CONVERSIONS"),t}}_rebuildInternalTextures(){let e=this._internalTexturesCache.slice();for(let t of e)t._rebuild()}_rebuildRenderTargetWrappers(){let e=this._renderTargetWrapperCache.slice();for(let t of e)t._rebuild()}_rebuildEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}pr.ResetCache()}_rebuildGraphicsResources(){var e;this.wipeCaches(!0),this._rebuildEffects(),(e=this._rebuildComputeEffects)==null||e.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){te.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout(()=>{this._clearEmptyResources();let t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,r=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=r,this._stencilState.stencilTest=s,this._flagContextRestored()},0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return 0}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){let e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e){this._activeRenderLoops.length=0,this._cancelFrame();return}let t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),this._activeRenderLoops.length==0&&this._cancelFrame())}_cancelFrame(){if(this._frameHandler!==0){let e=this._frameHandler;if(this._frameHandler=0,Ar()){let{cancelAnimationFrame:t}=this.getHostWindow()||window;if(typeof t=="function")return t(e)}else if(typeof cancelAnimationFrame=="function")return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}get maxFPS(){return this._maxFPS}set maxFPS(e){if(this._maxFPS=e,e!==void 0){if(e<=0){this._minFrameTime=Number.MAX_VALUE;return}this._minFrameTime=1e3/e}}_isOverFrameTime(e){if(!e||this._maxFPS===void 0)return!1;let t=e-this._lastFrameTime;return this._lastFrameTime=e,this._renderAccumulator+=t,this._renderAccumulator<this._minFrameTime?!0:(this._renderAccumulator-=this._minFrameTime,this._renderAccumulator>this._minFrameTime&&(this._renderAccumulator=this._minFrameTime),!1)}_processFrame(e){if(this._frameHandler=0,!this._contextWasLost&&!this._isOverFrameTime(e)){let t=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(t=!1),t&&(this.beginFrame(),!this.skipFrameRender&&!this._renderViews()&&this._renderFrame(),this.endFrame())}}_renderLoop(e){this._processFrame(e),this._activeRenderLoops.length>0&&this._frameHandler===0&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e<this._activeRenderLoops.length;e++){let t=this._activeRenderLoops[e];t()}}_renderViews(){return!1}_queueNewFrame(e,t){return CG(e,t)}runRenderLoop(e){this._activeRenderLoops.indexOf(e)===-1&&(this._activeRenderLoops.push(e),this._activeRenderLoops.length===1&&this._frameHandler===0&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){let e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){let e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}getHostWindow(){return Ar()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=!0}_rebuildTextures(){for(let e of this.scenes)e._rebuildTextures();for(let e of this._virtualScenes)e._rebuildTextures()}_releaseRenderTargetWrapper(e){let t=this._renderTargetWrapperCache.indexOf(e);t!==-1&&this._renderTargetWrapperCache.splice(t,1)}get currentViewport(){return this._cachedViewport}setViewport(e,t,i){let r=t||this.getRenderWidth(),s=i||this.getRenderHeight(),a=e.x||0,o=e.y||0;this._cachedViewport=e,this._viewport(a*r,o*s,r*e.width,s*e.height)}createCanvasImage(){return document.createElement("img")}createCanvasPath2D(e){return new Path2D(e)}get description(){let e=this.name+this.version;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}_createTextureBase(e,t,i,r,s=3,a=null,o=null,l,c,f=null,d=null,u=null,h=null,m,g,p){e=e||"";let _=e.substring(0,5)==="data:",v=e.substring(0,5)==="blob:",E=_&&e.indexOf(";base64,")!==-1,S=d||new Xi(this,1);S!==d&&(S.label=e.substring(0,60));let T=e;this._transformTextureUrl&&!E&&!d&&!f&&(e=this._transformTextureUrl(e)),T!==e&&(S._originalUrl=T);let A=e.lastIndexOf("."),R=h||(A>-1?e.substring(A).toLowerCase():"");R.indexOf("?")>-1&&(R=R.split("?")[0]);let I=n.GetCompatibleTextureLoader(R,m);r&&r.addPendingData(S),S.url=e,S.generateMipMaps=!t,S.samplingMode=s,S.invertY=i,S._useSRGBBuffer=this._getUseSRGBBuffer(!!p,t),this._doNotHandleContextLost||(S._buffer=f);let C=null;a&&!d&&(C=S.onLoadedObservable.add(a)),d||this._internalTexturesCache.push(S);let L=(w,G)=>{r&&r.removePendingData(S),e===T?(C&&S.onLoadedObservable.remove(C),Oe.UseFallbackTexture&&e!==Oe.FallbackTexture&&this._createTextureBase(Oe.FallbackTexture,t,S.invertY,r,s,null,o,l,c,f,S),w=(w||"Unknown error")+(Oe.UseFallbackTexture?" - Fallback texture was used":""),S.onErrorObservable.notifyObservers({message:w,exception:G}),o&&o(w,G)):(te.Warn(`Failed to load ${e}, falling back to ${T}`),this._createTextureBase(T,t,S.invertY,r,s,a,o,l,c,f,S,u,h,m,g,p))};if(I){let w=async G=>{(await I).loadData(G,S,(N,B,V,q,K,J)=>{J?L("TextureLoader failed to load data"):l(S,R,r,{width:N,height:B},S.invertY,!V,q,()=>(K(),!1),s)},g)};if(!f)this._loadFile(e,async G=>{try{await w(new Uint8Array(G))}catch(O){L("Failed to parse texture data",O)}},void 0,r?r.offlineProvider:void 0,!0,(G,O)=>{L("Unable to load "+(G&&G.responseURL,O))});else{let G=async O=>{try{await w(O)}catch(N){L("Failed to parse texture data",N)}};f instanceof ArrayBuffer?G(new Uint8Array(f)):ArrayBuffer.isView(f)?G(f):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null)}}else{let w=G=>{v&&!this._doNotHandleContextLost&&(S._buffer=G),l(S,R,r,G,S.invertY,t,!1,c,s)};!_||E?f&&(typeof f.decoding=="string"||f.close)?w(f):n._FileToolsLoadImage(e||"",w,L,r?r.offlineProvider:null,m,S.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0,this):typeof f=="string"||f instanceof ArrayBuffer||ArrayBuffer.isView(f)||f instanceof Blob?n._FileToolsLoadImage(f,w,L,r?r.offlineProvider:null,m,S.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0,this):f&&w(f)}return S}_rebuildBuffers(){for(let e of this._uniformBuffers)e._rebuildAfterContextLost()}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:jf()?document:null}getLoadedTexturesCache(){return this._internalTexturesCache}clearInternalTexturesCache(){this._internalTexturesCache.length=0}getCaps(){return this._caps}resetTextureCache(){for(let e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}get name(){return this._name}set name(e){this._name=e}static get NpmPackage(){return"babylonjs@9.6.0"}static get Version(){return"9.6.0"}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get isStencilEnable(){return this._isStencilEnable}getCreationOptions(){return this._creationOptions}constructor(e,t,i){var a,o,l,c,f,d,u,h,m,g;this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new rR,this._stencilStateComposer=new nR,this._stencilState=new wu,this._alphaState=new tp(!1),this._alphaMode=Array(8).fill(-1),this._alphaEquation=Array(8).fill(-1),this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this._enableGPUDebugMarkers=!1,this.onCanvasBlurObservable=new re,this.onCanvasFocusObservable=new re,this.onNewSceneAddedObservable=new re,this.onResizeObservable=new re,this.onCanvasPointerOutObservable=new re,this.onEffectErrorObservable=new re,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=0,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new re,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=p=>this._renderLoop(p),this._lastFrameTime=0,this._renderAccumulator=0,this.skipFrameRender=!1,this.onBeforeShaderCompilationObservable=new re,this.onAfterShaderCompilationObservable=new re,this.onBeginFrameObservable=new re,this.onEndFrameObservable=new re,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new re,this.onContextRestoredObservable=new re,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new re,this.onReleaseEffectsObservable=new re,Oe.Instances.push(this),this.startTime=br.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,ys.SetMatrixPrecision(!!t.useLargeWorldRendering||!!t.useHighPrecisionMatrix),Tc()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=i!=null?i:!1,t.antialias=e!=null?e:t.antialias,t.deterministicLockstep=(a=t.deterministicLockstep)!=null?a:!1,t.lockstepMaxSteps=(o=t.lockstepMaxSteps)!=null?o:4,t.timeStep=(l=t.timeStep)!=null?l:1/60,t.stencil=(c=t.stencil)!=null?c:!0,this._audioContext=(d=(f=t.audioEngineOptions)==null?void 0:f.audioContext)!=null?d:null,this._audioDestination=(h=(u=t.audioEngineOptions)==null?void 0:u.audioDestination)!=null?h:null,this.premultipliedAlpha=(m=t.premultipliedAlpha)!=null?m:!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=(g=t.useExactSrgbConversions)!=null?g:!1;let r=Ar()&&window.devicePixelRatio||1,s=t.limitDeviceRatio||r;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(s,r):1,this._lastDevicePixelRatio=r,this._creationOptions=t}resize(e=!1){var r,s;let t,i;if(this.adaptToDeviceRatio){let a=Ar()&&window.devicePixelRatio||1,o=this._lastDevicePixelRatio/a;this._lastDevicePixelRatio=a,this._hardwareScalingLevel*=o}if(Ar()&&jf())if(this._renderingCanvas){let a=(s=(r=this._renderingCanvas).getBoundingClientRect)==null?void 0:s.call(r);t=this._renderingCanvas.clientWidth||(a==null?void 0:a.width)||this._renderingCanvas.width*this._hardwareScalingLevel||100,i=this._renderingCanvas.clientHeight||(a==null?void 0:a.height)||this._renderingCanvas.height*this._hardwareScalingLevel||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){if(!this._renderingCanvas||(e=e|0,t=t|0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t))return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(let r=0;r<this.scenes.length;r++){let s=this.scenes[r];for(let a=0;a<s.cameras.length;a++){let o=s.cameras[a];o._currentRenderId=0}}this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this)}return!0}createRawTexture(e,t,i,r,s,a,o,l,c,f,d,u){throw $e("engine.rawTexture")}createRawCubeTexture(e,t,i,r,s,a,o,l){throw $e("engine.rawTexture")}createRawTexture3D(e,t,i,r,s,a,o,l,c,f,d){throw $e("engine.rawTexture")}createRawTexture2DArray(e,t,i,r,s,a,o,l,c,f,d,u){throw $e("engine.rawTexture")}_sharedInit(e){this._renderingCanvas=e}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{let e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&jf()&&"ontouchend"in document},this._checkForMobile(),Ar()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){var t;(t=this._drawCalls)==null||t.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return this._timeStep*1e3}_createImageBitmapFromSource(e,t){throw new Error("createImageBitmapFromSource is not implemented")}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){throw new Error("resizeImageBitmap is not implemented")}getFontOffset(e){throw new Error("getFontOffset is not implemented")}static _CreateCanvas(e,t){if(typeof document=="undefined")return new OffscreenCanvas(e,t);let i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return n._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,r,s,a,o){throw $e("FileTools")}_loadFile(e,t,i,r,s,a){let o=kx(e,t,i,r,s,a);return this._activeRequests.push(o),o.onCompleteObservable.add(()=>{let l=this._activeRequests.indexOf(o);l!==-1&&this._activeRequests.splice(l,1)}),o}static _FileToolsLoadFile(e,t,i,r,s,a){if($m.loadFile)return $m.loadFile(e,t,i,r,s,a);throw $e("FileTools")}dispose(){var t;for(this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();(t=this.releaseComputeEffects)==null||t.call(this),pr.ResetCache();for(let i of this._activeRequests)i.abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),this.onEffectErrorObservable.clear(),Ar()&&window.removeEventListener("resize",this._checkForMobile);let e=Oe.Instances.indexOf(this);e>=0&&Oe.Instances.splice(e,1),Oe.Instances.length||(Oe.OnEnginesDisposedObservable.notifyObservers(this),Oe.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw $e("LoadingScreen")}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i<Oe.Instances.length;i++){let r=Oe.Instances[i];for(let s=0;s<r.scenes.length;s++)r.scenes[s].markAllMaterialsAsDirty(e,t)}}static GetCompatibleTextureLoader(e,t){return null}};ye._RenderPassIdCounter=0;ye._RescalePostProcessFactory=null;ye.CollisionsEpsilon=.001;ye.QueueNewFrame=CG});function sR(n){return n.getPipelineContext===void 0}var eL=y(()=>{});var aR,PG=y(()=>{aR=class{constructor(){this.shaderLanguage=0}postProcessor(e,t,i,r,s){if(s.drawBuffersExtensionDisabled){let a=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(a,"")}return e}}});var cde,oR,LG=y(()=>{cde=/(flat\s)?\s*varying\s*.*/,oR=class{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return cde.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){let r=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,s=/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;if(e=e.replace(s,""),e=e.replace(/texture2D\s*\(/g,"texture("),i){let a=e.search(/layout *\(location *= *0\) *out/g)!==-1,o=t.indexOf("#define DUAL_SOURCE_BLENDING")!==-1,l=o?`layout(location = 0, index = 0) out vec4 glFragColor;
layout(location = 0, index = 1) out vec4 glFragColor2;
`:`layout(location = 0) out vec4 glFragColor;
`;o&&(e=`#extension GL_EXT_blend_func_extended : require
`+e),e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/void\s+?main\s*\(/g,(r||a?"":l)+"void main(")}else if(t.indexOf("#define VERTEXOUTPUT_INVARIANT")>=0&&(e=`invariant gl_Position;
`+e),t.indexOf("#define MULTIVIEW")!==-1)return`#extension GL_OVR_multiview2 : require
layout (num_views = 2) in;
`+e;return e}}});var Fu,tL=y(()=>{Fu=class n{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=n._Counter++}};Fu._Counter=0});var Dl,lR=y(()=>{tL();Dl=class extends Fu{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}});function Bu(n){let e=1;do e*=2;while(e<n);return e===n}function pv(n,e,t){return n*(1-t)+e*t}function iL(n){let e=DG(n),t=cR(n);return e-n>n-t?t:e}function DG(n){return n--,n|=n>>1,n|=n>>2,n|=n>>4,n|=n>>8,n|=n>>16,n++,n}function cR(n){return n=n|n>>1,n=n|n>>2,n=n|n>>4,n=n|n>>8,n=n|n>>16,n-(n>>1)}function Un(n,e,t=2){let i;switch(t){case 1:i=cR(n);break;case 2:i=iL(n);break;default:i=DG(n);break}return Math.min(i,e)}var Bo=y(()=>{});var ip,rL=y(()=>{ip=class{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&(e=t.createTexture(),!e))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(let e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t,i;return(i=(t=this._MSAARenderBuffers)==null?void 0:t[e])!=null?i:null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}});function nL(n){return n===13||n===14||n===15||n===16||n===17||n===18||n===19}function xc(n){return n===13||n===17||n===18||n===19}var gv=y(()=>{});var OG={};Be(OG,{ThinEngine:()=>Pt});var sL,Pt,Is=y(()=>{Nu();HP();Yr();eL();wt();qa();PG();LG();lR();Bo();rL();ea();Zf();QP();gv();JP();sL=class{},Pt=class n extends ye{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return pr.ShadersRepository}static set ShadersRepository(e){pr.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,i,r){if(i=i||{},super(t!=null?t:i.antialias,i,r),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let s;if(e.getContext){if(s=e,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();let l=navigator.userAgent;for(let c of n.ExceptionList){let f=c.key,d=c.targets;if(new RegExp(f).test(l)){if(c.capture&&c.captureConstraint){let h=c.capture,m=c.captureConstraint,p=new RegExp(h).exec(l);if(p&&p.length>0&&parseInt(p[p.length-1])>=m)continue}for(let h of d)switch(h){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1;break}}}}if(this._doNotHandleContextLost?this._onContextLost=()=>{Wx(this._gl)}:(this._onContextLost=l=>{l.preventDefault(),this._contextWasLost=!0,Wx(this._gl),te.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},s.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),s.addEventListener("webglcontextlost",this._onContextLost,!1),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=s.getContext("webgl2",i)||s.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(l){}if(!this._gl){if(!s)throw new Error("The provided canvas is null or undefined.");try{this._gl=s.getContext("webgl",i)||s.getContext("experimental-webgl",i)}catch(l){throw new Error("WebGL not supported",{cause:l})}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,s=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";let l=this._gl.getContextAttributes();l&&(i.stencil=l.stencil)}this._sharedInit(s),this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),i.useHighPrecisionFloats!==void 0&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let l=0;l<this._caps.maxVertexAttribs;l++)this._currentBufferPointers[l]=new sL;this._shaderProcessor=this.webGLVersion>1?new oR:new aR;let a=`Babylon.js v${n.Version}`;te.Log(a+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",a);let o=Jn(this._gl);o.validateShaderPrograms=this.validateShaderPrograms,o.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(let e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_initGLContext(){var i;this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),shaderFloatPrecision:0,parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||this._gl.getExtension("OES_standard_derivatives")!==null,maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||this._gl.getExtension("OES_element_index_uint")!==null,fragmentDepthSupported:this._webGLVersion>1||this._gl.getExtension("EXT_frag_depth")!==null,highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),blendFloat:this._gl.getExtension("EXT_float_blend")!==null,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:this._webGLVersion!==1,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1,textureNorm16:!!this._gl.getExtension("EXT_texture_norm16"),blendParametersPerTarget:!1,dualSourceBlending:!1,supportReadWriteStorageTextures:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);let e=this._gl.getExtension("WEBGL_debug_renderer_info");e!=null&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),this._gl.HALF_FLOAT_OES!==36193&&(this._gl.HALF_FLOAT_OES=36193),this._gl.RGBA16F!==34842&&(this._gl.RGBA16F=34842),this._gl.RGBA32F!==34836&&(this._gl.RGBA32F=34836),this._gl.DEPTH24_STENCIL8!==35056&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(this._webGLVersion===1&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=((i=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))!=null?i:0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.textureNorm16&&(this._gl.R16_EXT=33322,this._gl.RG16_EXT=33324,this._gl.RGB16_EXT=32852,this._gl.RGBA16_EXT=32859,this._gl.R16_SNORM_EXT=36760,this._gl.RG16_SNORM_EXT=36761,this._gl.RGB16_SNORM_EXT=36762,this._gl.RGBA16_SNORM_EXT=36763);let t=this._gl.getExtension("OES_draw_buffers_indexed");if(this._caps.blendParametersPerTarget=!!t,this._alphaState=new tp(this._caps.blendParametersPerTarget),t&&(this._gl.blendEquationSeparateIndexed=t.blendEquationSeparateiOES.bind(t),this._gl.blendEquationIndexed=t.blendEquationiOES.bind(t),this._gl.blendFuncSeparateIndexed=t.blendFuncSeparateiOES.bind(t),this._gl.blendFuncIndexed=t.blendFunciOES.bind(t),this._gl.colorMaskIndexed=t.colorMaskiOES.bind(t),this._gl.disableIndexed=t.disableiOES.bind(t),this._gl.enableIndexed=t.enableiOES.bind(t)),this._caps.dualSourceBlending=!!this._gl.getExtension("WEBGL_blend_func_extended"),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&this._gl.HALF_FLOAT_OES!==5131&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=this._maxMSAASamplesOverride!==null?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES),this._caps.maxDrawBuffers=this._gl.getParameter(this._gl.MAX_DRAW_BUFFERS);else{let r=this._gl.getExtension("WEBGL_draw_buffers");if(r!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=r.drawBuffersWEBGL.bind(r),this._caps.maxDrawBuffers=this._gl.getParameter(r.MAX_DRAW_BUFFERS_WEBGL),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let s=0;s<16;s++)this._gl["COLOR_ATTACHMENT"+s+"_WEBGL"]=r["COLOR_ATTACHMENT"+s+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{let r=this._gl.getExtension("WEBGL_depth_texture");r!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=r.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{let r=this._gl.getExtension("OES_vertex_array_object");r!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=r.createVertexArrayOES.bind(r),this._gl.bindVertexArray=r.bindVertexArrayOES.bind(r),this._gl.deleteVertexArray=r.deleteVertexArrayOES.bind(r))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{let r=this._gl.getExtension("ANGLE_instanced_arrays");r!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=r.drawArraysInstancedANGLE.bind(r),this._gl.drawElementsInstanced=r.drawElementsInstancedANGLE.bind(r),this._gl.vertexAttribDivisor=r.vertexAttribDivisorANGLE.bind(r)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){let r=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),s=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);if(r&&s&&(this._caps.highPrecisionShaderSupported=r.precision!==0&&s.precision!==0,this._caps.shaderFloatPrecision=Math.min(r.precision,s.precision)),!this._shouldUseHighPrecisionShader){let a=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.MEDIUM_FLOAT),o=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.MEDIUM_FLOAT);a&&o&&(this._caps.shaderFloatPrecision=Math.min(a.precision,o.precision))}this._caps.shaderFloatPrecision<10&&(this._caps.shaderFloatPrecision=10)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{let r=this._gl.getExtension("EXT_blend_minmax");r!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=r.MAX_EXT,this._gl.MIN=r.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{let r=this._gl.getExtension("EXT_sRGB");r!=null&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:r.SRGB_EXT,SRGB8:r.SRGB_ALPHA_EXT,SRGB8_ALPHA8:r.SRGB_ALPHA_EXT})}if(this._creationOptions){let r=this._creationOptions.forceSRGBBufferSupportState;r!==void 0&&(this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&r)}}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let r=0;r<this._maxSimultaneousTextures;r++)this._nextFreeTextureSlots.push(r);this._glRenderer==="Mali-G72"&&(this._caps.disableMorphTargetTexture=!0)}_initFeatures(){this._features={forceBitmapOverHTMLImageElement:typeof HTMLImageElement=="undefined",supportRenderAndCopyToLodForFloatTextures:this._webGLVersion!==1,supportDepthStencilTexture:this._webGLVersion!==1,supportShadowSamplers:this._webGLVersion!==1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:this._webGLVersion!==1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:this._webGLVersion!==1,basisNeedsPOT:this._webGLVersion===1,support3DTextures:this._webGLVersion!==1,needTypeSuffixInShaderConstants:this._webGLVersion!==1,supportMSAA:this._webGLVersion!==1,supportSSAO2:this._webGLVersion!==1,supportIBLShadows:this._webGLVersion!==1,supportExtendedTextureFormats:this._webGLVersion!==1,supportSwitchCaseInShader:this._webGLVersion!==1,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);let e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}extractDriverInfo(){let e=this.getGlInfo();return e&&e.renderer?e.renderer:""}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight}clear(e,t,i,r=!1,s=0){var l,c;let a=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=a;let o=0;if(t&&e){let f=!0;if(this._currentRenderTarget){let d=(l=this._currentRenderTarget.texture)==null?void 0:l.format;if(d===8||d===9||d===10||d===11){let u=(c=this._currentRenderTarget.texture)==null?void 0:c.type;u===7||u===5?(n._TempClearColorUint32[0]=e.r*255,n._TempClearColorUint32[1]=e.g*255,n._TempClearColorUint32[2]=e.b*255,n._TempClearColorUint32[3]=e.a*255,this._gl.clearBufferuiv(this._gl.COLOR,0,n._TempClearColorUint32),f=!1):(n._TempClearColorInt32[0]=e.r*255,n._TempClearColorInt32[1]=e.g*255,n._TempClearColorInt32[2]=e.b*255,n._TempClearColorInt32[3]=e.a*255,this._gl.clearBufferiv(this._gl.COLOR,0,n._TempClearColorInt32),f=!1)}}f&&(this._gl.clearColor(e.r,e.g,e.b,e.a!==void 0?e.a:1),o|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),o|=this._gl.DEPTH_BUFFER_BIT),r&&(this._gl.clearStencil(s),o|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(o)}_viewport(e,t,i,r){(e!==this._viewportCached.x||t!==this._viewportCached.y||i!==this._viewportCached.z||r!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r,this._gl.viewport(e,t,i,r))}endFrame(){super.endFrame(),this._badOS&&this.flushFramebuffer()}get performanceMonitor(){throw new Error("Not Supported by ThinEngine")}bindFramebuffer(e,t=0,i,r,s,a=0,o=0){var d,u,h,m,g,p;let l=e;this._currentRenderTarget&&this._resolveAndGenerateMipMapsFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(l._framebuffer);let c=this._gl;e.isMulti||(e.is2DArray||e.is3D?(c.framebufferTextureLayer(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,(d=e.texture._hardwareTexture)==null?void 0:d.underlyingResource,a,o),l._currentLOD=a):e.isCube?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+t,(u=e.texture._hardwareTexture)==null?void 0:u.underlyingResource,a):l._currentLOD!==a&&(c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,(h=e.texture._hardwareTexture)==null?void 0:h.underlyingResource,a),l._currentLOD=a));let f=e._depthStencilTexture;if(f){e.is3D&&(e.texture.width!==f.width||e.texture.height!==f.height||e.texture.depth!==f.depth)&&te.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment");let _=e._depthStencilTextureWithStencil?c.DEPTH_STENCIL_ATTACHMENT:c.DEPTH_ATTACHMENT;e.is2DArray||e.is3D?c.framebufferTextureLayer(c.FRAMEBUFFER,_,(m=f._hardwareTexture)==null?void 0:m.underlyingResource,a,o):e.isCube?c.framebufferTexture2D(c.FRAMEBUFFER,_,c.TEXTURE_CUBE_MAP_POSITIVE_X+t,(g=f._hardwareTexture)==null?void 0:g.underlyingResource,a):c.framebufferTexture2D(c.FRAMEBUFFER,_,c.TEXTURE_2D,(p=f._hardwareTexture)==null?void 0:p.underlyingResource,a)}l._MSAAFramebuffer&&this._bindUnboundFramebuffer(l._MSAAFramebuffer),this._cachedViewport&&!s?this.setViewport(this._cachedViewport,i,r):(i||(i=e.width,a&&(i=i/Math.pow(2,a))),r||(r=e.height,a&&(r=r/Math.pow(2,a))),this._viewport(0,0,i,r)),this.wipeCaches()}setStateCullFaceType(e,t){var r,s;let i=(s=(r=this.cullBackFaces)!=null?r:e)==null||s?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==i||t)&&(this._depthCullingState.cullFace=i)}setState(e,t=0,i,r=!1,s,a,o=0){(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e),this.setStateCullFaceType(s,i),this.setZOffset(t),this.setZOffsetUnits(o);let l=r?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==l||i)&&(this._depthCullingState.frontFace=l),this._stencilStateComposer.stencilMaterial=a}_resolveAndGenerateMipMapsFramebuffer(e,t=!1){e.disableAutomaticMSAAResolve||(e.isMulti?this.resolveMultiFramebuffer(e):this.resolveFramebuffer(e)),t||(e.isMulti?this.generateMipMapsMultiFramebuffer(e):this.generateMipMapsFramebuffer(e))}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return this._currentFramebuffer===null}generateMipmaps(e){let t=this._getTextureTarget(e);this._bindTextureDirectly(t,e,!0),this._gl.generateMipmap(t),this._bindTextureDirectly(t,null)}unBindFramebuffer(e,t,i){let r=e;this._currentRenderTarget=null,this._resolveAndGenerateMipMapsFramebuffer(e,t),i&&(r._MSAAFramebuffer&&this._bindUnboundFramebuffer(r._framebuffer),i()),this._bindUnboundFramebuffer(null)}generateMipMapsFramebuffer(e){var t;!e.isMulti&&((t=e.texture)!=null&&t.generateMipMaps)&&!e.isCube&&this.generateMipmaps(e.texture)}resolveFramebuffer(e){let t=e,i=this._gl;if(!t._MSAAFramebuffer||t.isMulti)return;let r=t.resolveMSAAColors?i.COLOR_BUFFER_BIT:0;r|=t._generateDepthBuffer&&t.resolveMSAADepth?i.DEPTH_BUFFER_BIT:0,r|=t._generateStencilBuffer&&t.resolveMSAAStencil?i.STENCIL_BUFFER_BIT:0,i.bindFramebuffer(i.READ_FRAMEBUFFER,t._MSAAFramebuffer),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),i.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,r,i.NEAREST)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e,t,i){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){let i=this._gl.createBuffer();if(!i)throw new Error("Unable to create vertex buffer");let r=new Dl(i);return this.bindArrayBuffer(r),typeof e!="number"?e instanceof Array?(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t),r.capacity=e.length*4):(this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),r.capacity=e.byteLength):(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Uint8Array(e),t),r.capacity=e),this._resetVertexBufferBinding(),r.references=1,r}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,i){let r=this._gl.createBuffer(),s=new Dl(r);if(!r)throw new Error("Unable to create index buffer");this.bindIndexBuffer(s);let a=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,a,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),s.references=1,s.is32Bits=a.BYTES_PER_ELEMENT===4,s}_normalizeIndexData(e){if(e.BYTES_PER_ELEMENT===2)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let i=0;i<e.length;i++)if(e[i]>=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){let r=e.program,s=this._gl.getUniformBlockIndex(r,t);this._gl.uniformBlockBinding(r,s,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,r,s,a,o){let l=this._currentBufferPointers[t];if(!l)return;let c=!1;l.active?(l.buffer!==e&&(l.buffer=e,c=!0),l.size!==i&&(l.size=i,c=!0),l.type!==r&&(l.type=r,c=!0),l.normalized!==s&&(l.normalized=s,c=!0),l.stride!==a&&(l.stride=a,c=!0),l.offset!==o&&(l.offset=o,c=!0)):(c=!0,l.active=!0,l.index=t,l.size=i,l.type=r,l.normalized=s,l.stride=a,l.offset=o,l.buffer=e),(c||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),r===this._gl.UNSIGNED_INT||r===this._gl.INT?this._gl.vertexAttribIPointer(t,i,r,a,o):this._gl.vertexAttribPointer(t,i,r,s,a,o))}_bindIndexBufferWithCache(e){e!=null&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){let r=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s<r.length;s++){let a=t.getAttributeLocation(s);if(a>=0){let o=r[s],l=null;if(i&&(l=i[o]),l||(l=e[o]),!l)continue;this._gl.enableVertexAttribArray(a),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[a]=!0);let c=l.getBuffer();c&&(this._vertexAttribPointer(c,a,l.getSize(),l.type,l.normalized,l.byteStride,l.byteOffset),l.getIsInstanced()&&(this._gl.vertexAttribDivisor(a,l.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(a),this._currentInstanceBuffers.push(c))))}}}recordVertexArrayObject(e,t,i,r){let s=this._gl.createVertexArray();if(!s)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,r),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=t!=null&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,r,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;let a=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let o=0;for(let l=0;l<a;l++)if(l<i.length){let c=s.getAttributeLocation(l);c>=0&&(this._gl.enableVertexAttribArray(c),this._vertexAttribArraysEnabled[c]=!0,this._vertexAttribPointer(e,c,i[l],this._gl.FLOAT,!1,r,o)),o+=i[l]*4}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,r){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,r)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t<i;t++){let r=this._currentInstanceBuffers[t];e!=r&&r.references&&(e=r,this.bindArrayBuffer(r));let s=this._currentInstanceLocations[t];this._gl.vertexAttribDivisor(s,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0}releaseVertexArrayObject(e){this._gl.deleteVertexArray(e)}_releaseBuffer(e){return e.references--,e.references===0?(this._deleteBuffer(e),!0):!1}_deleteBuffer(e){this._gl.deleteBuffer(e.underlyingResource)}updateAndBindInstancesBuffer(e,t,i){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),i[0].index!==void 0)this.bindInstancesBuffer(e,i,!0);else for(let r=0;r<4;r++){let s=i[r];this._vertexAttribArraysEnabled[s]||(this._gl.enableVertexAttribArray(s),this._vertexAttribArraysEnabled[s]=!0),this._vertexAttribPointer(e,s,4,this._gl.FLOAT,!1,64,r*16),this._gl.vertexAttribDivisor(s,1),this._currentInstanceLocations.push(s),this._currentInstanceBuffers.push(e)}}bindInstancesBuffer(e,t,i=!0){this.bindArrayBuffer(e);let r=0;if(i)for(let s=0;s<t.length;s++){let a=t[s];r+=a.attributeSize*4}for(let s=0;s<t.length;s++){let a=t[s];a.index===void 0&&(a.index=this._currentEffect.getAttributeLocationByName(a.attributeName)),!(a.index<0)&&(this._vertexAttribArraysEnabled[a.index]||(this._gl.enableVertexAttribArray(a.index),this._vertexAttribArraysEnabled[a.index]=!0),this._vertexAttribPointer(e,a.index,a.attributeSize,a.attributeType||this._gl.FLOAT,a.normalized||!1,r,a.offset),this._gl.vertexAttribDivisor(a.index,a.divisor===void 0?1:a.divisor),this._currentInstanceLocations.push(a.index),this._currentInstanceBuffers.push(e))}}disableInstanceAttributeByName(e){if(!this._currentEffect)return;let t=this._currentEffect.getAttributeLocationByName(e);this.disableInstanceAttribute(t)}disableInstanceAttribute(e){let t=!1,i;for(;(i=this._currentInstanceLocations.indexOf(e))!==-1;)this._currentInstanceLocations.splice(i,1),this._currentInstanceBuffers.splice(i,1),t=!0;t&&(this._gl.vertexAttribDivisor(e,0),this.disableAttributeByIndex(e))}disableAttributeByIndex(e){this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1}draw(e,t,i,r){this.drawElementsType(e?0:1,t,i,r)}drawPointClouds(e,t,i){this.drawArraysType(2,e,t,i)}drawUnIndexed(e,t,i,r){this.drawArraysType(e?0:1,t,i,r)}drawElementsType(e,t,i,r){this.applyStates(),this._reportDrawCall();let s=this._drawMode(e),a=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,o=this._uintIndicesCurrentlySet?4:2;r?this._gl.drawElementsInstanced(s,i,a,t*o,r):this._gl.drawElements(s,i,a,t*o)}drawArraysType(e,t,i,r){this.applyStates(),this._reportDrawCall();let s=this._drawMode(e);r?this._gl.drawArraysInstanced(s,t,i,r):this._gl.drawArrays(s,t,i)}_drawMode(e){switch(e){case 0:return this._gl.TRIANGLES;case 2:return this._gl.POINTS;case 1:return this._gl.LINES;case 3:return this._gl.POINTS;case 4:return this._gl.LINES;case 5:return this._gl.LINE_LOOP;case 6:return this._gl.LINE_STRIP;case 7:return this._gl.TRIANGLE_STRIP;case 8:return this._gl.TRIANGLE_FAN;default:return this._gl.TRIANGLES}}_releaseEffect(e){this._compiledEffects[e._key]&&delete this._compiledEffects[e._key];let t=e.getPipelineContext();t&&this._deletePipelineContext(t)}_deletePipelineContext(e){let t=e;t&&t.program&&(t.program.__SPECTOR_rebuildProgram=null,tR(t),this._gl&&(this._currentProgram===t.program&&this._setProgram(null),this._gl.deleteProgram(t.program)))}_getGlobalDefines(e){return zx(e,this.isNDCHalfZRange,this.useReverseDepthBuffer,this.useExactSrgbConversions)}createEffect(e,t,i,r,s,a,o,l,c,f=0,d){var E,S,T;let u=typeof e=="string"?e:e.vertexToken||e.vertexSource||e.vertexElement||e.vertex,h=typeof e=="string"?e:e.fragmentToken||e.fragmentSource||e.fragmentElement||e.fragment,m=this._getGlobalDefines(),g=t.attributes!==void 0,p=(E=s!=null?s:t.defines)!=null?E:"";m&&(p+=m);let _=u+"+"+h+"@"+p;if(this._compiledEffects[_]){let A=this._compiledEffects[_];return o&&A.isReady()&&o(A),A._refCount++,A}this._gl&&Jn(this._gl);let v=new pr(e,t,g?this:i,r,this,s,a,o,l,c,_,(S=t.shaderLanguage)!=null?S:f,(T=t.extraInitializationsAsync)!=null?T:d);return this._compiledEffects[_]=v,v}_getShaderSource(e){return this._gl.getShaderSource(e)}createRawShaderProgram(e,t,i,r,s=null){let a=Jn(this._gl);return a._contextWasLost=this._contextWasLost,a.validateShaderPrograms=this.validateShaderPrograms,zP(e,t,i,r||this._gl,s)}createShaderProgram(e,t,i,r,s,a=null){let o=Jn(this._gl);return o._contextWasLost=this._contextWasLost,o.validateShaderPrograms=this.validateShaderPrograms,WP(e,t,i,r,s||this._gl,a)}inlineShaderCode(e){return e}createPipelineContext(e){if(this._gl){let i=Jn(this._gl);i.parallelShaderCompile=this._caps.parallelShaderCompile}let t=sG(this._gl,e);return t.engine=this,t}createMaterialContext(){}createDrawContext(){}_finalizePipelineContext(e){return Xx(e,this._gl,this.validateShaderPrograms)}_preparePipelineContextAsync(e,t,i,r,s,a,o,l,c,f,d){let u=Jn(this._gl);return u._contextWasLost=this._contextWasLost,u.validateShaderPrograms=this.validateShaderPrograms,u._createShaderProgramInjection=this._createShaderProgram.bind(this),u.createRawShaderProgramInjection=this.createRawShaderProgram.bind(this),u.createShaderProgramInjection=this.createShaderProgram.bind(this),u.loadFileInjection=this._loadFile.bind(this),oG(e,t,i,r,s,a,o,l,c,f,d)}_createShaderProgram(e,t,i,r,s=null){return Hx(e,t,i,r,s)}_isRenderingStateCompiled(e){return this._isDisposed?!1:aG(e,this._gl,this.validateShaderPrograms)}_executeWhenRenderingStateIsCompiled(e,t){cG(e,t)}getUniforms(e,t){let i=new Array,r=e;for(let s=0;s<t.length;s++)i.push(this._gl.getUniformLocation(r.program,t[s]));return i}getAttributes(e,t){let i=[],r=e;for(let s=0;s<t.length;s++)try{i.push(this._gl.getAttribLocation(r.program,t[s]))}catch(a){i.push(-1)}return i}enableEffect(e){e=e!==null&&sR(e)?e.effect:e,!(!e||e===this._currentEffect)&&(this._stencilStateComposer.stencilMaterial=void 0,this.bindSamplers(e),this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setInt(e,t){return e?(this._gl.uniform1i(e,t),!0):!1}setInt2(e,t,i){return e?(this._gl.uniform2i(e,t,i),!0):!1}setInt3(e,t,i,r){return e?(this._gl.uniform3i(e,t,i,r),!0):!1}setInt4(e,t,i,r,s){return e?(this._gl.uniform4i(e,t,i,r,s),!0):!1}setIntArray(e,t){return e?(this._gl.uniform1iv(e,t),!0):!1}setIntArray2(e,t){return!e||t.length%2!==0?!1:(this._gl.uniform2iv(e,t),!0)}setIntArray3(e,t){return!e||t.length%3!==0?!1:(this._gl.uniform3iv(e,t),!0)}setIntArray4(e,t){return!e||t.length%4!==0?!1:(this._gl.uniform4iv(e,t),!0)}setUInt(e,t){return e?(this._gl.uniform1ui(e,t),!0):!1}setUInt2(e,t,i){return e?(this._gl.uniform2ui(e,t,i),!0):!1}setUInt3(e,t,i,r){return e?(this._gl.uniform3ui(e,t,i,r),!0):!1}setUInt4(e,t,i,r,s){return e?(this._gl.uniform4ui(e,t,i,r,s),!0):!1}setUIntArray(e,t){return e?(this._gl.uniform1uiv(e,t),!0):!1}setUIntArray2(e,t){return!e||t.length%2!==0?!1:(this._gl.uniform2uiv(e,t),!0)}setUIntArray3(e,t){return!e||t.length%3!==0?!1:(this._gl.uniform3uiv(e,t),!0)}setUIntArray4(e,t){return!e||t.length%4!==0?!1:(this._gl.uniform4uiv(e,t),!0)}setArray(e,t){return!e||t.length<1?!1:(this._gl.uniform1fv(e,t),!0)}setArray2(e,t){return!e||t.length%2!==0?!1:(this._gl.uniform2fv(e,t),!0)}setArray3(e,t){return!e||t.length%3!==0?!1:(this._gl.uniform3fv(e,t),!0)}setArray4(e,t){return!e||t.length%4!==0?!1:(this._gl.uniform4fv(e,t),!0)}setMatrices(e,t){return e?(this._gl.uniformMatrix4fv(e,!1,t),!0):!1}setMatrix3x3(e,t){return e?(this._gl.uniformMatrix3fv(e,!1,t),!0):!1}setMatrix2x2(e,t){return e?(this._gl.uniformMatrix2fv(e,!1,t),!0):!1}setFloat(e,t){return e?(this._gl.uniform1f(e,t),!0):!1}setFloat2(e,t,i){return e?(this._gl.uniform2f(e,t,i),!0):!1}setFloat3(e,t,i,r){return e?(this._gl.uniform3f(e,t,i,r),!0):!1}setFloat4(e,t,i,r,s){return e?(this._gl.uniform4f(e,t,i,r,s),!0):!1}applyStates(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl,this._currentRenderTarget&&this._currentRenderTarget.textures?this._currentRenderTarget.textures.length:1),this._colorWriteChanged){this._colorWriteChanged=!1;let e=this._colorWrite;this._gl.colorMask(e,e,e,e)}}wipeCaches(e){this.preventCacheWipeBetweenFrames&&!e||(this._currentEffect=null,this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0,this._unbindVertexArrayObject(),e&&(this._currentProgram=null,this.resetTextureCache(),this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._resetAlphaMode(),this._colorWrite=!0,this._colorWriteChanged=!0,this._unpackFlipYCached=null,this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this._mustWipeVertexAttributes=!0,this.unbindAllAttributes()),this._resetVertexBufferBinding(),this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null,this.bindIndexBuffer(null))}_getSamplingParameters(e,t){let i=this._gl,r=i.NEAREST,s=i.NEAREST,a=!1;switch(e){case 11:r=i.LINEAR,t?s=i.LINEAR_MIPMAP_NEAREST:s=i.LINEAR;break;case 3:r=i.LINEAR,a=!0,t?s=i.LINEAR_MIPMAP_LINEAR:s=i.LINEAR;break;case 8:a=!0,r=i.NEAREST,t?s=i.NEAREST_MIPMAP_LINEAR:s=i.NEAREST;break;case 4:r=i.NEAREST,t?s=i.NEAREST_MIPMAP_NEAREST:s=i.NEAREST;break;case 5:r=i.NEAREST,t?s=i.LINEAR_MIPMAP_NEAREST:s=i.LINEAR;break;case 6:a=!0,r=i.NEAREST,t?s=i.LINEAR_MIPMAP_LINEAR:s=i.LINEAR;break;case 7:r=i.NEAREST,s=i.LINEAR;break;case 1:r=i.NEAREST,s=i.NEAREST;break;case 9:r=i.LINEAR,t?s=i.NEAREST_MIPMAP_NEAREST:s=i.NEAREST;break;case 10:a=!0,r=i.LINEAR,t?s=i.NEAREST_MIPMAP_LINEAR:s=i.NEAREST;break;case 2:r=i.LINEAR,s=i.LINEAR;break;case 12:r=i.LINEAR,s=i.NEAREST;break}return{min:s,mag:r,hasMipMaps:a}}_createTexture(){let e=this._gl.createTexture();if(!e)throw new Error("Unable to create texture");return e}_createHardwareTexture(){return new ip(this._createTexture(),this._gl)}_createInternalTexture(e,t,i=!0,r=0){var G;let s,a=!1,o=0,l=3,c=5,f=!1,d=1,u,h=!1,m=0,g=!1;t!==void 0&&typeof t=="object"?(s=!!t.generateMipMaps,a=!!t.createMipMaps,o=t.type===void 0?0:t.type,l=t.samplingMode===void 0?3:t.samplingMode,c=t.format===void 0?5:t.format,f=t.useSRGBBuffer===void 0?!1:t.useSRGBBuffer,d=(G=t.samples)!=null?G:1,u=t.label,h=!!t.createMSAATexture,m=t.comparisonFunction||0,g=!!t.isCube):s=!!t,f&&(f=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU)),(o===1&&!this._caps.textureFloatLinearFiltering||o===2&&!this._caps.textureHalfFloatLinearFiltering)&&(l=1),o===1&&!this._caps.textureFloat&&(o=0,te.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let p=nL(c),_=xc(c),v=this._gl,E=new Xi(this,r),S=e.width||e,T=e.height||e,A=e.depth||0,R=e.layers||0,M=this._getSamplingParameters(l,(s||a)&&!p),I=R!==0?v.TEXTURE_2D_ARRAY:A!==0?v.TEXTURE_3D:g?v.TEXTURE_CUBE_MAP:v.TEXTURE_2D,C=p?this._getInternalFormatFromDepthTextureFormat(c,!0,_):this._getRGBABufferInternalSizedFormat(o,c,f),L=p?_?v.DEPTH_STENCIL:v.DEPTH_COMPONENT:this._getInternalFormat(c),w=p?this._getWebGLTextureTypeFromDepthTextureFormat(c):this._getWebGLTextureType(o);if(this._bindTextureDirectly(I,E),R!==0)E.is2DArray=!0,v.texImage3D(I,0,C,S,T,R,0,L,w,null);else if(A!==0)E.is3D=!0,v.texImage3D(I,0,C,S,T,A,0,L,w,null);else if(g){E.isCube=!0;for(let O=0;O<6;O++)v.texImage2D(v.TEXTURE_CUBE_MAP_POSITIVE_X+O,0,C,S,T,0,L,w,null)}else v.texImage2D(I,0,C,S,T,0,L,w,null);if(v.texParameteri(I,v.TEXTURE_MAG_FILTER,M.mag),v.texParameteri(I,v.TEXTURE_MIN_FILTER,M.min),v.texParameteri(I,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(I,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE),p&&this.webGLVersion>1&&(m===0?(v.texParameteri(I,v.TEXTURE_COMPARE_FUNC,515),v.texParameteri(I,v.TEXTURE_COMPARE_MODE,v.NONE)):(v.texParameteri(I,v.TEXTURE_COMPARE_FUNC,m),v.texParameteri(I,v.TEXTURE_COMPARE_MODE,v.COMPARE_REF_TO_TEXTURE))),(s||a)&&this._gl.generateMipmap(I),this._bindTextureDirectly(I,null),E._useSRGBBuffer=f,E.baseWidth=S,E.baseHeight=T,E.width=S,E.height=T,E.depth=R||A,E.isReady=!0,E.samples=d,E.generateMipMaps=s,E.samplingMode=l,E.type=o,E.format=c,E.label=u,E.comparisonFunction=m,this._internalTexturesCache.push(E),h){let O;if(nL(E.format)?O=this._setupFramebufferDepthAttachments(xc(E.format),E.format!==19,E.width,E.height,d,E.format,!0):O=this._createRenderBuffer(E.width,E.height,d,-1,this._getRGBABufferInternalSizedFormat(E.type,E.format,E._useSRGBBuffer),-1),!O)throw new Error("Unable to create render buffer");E._autoMSAAManagement=!0;let N=E._hardwareTexture;N||(N=E._hardwareTexture=this._createHardwareTexture()),N.addMSAARenderBuffer(O)}return E}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,r,s=3,a=null,o=null,l=null,c=null,f=null,d=null,u,h,m,g){return this._createTextureBase(e,t,i,r,s,a,o,(...p)=>this._prepareWebGLTexture(...p,f),(p,_,v,E,S,T)=>{let A=this._gl,R=v.width===p&&v.height===_;S._creationFlags=m!=null?m:0;let M=this._getTexImageParametersForCreateTexture(S.format,S._useSRGBBuffer);if(R)return A.texImage2D(A.TEXTURE_2D,0,M.internalFormat,M.format,M.type,v),!1;let I=this._caps.maxTextureSize;if(v.width>I||v.height>I||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=p,this._workingCanvas.height=_,this._workingContext.drawImage(v,0,0,v.width,v.height,0,0,p,_),A.texImage2D(A.TEXTURE_2D,0,M.internalFormat,M.format,M.type,this._workingCanvas),S.width=p,S.height=_),!1;{let C=new Xi(this,2);this._bindTextureDirectly(A.TEXTURE_2D,C,!0),A.texImage2D(A.TEXTURE_2D,0,M.internalFormat,M.format,M.type,v),this._rescaleTexture(C,S,r,M.format,()=>{this._releaseTexture(C),this._bindTextureDirectly(A.TEXTURE_2D,S,!0),T()})}return!0},l,c,f,d,u,h,g)}_getTexImageParametersForCreateTexture(e,t){let i,r;return this.webGLVersion===1?(i=this._getInternalFormat(e,t),r=i):(i=this._getInternalFormat(e,!1),r=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:r,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,r,s){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){let r=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(r,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(r,this._gl.TEXTURE_MIN_FILTER,s.min),i&&s.hasMipMaps&&(t.generateMipMaps=!0,this._gl.generateMipmap(r)),this._bindTextureDirectly(r,null),t.samplingMode=e}updateTextureDimensions(e,t,i,r=1){}updateTextureWrappingMode(e,t,i=null,r=null){let s=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&r!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(r),e),e._cachedWrapR=r),this._bindTextureDirectly(s,null)}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,a=0,o=0){let l=this._gl,c=l.TEXTURE_2D;if(e.isCube&&(c=l.TEXTURE_CUBE_MAP_POSITIVE_X+a),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=l.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 37809:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;break;case 37810:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;break;case 37811:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;break;case 37812:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;break;case 37813:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;break;case 37814:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;break;case 37815:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;break;case 37816:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;break;case 37817:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;break;case 37818:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;break;case 37819:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;break;case 37820:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;break;case 37821:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;break;case 33776:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1;break}if(e.generateMipMaps){let f=e._hardwareTexture;f.memoryAllocated||(l.texStorage2D(e.isCube?l.TEXTURE_CUBE_MAP:l.TEXTURE_2D,Math.floor(Math.log2(Math.max(i,r)))+1,t,e.width,e.height),f.memoryAllocated=!0),this._gl.compressedTexSubImage2D(c,o,0,0,i,r,t,s)}else this._gl.compressedTexImage2D(c,o,t,i,r,0,s)}_uploadDataToTextureDirectly(e,t,i=0,r=0,s,a=!1){let o=this._gl,l=this._getWebGLTextureType(e.type),c=this._getInternalFormat(e.format),f=s===void 0?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let d=o.TEXTURE_2D;e.isCube&&(d=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);let u=Math.round(Math.log(e.width)*Math.LOG2E),h=Math.round(Math.log(e.height)*Math.LOG2E),m=a?e.width:Math.pow(2,Math.max(u-r,0)),g=a?e.height:Math.pow(2,Math.max(h-r,0));o.texImage2D(d,r,f,m,g,0,c,l,t)}updateTextureData(e,t,i,r,s,a,o=0,l=0,c=!1){let f=this._gl,d=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let h=f.TEXTURE_2D,m=f.TEXTURE_2D;e.isCube&&(m=f.TEXTURE_CUBE_MAP_POSITIVE_X+o,h=f.TEXTURE_CUBE_MAP),this._bindTextureDirectly(h,e,!0),f.texSubImage2D(m,l,i,r,s,a,u,d,t),c&&this._gl.generateMipmap(m),this._bindTextureDirectly(h,null)}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){let s=this._gl,a=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(a,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(a,null,!0)}_prepareWebGLTextureContinuation(e,t,i,r,s){let a=this._gl;if(!a)return;let o=this._getSamplingParameters(s,!i);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,o.mag),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,o.min),!i&&!r&&a.generateMipmap(a.TEXTURE_2D),this._bindTextureDirectly(a.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,r,s,a,o,l,c,f){let d=this.getCaps().maxTextureSize,u=Math.min(d,this.needPOTTextures?Un(r.width,d):r.width),h=Math.min(d,this.needPOTTextures?Un(r.height,d):r.height),m=this._gl;if(m){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(m.TEXTURE_2D,e,!0),this._unpackFlipY(s===void 0?!0:!!s),e.baseWidth=r.width,e.baseHeight=r.height,e.width=u,e.height=h,e.isReady=!0,e.type=e.type!==-1?e.type:0,e.format=e.format!==-1?e.format:f!=null?f:t===".jpg"&&!e._useSRGBBuffer?4:5,!l(u,h,r,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,a,o,c)})&&this._prepareWebGLTextureContinuation(e,i,a,o,c)}}_getInternalFormatFromDepthTextureFormat(e,t,i){let r=this._gl;if(!t)return r.STENCIL_INDEX8;let a=i?r.DEPTH_STENCIL:r.DEPTH_COMPONENT;return this.webGLVersion>1?e===15?a=r.DEPTH_COMPONENT16:e===16?a=r.DEPTH_COMPONENT24:e===17||e===13?a=i?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24:e===14?a=r.DEPTH_COMPONENT32F:e===18&&(a=i?r.DEPTH32F_STENCIL8:r.DEPTH_COMPONENT32F):a=r.DEPTH_COMPONENT16,a}_getWebGLTextureTypeFromDepthTextureFormat(e){let t=this._gl,i=t.UNSIGNED_INT;return e===15?i=t.UNSIGNED_SHORT:e===17||e===13?i=t.UNSIGNED_INT_24_8:e===14?i=t.FLOAT:e===18?i=t.FLOAT_32_UNSIGNED_INT_24_8_REV:e===19&&(i=t.UNSIGNED_BYTE),i}_setupFramebufferDepthAttachments(e,t,i,r,s=1,a,o=!1){let l=this._gl;a=a!=null?a:e?13:14;let c=this._getInternalFormatFromDepthTextureFormat(a,t,e);return e&&t?this._createRenderBuffer(i,r,s,l.DEPTH_STENCIL,c,o?-1:l.DEPTH_STENCIL_ATTACHMENT):t?this._createRenderBuffer(i,r,s,c,c,o?-1:l.DEPTH_ATTACHMENT):e?this._createRenderBuffer(i,r,s,c,c,o?-1:l.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,r,s,a,o=!0){let c=this._gl.createRenderbuffer();return this._updateRenderBuffer(c,e,t,i,r,s,a,o)}_updateRenderBuffer(e,t,i,r,s,a,o,l=!0){let c=this._gl;return c.bindRenderbuffer(c.RENDERBUFFER,e),r>1&&c.renderbufferStorageMultisample?c.renderbufferStorageMultisample(c.RENDERBUFFER,r,a,t,i):c.renderbufferStorage(c.RENDERBUFFER,s,t,i),o!==-1&&c.framebufferRenderbuffer(c.FRAMEBUFFER,o,c.RENDERBUFFER,e),l&&c.bindRenderbuffer(c.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture),this.unbindAllTextures();let t=this._internalTexturesCache.indexOf(e);t!==-1&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_deleteTexture(e){e==null||e.release()}_setProgram(e){this._currentProgram!==e&&(lG(e,this._gl),this._currentProgram=e)}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.program);let i=e.getSamplers();for(let r=0;r<i.length;r++){let s=e.getUniform(i[r]);s&&(this._boundUniforms[r]=s)}this._currentEffect=null}_activateCurrentTexture(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)}_bindTextureDirectly(e,t,i=!1,r=!1){var l,c;let s=!1,a=t&&t._associatedChannel>-1;if(i&&a&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||r){if(this._activateCurrentTexture(),t&&t.isMultiview)throw te.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,(c=(l=t==null?void 0:t._hardwareTexture)==null?void 0:l.underlyingResource)!=null?c:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(s=!0,this._activateCurrentTexture());return a&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),s}_bindTexture(e,t,i){if(e===void 0)return;t&&(t._associatedChannel=e),this._activeChannel=e;let r=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(r,t)}unbindAllTextures(){for(let e=0;e<this._maxSimultaneousTextures;e++)this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,r){e!==void 0&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){let i=this._boundUniforms[e];!i||i._currentState===t||(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,r=!1,s=""){if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;let c=t.getInternalTexture();c&&(c._associatedChannel=e),t.update()}else if(t.delayLoadState===4)return t.delayLoad(),!1;let a;r?a=t.depthStencilTexture:t.isReady()?a=t.getInternalTexture():t.isCube?a=this.emptyCubeTexture:t.is3D?a=this.emptyTexture3D:t.is2DArray?a=this.emptyTexture2DArray:a=this.emptyTexture,!i&&a&&(a._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===a&&(i||this._bindSamplerUniformToChannel(a._associatedChannel,e),o=!1),this._activeChannel=e;let l=this._getTextureTarget(a);if(o&&this._bindTextureDirectly(l,a,i),a&&!a.isMultiview){if(a.isCube&&a._cachedCoordinatesMode!==t.coordinatesMode){a._cachedCoordinatesMode=t.coordinatesMode;let c=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=c,t.wrapV=c}a._cachedWrapU!==t.wrapU&&(a._cachedWrapU=t.wrapU,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),a)),a._cachedWrapV!==t.wrapV&&(a._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),a)),a.is3D&&a._cachedWrapR!==t.wrapR&&(a._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),a)),this._setAnisotropicLevel(l,a,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,r){if(!(e===void 0||!t)){(!this._textureUnits||this._textureUnits.length!==i.length)&&(this._textureUnits=new Int32Array(i.length));for(let s=0;s<i.length;s++){let a=i[s].getInternalTexture();a?(this._textureUnits[s]=e+s,a._associatedChannel=e+s):this._textureUnits[s]=-1}this._gl.uniform1iv(t,this._textureUnits);for(let s=0;s<i.length;s++)this._setTexture(this._textureUnits[s],i[s],!0)}}_setAnisotropicLevel(e,t,i){let r=this._caps.textureAnisotropicFilterExtension;t.samplingMode!==11&&t.samplingMode!==3&&t.samplingMode!==2&&(i=1),r&&t._cachedAnisotropicFilteringLevel!==i&&(this._setTextureParameterFloat(e,r.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(i,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=i)}_setTextureParameterFloat(e,t,i,r){this._bindTextureDirectly(e,r,!0,!0),this._gl.texParameterf(e,t,i)}_setTextureParameterInteger(e,t,i,r){r&&this._bindTextureDirectly(e,r,!0,!0),this._gl.texParameteri(e,t,i)}unbindAllAttributes(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(let e=0;e<this._caps.maxVertexAttribs;e++)this.disableAttributeByIndex(e);return}for(let e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)e>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){this._compiledEffects={},this.onReleaseEffectsObservable.notifyObservers(this)}dispose(){var e;Ar()&&this._renderingCanvas&&(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._onContextRestored&&this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&((e=this._gl.getExtension("WEBGL_lose_context"))==null||e.loseContext()),Wx(this._gl)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){let t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0,r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);let s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);let a=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&a===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);let o=t.RGBA,l=t.UNSIGNED_BYTE,c=new Uint8Array(4);t.readPixels(0,0,1,1,o,l,c),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(this._webGLVersion===1){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:case 33322:case 36760:i=this._gl.RED;break;case 7:case 33324:case 36761:i=this._gl.RG;break;case 4:case 32852:case 36762:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:case 32859:case 36763:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;break}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER;break}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(this._webGLVersion===1){if(t!==void 0)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 36760:return this._gl.R16_SNORM_EXT;case 36761:return this._gl.RG16_SNORM_EXT;case 36762:return this._gl.RGB16_SNORM_EXT;case 36763:return this._gl.RGBA16_SNORM_EXT;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;case 11:return this._gl.RGBA16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 33322:return this._gl.R16_EXT;case 33324:return this._gl.RG16_EXT;case 32852:return this._gl.RGB16_EXT;case 32859:return this._gl.RGBA16_EXT;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;case 11:return this._gl.RGBA16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;case 11:return this._gl.RGBA32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;case 11:return this._gl.RGBA32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;case 5:return this._gl.RGBA32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;case 5:return this._gl.RGBA16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,r,s=!0,a=!0,o=null){let l=s?4:3,c=s?this._gl.RGBA:this._gl.RGB,f=i*r*l;if(!o)o=new Uint8Array(f);else if(o.length<f)return te.Error(`Data buffer is too small to store the read pixels (${o.length} should be more than ${f})`),Promise.resolve(o);return a&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,r,c,this._gl.UNSIGNED_BYTE,o),Promise.resolve(o)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(this._HasMajorPerformanceCaveat!==null)return!this._HasMajorPerformanceCaveat;if(this._IsSupported===null)try{let e=ye._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=t!=null&&!!globalThis.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(this._HasMajorPerformanceCaveat===null)try{let e=ye._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}};Pt._TempClearColorUint32=new Uint32Array(4);Pt._TempClearColorInt32=new Int32Array(4);Pt.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}];Pt._ConcatenateShader=Gx;Pt._IsSupported=null;Pt._HasMajorPerformanceCaveat=null});var fR,aL,NG=y(()=>{Ac();fR=class{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new aL(e)}sampleFrame(e=br.Now){if(this._enabled){if(this._lastFrameTimeMs!=null){let t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){let e=this._rollingFrameTime.history(0);return e===0?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}},aL=class{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){let i=this._samples[this._pos];t=i-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(i-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;let t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){let t=this._samples.length;return(e%t+t)%t}}});var wG=y(()=>{Is();Pt.prototype.setAlphaMode=function(n,e=!1,t=0){if(this._alphaMode[t]===n){if(!e){let r=n===0;this.depthCullingState.depthMask!==r&&(this.depthCullingState.depthMask=r)}return}let i=n===0;this._alphaState.setAlphaBlend(!i,t),this._alphaState.setAlphaMode(n,t),e||(this.depthCullingState.depthMask=i),this._alphaMode[t]=n}});function FG(n,e,t,i){let r,s=1;i===1?r=new Float32Array(e*t*4):i===2?(r=new Uint16Array(e*t*4),s=15360):i===7?r=new Uint32Array(e*t*4):r=new Uint8Array(e*t*4);for(let a=0;a<e;a++)for(let o=0;o<t;o++){let l=(o*e+a)*3,c=(o*e+a)*4;r[c+0]=n[l+0],r[c+1]=n[l+1],r[c+2]=n[l+2],r[c+3]=s}return r}function BG(n){return function(e,t,i,r,s,a,o,l,c=null,f=0){let d=n?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,u=n?10:11,h=new Xi(this,u);h.baseWidth=t,h.baseHeight=i,h.baseDepth=r,h.width=t,h.height=i,h.depth=r,h.format=s,h.type=f,h.generateMipMaps=a,h.samplingMode=l,n?h.is3D=!0:h.is2DArray=!0,this._doNotHandleContextLost||(h._bufferView=e),n?this.updateRawTexture3D(h,e,s,o,c,f):this.updateRawTexture2DArray(h,e,s,o,c,f),this._bindTextureDirectly(d,h,!0);let m=this._getSamplingParameters(l,a);return this._gl.texParameteri(d,this._gl.TEXTURE_MAG_FILTER,m.mag),this._gl.texParameteri(d,this._gl.TEXTURE_MIN_FILTER,m.min),a&&this._gl.generateMipmap(d),this._bindTextureDirectly(d,null),this._internalTexturesCache.push(h),h}}function UG(n){return function(e,t,i,r,s=null,a=0){let o=n?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,l=this._getWebGLTextureType(a),c=this._getInternalFormat(i),f=this._getRGBABufferInternalSizedFormat(a,i);this._bindTextureDirectly(o,e,!0),this._unpackFlipY(r===void 0?!0:!!r),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),e.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&t?this._gl.compressedTexImage3D(o,0,this.getCaps().s3tc[s],e.width,e.height,e.depth,0,t):this._gl.texImage3D(o,0,f,e.width,e.height,e.depth,0,c,l,t),e.generateMipMaps&&this._gl.generateMipmap(o),this._bindTextureDirectly(o,null),e.isReady=!0}}var VG=y(()=>{ea();wt();Is();Bo();Pt.prototype.updateRawTexture=function(n,e,t,i,r=null,s=0,a=!1){if(!n)return;let o=this._getRGBABufferInternalSizedFormat(s,t,a),l=this._getInternalFormat(t),c=this._getWebGLTextureType(s);this._bindTextureDirectly(this._gl.TEXTURE_2D,n,!0),this._unpackFlipY(i===void 0?!0:!!i),this._doNotHandleContextLost||(n._bufferView=e,n.format=t,n.type=s,n.invertY=i,n._compression=r),n.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&e?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],n.width,n.height,0,e):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,n.width,n.height,0,l,c,e),n.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),n.isReady=!0};Pt.prototype.createRawTexture=function(n,e,t,i,r,s,a,o=null,l=0,c=0,f=!1){let d=new Xi(this,3);d.baseWidth=e,d.baseHeight=t,d.width=e,d.height=t,d.format=i,d.generateMipMaps=r,d.samplingMode=a,d.invertY=s,d._compression=o,d.type=l,d._useSRGBBuffer=this._getUseSRGBBuffer(f,!r),this._doNotHandleContextLost||(d._bufferView=n),this.updateRawTexture(d,n,i,s,o,l,d._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,d,!0);let u=this._getSamplingParameters(a,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,u.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,u.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(d),d};Pt.prototype.createRawCubeTexture=function(n,e,t,i,r,s,a,o=null){let l=this._gl,c=new Xi(this,8);c.isCube=!0,c.format=t,c.type=i,this._doNotHandleContextLost||(c._bufferViewArray=n);let f=this._getWebGLTextureType(i),d=this._getInternalFormat(t);d===l.RGB&&(d=l.RGBA),f===l.FLOAT&&!this._caps.textureFloatLinearFiltering?(r=!1,a=1,te.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):f===this._gl.HALF_FLOAT_OES&&!this._caps.textureHalfFloatLinearFiltering?(r=!1,a=1,te.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):f===l.FLOAT&&!this._caps.textureFloatRender?(r=!1,te.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):f===l.HALF_FLOAT&&!this._caps.colorBufferFloat&&(r=!1,te.Warn("Render to half float textures is not supported. Mipmap generation forced to false."));let u=e,h=u;if(c.width=u,c.height=h,c.invertY=s,c._compression=o,!this.needPOTTextures||Bu(c.width)&&Bu(c.height)||(r=!1),n)this.updateRawCubeTexture(c,n,t,i,s,o);else{let p=this._getRGBABufferInternalSizedFormat(i),_=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,c,!0);for(let v=0;v<6;v++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+v,_,this.getCaps().s3tc[o],c.width,c.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+v,_,p,c.width,c.height,0,d,f,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,c,!0),n&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);let g=this._getSamplingParameters(a,r);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,g.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,g.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),c.generateMipMaps=r,c.samplingMode=a,c.isReady=!0,c};Pt.prototype.updateRawCubeTexture=function(n,e,t,i,r,s=null,a=0){n._bufferViewArray=e,n.format=t,n.type=i,n.invertY=r,n._compression=s;let o=this._gl,l=this._getWebGLTextureType(i),c=this._getInternalFormat(t),f=this._getRGBABufferInternalSizedFormat(i),d=!1;c===o.RGB&&(c=o.RGBA,d=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,n,!0),this._unpackFlipY(r===void 0?!0:!!r),n.width%4!==0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let h=0;h<6;h++){let m=e[h];s?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+h,a,this.getCaps().s3tc[s],n.width,n.height,0,m):(d&&(m=FG(m,n.width,n.height,i)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+h,a,f,n.width,n.height,0,c,l,m))}(!this.needPOTTextures||Bu(n.width)&&Bu(n.height))&&n.generateMipMaps&&a===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),n.isReady=!0};Pt.prototype.createRawCubeTextureFromUrl=function(n,e,t,i,r,s,a,o,l=null,c=null,f=3,d=!1){let u=this._gl,h=this.createRawCubeTexture(null,t,i,r,!s,d,f,null);e==null||e.addPendingData(h),h.url=n,h.isReady=!1,this._internalTexturesCache.push(h);let m=(p,_)=>{e==null||e.removePendingData(h),c&&c(p?p.status+" "+p.statusText:"Failed to parse texture data",_)},g=async p=>{if(!h._hardwareTexture)return;let _=a(p);if(!_)return;let v=_ instanceof Promise?await _:_,E=h.width;if(o){let S=this._getWebGLTextureType(r),T=this._getInternalFormat(i),A=this._getRGBABufferInternalSizedFormat(r),R=!1;T===u.RGB&&(T=u.RGBA,R=!0),this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,h,!0),this._unpackFlipY(!1);let M=o(v);for(let I=0;I<M.length;I++){let C=E>>I;for(let L=0;L<6;L++){let w=M[I][L];R&&(w=FG(w,C,C,r)),u.texImage2D(L,I,A,C,C,0,T,S,w)}}this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(h,v,i,r,d);h.isReady=!0,e==null||e.removePendingData(h),h.onLoadedObservable.notifyObservers(h),h.onLoadedObservable.clear(),l&&l()};return this._loadFile(n,p=>{g(p).catch(_=>{m(void 0,_)})},void 0,e==null?void 0:e.offlineProvider,!0,m),h};Pt.prototype.createRawTexture2DArray=BG(!1);Pt.prototype.createRawTexture3D=BG(!0);Pt.prototype.updateRawTexture2DArray=UG(!1);Pt.prototype.updateRawTexture3D=UG(!0)});var GG=y(()=>{Is();Zf();Pt.prototype._readTexturePixelsSync=function(n,e,t,i=-1,r=0,s=null,a=!0,o=!1,l=0,c=0){var u,h,m;let f=this._gl;if(!f)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){let g=f.createFramebuffer();if(!g)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=g}f.bindFramebuffer(f.FRAMEBUFFER,this._dummyFramebuffer),i>-1&&(n.is2DArray||n.is3D)?f.framebufferTextureLayer(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,(u=n._hardwareTexture)==null?void 0:u.underlyingResource,r,i):i>-1?f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_CUBE_MAP_POSITIVE_X+i,(h=n._hardwareTexture)==null?void 0:h.underlyingResource,r):f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,(m=n._hardwareTexture)==null?void 0:m.underlyingResource,r);let d=n.type!==void 0?this._getWebGLTextureType(n.type):f.UNSIGNED_BYTE;return o?s||(s=rG(n.type,4*e*t)):d===f.UNSIGNED_BYTE?(s||(s=new Uint8Array(4*e*t)),d=f.UNSIGNED_BYTE):(s||(s=new Float32Array(4*e*t)),d=f.FLOAT),a&&this.flushFramebuffer(),f.readPixels(l,c,e,t,f.RGBA,d,s),f.bindFramebuffer(f.FRAMEBUFFER,this._currentFramebuffer),s};Pt.prototype._readTexturePixels=function(n,e,t,i=-1,r=0,s=null,a=!0,o=!1,l=0,c=0){return Promise.resolve(this._readTexturePixelsSync(n,e,t,i,r,s,a,o,l,c))}});var kG=y(()=>{Is();Pt.prototype.updateDynamicIndexBuffer=function(n,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(n);let i;n.is32Bits?i=e instanceof Uint32Array?e:new Uint32Array(e):i=e instanceof Uint16Array?e:new Uint16Array(e),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,i,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()};Pt.prototype.updateDynamicVertexBuffer=function(n,e,t,i){this.bindArrayBuffer(n),t===void 0&&(t=0);let r=e.byteLength||e.length;i===void 0||i>=r&&t===0?e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,new Float32Array(e)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,e):e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,new Float32Array(e).subarray(0,i/4)):(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,i):e=new Uint8Array(e,0,i),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,e)),this._resetVertexBufferBinding()}});var zG=y(()=>{Is();ea();wt();Bo();Pt.prototype._createDepthStencilCubeTexture=function(n,e){let t=new Xi(this,12);if(t.isCube=!0,this.webGLVersion===1)return te.Error("Depth cube texture is not supported by WebGL 1."),t;let i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,t,!0),this._setupDepthStencilTexture(t,n,i.bilinearFiltering,i.comparisonFunction);for(let s=0;s<6;s++)i.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,r.DEPTH24_STENCIL8,n,n,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,r.DEPTH_COMPONENT24,n,n,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(t),t};Pt.prototype._setCubeMapTextureParams=function(n,e,t){let i=this._gl;i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MIN_FILTER,e?i.LINEAR_MIPMAP_LINEAR:i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),n.samplingMode=e?3:2,e&&this.getCaps().textureMaxLevel&&t!==void 0&&t>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,t),n._maxLodLevel=t),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)};Pt.prototype.createCubeTexture=function(n,e,t,i,r=null,s=null,a,o=null,l=!1,c=0,f=0,d=null,u,h=!1,m=null){let g=this._gl;return this.createCubeTextureBase(n,e,t,!!i,r,s,a,o,l,c,f,d,p=>this._bindTextureDirectly(g.TEXTURE_CUBE_MAP,p,!0),(p,_)=>{let v=this.needPOTTextures?Un(_[0].width,this._caps.maxCubemapTextureSize):_[0].width,E=v,S=[g.TEXTURE_CUBE_MAP_POSITIVE_X,g.TEXTURE_CUBE_MAP_POSITIVE_Y,g.TEXTURE_CUBE_MAP_POSITIVE_Z,g.TEXTURE_CUBE_MAP_NEGATIVE_X,g.TEXTURE_CUBE_MAP_NEGATIVE_Y,g.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(g.TEXTURE_CUBE_MAP,p,!0),this._unpackFlipY(!1);let T=a?this._getInternalFormat(a,p._useSRGBBuffer):p._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:g.RGBA,A=a?this._getInternalFormat(a):g.RGBA;p._useSRGBBuffer&&this.webGLVersion===1&&(A=T);for(let R=0;R<S.length;R++)if(_[R].width!==v||_[R].height!==E){if(this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext){te.Warn("Cannot create canvas to resize texture.");return}this._workingCanvas.width=v,this._workingCanvas.height=E,this._workingContext.drawImage(_[R],0,0,_[R].width,_[R].height,0,0,v,E),g.texImage2D(S[R],0,T,A,g.UNSIGNED_BYTE,this._workingCanvas)}else g.texImage2D(S[R],0,T,A,g.UNSIGNED_BYTE,_[R]);i||g.generateMipmap(g.TEXTURE_CUBE_MAP),this._setCubeMapTextureParams(p,!i),p.width=v,p.height=E,p.isReady=!0,a&&(p.format=a),p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear(),r&&r()},!!h,m)};Pt.prototype.generateMipMapsForCubemap=function(n,e=!0){if(n.generateMipMaps){let t=this._gl;this._bindTextureDirectly(t.TEXTURE_CUBE_MAP,n,!0),t.generateMipmap(t.TEXTURE_CUBE_MAP),e&&this._bindTextureDirectly(t.TEXTURE_CUBE_MAP,null)}}});var dR,WG=y(()=>{gv();dR=class{get depthStencilTexture(){return this._depthStencilTexture}setDepthStencilTexture(e,t=!0){t&&this._depthStencilTexture&&this._depthStencilTexture.dispose(),this._depthStencilTexture=e,this._generateDepthBuffer=this._generateStencilBuffer=this._depthStencilTextureWithStencil=!1,e&&(this._generateDepthBuffer=!0,this._generateStencilBuffer=this._depthStencilTextureWithStencil=xc(e.format))}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get is3D(){return this.depth>0}get size(){return this.width}get width(){var e;return(e=this._size.width)!=null?e:this._size}get height(){var e;return(e=this._size.height)!=null?e:this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){var e,t;return(t=(e=this._textures)==null?void 0:e[0])!=null?t:null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}getBaseArrayLayer(e){var s,a,o,l;if(!this._textures)return-1;let t=this._textures[e],i=(a=(s=this._layerIndices)==null?void 0:s[e])!=null?a:0,r=(l=(o=this._faceIndices)==null?void 0:o[e])!=null?l:0;return t.isCube?i*6+r:t.is3D?0:i}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;let r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}resolveMSAATextures(){this.isMulti?this._engine.resolveMultiFramebuffer(this):this._engine.resolveFramebuffer(this)}generateMipMaps(){this._engine._currentRenderTarget===this&&(this.isMulti?this._engine.unBindMultiColorAttachmentFramebuffer(this,!0):this._engine.unBindFramebuffer(this,!0)),this.isMulti?this._engine.generateMipMapsMultiFramebuffer(this):this._engine.generateMipMapsFramebuffer(this)}constructor(e,t,i,r,s){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this.disableAutomaticMSAAResolve=!1,this.resolveMSAAColors=!0,this.resolveMSAADepth=!1,this.resolveMSAAStencil=!1,this.depthReadOnly=!1,this.stencilReadOnly=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=r,this._depthStencilTexture=null,this.label=s}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),t!==void 0&&t>=0&&(this._layerIndices[e]=t),i!==void 0&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,a){var o;return(o=this._depthStencilTexture)==null||o.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=a,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:s,label:a},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var t,i,r,s,a,o,l,c;let e=null;if(this._isMulti){let f=this.textures;if(f&&f.length>0){let d=!1,u=f.length,h=-1,m=f[f.length-1]._source;(m===14||m===12)&&(d=!0,h=f[f.length-1].format,u--);let g=[],p=[],_=[],v=[],E=[],S=[],T=[],A={};for(let I=0;I<u;++I){let C=f[I];g.push(C.samplingMode),p.push(C.type),_.push(C.format),A[C.uniqueId]!==void 0?(v.push(-1),T.push(0)):(A[C.uniqueId]=I,C.is2DArray?(v.push(35866),T.push(C.depth)):C.isCube?(v.push(34067),T.push(0)):C.is3D?(v.push(32879),T.push(C.depth)):(v.push(3553),T.push(0))),this._faceIndices&&E.push((t=this._faceIndices[I])!=null?t:0),this._layerIndices&&S.push((i=this._layerIndices[I])!=null?i:0)}let R={samplingModes:g,generateMipMaps:f[0].generateMipMaps,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:this._generateStencilBuffer,generateDepthTexture:d,depthTextureFormat:h,types:p,formats:_,textureCount:u,targetTypes:v,faceIndex:E,layerIndex:S,layerCounts:T,label:this.label},M={width:this.width,height:this.height,depth:this.depth};e=this._engine.createMultipleRenderTarget(M,R);for(let I=0;I<u;++I){if(v[I]!==-1)continue;let C=A[f[I].uniqueId];e.setTexture(e.textures[C],I)}}}else{let f={};if(f.generateDepthBuffer=this._generateDepthBuffer,f.generateMipMaps=(s=(r=this.texture)==null?void 0:r.generateMipMaps)!=null?s:!1,f.generateStencilBuffer=this._generateStencilBuffer,f.samplingMode=(a=this.texture)==null?void 0:a.samplingMode,f.type=(o=this.texture)==null?void 0:o.type,f.format=(l=this.texture)==null?void 0:l.format,f.noColorAttachment=!this._textures,f.label=this.label,this.isCube)e=this._engine.createRenderTargetCubeTexture(this.width,f);else{let d={width:this.width,height:this.height,layers:this.is2DArray||this.is3D?(c=this.texture)==null?void 0:c.depth:void 0};e=this._engine.createRenderTargetTexture(d,f)}e.texture&&(e.texture.isReady=!0)}return e}_swapRenderTargetWrapper(e){if(this._textures&&e._textures)for(let t=0;t<this._textures.length;++t)this._textures[t]._swapAndDie(e._textures[t],!1),e._textures[t].isReady=!0;this._depthStencilTexture&&e._depthStencilTexture&&(this._depthStencilTexture._swapAndDie(e._depthStencilTexture),e._depthStencilTexture.isReady=!0),this._textures=null,this._depthStencilTexture=null}_rebuild(){let e=this._cloneRenderTargetWrapper();if(e){if(this._depthStencilTexture){let t=this._depthStencilTexture.samplingMode,i=this._depthStencilTexture.format,r=t===2||t===3||t===11;e.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction,r,this._depthStencilTextureWithStencil,this._depthStencilTexture.samples,i,this._depthStencilTextureLabel)}this.samples>1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e<this._textures.length;++e)this._textures[e].dispose();this._textures=null}dispose(e=!1){var t;e||((t=this._depthStencilTexture)==null||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}});var uR,HG=y(()=>{WG();gv();uR=class extends dR{setDepthStencilTexture(e,t=!0){if(super.setDepthStencilTexture(e,t),!e)return;let i=this._engine,r=this._context,s=e._hardwareTexture;if(s&&e._autoMSAAManagement&&this._MSAAFramebuffer){let a=i._currentFramebuffer;i._bindUnboundFramebuffer(this._MSAAFramebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,xc(e.format)?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,r.RENDERBUFFER,s.getMSAARenderBuffer()),i._bindUnboundFramebuffer(a)}}constructor(e,t,i,r,s){super(e,t,i,r),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=s}_cloneRenderTargetWrapper(){let e;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,a){if(this._depthStencilBuffer){let o=this._engine,l=o._currentFramebuffer,c=this._context;o._bindUnboundFramebuffer(this._framebuffer),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.DEPTH_STENCIL_ATTACHMENT,c.RENDERBUFFER,null),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.DEPTH_ATTACHMENT,c.RENDERBUFFER,null),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.STENCIL_ATTACHMENT,c.RENDERBUFFER,null),o._bindUnboundFramebuffer(l),c.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null}return super.createDepthStencilTexture(e,t,i,r,s,a)}shareDepth(e){super.shareDepth(e);let t=this._context,i=this._depthStencilBuffer,r=e._MSAAFramebuffer||e._framebuffer,s=this._engine;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;let a=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;s._bindUnboundFramebuffer(r),t.framebufferRenderbuffer(t.FRAMEBUFFER,a,t.RENDERBUFFER,i),s._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,r=0){var f,d,u,h;let s=e._hardwareTexture;if(!s)return;let a=this._framebuffer,o=this._engine,l=o._currentFramebuffer;o._bindUnboundFramebuffer(a);let c;if(o.webGLVersion>1){let m=this._context;c=m["COLOR_ATTACHMENT"+t],e.is2DArray||e.is3D?(i=(d=i!=null?i:(f=this.layerIndices)==null?void 0:f[t])!=null?d:0,m.framebufferTextureLayer(m.FRAMEBUFFER,c,s.underlyingResource,r,i)):e.isCube?(i=(h=i!=null?i:(u=this.faceIndices)==null?void 0:u[t])!=null?h:0,m.framebufferTexture2D(m.FRAMEBUFFER,c,m.TEXTURE_CUBE_MAP_POSITIVE_X+i,s.underlyingResource,r)):m.framebufferTexture2D(m.FRAMEBUFFER,c,m.TEXTURE_2D,s.underlyingResource,r)}else{let m=this._context;c=m["COLOR_ATTACHMENT"+t+"_WEBGL"];let g=i!==void 0?m.TEXTURE_CUBE_MAP_POSITIVE_X+i:m.TEXTURE_2D;m.framebufferTexture2D(m.FRAMEBUFFER,c,g,s.underlyingResource,r)}if(e._autoMSAAManagement&&this._MSAAFramebuffer){let m=this._context;o._bindUnboundFramebuffer(this._MSAAFramebuffer),m.framebufferRenderbuffer(m.FRAMEBUFFER,c,m.RENDERBUFFER,s.getMSAARenderBuffer())}o._bindUnboundFramebuffer(l)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var r,s;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;let i=(s=(r=this._attachments)==null?void 0:r.length)!=null?s:this.textures.length;for(let a=0;a<i;a++){let o=this.textures[a];o&&(o.is2DArray||o.is3D?this._bindTextureRenderTarget(o,a,this.layerIndices[a]):o.isCube?this._bindTextureRenderTarget(o,a,this.faceIndices[a]):this._bindTextureRenderTarget(o,a))}}setLayerAndFaceIndex(e=0,t,i){if(super.setLayerAndFaceIndex(e,t,i),!this.textures||!this.layerIndices||!this.faceIndices)return;let r=this.textures[e];r.is2DArray||r.is3D?this._bindTextureRenderTarget(this.textures[e],e,this.layerIndices[e]):r.isCube&&this._bindTextureRenderTarget(this.textures[e],e,this.faceIndices[e])}resolveMSAATextures(){let e=this._engine,t=e._currentFramebuffer;e._bindUnboundFramebuffer(this._MSAAFramebuffer),super.resolveMSAATextures(),e._bindUnboundFramebuffer(t)}dispose(e=this._disposeOnlyFramebuffers){let t=this._context;e||(this._colorTextureArray&&(this._context.deleteTexture(this._colorTextureArray),this._colorTextureArray=null),this._depthStencilTextureArray&&(this._context.deleteTexture(this._depthStencilTextureArray),this._depthStencilTextureArray=null)),this._framebuffer&&(t.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._depthStencilBuffer&&(t.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null),this._MSAAFramebuffer&&(t.deleteFramebuffer(this._MSAAFramebuffer),this._MSAAFramebuffer=null),super.dispose(e)}}});var oL=y(()=>{Yr();ye.prototype.createDepthStencilTexture=function(n,e,t){if(e.isCube){let i=n.width||n;return this._createDepthStencilCubeTexture(i,e)}else return this._createDepthStencilTexture(n,e,t)}});var XG=y(()=>{ea();wt();Is();HG();gv();oL();Pt.prototype._createHardwareRenderTargetWrapper=function(n,e,t){let i=new uR(n,e,t,this,this._gl);return this._renderTargetWrapperCache.push(i),i};Pt.prototype.createRenderTargetTexture=function(n,e){var g,p;let t=this._createHardwareRenderTargetWrapper(!1,!1,n),i=!0,r=!1,s=!1,a,o=1,l;e!==void 0&&typeof e=="object"&&(i=(g=e.generateDepthBuffer)!=null?g:!0,r=!!e.generateStencilBuffer,s=!!e.noColorAttachment,a=e.colorAttachment,o=(p=e.samples)!=null?p:1,l=e.label);let c=a||(s?null:this._createInternalTexture(n,e,!0,5)),f=n.width||n,d=n.height||n,u=this._currentFramebuffer,h=this._gl,m=h.createFramebuffer();if(this._bindUnboundFramebuffer(m),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(r,i,f,d),c&&!c.is2DArray&&!c.is3D&&h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_2D,c._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(u),t.label=l!=null?l:"RenderTargetWrapper",t._framebuffer=m,t._generateDepthBuffer=i,t._generateStencilBuffer=r,t.setTextures(c),!a)this.updateRenderTargetTextureSampleCount(t,o);else if(t._samples=a.samples,a.samples>1){let _=a._hardwareTexture.getMSAARenderBuffer(0);t._MSAAFramebuffer=h.createFramebuffer(),this._bindUnboundFramebuffer(t._MSAAFramebuffer),h.framebufferRenderbuffer(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.RENDERBUFFER,_),this._bindUnboundFramebuffer(null)}return t};Pt.prototype._createDepthStencilTexture=function(n,e,t){var h;let i=this._gl,r=n.layers||0,s=n.depth||0,a=i.TEXTURE_2D;r!==0?a=i.TEXTURE_2D_ARRAY:s!==0&&(a=i.TEXTURE_3D);let o=new Xi(this,12);if(o.label=e.label,!this._caps.depthTextureExtension)return te.Error("Depth texture is not supported by your browser or hardware."),o;let l={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e};if(this._bindTextureDirectly(a,o,!0),this._setupDepthStencilTexture(o,n,l.comparisonFunction===0?!1:l.bilinearFiltering,l.comparisonFunction,l.samples),l.depthTextureFormat!==void 0){if(l.depthTextureFormat!==15&&l.depthTextureFormat!==16&&l.depthTextureFormat!==17&&l.depthTextureFormat!==13&&l.depthTextureFormat!==14&&l.depthTextureFormat!==18)return te.Error(`Depth texture ${l.depthTextureFormat} format is not supported.`),o;o.format=l.depthTextureFormat}else o.format=l.generateStencil?13:16;let c=xc(o.format),f=this._getWebGLTextureTypeFromDepthTextureFormat(o.format),d=c?i.DEPTH_STENCIL:i.DEPTH_COMPONENT,u=this._getInternalFormatFromDepthTextureFormat(o.format,!0,c);return o.is2DArray?i.texImage3D(a,0,u,o.width,o.height,r,0,d,f,null):o.is3D?i.texImage3D(a,0,u,o.width,o.height,s,0,d,f,null):i.texImage2D(a,0,u,o.width,o.height,0,d,f,null),this._bindTextureDirectly(a,null),this._internalTexturesCache.push(o),t._depthStencilBuffer&&(i.deleteRenderbuffer(t._depthStencilBuffer),t._depthStencilBuffer=null),this._bindUnboundFramebuffer((h=t._MSAAFramebuffer)!=null?h:t._framebuffer),t._generateStencilBuffer=c,t._depthStencilTextureWithStencil=c,t._depthStencilBuffer=this._setupFramebufferDepthAttachments(t._generateStencilBuffer,t._generateDepthBuffer,t.width,t.height,t.samples,o.format),this._bindUnboundFramebuffer(null),o};Pt.prototype.updateRenderTargetTextureSampleCount=function(n,e){var s,a;if(this.webGLVersion<2||!n)return 1;if(n.samples===e)return e;let t=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),n._depthStencilBuffer&&(t.deleteRenderbuffer(n._depthStencilBuffer),n._depthStencilBuffer=null),n._MSAAFramebuffer&&(t.deleteFramebuffer(n._MSAAFramebuffer),n._MSAAFramebuffer=null);let i=(s=n.texture)==null?void 0:s._hardwareTexture;if(i==null||i.releaseMSAARenderBuffers(),n.texture&&e>1&&typeof t.renderbufferStorageMultisample=="function"){let o=t.createFramebuffer();if(!o)throw new Error("Unable to create multi sampled framebuffer");n._MSAAFramebuffer=o,this._bindUnboundFramebuffer(n._MSAAFramebuffer);let l=this._createRenderBuffer(n.texture.width,n.texture.height,e,-1,this._getRGBABufferInternalSizedFormat(n.texture.type,n.texture.format,n.texture._useSRGBBuffer),t.COLOR_ATTACHMENT0,!1);if(!l)throw new Error("Unable to create multi sampled framebuffer");i==null||i.addMSAARenderBuffer(l)}this._bindUnboundFramebuffer((a=n._MSAAFramebuffer)!=null?a:n._framebuffer),n.texture&&(n.texture.samples=e),n._samples=e;let r=n._depthStencilTexture?n._depthStencilTexture.format:void 0;return n._depthStencilBuffer=this._setupFramebufferDepthAttachments(n._generateStencilBuffer,n._generateDepthBuffer,n.width,n.height,e,r),this._bindUnboundFramebuffer(null),e};Pt.prototype._setupDepthStencilTexture=function(n,e,t,i,r=1){var u,h;let s=(u=e.width)!=null?u:e,a=(h=e.height)!=null?h:e,o=e.layers||0,l=e.depth||0;n.baseWidth=s,n.baseHeight=a,n.width=s,n.height=a,n.is2DArray=o>0,n.depth=o||l,n.isReady=!0,n.samples=r,n.generateMipMaps=!1,n.samplingMode=t?2:1,n.type=0,n._comparisonFunction=i;let c=this._gl,f=this._getTextureTarget(n),d=this._getSamplingParameters(n.samplingMode,!1);c.texParameteri(f,c.TEXTURE_MAG_FILTER,d.mag),c.texParameteri(f,c.TEXTURE_MIN_FILTER,d.min),c.texParameteri(f,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(f,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(i===0?(c.texParameteri(f,c.TEXTURE_COMPARE_FUNC,515),c.texParameteri(f,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(f,c.TEXTURE_COMPARE_FUNC,i),c.texParameteri(f,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))}});var YG=y(()=>{Is();Pt.prototype.setDepthStencilTexture=function(n,e,t,i){n!==void 0&&(e&&(this._boundUniforms[n]=e),!t||!t.depthStencilTexture?this._setTexture(n,null,void 0,void 0,i):this._setTexture(n,t,!1,!0,i))}});var KG=y(()=>{ea();wt();Is();Pt.prototype.createRenderTargetCubeTexture=function(n,e){let t=this._createHardwareRenderTargetWrapper(!1,!0,n),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,(i.type===1&&!this._caps.textureFloatLinearFiltering||i.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(i.samplingMode=1);let r=this._gl,s=new Xi(this,5);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,s,!0);let a=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type===1&&!this._caps.textureFloat&&(i.type=0,te.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,a.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,a.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let l=0;l<6;l++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+l,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),n,n,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);let o=r.createFramebuffer();return this._bindUnboundFramebuffer(o),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,n,n),i.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),t._framebuffer=o,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer,s.width=n,s.height=n,s.isReady=!0,s.isCube=!0,s.samples=1,s.generateMipMaps=i.generateMipMaps,s.samplingMode=i.samplingMode,s.type=i.type,s.format=i.format,this._internalTexturesCache.push(s),t.setTextures(s),t}});var jG,rp,Mr,Vt,es=y(()=>{jG=.45454545454545453,rp=2.2,Mr=(1+Math.sqrt(5))/2,Vt=.001});function yn(n,e){let t=[];for(let i=0;i<n;++i)t.push(e());return t}function Rc(n,e){return yn(n,e)}function fde(n,e,t){let i=n[e];if(typeof i!="function")return null;let r=function(){let s=n.length,a=r.previous.apply(n,arguments);return t(e,s),a};return i.next=r,r.previous=i,n[e]=r,()=>{let s=r.previous;if(!s)return;let a=r.next;a?(s.next=a,a.previous=s):(s.next=void 0,n[e]=s),r.next=void 0,r.previous=void 0}}function hR(n,e){let t=dde.map(i=>fde(n,i,e));return()=>{for(let i of t)i==null||i()}}var dde,Ol=y(()=>{dde=["push","splice","pop","shift","unshift"]});function zt(n,e){ZG[n]=e}function Vn(n){return ZG[n]}var ZG,ir=y(()=>{ZG={}});function Ci(n,e,t=1401298e-51){return Math.abs(n-e)<=t}function gr(n,e){return n===e?n:Math.random()*(e-n)+n}function Uo(n,e,t){return n+(e-n)*t}function qG(n,e,t,i,r){let s=r*r,a=r*s,o=2*a-3*s+1,l=-2*a+3*s,c=a-2*s+r,f=a-s;return n*o+t*l+e*c+i*f}function Gt(n,e=0,t=1){return Math.min(t,Math.max(e,n))}function QG(n){return n-=Math.PI*2*Math.floor((n+Math.PI)/(Math.PI*2)),n}function Vo(n){let e=n.toString(16);return n<=15?("0"+e).toUpperCase():e.toUpperCase()}function $G(n){if(Math.log2)return Math.floor(Math.log2(n));if(n<0)return NaN;if(n===0)return-1/0;let e=0;if(n<1){for(;n<1;)e++,n=n*2;e=-e}else if(n>1)for(;n>1;)e++,n=Math.floor(n/2);return e}function mR(n,e){let t=n%e;return t===0?e:mR(e,t)}var ts=y(()=>{});function JG(n){n.updateFlag=np._UpdateFlagSeed++}function lL(n,e,t,i=0){let r=n.asArray(),s=e.asArray(),a=r[0],o=r[1],l=r[2],c=r[3],f=r[4],d=r[5],u=r[6],h=r[7],m=r[8],g=r[9],p=r[10],_=r[11],v=r[12],E=r[13],S=r[14],T=r[15],A=s[0],R=s[1],M=s[2],I=s[3],C=s[4],L=s[5],w=s[6],G=s[7],O=s[8],N=s[9],B=s[10],V=s[11],q=s[12],K=s[13],J=s[14],Y=s[15];t[i]=a*A+o*C+l*O+c*q,t[i+1]=a*R+o*L+l*N+c*K,t[i+2]=a*M+o*w+l*B+c*J,t[i+3]=a*I+o*G+l*V+c*Y,t[i+4]=f*A+d*C+u*O+h*q,t[i+5]=f*R+d*L+u*N+h*K,t[i+6]=f*M+d*w+u*B+h*J,t[i+7]=f*I+d*G+u*V+h*Y,t[i+8]=m*A+g*C+p*O+_*q,t[i+9]=m*R+g*L+p*N+_*K,t[i+10]=m*M+g*w+p*B+_*J,t[i+11]=m*I+g*G+p*V+_*Y,t[i+12]=v*A+E*C+S*O+T*q,t[i+13]=v*R+E*L+S*N+T*K,t[i+14]=v*M+E*w+S*B+T*J,t[i+15]=v*I+E*G+S*V+T*Y}function Uu(n,e,t,i=0){lL(n,e,t.asArray(),i),JG(t)}function ek(n,e,t=0){let i=n.asArray();e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15]}function _v(n,e){let t=cL(n,e.asArray());return t&&JG(e),t}function cL(n,e){let t=n.asArray(),i=t[0],r=t[1],s=t[2],a=t[3],o=t[4],l=t[5],c=t[6],f=t[7],d=t[8],u=t[9],h=t[10],m=t[11],g=t[12],p=t[13],_=t[14],v=t[15],E=h*v-_*m,S=u*v-p*m,T=u*_-p*h,A=d*v-g*m,R=d*_-h*g,M=d*p-g*u,I=+(l*E-c*S+f*T),C=-(o*E-c*A+f*R),L=+(o*S-l*A+f*M),w=-(o*T-l*R+c*M),G=i*I+r*C+s*L+a*w;if(G===0)return!1;let O=1/G,N=c*v-_*f,B=l*v-p*f,V=l*_-p*c,q=o*v-g*f,K=o*_-g*c,J=o*p-g*l,Y=c*m-h*f,j=l*m-u*f,ue=l*h-u*c,Ee=o*m-d*f,Ue=o*h-d*c,se=o*u-d*l,ve=-(r*E-s*S+a*T),ne=+(i*E-s*A+a*R),me=-(i*S-r*A+a*M),Le=+(i*T-r*R+s*M),de=+(r*N-s*B+a*V),be=-(i*N-s*q+a*K),we=+(i*B-r*q+a*J),dt=-(i*V-r*K+s*J),Ve=-(r*Y-s*j+a*ue),Ze=+(i*Y-s*Ee+a*Ue),Kt=-(i*j-r*Ee+a*se),Bt=+(i*ue-r*Ue+s*se);return e[0]=I*O,e[1]=ve*O,e[2]=de*O,e[3]=Ve*O,e[4]=C*O,e[5]=ne*O,e[6]=be*O,e[7]=Ze*O,e[8]=L*O,e[9]=me*O,e[10]=we*O,e[11]=Kt*O,e[12]=w*O,e[13]=Le*O,e[14]=dt*O,e[15]=Bt*O,!0}var np,fL=y(()=>{np=class{};np._UpdateFlagSeed=0});var Cs,Fe,b,Vi,je,Q,Ye,ee,Vu,He=y(()=>{es();Ol();ir();$P();Yi();ts();fL();Cs=n=>parseInt(n.toString().replace(/\W/g,"")),Fe=class n{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=Cs(this.x),t=Cs(this.y),i=e;return i=i*397^t,i}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return n.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new n(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new n(this.x+e.x,this.y+e.y)}subtract(e){return new n(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new n(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new n(this.x*e,this.y*t)}divide(e){return new n(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new n(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new n(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new n(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=Vt){return e&&Ci(this.x,e.x,t)&&Ci(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new n(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new n(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotate(e){return this.rotateToRef(e,new n)}rotateToRef(e,t){let i=Math.cos(e),r=Math.sin(e);return t.x=i*this.x-r*this.y,t.y=r*this.x+i*this.y,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){let e=new n;return this.normalizeToRef(e),e}normalizeToRef(e){let t=this.length();return t===0&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new n(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new n(0,0)}static One(){return new n(1,1)}static Random(e=0,t=1){return new n(gr(e,t),gr(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(gr(e,t),gr(e,t))}static get ZeroReadOnly(){return n._ZeroReadOnly}static FromArray(e,t=0){return new n(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,r,s){let a=s*s,o=s*a,l=.5*(2*t.x+(-e.x+i.x)*s+(2*e.x-5*t.x+4*i.x-r.x)*a+(-e.x+3*t.x-3*i.x+r.x)*o),c=.5*(2*t.y+(-e.y+i.y)*s+(2*e.y-5*t.y+4*i.y-r.y)*a+(-e.y+3*t.y-3*i.y+r.y)*o);return new n(l,c)}static ClampToRef(e,t,i,r){return r.x=Gt(e.x,t.x,i.x),r.y=Gt(e.y,t.y,i.y),r}static Clamp(e,t,i){let r=Gt(e.x,t.x,i.x),s=Gt(e.y,t.y,i.y);return new n(r,s)}static Hermite(e,t,i,r,s){let a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,f=o-2*a+s,d=o-a,u=e.x*l+i.x*c+t.x*f+r.x*d,h=e.y*l+i.y*c+t.y*f+r.y*d;return new n(u,h)}static Hermite1stDerivative(e,t,i,r,s){return this.Hermite1stDerivativeToRef(e,t,i,r,s,new n)}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let o=s*s;return a.x=(o-s)*6*e.x+(3*o-4*s+1)*t.x+(-o+s)*6*i.x+(3*o-2*s)*r.x,a.y=(o-s)*6*e.y+(3*o-4*s+1)*t.y+(-o+s)*6*i.y+(3*o-2*s)*r.y,a}static Lerp(e,t,i){return n.LerpToRef(e,t,i,new n)}static LerpToRef(e,t,i,r){return r.x=e.x+(t.x-e.x)*i,r.y=e.y+(t.y-e.y)*i,r}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return n.NormalizeToRef(e,new n)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){let i=e.x<t.x?e.x:t.x,r=e.y<t.y?e.y:t.y;return new n(i,r)}static Maximize(e,t){let i=e.x>t.x?e.x:t.x,r=e.y>t.y?e.y:t.y;return new n(i,r)}static Transform(e,t){return n.TransformToRef(e,t,new n)}static TransformToRef(e,t,i){let r=t.m,s=e.x*r[0]+e.y*r[4]+r[12],a=e.x*r[1]+e.y*r[5]+r[13];return i.x=s,i.y=a,i}static PointInTriangle(e,t,i,r){let s=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),a=s<0?-1:1,o=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*a,l=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*a;return o>0&&l>0&&o+l<2*s*a}static Distance(e,t){return Math.sqrt(n.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y;return i*i+r*r}static Center(e,t){return n.CenterToRef(e,t,new n)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){let r=n.DistanceSquared(t,i);if(r===0)return n.Distance(e,t);let s=i.subtract(t),a=Math.max(0,Math.min(1,n.Dot(e.subtract(t),s)/r)),o=t.add(s.multiplyByFloats(a,a));return n.Distance(e,o)}};Fe._V8PerformanceHack=new Fe(.5,.5);Fe._ZeroReadOnly=Fe.Zero();Object.defineProperties(Fe.prototype,{dimension:{value:[2]},rank:{value:1}});b=class n{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=Cs(this._x),t=Cs(this._y),i=Cs(this._z),r=e;return r=r*397^t,r=r*397^i,r}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return n.FromArrayToRef(e,t,this),this}toQuaternion(){return je.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new n(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._isDirty=!0,t}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new n(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new n(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._isDirty=!0,r}negate(){return new n(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e._x=this._x*-1,e._y=this._y*-1,e._z=this._z*-1,e._isDirty=!0,e}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new n(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._isDirty=!0,t}getNormalToRef(e){let t=this.length(),i=Math.acos(this._y/t),r=Math.atan2(this._z,this._x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;let s=t*Math.sin(i)*Math.cos(r),a=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(r);return e.set(s,a,o),e}applyRotationQuaternionToRef(e,t){let i=this._x,r=this._y,s=this._z,a=e._x,o=e._y,l=e._z,c=e._w,f=2*(o*s-l*r),d=2*(l*i-a*s),u=2*(a*r-o*i);return t._x=i+c*f+o*u-l*d,t._y=r+c*d+l*f-a*u,t._z=s+c*u+a*d-o*f,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new n)}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._isDirty=!0,t}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new n)}projectOnPlaneToRef(e,t,i){let r=e.normal,s=e.d,a=Ye.Vector3[0];this.subtractToRef(t,a),a.normalize();let o=n.Dot(a,r);if(Math.abs(o)<1e-10)i.setAll(1/0);else{let l=-(n.Dot(t,r)+s)/o,c=a.scaleInPlace(l);t.addToRef(c,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=Vt){return e&&Ci(this._x,e._x,t)&&Ci(this._y,e._y,t)&&Ci(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t._x=this._x*e._x,t._y=this._y*e._y,t._z=this._z*e._z,t._isDirty=!0,t}multiplyByFloats(e,t,i){return new n(this._x*e,this._y*t,this._z*i)}divide(e){return new n(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t._x=this._x/e._x,t._y=this._y/e._y,t._z=this._z/e._z,t._isDirty=!0,t}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return e<this._x&&(this.x=e),t<this._y&&(this.y=t),i<this._z&&(this.z=i),this}maximizeInPlaceFromFloats(e,t,i){return e>this._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){let t=Math.abs(this._x),i=Math.abs(this._y);if(!Ci(t,i,e))return!0;let r=Math.abs(this._z);return!Ci(t,r,e)||!Ci(i,r,e)}get isNonUniform(){let e=Math.abs(this._x),t=Math.abs(this._y);if(e!==t)return!0;let i=Math.abs(this._z);return e!==i}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new n(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fractToRef(e){return e._x=this._x-Math.floor(this._x),e._y=this._y-Math.floor(this._y),e._z=this._z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new n(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z===0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if(e=e.toLowerCase(),e==="xyz")return this;let t=Ye.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(Ye.Matrix[0]),n.TransformCoordinatesToRef(this,Ye.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,Ye.Vector3[0]),Ye.Vector3[0].rotateByQuaternionToRef(e,Ye.Vector3[0]),t.addToRef(Ye.Vector3[0],i),i}cross(e){return n.CrossToRef(this,e,new n)}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new n)}normalizeToRef(e){let t=this.length();return t===0||t===1?(e._x=this._x,e._y=this._y,e._z=this._z,e._isDirty=!0,e):this.scaleToRef(1/t,e)}clone(){return new n(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,r){let s=n.Dot(e,i),a=n.Dot(t,i);return(s-r)/(s-a)}static GetAngleBetweenVectors(e,t,i){let r=e.normalizeToRef(Ye.Vector3[1]),s=t.normalizeToRef(Ye.Vector3[2]),a=n.Dot(r,s);a=Gt(a,-1,1);let o=Math.acos(a),l=Ye.Vector3[3];return n.CrossToRef(r,s,l),n.Dot(l,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(a)}static GetAngleBetweenVectorsOnPlane(e,t,i){Ye.Vector3[0].copyFrom(e);let r=Ye.Vector3[0];Ye.Vector3[1].copyFrom(t);let s=Ye.Vector3[1];Ye.Vector3[2].copyFrom(i);let a=Ye.Vector3[2],o=Ye.Vector3[3],l=Ye.Vector3[4];r.normalize(),s.normalize(),a.normalize(),n.CrossToRef(a,r,o),n.CrossToRef(o,a,l);let c=Math.atan2(n.Dot(s,o),n.Dot(s,l));return QG(c)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){let r=ee.Vector3[0];return t.subtractToRef(e,r),i._y=Math.atan2(r.x,r.z)||0,i._x=Math.atan2(Math.sqrt(r.x**2+r.z**2),r.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){let i=n.Zero();return n.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,r){i=Gt(i,0,1);let s=Ye.Vector3[0],a=Ye.Vector3[1];s.copyFrom(e);let o=s.length();s.normalizeFromLength(o),a.copyFrom(t);let l=a.length();a.normalizeFromLength(l);let c=n.Dot(s,a),f,d;if(c<1-Vt){let u=Math.acos(c),h=1/Math.sin(u);f=Math.sin((1-i)*u)*h,d=Math.sin(i*u)*h}else f=1-i,d=i;return s.scaleInPlace(f),a.scaleInPlace(d),r.copyFrom(s).addInPlace(a),r.scaleInPlace(Uo(o,l,i)),r}static SmoothToRef(e,t,i,r,s){return n.SlerpToRef(e,t,r===0?1:i/r,s),s}static FromArray(e,t=0){return new n(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return n.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return n.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,r){return r.copyFromFloats(e,t,i),r}static Zero(){return new n(0,0,0)}static One(){return new n(1,1,1)}static Up(){return new n(0,1,0)}static get UpReadOnly(){return n._UpReadOnly}static get DownReadOnly(){return n._DownReadOnly}static get RightReadOnly(){return n._RightReadOnly}static get LeftReadOnly(){return n._LeftReadOnly}static get LeftHandedForwardReadOnly(){return n._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return n._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return n._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return n._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return n._ZeroReadOnly}static get OneReadOnly(){return n._OneReadOnly}static Down(){return new n(0,-1,0)}static Forward(e=!1){return new n(0,0,e?-1:1)}static Backward(e=!1){return new n(0,0,e?1:-1)}static Right(){return new n(1,0,0)}static Left(){return new n(-1,0,0)}static Random(e=0,t=1){return new n(gr(e,t),gr(e,t),gr(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(gr(e,t),gr(e,t),gr(e,t))}static TransformCoordinates(e,t){let i=n.Zero();return n.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return n.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){let a=r.m,o=e*a[0]+t*a[4]+i*a[8]+a[12],l=e*a[1]+t*a[5]+i*a[9]+a[13],c=e*a[2]+t*a[6]+i*a[10]+a[14],f=1/(e*a[3]+t*a[7]+i*a[11]+a[15]);return s._x=o*f,s._y=l*f,s._z=c*f,s._isDirty=!0,s}static TransformNormal(e,t){let i=n.Zero();return n.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,r,s){let a=r.m;return s._x=e*a[0]+t*a[4]+i*a[8],s._y=e*a[1]+t*a[5]+i*a[9],s._z=e*a[2]+t*a[6]+i*a[10],s._isDirty=!0,s}static CatmullRom(e,t,i,r,s){let a=s*s,o=s*a,l=.5*(2*t._x+(-e._x+i._x)*s+(2*e._x-5*t._x+4*i._x-r._x)*a+(-e._x+3*t._x-3*i._x+r._x)*o),c=.5*(2*t._y+(-e._y+i._y)*s+(2*e._y-5*t._y+4*i._y-r._y)*a+(-e._y+3*t._y-3*i._y+r._y)*o),f=.5*(2*t._z+(-e._z+i._z)*s+(2*e._z-5*t._z+4*i._z-r._z)*a+(-e._z+3*t._z-3*i._z+r._z)*o);return new n(l,c,f)}static Clamp(e,t,i){let r=new n;return n.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){let s=e._x;s=s>i._x?i._x:s,s=s<t._x?t._x:s;let a=e._y;a=a>i._y?i._y:a,a=a<t._y?t._y:a;let o=e._z;return o=o>i._z?i._z:o,o=o<t._z?t._z:o,r.copyFromFloats(s,a,o),r}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static Hermite(e,t,i,r,s){let a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,f=o-2*a+s,d=o-a,u=e._x*l+i._x*c+t._x*f+r._x*d,h=e._y*l+i._y*c+t._y*f+r._y*d,m=e._z*l+i._z*c+t._z*f+r._z*d;return new n(u,h,m)}static Hermite1stDerivative(e,t,i,r,s){let a=new n;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let o=s*s;return a._x=(o-s)*6*e._x+(3*o-4*s+1)*t._x+(-o+s)*6*i._x+(3*o-2*s)*r._x,a._y=(o-s)*6*e._y+(3*o-4*s+1)*t._y+(-o+s)*6*i._y+(3*o-2*s)*r._y,a._z=(o-s)*6*e._z+(3*o-4*s+1)*t._z+(-o+s)*6*i._z+(3*o-2*s)*r._z,a._isDirty=!0,a}static Lerp(e,t,i){let r=new n(0,0,0);return n.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){return r._x=e._x+(t._x-e._x)*i,r._y=e._y+(t._y-e._y)*i,r._z=e._z+(t._z-e._z)*i,r._isDirty=!0,r}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z}static Cross(e,t){let i=new n;return n.CrossToRef(e,t,i),i}static CrossToRef(e,t,i){let r=e._y*t._z-e._z*t._y,s=e._z*t._x-e._x*t._z,a=e._x*t._y-e._y*t._x;return i.copyFromFloats(r,s,a),i}static Normalize(e){let t=n.Zero();return n.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Project(e,t,i,r){let s=new n;return n.ProjectToRef(e,t,i,r,s),s}static ProjectToRef(e,t,i,r,s){var g;let a=r.width,o=r.height,l=r.x,c=r.y,f=Ye.Matrix[1],d=(g=Oe.LastCreatedEngine)==null?void 0:g.isNDCHalfZRange,u=d?1:.5,h=d?0:.5;Q.FromValuesToRef(a/2,0,0,0,0,-o/2,0,0,0,0,u,0,l+a/2,o/2+c,h,1,f);let m=Ye.Matrix[0];return t.multiplyToRef(i,m),m.multiplyToRef(f,m),n.TransformCoordinatesToRef(e,m,s),s}static Reflect(e,t){return this.ReflectToRef(e,t,new n)}static ReflectToRef(e,t,i){let r=ee.Vector3[0];return r.copyFrom(t).scaleInPlace(2*n.Dot(e,t)),i.copyFrom(e).subtractInPlace(r)}static UnprojectFromTransform(e,t,i,r,s){return this.Unproject(e,t,i,r,s,Q.IdentityReadOnly)}static Unproject(e,t,i,r,s,a){let o=new n;return n.UnprojectToRef(e,t,i,r,s,a,o),o}static UnprojectToRef(e,t,i,r,s,a,o){return n.UnprojectFloatsToRef(e._x,e._y,e._z,t,i,r,s,a,o),o}static UnprojectFloatsToRef(e,t,i,r,s,a,o,l,c){var u;let f=Ye.Matrix[0];a.multiplyToRef(o,f),f.multiplyToRef(l,f),f.invert();let d=Ye.Vector3[0];return d.x=e/r*2-1,d.y=-(t/s*2-1),(u=Oe.LastCreatedEngine)!=null&&u.isNDCHalfZRange?d.z=i:d.z=2*i-1,n.TransformCoordinatesToRef(d,f,c),c}static Minimize(e,t){let i=new n;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){let i=new n;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(n.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e._x-t._x,r=e._y-t._y,s=e._z-t._z;return i*i+r*r+s*s}static ProjectOnTriangleToRef(e,t,i,r,s){let a=Ye.Vector3[0],o=Ye.Vector3[1],l=Ye.Vector3[2],c=Ye.Vector3[3],f=Ye.Vector3[4];i.subtractToRef(t,a),r.subtractToRef(t,o),r.subtractToRef(i,l);let d=a.length(),u=o.length(),h=l.length();if(d<Vt||u<Vt||h<Vt)return s.copyFrom(t),n.Distance(e,t);e.subtractToRef(t,f),n.CrossToRef(a,o,c);let m=c.length();if(m<Vt)return s.copyFrom(t),n.Distance(e,t);c.normalizeFromLength(m);let g=f.length();if(g<Vt)return s.copyFrom(t),0;f.normalizeFromLength(g);let p=n.Dot(c,f),_=Ye.Vector3[5],v=Ye.Vector3[6];_.copyFrom(c).scaleInPlace(-g*p),v.copyFrom(e).addInPlace(_);let E=Ye.Vector3[4],S=Ye.Vector3[5],T=Ye.Vector3[7],A=Ye.Vector3[8];E.copyFrom(a).scaleInPlace(1/d),A.copyFrom(o).scaleInPlace(1/u),E.addInPlace(A).scaleInPlace(-1),S.copyFrom(a).scaleInPlace(-1/d),A.copyFrom(l).scaleInPlace(1/h),S.addInPlace(A).scaleInPlace(-1),T.copyFrom(l).scaleInPlace(-1/h),A.copyFrom(o).scaleInPlace(-1/u),T.addInPlace(A).scaleInPlace(-1);let R=Ye.Vector3[9],M;R.copyFrom(v).subtractInPlace(t),n.CrossToRef(E,R,A),M=n.Dot(A,c);let I=M;R.copyFrom(v).subtractInPlace(i),n.CrossToRef(S,R,A),M=n.Dot(A,c);let C=M;R.copyFrom(v).subtractInPlace(r),n.CrossToRef(T,R,A),M=n.Dot(A,c);let L=M,w=Ye.Vector3[10],G,O;I>0&&C<0?(w.copyFrom(a),G=t,O=i):C>0&&L<0?(w.copyFrom(l),G=i,O=r):(w.copyFrom(o).scaleInPlace(-1),G=r,O=t);let N=Ye.Vector3[9],B=Ye.Vector3[4];if(G.subtractToRef(v,A),O.subtractToRef(v,N),n.CrossToRef(A,N,B),!(n.Dot(B,c)<0))return s.copyFrom(v),Math.abs(g*p);let q=Ye.Vector3[5];n.CrossToRef(w,B,q),q.normalize();let K=Ye.Vector3[9];K.copyFrom(G).subtractInPlace(v);let J=K.length();if(J<Vt)return s.copyFrom(G),n.Distance(e,G);K.normalizeFromLength(J);let Y=n.Dot(q,K),j=Ye.Vector3[7];j.copyFrom(v).addInPlace(q.scaleInPlace(J*Y)),A.copyFrom(j).subtractInPlace(G),g=w.length(),w.normalizeFromLength(g);let ue=n.Dot(A,w)/Math.max(g,Vt);return ue=Gt(ue,0,1),j.copyFrom(G).addInPlace(w.scaleInPlace(ue*g)),s.copyFrom(j),n.Distance(e,j)}static Center(e,t){return n.CenterToRef(e,t,n.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e._x+t._x)/2,(e._y+t._y)/2,(e._z+t._z)/2)}static RotationFromAxis(e,t,i){let r=new n;return n.RotationFromAxisToRef(e,t,i,r),r}static RotationFromAxisToRef(e,t,i,r){let s=Ye.Quaternion[0];return je.RotationQuaternionFromAxisToRef(e,t,i,s),s.toEulerAnglesToRef(r),r}};b._V8PerformanceHack=new b(.5,.5,.5);b._UpReadOnly=b.Up();b._DownReadOnly=b.Down();b._LeftHandedForwardReadOnly=b.Forward(!1);b._RightHandedForwardReadOnly=b.Forward(!0);b._LeftHandedBackwardReadOnly=b.Backward(!1);b._RightHandedBackwardReadOnly=b.Backward(!0);b._RightReadOnly=b.Right();b._LeftReadOnly=b.Left();b._ZeroReadOnly=b.Zero();b._OneReadOnly=b.One();Object.defineProperties(b.prototype,{dimension:{value:[3]},rank:{value:1}});Vi=class n{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,r=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Vector4"}getHashCode(){let e=Cs(this._x),t=Cs(this._y),i=Cs(this._z),r=Cs(this._w),s=e;return s=s*397^t,s=s*397^i,s=s*397^r,s}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t){return t===void 0&&(t=0),e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return n.FromArrayToRef(e,t,this),this}addInPlace(e){return this.x+=e._x,this.y+=e._y,this.z+=e._z,this.w+=e._w,this}addInPlaceFromFloats(e,t,i,r){return this.x+=e,this.y+=t,this.z+=i,this.w+=r,this}add(e){return new n(this._x+e.x,this._y+e.y,this._z+e.z,this._w+e.w)}addToRef(e,t){return t.x=this._x+e.x,t.y=this._y+e.y,t.z=this._z+e.z,t.w=this._w+e.w,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subtract(e){return new n(this._x-e.x,this._y-e.y,this._z-e.z,this._w-e.w)}subtractToRef(e,t){return t.x=this._x-e.x,t.y=this._y-e.y,t.z=this._z-e.z,t.w=this._w-e.w,t}subtractFromFloats(e,t,i,r){return new n(this._x-e,this._y-t,this._z-i,this._w-r)}subtractFromFloatsToRef(e,t,i,r,s){return s.x=this._x-e,s.y=this._y-t,s.z=this._z-i,s.w=this._w-r,s}negate(){return new n(-this._x,-this._y,-this._z,-this._w)}negateInPlace(){return this.x*=-1,this.y*=-1,this.z*=-1,this.w*=-1,this}negateToRef(e){return e.x=-this._x,e.y=-this._y,e.z=-this._z,e.w=-this._w,e}scaleInPlace(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}scale(e){return new n(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t.x=this._x*e,t.y=this._y*e,t.z=this._z*e,t.w=this._w*e,t}scaleAndAddToRef(e,t){return t.x+=this._x*e,t.y+=this._y*e,t.z+=this._z*e,t.w+=this._w*e,t}equals(e){return e&&this._x===e.x&&this._y===e.y&&this._z===e.z&&this._w===e.w}equalsWithEpsilon(e,t=Vt){return e&&Ci(this._x,e.x,t)&&Ci(this._y,e.y,t)&&Ci(this._z,e.z,t)&&Ci(this._w,e.w,t)}equalsToFloats(e,t,i,r){return this._x===e&&this._y===t&&this._z===i&&this._w===r}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiply(e){return new n(this._x*e.x,this._y*e.y,this._z*e.z,this._w*e.w)}multiplyToRef(e,t){return t.x=this._x*e.x,t.y=this._y*e.y,t.z=this._z*e.z,t.w=this._w*e.w,t}multiplyByFloats(e,t,i,r){return new n(this._x*e,this._y*t,this._z*i,this._w*r)}divide(e){return new n(this._x/e.x,this._y/e.y,this._z/e.z,this._w/e.w)}divideToRef(e,t){return t.x=this._x/e.x,t.y=this._y/e.y,t.z=this._z/e.z,t.w=this._w/e.w,t}divideInPlace(e){return this.divideToRef(e,this)}minimizeInPlace(e){return e.x<this._x&&(this.x=e.x),e.y<this._y&&(this.y=e.y),e.z<this._z&&(this.z=e.z),e.w<this._w&&(this.w=e.w),this}maximizeInPlace(e){return e.x>this._x&&(this.x=e.x),e.y>this._y&&(this.y=e.y),e.z>this._z&&(this.z=e.z),e.w>this._w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,r){return this.x=Math.min(e,this._x),this.y=Math.min(t,this._y),this.z=Math.min(i,this._z),this.w=Math.min(r,this._w),this}maximizeInPlaceFromFloats(e,t,i,r){return this.x=Math.max(e,this._x),this.y=Math.max(t,this._y),this.z=Math.max(i,this._z),this.w=Math.max(r,this._w),this}floorToRef(e){return e.x=Math.floor(this._x),e.y=Math.floor(this._y),e.z=Math.floor(this._z),e.w=Math.floor(this._w),e}floor(){return new n(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z),Math.floor(this._w))}fractToRef(e){return e.x=this._x-Math.floor(this._x),e.y=this._y-Math.floor(this._y),e.z=this._z-Math.floor(this._z),e.w=this._w-Math.floor(this._w),e}fract(){return new n(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z),this._w-Math.floor(this._w))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new n)}normalizeToRef(e){let t=this.length();return t===0||t===1?(e.x=this._x,e.y=this._y,e.z=this._z,e.w=this._w,e):this.scaleToRef(1/t,e)}toVector3(){return new b(this._x,this._y,this._z)}clone(){return new n(this._x,this._y,this._z,this._w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this._x*e.x+this._y*e.y+this._z*e.z+this._w*e.w}static FromArray(e,t){return t||(t=0),new n(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return n.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,r,s){return s.x=e,s.y=t,s.z=i,s.w=r,s}static Zero(){return new n(0,0,0,0)}static One(){return new n(1,1,1,1)}static Random(e=0,t=1){return new n(gr(e,t),gr(e,t),gr(e,t),gr(e,t))}static RandomToRef(e=0,t=1,i){return i.x=gr(e,t),i.y=gr(e,t),i.z=gr(e,t),i.w=gr(e,t),i}static Clamp(e,t,i){return n.ClampToRef(e,t,i,new n)}static ClampToRef(e,t,i,r){return r.x=Gt(e.x,t.x,i.x),r.y=Gt(e.y,t.y,i.y),r.z=Gt(e.z,t.z,i.z),r.w=Gt(e.w,t.w,i.w),r}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return n._ZeroReadOnly}static Normalize(e){return n.NormalizeToRef(e,new n)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){let i=new n;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){let i=new n;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(n.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,a=e.w-t.w;return i*i+r*r+s*s+a*a}static Center(e,t){return n.CenterToRef(e,t,new n)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return n.TransformCoordinatesToRef(e,t,new n)}static TransformCoordinatesToRef(e,t,i){return n.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){let a=r.m,o=e*a[0]+t*a[4]+i*a[8]+a[12],l=e*a[1]+t*a[5]+i*a[9]+a[13],c=e*a[2]+t*a[6]+i*a[10]+a[14],f=e*a[3]+t*a[7]+i*a[11]+a[15];return s.x=o,s.y=l,s.z=c,s.w=f,s}static TransformNormal(e,t){return n.TransformNormalToRef(e,t,new n)}static TransformNormalToRef(e,t,i){let r=t.m,s=e.x*r[0]+e.y*r[4]+e.z*r[8],a=e.x*r[1]+e.y*r[5]+e.z*r[9],o=e.x*r[2]+e.y*r[6]+e.z*r[10];return i.x=s,i.y=a,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,r,s,a){let o=s.m;return a.x=e*o[0]+t*o[4]+i*o[8],a.y=e*o[1]+t*o[5]+i*o[9],a.z=e*o[2]+t*o[6]+i*o[10],a.w=r,a}static FromVector3(e,t=0){return new n(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}};Vi._V8PerformanceHack=new Vi(.5,.5,.5,.5);Vi._ZeroReadOnly=Vi.Zero();Object.defineProperties(Vi.prototype,{dimension:{value:[4]},rank:{value:1}});je=class n{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,r=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=Cs(this._x),t=Cs(this._y),i=Cs(this._z),r=Cs(this._w),s=e;return s=s*397^t,s=s*397^i,s=s*397^r,s}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return n.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=Vt){return e&&Ci(this._x,e._x,t)&&Ci(this._y,e._y,t)&&Ci(this._z,e._z,t)&&Ci(this._w,e._w,t)}isApprox(e,t=Vt){return e&&(Ci(this._x,e._x,t)&&Ci(this._y,e._y,t)&&Ci(this._z,e._z,t)&&Ci(this._w,e._w,t)||Ci(this._x,-e._x,t)&&Ci(this._y,-e._y,t)&&Ci(this._z,-e._z,t)&&Ci(this._w,-e._w,t))}clone(){return new n(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._isDirty=!0,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new n(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,r){return this._x+=e,this._y+=t,this._z+=i,this._w+=r,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,r){return this.subtractFromFloatsToRef(e,t,i,r,new n)}subtractFromFloatsToRef(e,t,i,r,s){return s._x=this._x-e,s._y=this._y-t,s._z=this._z-i,s._w=this._w-r,s._isDirty=!0,s}subtract(e){return new n(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new n(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){let t=new n(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){let i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,r=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,s=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,a=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,r,s,a),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,r){return this._x*=e,this._y*=t,this._z*=i,this._w*=r,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new n)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,r){return this._x===e&&this._y===t&&this._z===i&&this._w===r}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new n(-this._x,-this._y,-this._z,this._w)}invert(){let e=this.conjugate(),t=this.lengthSquared();return t==0||t==1||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();let e=this.lengthSquared();return e==0||e==1?this:(this.scaleInPlace(1/e),this)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){let e=new n(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){let t=this.length();return t===0||t===1?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){let e=b.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){let t=this._z,i=this._x,r=this._y,s=this._w,a=r*t-i*s,o=.4999999;if(a<-o)e._y=2*Math.atan2(r,s),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(a>o)e._y=2*Math.atan2(r,s),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{let l=s*s,c=t*t,f=i*i,d=r*r;e._z=Math.atan2(2*(i*r+t*s),-c-f+d+l),e._x=Math.asin(-2*a),e._y=Math.atan2(2*(t*i+r*s),c-f-d+l),e._isDirty=!0}return e}toAlphaBetaGammaToRef(e){let t=this._z,i=this._x,r=this._y,s=this._w,a=Math.sqrt(i*i+r*r),o=Math.sqrt(t*t+s*s),l=2*Math.atan2(a,o),c=2*Math.atan2(t,s),f=2*Math.atan2(r,i),d=(c+f)/2,u=(c-f)/2;return e.set(u,l,d),e}toRotationMatrix(e){return Q.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return n.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}toAxisAngle(){let e=b.Zero(),t=this.toAxisAngleToRef(e);return{axis:e,angle:t}}toAxisAngleToRef(e){let t,i=Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z),r=this._w;return i>0?(t=2*Math.atan2(i,r),e.set(this._x/i,this._y/i,this._z/i)):(t=0,e.set(1,0,0)),t}static FromRotationMatrix(e){let t=new n;return n.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){let i=e.m,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],f=i[2],d=i[6],u=i[10],h=r+l+u,m;return h>0?(m=.5/Math.sqrt(h+1),t._w=.25/m,t._x=(d-c)*m,t._y=(a-f)*m,t._z=(o-s)*m,t._isDirty=!0):r>l&&r>u?(m=2*Math.sqrt(1+r-l-u),t._w=(d-c)/m,t._x=.25*m,t._y=(s+o)/m,t._z=(a+f)/m,t._isDirty=!0):l>u?(m=2*Math.sqrt(1+l-r-u),t._w=(a-f)/m,t._x=(s+o)/m,t._y=.25*m,t._z=(c+d)/m,t._isDirty=!0):(m=2*Math.sqrt(1+u-r-l),t._w=(o-s)/m,t._x=(a+f)/m,t._y=(c+d)/m,t._z=.25*m,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){let r=n.Dot(e,t);return 1-r*r<=i}static SmoothToRef(e,t,i,r,s){let a=r===0?1:i/r;return a=Gt(a,0,1),n.SlerpToRef(e,t,a,s),s}static Zero(){return new n(0,0,0,0)}static Inverse(e){return new n(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new n(0,0,0,1)}static IsIdentity(e){return e&&e._x===0&&e._y===0&&e._z===0&&e._w===1}static RotationAxis(e,t){return n.RotationAxisToRef(e,t,new n)}static RotationAxisToRef(e,t,i){i._w=Math.cos(t/2);let r=Math.sin(t/2)/e.length();return i._x=e._x*r,i._y=e._y*r,i._z=e._z*r,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new n(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,r,s){return s.copyFromFloats(e,t,i,r),s}static FromEulerAngles(e,t,i){let r=new n;return n.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerAnglesToRef(e,t,i,r){return n.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerVector(e){let t=new n;return n.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return n.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,r=Vt){let s=b.Dot(e,t)+1;return s<r?Math.abs(e.x)>Math.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(b.CrossToRef(e,t,ee.Vector3[0]),i.set(ee.Vector3[0].x,ee.Vector3[0].y,ee.Vector3[0].z,s)),i.normalize()}static RotationYawPitchRoll(e,t,i){let r=new n;return n.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){let s=i*.5,a=t*.5,o=e*.5,l=Math.sin(s),c=Math.cos(s),f=Math.sin(a),d=Math.cos(a),u=Math.sin(o),h=Math.cos(o);return r._x=h*f*c+u*d*l,r._y=u*d*c-h*f*l,r._z=h*d*l-u*f*c,r._w=h*d*c+u*f*l,r._isDirty=!0,r}static RotationAlphaBetaGamma(e,t,i){let r=new n;return n.RotationAlphaBetaGammaToRef(e,t,i,r),r}static RotationAlphaBetaGammaToRef(e,t,i,r){let s=(i+e)*.5,a=(i-e)*.5,o=t*.5;return r._x=Math.cos(a)*Math.sin(o),r._y=Math.sin(a)*Math.sin(o),r._z=Math.sin(s)*Math.cos(o),r._w=Math.cos(s)*Math.cos(o),r._isDirty=!0,r}static RotationQuaternionFromAxis(e,t,i){let r=new n(0,0,0,0);return n.RotationQuaternionFromAxisToRef(e,t,i,r),r}static RotationQuaternionFromAxisToRef(e,t,i,r){let s=Ye.Matrix[0];return e=e.normalizeToRef(Ye.Vector3[0]),t=t.normalizeToRef(Ye.Vector3[1]),i=i.normalizeToRef(Ye.Vector3[2]),Q.FromXYZAxesToRef(e,t,i,s),n.FromRotationMatrixToRef(s,r),r}static FromLookDirectionLH(e,t){let i=new n;return n.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){let r=Ye.Matrix[0];return Q.LookDirectionLHToRef(e,t,r),n.FromRotationMatrixToRef(r,i),i}static FromLookDirectionRH(e,t){let i=new n;return n.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){let r=Ye.Matrix[0];return Q.LookDirectionRHToRef(e,t,r),n.FromRotationMatrixToRef(r,i)}static Slerp(e,t,i){let r=n.Identity();return n.SlerpToRef(e,t,i,r),r}static SlerpToRef(e,t,i,r){let s,a,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,l=!1;if(o<0&&(l=!0,o=-o),o>.999999)a=1-i,s=l?-i:i;else{let c=Math.acos(o),f=1/Math.sin(c);a=Math.sin((1-i)*c)*f,s=l?-Math.sin(i*c)*f:Math.sin(i*c)*f}return r._x=a*e._x+s*t._x,r._y=a*e._y+s*t._y,r._z=a*e._z+s*t._z,r._w=a*e._w+s*t._w,r._isDirty=!0,r}static Hermite(e,t,i,r,s){let a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,f=o-2*a+s,d=o-a,u=e._x*l+i._x*c+t._x*f+r._x*d,h=e._y*l+i._y*c+t._y*f+r._y*d,m=e._z*l+i._z*c+t._z*f+r._z*d,g=e._w*l+i._w*c+t._w*f+r._w*d;return new n(u,h,m,g)}static Hermite1stDerivative(e,t,i,r,s){let a=new n;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let o=s*s;return a._x=(o-s)*6*e._x+(3*o-4*s+1)*t._x+(-o+s)*6*i._x+(3*o-2*s)*r._x,a._y=(o-s)*6*e._y+(3*o-4*s+1)*t._y+(-o+s)*6*i._y+(3*o-2*s)*r._y,a._z=(o-s)*6*e._z+(3*o-4*s+1)*t._z+(-o+s)*6*i._z+(3*o-2*s)*r._z,a._w=(o-s)*6*e._w+(3*o-4*s+1)*t._w+(-o+s)*6*i._w+(3*o-2*s)*r._w,a._isDirty=!0,a}static Normalize(e){let t=n.Zero();return n.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){let r=new n;return n.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){return r.copyFromFloats(Gt(e.x,t.x,i.x),Gt(e.y,t.y,i.y),Gt(e.z,t.z,i.z),Gt(e.w,t.w,i.w))}static Random(e=0,t=1){return new n(gr(e,t),gr(e,t),gr(e,t),gr(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(gr(e,t),gr(e,t),gr(e,t),gr(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(n.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,a=e.w-t.w;return i*i+r*r+s*s+a*a}static Center(e,t){return n.CenterToRef(e,t,n.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}};je._V8PerformanceHack=new je(.5,.5,.5,.5);Object.defineProperties(je.prototype,{dimension:{value:[4]},rank:{value:1}});Q=class n{static get Use64Bits(){return ys.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=np._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,r=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=this._isIdentity?!1:t,this._isIdentity3x2Dirty=this._isIdentity3x2?!1:r}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,ys.MatrixTrackPrecisionChange&&ys.MatrixTrackedMatrices.push(this),this._m=new ys.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;let e=this._m;this._isIdentity=e[0]===1&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===1&&e[6]===0&&e[7]===0&&e[8]===0&&e[9]===0&&e[10]===1&&e[11]===0&&e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,this._m[0]!==1||this._m[5]!==1||this._m[15]!==1?this._isIdentity3x2=!1:this._m[1]!==0||this._m[2]!==0||this._m[3]!==0||this._m[4]!==0||this._m[6]!==0||this._m[7]!==0||this._m[8]!==0||this._m[9]!==0||this._m[10]!==0||this._m[11]!==0||this._m[12]!==0||this._m[13]!==0||this._m[14]!==0?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(this._isIdentity===!0)return 1;let e=this._m,t=e[0],i=e[1],r=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],f=e[8],d=e[9],u=e[10],h=e[11],m=e[12],g=e[13],p=e[14],_=e[15],v=u*_-p*h,E=d*_-g*h,S=d*p-g*u,T=f*_-m*h,A=f*p-u*m,R=f*g-m*d,M=+(o*v-l*E+c*S),I=-(a*v-l*T+c*A),C=+(a*E-o*T+c*R),L=-(a*S-o*A+l*R);return t*M+i*I+r*C+s*L}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}
${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}
${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}
${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;let i=this._m;for(let r=0;r<16;r++)e[t+r]=i[r];return this}asArray(){return this._m}fromArray(e,t=0){return n.FromArrayToRef(e,t,this)}copyFromFloats(...e){return n.FromArrayToRef(e,0,this)}set(...e){let t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){let t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return n.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){let t=new n;return this.addToRef(e,t),t}addToRef(e,t){let i=this._m,r=t._m,s=e.m;for(let a=0;a<16;a++)r[a]=i[a]+s[a];return t.markAsUpdated(),t}addToSelf(e){let t=this._m,i=e.m;return t[0]+=i[0],t[1]+=i[1],t[2]+=i[2],t[3]+=i[3],t[4]+=i[4],t[5]+=i[5],t[6]+=i[6],t[7]+=i[7],t[8]+=i[8],t[9]+=i[9],t[10]+=i[10],t[11]+=i[11],t[12]+=i[12],t[13]+=i[13],t[14]+=i[14],t[15]+=i[15],this.markAsUpdated(),this}addInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]+=i[r];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){let t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]-=i[r];return this.markAsUpdated(),this}subtractToRef(e,t){let i=this._m,r=e.m,s=t._m;for(let a=0;a<16;a++)s[a]=i[a]-r[a];return t.markAsUpdated(),t}subtractInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]-=i[r];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new n)}subtractFromFloatsToRef(...e){let t=e.pop(),i=this._m,r=t._m,s=e;for(let a=0;a<16;a++)r[a]=i[a]-s[a];return t.markAsUpdated(),t}invertToRef(e){return this._isIdentity===!0?(n.IdentityToRef(e),e):(cL(this,e.asArray())?e.markAsUpdated():e.copyFrom(this),e)}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new b(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){let e=this.m;return n.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1),this}copyFrom(e){e.copyToArray(this._m);let t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){return ek(this,e,t),this}multiply(e){let t=new n;return this.multiplyToRef(e,t),t}multiplyInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]*=i[r];return this.markAsUpdated(),this}multiplyByFloats(...e){let t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){let t=e.pop(),i=this._m,r=t._m,s=e;for(let a=0;a<16;a++)r[a]=i[a]*s[a];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){return lL(this,e,t,i),this}divide(e){return this.divideToRef(e,new n)}divideToRef(e,t){let i=this._m,r=e.m,s=t._m;for(let a=0;a<16;a++)s[a]=i[a]/r[a];return t.markAsUpdated(),t}divideInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]/=i[r];return this.markAsUpdated(),this}minimizeInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]=Math.min(t[r],i[r]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){let t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]=Math.min(t[r],i[r]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){let t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new n)}negateInPlace(){let e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){let t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=-t[r];return e.markAsUpdated(),e}equals(e){let t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;let i=this.m,r=t.m;return i[0]===r[0]&&i[1]===r[1]&&i[2]===r[2]&&i[3]===r[3]&&i[4]===r[4]&&i[5]===r[5]&&i[6]===r[6]&&i[7]===r[7]&&i[8]===r[8]&&i[9]===r[9]&&i[10]===r[10]&&i[11]===r[11]&&i[12]===r[12]&&i[13]===r[13]&&i[14]===r[14]&&i[15]===r[15]}equalsWithEpsilon(e,t=0){let i=this._m,r=e.m;for(let s=0;s<16;s++)if(!Ci(i[s],r[s],t))return!1;return!0}equalsToFloats(...e){let t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new n)}floorToRef(e){let t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=Math.floor(t[r]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new n)}fractToRef(e){let t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=t[r]-Math.floor(t[r]);return e.markAsUpdated(),e}clone(){let e=new n;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=Cs(this._m[0]);for(let t=1;t<16;t++)e=e*397^Cs(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new je,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,r,s=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;let a=this._m;if(i&&i.copyFromFloats(a[12],a[13],a[14]),e=e||Ye.Vector3[0],e.x=Math.sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]),e.y=Math.sqrt(a[4]*a[4]+a[5]*a[5]+a[6]*a[6]),e.z=Math.sqrt(a[8]*a[8]+a[9]*a[9]+a[10]*a[10]),r){let o=(s?r.absoluteScaling.x:r.scaling.x)<0?-1:1,l=(s?r.absoluteScaling.y:r.scaling.y)<0?-1:1,c=(s?r.absoluteScaling.z:r.scaling.z)<0?-1:1;e.x*=o,e.y*=l,e.z*=c}else this.determinant()<=0&&(e.y*=-1);if(e._x===0||e._y===0||e._z===0)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){let o=1/e._x,l=1/e._y,c=1/e._z;n.FromValuesToRef(a[0]*o,a[1]*o,a[2]*o,0,a[4]*l,a[5]*l,a[6]*l,0,a[8]*c,a[9]*c,a[10]*c,0,0,0,0,1,Ye.Matrix[0]),je.FromRotationMatrixToRef(Ye.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;let t=e*4;return new Vi(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){let i=e*4;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){let e=new n;return n.TransposeToRef(this,e),e}transposeToRef(e){return n.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,r,s){if(e<0||e>3)return this;let a=e*4;return this._m[a+0]=t,this._m[a+1]=i,this._m[a+2]=r,this._m[a+3]=s,this.markAsUpdated(),this}scale(e){let t=new n;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){let t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){let t=Ye.Matrix[0];this.invertToRef(t),t.transposeToRef(e);let i=e._m;return n.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){let e=new n;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){let t=Ye.Vector3[0];if(!this.decompose(t))return n.IdentityToRef(e),e;let i=this._m,r=1/t._x,s=1/t._y,a=1/t._z;return n.FromValuesToRef(i[0]*r,i[1]*r,i[2]*r,0,i[4]*s,i[5]*s,i[6]*s,0,i[8]*a,i[9]*a,i[10]*a,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){let e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){let e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){let i=new n;return n.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let r=0;r<16;r++)i._m[r]=e[r+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,r){return r._m[0]=e[0+t]*i,r._m[1]=e[1+t]*i,r._m[2]=e[2+t]*i,r._m[3]=e[3+t]*i,r._m[4]=e[4+t]*i,r._m[5]=e[5+t]*i,r._m[6]=e[6+t]*i,r._m[7]=e[7+t]*i,r._m[8]=e[8+t]*i,r._m[9]=e[9+t]*i,r._m[10]=e[10+t]*i,r._m[11]=e[11+t]*i,r._m[12]=e[12+t]*i,r._m[13]=e[13+t]*i,r._m[14]=e[14+t]*i,r._m[15]=e[15+t]*i,r.markAsUpdated(),r}static get IdentityReadOnly(){return n._IdentityReadOnly}static FromValuesToRef(e,t,i,r,s,a,o,l,c,f,d,u,h,m,g,p,_){let v=_._m;v[0]=e,v[1]=t,v[2]=i,v[3]=r,v[4]=s,v[5]=a,v[6]=o,v[7]=l,v[8]=c,v[9]=f,v[10]=d,v[11]=u,v[12]=h,v[13]=m,v[14]=g,v[15]=p,_.markAsUpdated()}static FromValues(e,t,i,r,s,a,o,l,c,f,d,u,h,m,g,p){let _=new n,v=_._m;return v[0]=e,v[1]=t,v[2]=i,v[3]=r,v[4]=s,v[5]=a,v[6]=o,v[7]=l,v[8]=c,v[9]=f,v[10]=d,v[11]=u,v[12]=h,v[13]=m,v[14]=g,v[15]=p,_.markAsUpdated(),_}static Compose(e,t,i){let r=new n;return n.ComposeToRef(e,t,i,r),r}static ComposeToRef(e,t,i,r){let s=r._m,a=t._x,o=t._y,l=t._z,c=t._w,f=a+a,d=o+o,u=l+l,h=a*f,m=a*d,g=a*u,p=o*d,_=o*u,v=l*u,E=c*f,S=c*d,T=c*u,A=e._x,R=e._y,M=e._z;return s[0]=(1-(p+v))*A,s[1]=(m+T)*A,s[2]=(g-S)*A,s[3]=0,s[4]=(m-T)*R,s[5]=(1-(h+v))*R,s[6]=(_+E)*R,s[7]=0,s[8]=(g+S)*M,s[9]=(_-E)*M,s[10]=(1-(h+p))*M,s[11]=0,s[12]=i._x,s[13]=i._y,s[14]=i._z,s[15]=1,r.markAsUpdated(),r}static Identity(){let e=n.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return n.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){let e=n.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){let t=new n;return n.RotationXToRef(e,t),t}static Invert(e){let t=new n;return e.invertToRef(t),t}static RotationXToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return n.FromValuesToRef(1,0,0,0,0,r,i,0,0,-i,r,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationY(e){let t=new n;return n.RotationYToRef(e,t),t}static RotationYToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return n.FromValuesToRef(r,0,-i,0,0,1,0,0,i,0,r,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationZ(e){let t=new n;return n.RotationZToRef(e,t),t}static RotationZToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return n.FromValuesToRef(r,i,0,0,-i,r,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationAxis(e,t){let i=new n;return n.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){let r=Math.sin(-t),s=Math.cos(-t),a=1-s;e=e.normalizeToRef(Ye.Vector3[0]);let o=i._m;return o[0]=e._x*e._x*a+s,o[1]=e._x*e._y*a-e._z*r,o[2]=e._x*e._z*a+e._y*r,o[3]=0,o[4]=e._y*e._x*a+e._z*r,o[5]=e._y*e._y*a+s,o[6]=e._y*e._z*a-e._x*r,o[7]=0,o[8]=e._z*e._x*a-e._y*r,o[9]=e._z*e._y*a+e._x*r,o[10]=e._z*e._z*a+s,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,r=!1){let s=b.Dot(t,e),a=i._m;if(s<-1+Vt)a[0]=-1,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=r?1:-1,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=r?-1:1,a[11]=0;else{let o=b.Cross(t,e),l=1/(1+s);a[0]=o._x*o._x*l+s,a[1]=o._y*o._x*l-o._z,a[2]=o._z*o._x*l+o._y,a[3]=0,a[4]=o._x*o._y*l+o._z,a[5]=o._y*o._y*l+s,a[6]=o._z*o._y*l-o._x,a[7]=0,a[8]=o._x*o._z*l-o._y,a[9]=o._y*o._z*l+o._x,a[10]=o._z*o._z*l+s,a[11]=0}return a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){let r=new n;return n.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){return je.RotationYawPitchRollToRef(e,t,i,Ye.Quaternion[0]),Ye.Quaternion[0].toRotationMatrix(r),r}static Scaling(e,t,i){let r=new n;return n.ScalingToRef(e,t,i,r),r}static ScalingToRef(e,t,i,r){return n.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,r),r._updateIdentityStatus(e===1&&t===1&&i===1),r}static Translation(e,t,i){let r=new n;return n.TranslationToRef(e,t,i,r),r}static TranslationToRef(e,t,i,r){return n.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,r),r._updateIdentityStatus(e===0&&t===0&&i===0),r}static Lerp(e,t,i){let r=new n;return n.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){let s=r._m,a=e.m,o=t.m;for(let l=0;l<16;l++)s[l]=a[l]*(1-i)+o[l]*i;return r.markAsUpdated(),r}static DecomposeLerp(e,t,i){let r=new n;return n.DecomposeLerpToRef(e,t,i,r),r}static DecomposeLerpToRef(e,t,i,r){let s=Ye.Vector3[0],a=Ye.Quaternion[0],o=Ye.Vector3[1];e.decompose(s,a,o);let l=Ye.Vector3[2],c=Ye.Quaternion[1],f=Ye.Vector3[3];t.decompose(l,c,f);let d=Ye.Vector3[4];b.LerpToRef(s,l,i,d);let u=Ye.Quaternion[2];je.SlerpToRef(a,c,i,u);let h=Ye.Vector3[5];return b.LerpToRef(o,f,i,h),n.ComposeToRef(d,u,h,r),r}static LookAtLH(e,t,i){let r=new n;return n.LookAtLHToRef(e,t,i,r),r}static LookAtLHToRef(e,t,i,r){let s=Ye.Vector3[0],a=Ye.Vector3[1],o=Ye.Vector3[2];t.subtractToRef(e,o),o.normalize(),b.CrossToRef(i,o,s);let l=s.lengthSquared();l===0?s.x=1:s.normalizeFromLength(Math.sqrt(l)),b.CrossToRef(o,s,a),a.normalize();let c=-b.Dot(s,e),f=-b.Dot(a,e),d=-b.Dot(o,e);return n.FromValuesToRef(s._x,a._x,o._x,0,s._y,a._y,o._y,0,s._z,a._z,o._z,0,c,f,d,1,r),r}static LookAtRH(e,t,i){let r=new n;return n.LookAtRHToRef(e,t,i,r),r}static LookAtRHToRef(e,t,i,r){let s=Ye.Vector3[0],a=Ye.Vector3[1],o=Ye.Vector3[2];e.subtractToRef(t,o),o.normalize(),b.CrossToRef(i,o,s);let l=s.lengthSquared();l===0?s.x=1:s.normalizeFromLength(Math.sqrt(l)),b.CrossToRef(o,s,a),a.normalize();let c=-b.Dot(s,e),f=-b.Dot(a,e),d=-b.Dot(o,e);return n.FromValuesToRef(s._x,a._x,o._x,0,s._y,a._y,o._y,0,s._z,a._z,o._z,0,c,f,d,1,r),r}static LookDirectionLH(e,t){let i=new n;return n.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){let r=Ye.Vector3[0];r.copyFrom(e),r.scaleInPlace(-1);let s=Ye.Vector3[1];return b.CrossToRef(t,r,s),n.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){let i=new n;return n.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){let r=Ye.Vector3[2];return b.CrossToRef(t,e,r),n.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,r,s){let a=new n;return n.OrthoLHToRef(e,t,i,r,a,s),a}static OrthoLHToRef(e,t,i,r,s,a){let o=i,l=r,c=2/e,f=2/t,d=2/(l-o),u=-(l+o)/(l-o);return n.FromValuesToRef(c,0,0,0,0,f,0,0,0,0,d,0,0,0,u,1,s),a&&s.multiplyToRef(Vu,s),s._updateIdentityStatus(c===1&&f===1&&d===1&&u===0),s}static OrthoOffCenterLH(e,t,i,r,s,a,o){let l=new n;return n.OrthoOffCenterLHToRef(e,t,i,r,s,a,l,o),l}static OrthoOffCenterLHToRef(e,t,i,r,s,a,o,l){let c=s,f=a,d=2/(t-e),u=2/(r-i),h=2/(f-c),m=-(f+c)/(f-c),g=(e+t)/(e-t),p=(r+i)/(i-r);return n.FromValuesToRef(d,0,0,0,0,u,0,0,0,0,h,0,g,p,m,1,o),l&&o.multiplyToRef(Vu,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,r,s,a,o,l,c,f,d){let u=-o*Math.cos(l),h=-o*Math.sin(l);return n.TranslationToRef(0,0,-c,Ye.Matrix[1]),n.FromValuesToRef(1,0,0,0,0,1,0,0,u,h,1,0,0,0,0,1,Ye.Matrix[0]),Ye.Matrix[1].multiplyToRef(Ye.Matrix[0],Ye.Matrix[0]),n.TranslationToRef(0,0,c,Ye.Matrix[1]),Ye.Matrix[0].multiplyToRef(Ye.Matrix[1],Ye.Matrix[0]),n.OrthoOffCenterLHToRef(e,t,i,r,s,a,f,d),Ye.Matrix[0].multiplyToRef(f,f),f}static OrthoOffCenterRH(e,t,i,r,s,a,o){let l=new n;return n.OrthoOffCenterRHToRef(e,t,i,r,s,a,l,o),l}static OrthoOffCenterRHToRef(e,t,i,r,s,a,o,l){return n.OrthoOffCenterLHToRef(e,t,i,r,s,a,o,l),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,r,s,a,o,l,c,f,d){let u=o*Math.cos(l),h=o*Math.sin(l);return n.TranslationToRef(0,0,c,Ye.Matrix[1]),n.FromValuesToRef(1,0,0,0,0,1,0,0,u,h,1,0,0,0,0,1,Ye.Matrix[0]),Ye.Matrix[1].multiplyToRef(Ye.Matrix[0],Ye.Matrix[0]),n.TranslationToRef(0,0,-c,Ye.Matrix[1]),Ye.Matrix[0].multiplyToRef(Ye.Matrix[1],Ye.Matrix[0]),n.OrthoOffCenterRHToRef(e,t,i,r,s,a,f,d),Ye.Matrix[0].multiplyToRef(f,f),f}static PerspectiveLH(e,t,i,r,s,a=0){let o=new n,l=i,c=r,f=2*l/e,d=2*l/t,u=(c+l)/(c-l),h=-2*c*l/(c-l),m=Math.tan(a);return n.FromValuesToRef(f,0,0,0,0,d,0,m,0,0,u,1,0,0,h,0,o),s&&o.multiplyToRef(Vu,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,r,s,a=0,o=!1){let l=new n;return n.PerspectiveFovLHToRef(e,t,i,r,l,!0,s,a,o),l}static PerspectiveFovLHToRef(e,t,i,r,s,a=!0,o,l=0,c=!1){let f=i,d=r,u=1/Math.tan(e*.5),h=a?u/t:u,m=a?u:u*t,g=c&&f===0?-1:d!==0?(d+f)/(d-f):1,p=c&&f===0?2*d:d!==0?-2*d*f/(d-f):-2*f,_=Math.tan(l);return n.FromValuesToRef(h,0,0,0,0,m,0,_,0,0,g,1,0,0,p,0,s),o&&s.multiplyToRef(Vu,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(e,t,i,r,s,a=!0,o,l=0){let c=1/Math.tan(e*.5),f=a?c/t:c,d=a?c:c*t,u=Math.tan(l);return n.FromValuesToRef(f,0,0,0,0,d,0,u,0,0,-i,1,0,0,1,0,s),o&&s.multiplyToRef(Vu,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(e,t,i,r,s,a=0,o=!1){let l=new n;return n.PerspectiveFovRHToRef(e,t,i,r,l,!0,s,a,o),l}static PerspectiveFovRHToRef(e,t,i,r,s,a=!0,o,l=0,c=!1){let f=i,d=r,u=1/Math.tan(e*.5),h=a?u/t:u,m=a?u:u*t,g=c&&f===0?1:d!==0?-(d+f)/(d-f):-1,p=c&&f===0?2*d:d!==0?-2*d*f/(d-f):-2*f,_=Math.tan(l);return n.FromValuesToRef(h,0,0,0,0,m,0,_,0,0,g,-1,0,0,p,0,s),o&&s.multiplyToRef(Vu,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(e,t,i,r,s,a=!0,o,l=0){let c=1/Math.tan(e*.5),f=a?c/t:c,d=a?c:c*t,u=Math.tan(l);return n.FromValuesToRef(f,0,0,0,0,d,0,u,0,0,-i,-1,0,0,-1,0,s),o&&s.multiplyToRef(Vu,s),s._updateIdentityStatus(!1),s}static GetFinalMatrix(e,t,i,r,s,a){let o=e.width,l=e.height,c=e.x,f=e.y,d=n.FromValues(o/2,0,0,0,0,-l/2,0,0,0,0,a-s,0,c+o/2,l/2+f,s,1),u=new n;return t.multiplyToRef(i,u),u.multiplyToRef(r,u),u.multiplyToRef(d,u)}static GetAsMatrix2x2(e){let t=e.m,i=[t[0],t[1],t[4],t[5]];return ys.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){let t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return ys.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){let t=new n;return n.TransposeToRef(e,t),t}static TransposeToRef(e,t){let i=e.m,r=i[0],s=i[4],a=i[8],o=i[12],l=i[1],c=i[5],f=i[9],d=i[13],u=i[2],h=i[6],m=i[10],g=i[14],p=i[3],_=i[7],v=i[11],E=i[15],S=t._m;return S[0]=r,S[1]=s,S[2]=a,S[3]=o,S[4]=l,S[5]=c,S[6]=f,S[7]=d,S[8]=u,S[9]=h,S[10]=m,S[11]=g,S[12]=p,S[13]=_,S[14]=v,S[15]=E,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){let t=new n;return n.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();let i=e.normal.x,r=e.normal.y,s=e.normal.z,a=-2*i,o=-2*r,l=-2*s;return n.FromValuesToRef(a*i+1,o*i,l*i,0,a*r,o*r+1,l*r,0,a*s,o*s,l*s+1,0,a*e.d,o*e.d,l*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,r){return n.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static FromQuaternionToRef(e,t){let i=e._x*e._x,r=e._y*e._y,s=e._z*e._z,a=e._x*e._y,o=e._z*e._w,l=e._z*e._x,c=e._y*e._w,f=e._y*e._z,d=e._x*e._w;return t._m[0]=1-2*(r+s),t._m[1]=2*(a+o),t._m[2]=2*(l-c),t._m[3]=0,t._m[4]=2*(a-o),t._m[5]=1-2*(s+i),t._m[6]=2*(f+d),t._m[7]=0,t._m[8]=2*(l+c),t._m[9]=2*(f-d),t._m[10]=1-2*(r+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}};Q._IdentityReadOnly=Q.Identity();Object.defineProperties(Q.prototype,{dimension:{value:[4,4]},rank:{value:2}});Ye=class{};Ye.Vector3=Rc(11,b.Zero);Ye.Matrix=Rc(2,Q.Identity);Ye.Quaternion=Rc(3,je.Zero);ee=class{};ee.Vector2=Rc(3,Fe.Zero);ee.Vector3=Rc(13,b.Zero);ee.Vector4=Rc(3,Vi.Zero);ee.Quaternion=Rc(3,je.Zero);ee.Matrix=Rc(8,Q.Identity);zt("BABYLON.Vector2",Fe);zt("BABYLON.Vector3",b);zt("BABYLON.Vector4",Vi);zt("BABYLON.Matrix",Q);Vu=Q.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1)});var tk,ta,ik,sp=y(()=>{He();(function(n){n[n.LOCAL=0]="LOCAL",n[n.WORLD=1]="WORLD",n[n.BONE=2]="BONE"})(tk||(tk={}));ta=class{};ta.X=new b(1,0,0);ta.Y=new b(0,1,0);ta.Z=new b(0,0,1);(function(n){n[n.X=0]="X",n[n.Y=1]="Y",n[n.Z=2]="Z"})(ik||(ik={}))});function ap(n){return Math.pow(n,rp)}function op(n){return n<=.04045?.0773993808*n:Math.pow(.947867299*(n+.055),2.4)}function lp(n){return Math.pow(n,jG)}function cp(n){return n<=.0031308?12.92*n:1.055*Math.pow(n,.41666)-.055}var he,ht,Gn,$t=y(()=>{Ol();ir();es();ts();he=class n{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return n.FromArrayToRef(e,t,this),this}toColor4(e=1){return new ht(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return this.r*.3+this.g*.59+this.b*.11}multiply(e){return new n(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new n(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=Vt){return Ci(this.r,e.r,t)&&Ci(this.g,e.g,t)&&Ci(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new n(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=Gt(this.r,e,t),i.g=Gt(this.g,e,t),i.b=Gt(this.b,e,t),i}add(e){return new n(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new n(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new n(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r}clone(){return new n(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){let e=Math.round(this.r*255),t=Math.round(this.g*255),i=Math.round(this.b*255);return"#"+Vo(e)+Vo(t)+Vo(i)}fromHexString(e){return e.substring(0,1)!=="#"||e.length!==7?this:(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255,this)}toHSV(){return this.toHSVToRef(new n)}toHSVToRef(e){let t=this.r,i=this.g,r=this.b,s=Math.max(t,i,r),a=Math.min(t,i,r),o=0,l=0,c=s,f=s-a;return s!==0&&(l=f/s),s!=a&&(s==t?(o=(i-r)/f,i<r&&(o+=6)):s==i?o=(r-t)/f+2:s==r&&(o=(t-i)/f+4),o*=60),e.r=o,e.g=l,e.b=c,e}toLinearSpace(e=!1){let t=new n;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=op(this.r),e.g=op(this.g),e.b=op(this.b)):(e.r=ap(this.r),e.g=ap(this.g),e.b=ap(this.b)),this}toGammaSpace(e=!1){let t=new n;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=cp(this.r),e.g=cp(this.g),e.b=cp(this.b)):(e.r=lp(this.r),e.g=lp(this.g),e.b=lp(this.b)),this}static HSVtoRGBToRef(e,t,i,r){let s=i*t,a=e/60,o=s*(1-Math.abs(a%2-1)),l=0,c=0,f=0;a>=0&&a<=1?(l=s,c=o):a>=1&&a<=2?(l=o,c=s):a>=2&&a<=3?(c=s,f=o):a>=3&&a<=4?(c=o,f=s):a>=4&&a<=5?(l=o,f=s):a>=5&&a<=6&&(l=s,f=o);let d=i-s;return r.r=l+d,r.g=c+d,r.b=f+d,r}static FromHSV(e,t,i){let r=new n(0,0,0);return n.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){return new n(0,0,0).fromHexString(e)}static FromArray(e,t=0){return new n(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new n(e/255,t/255,i/255)}static Lerp(e,t,i){let r=new n(0,0,0);return n.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,s){let a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,f=o-2*a+s,d=o-a,u=e.r*l+i.r*c+t.r*f+r.r*d,h=e.g*l+i.g*c+t.g*f+r.g*d,m=e.b*l+i.b*c+t.b*f+r.b*d;return new n(u,h,m)}static Hermite1stDerivative(e,t,i,r,s){let a=n.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let o=s*s;a.r=(o-s)*6*e.r+(3*o-4*s+1)*t.r+(-o+s)*6*i.r+(3*o-2*s)*r.r,a.g=(o-s)*6*e.g+(3*o-4*s+1)*t.g+(-o+s)*6*i.g+(3*o-2*s)*r.g,a.b=(o-s)*6*e.b+(3*o-4*s+1)*t.b+(-o+s)*6*i.b+(3*o-2*s)*r.b}static Red(){return new n(1,0,0)}static Green(){return new n(0,1,0)}static Blue(){return new n(0,0,1)}static Black(){return new n(0,0,0)}static get BlackReadOnly(){return n._BlackReadOnly}static White(){return new n(1,1,1)}static Purple(){return new n(.5,0,.5)}static Magenta(){return new n(1,0,1)}static Yellow(){return new n(1,1,0)}static Gray(){return new n(.5,.5,.5)}static Teal(){return new n(0,1,1)}static Random(){return new n(Math.random(),Math.random(),Math.random())}};he._V8PerformanceHack=new he(.5,.5,.5);he._BlackReadOnly=he.Black();Object.defineProperties(he.prototype,{dimension:{value:[3]},rank:{value:1}});ht=class n{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new n(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,r){return this.r+=e,this.g+=t,this.b+=i,this.a+=r,this}subtract(e){return new n(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,r){return new n(this.r-e,this.g-t,this.b-i,this.a-r)}subtractFromFloatsToRef(e,t,i,r,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s.a=this.a-r,s}scale(e){return new n(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=Gt(this.r,e,t),i.g=Gt(this.g,e,t),i.b=Gt(this.b,e,t),i.a=Gt(this.a,e,t),i}multiply(e){return new n(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,r){return new n(this.r*e,this.g*t,this.b*i,this.a*r)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,r){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(r,this.a),this}maximizeInPlaceFromFloats(e,t,i,r){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(r,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=Vt){return Ci(this.r,e.r,t)&&Ci(this.g,e.g,t)&&Ci(this.b,e.b,t)&&Ci(this.a,e.a,t)}equalsToFloats(e,t,i,r){return this.r===e&&this.g===t&&this.b===i&&this.a===r}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e=e*397^(this.a*255|0),e}clone(){return new n().copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){let t=Math.round(this.r*255),i=Math.round(this.g*255),r=Math.round(this.b*255);if(e)return"#"+Vo(t)+Vo(i)+Vo(r);let s=Math.round(this.a*255);return"#"+Vo(t)+Vo(i)+Vo(r)+Vo(s)}fromHexString(e){return e.substring(0,1)!=="#"||e.length!==9&&e.length!==7?this:(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255,e.length===9&&(this.a=parseInt(e.substring(7,9),16)/255),this)}toLinearSpace(e=!1){let t=new n;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=op(this.r),e.g=op(this.g),e.b=op(this.b)):(e.r=ap(this.r),e.g=ap(this.g),e.b=ap(this.b)),e.a=this.a,this}toGammaSpace(e=!1){let t=new n;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=cp(this.r),e.g=cp(this.g),e.b=cp(this.b)):(e.r=lp(this.r),e.g=lp(this.g),e.b=lp(this.b)),e.a=this.a,this}static FromHexString(e){return e.substring(0,1)!=="#"||e.length!==9&&e.length!==7?new n(0,0,0,0):new n(0,0,0,1).fromHexString(e)}static Lerp(e,t,i){return n.LerpToRef(e,t,i,new n)}static LerpToRef(e,t,i,r){return r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i,r}static Hermite(e,t,i,r,s){let a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,f=o-2*a+s,d=o-a,u=e.r*l+i.r*c+t.r*f+r.r*d,h=e.g*l+i.g*c+t.g*f+r.g*d,m=e.b*l+i.b*c+t.b*f+r.b*d,g=e.a*l+i.a*c+t.a*f+r.a*d;return new n(u,h,m,g)}static Hermite1stDerivative(e,t,i,r,s){let a=new n;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let o=s*s;a.r=(o-s)*6*e.r+(3*o-4*s+1)*t.r+(-o+s)*6*i.r+(3*o-2*s)*r.r,a.g=(o-s)*6*e.g+(3*o-4*s+1)*t.g+(-o+s)*6*i.g+(3*o-2*s)*r.g,a.b=(o-s)*6*e.b+(3*o-4*s+1)*t.b+(-o+s)*6*i.b+(3*o-2*s)*r.b,a.a=(o-s)*6*e.a+(3*o-4*s+1)*t.a+(-o+s)*6*i.a+(3*o-2*s)*r.a}static FromColor3(e,t=1){return new n(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new n(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new n(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===t*3){let i=[];for(let r=0;r<e.length;r+=3){let s=r/3*4;i[s]=e[r],i[s+1]=e[r+1],i[s+2]=e[r+2],i[s+3]=1}return i}return e}};ht._V8PerformanceHack=new ht(.5,.5,.5,.5);Object.defineProperties(ht.prototype,{dimension:{value:[4]},rank:{value:1}});Gn=class{};Gn.Color3=yn(3,he.Black);Gn.Color4=yn(3,()=>new ht(0,0,0,0));zt("BABYLON.Color3",he);zt("BABYLON.Color4",ht)});var Da,Gu=y(()=>{He();Da=class n{constructor(e,t,i,r){this.normal=new b(e,t,i),this.d=r}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new n(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=e*397^(this.d|0),e}normalize(){let e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),t=0;return e!==0&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){let t=n._TmpMatrix;e.invertToRef(t);let i=t.m,r=this.normal.x,s=this.normal.y,a=this.normal.z,o=this.d,l=r*i[0]+s*i[1]+a*i[2]+o*i[3],c=r*i[4]+s*i[5]+a*i[6]+o*i[7],f=r*i[8]+s*i[9]+a*i[10]+o*i[11],d=r*i[12]+s*i[13]+a*i[14]+o*i[15];return new n(l,c,f,d)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){let r=t.x-e.x,s=t.y-e.y,a=t.z-e.z,o=i.x-e.x,l=i.y-e.y,c=i.z-e.z,f=s*c-a*l,d=a*o-r*c,u=r*l-s*o,h=Math.sqrt(f*f+d*d+u*u),m;return h!==0?m=1/h:m=0,this.normal.x=f*m,this.normal.y=d*m,this.normal.z=u*m,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return b.Dot(this.normal,e)<=t}signedDistanceTo(e){return b.Dot(e,this.normal)+this.d}static FromArray(e){return new n(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){let r=new n(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){let i=new n(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){let r=-(t.x*e.x+t.y*e.y+t.z*e.z);return b.Dot(i,t)+r}};Da._TmpMatrix=Q.Identity()});var qf,pR=y(()=>{Gu();qf=class n{static GetPlanes(e){let t=[];for(let i=0;i<6;i++)t.push(new Da(0,0,0,0));return n.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){n.GetNearPlaneToRef(e,t[0]),n.GetFarPlaneToRef(e,t[1]),n.GetLeftPlaneToRef(e,t[2]),n.GetRightPlaneToRef(e,t[3]),n.GetTopPlaneToRef(e,t[4]),n.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}});var rk,fp,dL,dp,ku,zu=y(()=>{ts();He();es();(function(n){n[n.CW=0]="CW",n[n.CCW=1]="CCW"})(rk||(rk={}));fp=class n{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return this._radians*180/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){let i=t.subtract(e),r=Math.atan2(i.y,i.x);return new n(r)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(i===0)return new n(Math.PI/2);i=Math.sqrt(i);let r=e.dot(t)/i;r=Gt(r,-1,1);let s=Math.acos(r);return new n(s)}static FromRadians(e){return new n(e)}static FromDegrees(e){return new n(e*Math.PI/180)}},dL=class{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;let r=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,a=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,o=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new Fe((s*(t.y-i.y)-a*(e.y-t.y))/o,((e.x-t.x)*a-(t.x-i.x)*s)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=fp.BetweenTwoPoints(this.centerPoint,this.startPoint);let l=this.startAngle.degrees(),c=fp.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),f=fp.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();c-l>180&&(c-=360),c-l<-180&&(c+=360),f-c>180&&(f-=360),f-c<-180&&(f+=360),this.orientation=c-l<0?0:1,this.angle=fp.FromDegrees(this.orientation===0?l-f:f-l)}},dp=class n{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new Fe(e,t))}addLineTo(e,t){if(this.closed)return this;let i=new Fe(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,s=36){if(this.closed)return this;let a=this._points[this._points.length-1],o=new Fe(e,t),l=new Fe(i,r),c=new dL(a,o,l),f=c.angle.radians()/s;c.orientation===0&&(f*=-1);let d=c.startAngle.radians()+f;for(let u=0;u<s;u++){let h=Math.cos(d)*c.radius+c.centerPoint.x,m=Math.sin(d)*c.radius+c.centerPoint.y;this.addLineTo(h,m),d+=f}return this}addQuadraticCurveTo(e,t,i,r,s=36){if(this.closed)return this;let a=(l,c,f,d)=>(1-l)*(1-l)*c+2*l*(1-l)*f+l*l*d,o=this._points[this._points.length-1];for(let l=0;l<=s;l++){let c=l/s,f=a(c,o.x,e,i),d=a(c,o.y,t,r);this.addLineTo(f,d)}return this}addBezierCurveTo(e,t,i,r,s,a,o=36){if(this.closed)return this;let l=(f,d,u,h,m)=>(1-f)*(1-f)*(1-f)*d+3*f*(1-f)*(1-f)*u+3*f*f*(1-f)*h+f*f*f*m,c=this._points[this._points.length-1];for(let f=0;f<=o;f++){let d=f/o,u=l(d,c.x,e,i,s),h=l(d,c.y,t,r,a);this.addLineTo(u,h)}return this}isPointInside(e){let t=!1,i=this._points.length;for(let r=i-1,s=0;s<i;r=s++){let a=this._points[r],o=this._points[s],l=o.x-a.x,c=o.y-a.y;if(Math.abs(c)>Number.EPSILON){if(c<0&&(a=this._points[s],l=-l,o=this._points[r],c=-c),e.y<a.y||e.y>o.y)continue;if(e.y===a.y&&e.x===a.x)return!0;{let f=c*(e.x-a.x)-l*(e.y-a.y);if(f===0)return!0;if(f<0)continue;t=!t}}else{if(e.y!==a.y)continue;if(o.x<=e.x&&e.x<=a.x||a.x<=e.x&&e.x<=o.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){let t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){let e=this._points.length,t=0;for(let i=e-1,r=0;r<e;i=r++)t+=this._points[i].x*this._points[r].y-this._points[r].x*this._points[i].y;return t*.5}getPoints(){return this._points}getPointAtLengthPosition(e){if(e<0||e>1)return Fe.Zero();let t=e*this.length(),i=0;for(let r=0;r<this._points.length;r++){let s=(r+1)%this._points.length,a=this._points[r],l=this._points[s].subtract(a),c=l.length()+i;if(t>=i&&t<=c){let f=l.normalize(),d=t-i;return new Fe(a.x+f.x*d,a.y+f.y*d)}i=c}return Fe.Zero()}static StartingAt(e,t){return new n(e,t)}},ku=class n{constructor(e,t=null,i,r=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:b.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:Q.Identity()};for(let s=0;s<e.length;s++)this._curve[s]=e[s].clone();this._raw=i||!1,this._alignTangentsWithPath=r,this._compute(t,r)}getCurve(){return this._curve}getPoints(){return this._curve}length(){return this._distances[this._distances.length-1]}getTangents(){return this._tangents}getNormals(){return this._normals}getBinormals(){return this._binormals}getDistances(){return this._distances}getPointAt(e){return this._updatePointAtData(e).point}getTangentAt(e,t=!1){return this._updatePointAtData(e,t),t?b.TransformCoordinates(b.Forward(),this._pointAtData.interpolationMatrix):this._tangents[this._pointAtData.previousPointArrayIndex]}getNormalAt(e,t=!1){return this._updatePointAtData(e,t),t?b.TransformCoordinates(b.Right(),this._pointAtData.interpolationMatrix):this._normals[this._pointAtData.previousPointArrayIndex]}getBinormalAt(e,t=!1){return this._updatePointAtData(e,t),t?b.TransformCoordinates(b.UpReadOnly,this._pointAtData.interpolationMatrix):this._binormals[this._pointAtData.previousPointArrayIndex]}getDistanceAt(e){return this.length()*e}getPreviousPointIndexAt(e){return this._updatePointAtData(e),this._pointAtData.previousPointArrayIndex}getSubPositionAt(e){return this._updatePointAtData(e),this._pointAtData.subPosition}getClosestPositionTo(e){let t=Number.MAX_VALUE,i=0;for(let r=0;r<this._curve.length-1;r++){let s=this._curve[r+0],a=this._curve[r+1].subtract(s).normalize(),o=this._distances[r+1]-this._distances[r+0],l=Math.min(Math.max(b.Dot(a,e.subtract(s).normalize()),0)*b.Distance(s,e)/o,1),c=b.Distance(s.add(a.scale(l*o)),e);c<t&&(t=c,i=(this._distances[r+0]+o*l)/this.length())}return i}slice(e=0,t=1){if(e<0&&(e=1-e*-1%1),t<0&&(t=1-t*-1%1),e>t){let c=e;e=t,t=c}let i=this.getCurve(),r=this.getPointAt(e),s=this.getPreviousPointIndexAt(e),a=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,l=[];return e!==0&&(s++,l.push(r)),l.push(...i.slice(s,o)),(t!==1||e===1)&&l.push(a),new n(l,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let r=0;r<e.length;r++)this._curve[r].x=e[r].x,this._curve[r].y=e[r].y,this._curve[r].z=e[r].z;return this._compute(t,i),this}_compute(e,t=!1){let i=this._curve.length;if(i<2)return;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();let r=this._tangents[0],s=this._normalVector(r,e);this._normals[0]=s,this._raw||this._normals[0].normalize(),this._binormals[0]=b.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;let a,o,l,c,f;for(let d=1;d<i;d++)a=this._getLastNonNullVector(d),d<i-1&&(o=this._getFirstNonNullVector(d),this._tangents[d]=t?o:a.add(o),this._tangents[d].normalize()),this._distances[d]=this._distances[d-1]+this._curve[d].subtract(this._curve[d-1]).length(),l=this._tangents[d],f=this._binormals[d-1],this._normals[d]=b.Cross(f,l),this._raw||(this._normals[d].length()===0?(c=this._normals[d-1],this._normals[d]=c.clone()):this._normals[d].normalize()),this._binormals[d]=b.Cross(l,this._normals[d]),this._raw||this._binormals[d].normalize();this._pointAtData.id=NaN}_getFirstNonNullVector(e){let t=1,i=this._curve[e+t].subtract(this._curve[e]);for(;i.length()===0&&e+t+1<this._curve.length;)t++,i=this._curve[e+t].subtract(this._curve[e]);return i}_getLastNonNullVector(e){let t=1,i=this._curve[e].subtract(this._curve[e-t]);for(;i.length()===0&&e>t+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,r=e.length();if(r===0&&(r=1),t==null){let s;Ci(Math.abs(e.y)/r,1,Vt)?Ci(Math.abs(e.x)/r,1,Vt)?Ci(Math.abs(e.z)/r,1,Vt)?s=b.Zero():s=new b(0,0,1):s=new b(1,0,0):s=new b(0,-1,0),i=b.Cross(e,s)}else i=b.Cross(e,t),b.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;let i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let r=i[0],s,a=0,o=e*this.length();for(let l=1;l<i.length;l++){s=i[l];let c=b.Distance(r,s);if(a+=c,a===o)return this._setPointAtData(e,1,s,l,t);if(a>o){let d=(a-o)/c,u=r.subtract(s),h=s.add(u.scaleInPlace(d));return this._setPointAtData(e,1-d,h,l-1,t)}r=s}return this._pointAtData}_setPointAtData(e,t,i,r,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=Q.Identity();let e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){let t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),s=this._binormals[e].clone(),a=this._tangents[t].clone(),o=this._normals[t].clone(),l=this._binormals[t].clone(),c=je.RotationQuaternionFromAxis(r,s,i),f=je.RotationQuaternionFromAxis(o,l,a);je.Slerp(c,f,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}});var bc,gR=y(()=>{bc=class n{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=this.width|0;return e=e*397^(this.height|0),e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new n(this.width*e,this.height*t)}clone(){return new n(this.width,this.height)}equals(e){return e?this.width===e.width&&this.height===e.height:!1}get surface(){return this.width*this.height}static Zero(){return new n(0,0)}add(e){return new n(this.width+e.width,this.height+e.height)}subtract(e){return new n(this.width-e.width,this.height-e.height)}scale(e){return new n(this.width*e,this.height*e)}static Lerp(e,t,i){let r=e.width+(t.width-e.width)*i,s=e.height+(t.height-e.height)*i;return new n(r,s)}}});var nk=y(()=>{He()});var Go,up=y(()=>{Go=class n{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new n(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new n(this.x,this.y,this.width,this.height)}}});var sk=y(()=>{sp();$t();es();pR();zu();Gu();gR();He();nk();up()});var Nl,ude,Mc,yc,vv,wl,Ev=y(()=>{He();sk();Nl=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],ude=[()=>1,n=>n.y,n=>n.z,n=>n.x,n=>n.x*n.y,n=>n.y*n.z,n=>3*n.z*n.z-1,n=>n.x*n.z,n=>n.x*n.x-n.y*n.y],Mc=(n,e)=>Nl[n]*ude[n](e),yc=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4],vv=class n{constructor(){this.preScaled=!1,this.l00=b.Zero(),this.l1_1=b.Zero(),this.l10=b.Zero(),this.l11=b.Zero(),this.l2_2=b.Zero(),this.l2_1=b.Zero(),this.l20=b.Zero(),this.l21=b.Zero(),this.l22=b.Zero()}addLight(e,t,i){ee.Vector3[0].set(t.r,t.g,t.b);let r=ee.Vector3[0],s=ee.Vector3[1];r.scaleToRef(i,s),s.scaleToRef(Mc(0,e),ee.Vector3[2]),this.l00.addInPlace(ee.Vector3[2]),s.scaleToRef(Mc(1,e),ee.Vector3[2]),this.l1_1.addInPlace(ee.Vector3[2]),s.scaleToRef(Mc(2,e),ee.Vector3[2]),this.l10.addInPlace(ee.Vector3[2]),s.scaleToRef(Mc(3,e),ee.Vector3[2]),this.l11.addInPlace(ee.Vector3[2]),s.scaleToRef(Mc(4,e),ee.Vector3[2]),this.l2_2.addInPlace(ee.Vector3[2]),s.scaleToRef(Mc(5,e),ee.Vector3[2]),this.l2_1.addInPlace(ee.Vector3[2]),s.scaleToRef(Mc(6,e),ee.Vector3[2]),this.l20.addInPlace(ee.Vector3[2]),s.scaleToRef(Mc(7,e),ee.Vector3[2]),this.l21.addInPlace(ee.Vector3[2]),s.scaleToRef(Mc(8,e),ee.Vector3[2]),this.l22.addInPlace(ee.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(yc[0]),this.l1_1.scaleInPlace(yc[1]),this.l10.scaleInPlace(yc[2]),this.l11.scaleInPlace(yc[3]),this.l2_2.scaleInPlace(yc[4]),this.l2_1.scaleInPlace(yc[5]),this.l20.scaleInPlace(yc[6]),this.l21.scaleInPlace(yc[7]),this.l22.scaleInPlace(yc[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(Nl[0]),this.l1_1.scaleInPlace(Nl[1]),this.l10.scaleInPlace(Nl[2]),this.l11.scaleInPlace(Nl[3]),this.l2_2.scaleInPlace(Nl[4]),this.l2_1.scaleInPlace(Nl[5]),this.l20.scaleInPlace(Nl[6]),this.l21.scaleInPlace(Nl[7]),this.l22.scaleInPlace(Nl[8])}updateFromArray(e){return b.FromArrayToRef(e[0],0,this.l00),b.FromArrayToRef(e[1],0,this.l1_1),b.FromArrayToRef(e[2],0,this.l10),b.FromArrayToRef(e[3],0,this.l11),b.FromArrayToRef(e[4],0,this.l2_2),b.FromArrayToRef(e[5],0,this.l2_1),b.FromArrayToRef(e[6],0,this.l20),b.FromArrayToRef(e[7],0,this.l21),b.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return b.FromFloatsToRef(e[0],e[1],e[2],this.l00),b.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),b.FromFloatsToRef(e[6],e[7],e[8],this.l10),b.FromFloatsToRef(e[9],e[10],e[11],this.l11),b.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),b.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),b.FromFloatsToRef(e[18],e[19],e[20],this.l20),b.FromFloatsToRef(e[21],e[22],e[23],this.l21),b.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new n().updateFromArray(e)}static FromPolynomial(e){let t=new n;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}},wl=class n{constructor(){this.x=b.Zero(),this.y=b.Zero(),this.z=b.Zero(),this.xx=b.Zero(),this.yy=b.Zero(),this.zz=b.Zero(),this.xy=b.Zero(),this.yz=b.Zero(),this.zx=b.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=vv.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){ee.Vector3[0].copyFromFloats(e.r,e.g,e.b);let t=ee.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),ee.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),ee.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(ee.Vector3[0]).addInPlace(ee.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(ee.Vector3[0]).subtractInPlace(ee.Vector3[1]),this.zz.copyFrom(e.l00),ee.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(ee.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return new n().updateFromHarmonics(e)}static FromArray(e){let t=new n;return b.FromArrayToRef(e[0],0,t.x),b.FromArrayToRef(e[1],0,t.y),b.FromArrayToRef(e[2],0,t.z),b.FromArrayToRef(e[3],0,t.xx),b.FromArrayToRef(e[4],0,t.yy),b.FromArrayToRef(e[5],0,t.zz),b.FromArrayToRef(e[6],0,t.yz),b.FromArrayToRef(e[7],0,t.zx),b.FromArrayToRef(e[8],0,t.xy),t}}});function P(n,e,t,i){var r=arguments.length,s=r<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,i);else for(var o=n.length-1;o>=0;o--)(a=n[o])&&(s=(r<3?a(s):r>3?a(e,t,s):a(e,t))||s);return r>3&&s&&Object.defineProperty(e,t,s),s}var jt=y(()=>{});function ak(n){let e=n.getClassName();return vR[e]||(vR[e]={}),vR[e]}function ER(n){let e=n.getClassName();if(_R[e])return _R[e];_R[e]={};let t=_R[e],i=n,r=e;for(;r;){let s=vR[r];for(let l in s)t[l]=s[l];let a,o=!1;do{if(a=Object.getPrototypeOf(i),!a.getClassName){o=!0;break}if(a.getClassName()!==r)break;i=a}while(a);if(o)break;r=a.getClassName(),i=a}return t}var _R,vR,uL=y(()=>{_R={},vR={}});function Qa(n,e){return(t,i)=>{let r=ak(t);r[i]||(r[i]={type:n,sourceName:e})}}function hde(n,e=null){return(t,i)=>{let r=e||"_"+i;Object.defineProperty(t,i,{get:function(){return this[r]},set:function(s){var a;typeof((a=this[r])==null?void 0:a.equals)=="function"&&this[r].equals(s)||this[r]!==s&&(this[r]=s,t[n].apply(this))},enumerable:!0,configurable:!0})}}function le(n,e=null){return hde(n,e)}function F(n){return Qa(0,n)}function Xt(n){return Qa(1,n)}function yr(n){return Qa(2,n)}function hp(n){return Qa(3,n)}function mp(n){return Qa(4,n)}function nn(n){return Qa(5,n)}function SR(n){return Qa(6,n)}function ok(n){return Qa(7,n)}function pp(n){return Qa(8,n)}function lk(n){return Qa(9,n)}function ck(n){return Qa(10,n)}function fk(n){return Qa(11,n)}function ia(n,e,t,i){let r=t.value;t.value=(...s)=>{let a=r;if(typeof _native!="undefined"&&_native[e]){let o=_native[e];i?a=(...l)=>i(...l)?o(...l):r(...l):a=o}return n[e]=a,a(...s)}}function vt(n,e=null){return(t,i)=>{let r=i;Object.defineProperty(t,e||"",{get:function(){return this[r].value},set:function(a){var o,l;typeof((l=(o=this[r])==null?void 0:o.value)==null?void 0:l.equals)=="function"&&this[r].value.equals(a)||this[r].value!==a&&(this[r].value=a,t[n].apply(this))},enumerable:!0,configurable:!0})}}var Yt=y(()=>{uL();ia.filter=function(n){return(e,t,i)=>ia(e,t,i,n)}});function Qf(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}var Sv=y(()=>{});function mde(){return typeof _native!="undefined"&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}var Ur,Wu=y(()=>{Ur=class n{constructor(){this._xhr=mde(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(n.CustomRequestHeaders).length>0||n.CustomRequestModifiers.length>0}static _CleanUrl(e){return e=e.replace("file:http:","http:"),e=e.replace("file:https:","https:"),e}static _ShouldSkipRequestModifications(e){return n.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}static _CollectCustomizations(e,t={}){let i={...t};if(n._ShouldSkipRequestModifications(e))return{url:e,headers:i};for(let s in n.CustomRequestHeaders){let a=n.CustomRequestHeaders[s];a&&(i[s]=a)}let r={setRequestHeader:(s,a)=>{i[s]=a}};for(let s of n.CustomRequestModifiers){if(n._ShouldSkipRequestModifications(e))break;let a=s(r,e);typeof a=="string"&&(e=a)}return{url:e,headers:i}}static async FetchAsync(e,t={}){var r,s,a;let i=(r=t.method)!=null?r:"GET";if(typeof fetch!="undefined"){let{url:o,headers:l}=n._CollectCustomizations(n._CleanUrl(e),(s=t.headers)!=null?s:{});return await fetch(o,{method:i,headers:l,body:(a=t.body)!=null?a:void 0})}return await new Promise((o,l)=>{var f;let c=new n;c.responseType="arraybuffer",c.addEventListener("readystatechange",()=>{if(c.readyState===4)if(c.status>=200&&c.status<300){let d=typeof Headers!="undefined"?new Headers:void 0,u=c.getResponseHeader("Content-Type");u&&d&&d.set("Content-Type",u),o(typeof Response!="undefined"?new Response(c.response,{status:c.status,statusText:c.statusText,headers:d}):{ok:!0,status:c.status,statusText:c.statusText,headers:{get:h=>c.getResponseHeader(h)},arrayBuffer:async()=>await Promise.resolve(c.response)})}else l(new Error(`HTTP ${c.status} loading '${c.requestURL}': ${c.statusText}`))}),c.open(i,e,t.headers),c.send((f=t.body)!=null?f:null)})}get requestURL(){return this._requestURL}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){this._xhr.send(e)}open(e,t,i){let{url:r,headers:s}=n._CollectCustomizations(t,i);this._requestURL=n._CleanUrl(r),this._xhr.open(e,this._requestURL,!0);for(let a in s)this._xhr.setRequestHeader(a,s[a])}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}};Ur.CustomRequestHeaders={};Ur.CustomRequestModifiers=new Array;Ur.SkipRequestModificationForBabylonCDN=!0});var $f,dk=y(()=>{$f=class{};$f.FilesToLoad={}});var TR,uk=y(()=>{TR=class{static ExponentialBackoff(e=3,t=500){return(i,r,s)=>r.status!==0||s>=e||i.indexOf("file:")!==-1?-1:Math.pow(2,s)*t}}});var Ic,$a,ra,Tv=y(()=>{Ic=class extends Error{};Ic._setPrototypeOf=Object.setPrototypeOf||((n,e)=>(n.__proto__=e,n));$a={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002},ra=class n extends Ic{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",Ic._setPrototypeOf(this,n.prototype)}}});function pde(n){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",i,r,s,a,o,l,c,f=0;for(;f<n.length;)i=n[f++],r=f<n.length?n[f++]:Number.NaN,s=f<n.length?n[f++]:Number.NaN,a=i>>2,o=(i&3)<<4|r>>4,l=(r&15)<<2|s>>6,c=s&63,isNaN(r)?l=c=64:isNaN(s)&&(c=64),t+=e.charAt(a)+e.charAt(o)+e.charAt(l)+e.charAt(c);return t}function gde(n){let e=hL(n),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let r=0;r<t;r++)i[r]=e.charCodeAt(r);return i.buffer}var hk,gp,hL,mk,Av=y(()=>{hk=n=>{if(typeof TextDecoder!="undefined")return new TextDecoder().decode(n);let e="";for(let t=0;t<n.byteLength;t++)e+=String.fromCharCode(n[t]);return e};gp=n=>{let e=ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);return typeof e.toBase64=="function"?e.toBase64():pde(e)},hL=n=>atob(n),mk=n=>typeof Uint8Array.fromBase64=="function"?Uint8Array.fromBase64(n).buffer:gde(n)});function _de(n,e,t,i){switch(e){case 5120:{let r=n.getInt8(t);return i&&(r=Math.max(r/127,-1)),r}case 5121:{let r=n.getUint8(t);return i&&(r=r/255),r}case 5122:{let r=n.getInt16(t,!0);return i&&(r=Math.max(r/32767,-1)),r}case 5123:{let r=n.getUint16(t,!0);return i&&(r=r/65535),r}case 5124:return n.getInt32(t,!0);case 5125:return n.getUint32(t,!0);case 5126:return n.getFloat32(t,!0);default:throw new Error(`Invalid component type ${e}`)}}function vde(n,e,t,i,r){switch(e){case 5120:{i&&(r=Math.round(r*127)),n.setInt8(t,r);break}case 5121:{i&&(r=Math.round(r*255)),n.setUint8(t,r);break}case 5122:{i&&(r=Math.round(r*32767)),n.setInt16(t,r,!0);break}case 5123:{i&&(r=Math.round(r*65535)),n.setUint16(t,r,!0);break}case 5124:{n.setInt32(t,r,!0);break}case 5125:{n.setUint32(t,r,!0);break}case 5126:{n.setFloat32(t,r,!0);break}default:throw new Error(`Invalid component type ${e}`)}}function Fl(n){switch(n){case 5120:case 5121:return 1;case 5122:case 5123:return 2;case 5124:case 5125:case 5126:return 4;default:throw new Error(`Invalid type '${n}'`)}}function mL(n){switch(n){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5124:return Int32Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`Invalid component type '${n}'`)}}function Hu(n,e,t,i,r,s,a,o){let l=new Array(i),c=new Array(i);if(n instanceof Array){let f=e/4,d=t/4;for(let u=0;u<s;u+=i){for(let h=0;h<i;h++)l[h]=c[h]=n[f+h];o(c,u);for(let h=0;h<i;h++)l[h]!==c[h]&&(n[f+h]=c[h]);f+=d}}else{let f=ArrayBuffer.isView(n)?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),d=Fl(r);for(let u=0;u<s;u+=i){for(let h=0,m=e;h<i;h++,m+=d)l[h]=c[h]=_de(f,r,m,a);o(c,u);for(let h=0,m=e;h<i;h++,m+=d)l[h]!==c[h]&&vde(f,r,m,a,c[h]);e+=t}}}function pL(n,e,t,i,r,s,a,o){let l=e*Fl(t),c=a*e;if(t!==5126||r!==l){let f=new Float32Array(c);return Hu(n,i,r,e,t,c,s,(d,u)=>{for(let h=0;h<e;h++)f[u+h]=d[h]}),f}if(!(n instanceof Array||n instanceof Float32Array)||i!==0||n.length!==c)if(n instanceof Array){let f=i/4;return n.slice(f,f+c)}else if(ArrayBuffer.isView(n)){let f=n.byteOffset+i;return(f&3)!==0&&(te.Warn("Float array must be aligned to 4-bytes border"),o=!0),o?new Float32Array(n.buffer.slice(f,f+c*Float32Array.BYTES_PER_ELEMENT)):new Float32Array(n.buffer,f,c)}else return new Float32Array(n,i,c);return o?n.slice():n}function pk(n,e,t,i,r,s,a){let o=Fl(t),l=mL(t),c=s*e;if(Array.isArray(n)){if((i&3)!==0||(r&3)!==0)throw new Error("byteOffset and byteStride must be a multiple of 4 for number[] data.");let m=i/4,g=r/4;if(m+(s-1)*g+e>n.length)throw new Error("Last accessed index is out of bounds.");if(g<e)throw new Error("Data stride cannot be smaller than the component size.");if(g!==e){let _=new l(c);return Hu(n,i,r,e,t,c,!1,(v,E)=>{for(let S=0;S<e;S++)_[E+S]=v[S]}),_}return new l(n.slice(m,m+c))}let f,d=i;if(ArrayBuffer.isView(n)?(f=n.buffer,d+=n.byteOffset):f=n,d+(s-1)*r+e*o>f.byteLength)throw new Error("Last accessed byte is out of bounds.");let h=e*o;if(r<h)throw new Error("Byte stride cannot be smaller than the component's byte size.");if(r!==h){let m=new l(c);return Hu(f,d,r,e,t,c,!1,(g,p)=>{for(let _=0;_<e;_++)m[p+_]=g[_]}),m}return o!==1&&(d&o-1)!==0&&(te.Warn("Array must be aligned to border of element size. Data will be copied."),a=!0),a?new l(f.slice(d,d+c*o)):new l(f,d,c)}function gk(n,e,t,i,r,s,a,o){let l=e*Fl(t),c=a*e;if(o.length!==c)throw new Error("Output length is not valid");if(t!==5126||r!==l){Hu(n,i,r,e,t,c,s,(f,d)=>{for(let u=0;u<e;u++)o[d+u]=f[u]});return}if(n instanceof Array){let f=i/4;o.set(n,f)}else if(ArrayBuffer.isView(n)){let f=n.byteOffset+i;if((f&3)!==0){te.Warn("Float array must be aligned to 4-bytes border"),o.set(new Float32Array(n.buffer.slice(f,f+c*Float32Array.BYTES_PER_ELEMENT)));return}let d=new Float32Array(n.buffer,f,c);o.set(d)}else{let f=new Float32Array(n,i,c);o.set(f)}}function AR(n){let e=n.buffer;if(e instanceof ArrayBuffer)return n;let t=new ArrayBuffer(n.byteLength);return new Uint8Array(t).set(new Uint8Array(e,n.byteOffset,n.byteLength)),t}var _p=y(()=>{wt()});function ed(n){return mk(n.split(",")[1])}var vk,vp,xR,gL,Ede,Ji,RR,_k,Ep,Xu,Bl,bR,Ek,Sk,Jf,Tk,Ak,Sde,xv,Tde,Cc=y(()=>{Wu();qa();Si();dk();uk();Tv();Av();eR();Yi();wt();Ll();Zf();Yr();_p();vk=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i),vp=class n extends ra{constructor(e,t){super(e,$a.LoadFileError),this.name="LoadFileError",Ic._setPrototypeOf(this,n.prototype),t instanceof Ur?this.request=t:this.file=t}},xR=class n extends ra{constructor(e,t){super(e,$a.RequestFileError),this.request=t,this.name="RequestFileError",Ic._setPrototypeOf(this,n.prototype)}},gL=class n extends ra{constructor(e,t){super(e,$a.ReadFileError),this.file=t,this.name="ReadFileError",Ic._setPrototypeOf(this,n.prototype)}},Ede=n=>(n=n.replace(/#/gm,"%23"),n),Ji={DefaultRetryStrategy:TR.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:n=>n,ScriptBaseUrl:"",ScriptPreprocessUrl:n=>n,CleanUrl:Ede},RR=(n,e)=>{if(!(n&&n.indexOf("data:")===0)&&Ji.CorsBehavior)if(typeof Ji.CorsBehavior=="string"||Ji.CorsBehavior instanceof String)e.crossOrigin=Ji.CorsBehavior;else{let t=Ji.CorsBehavior(n);t&&(e.crossOrigin=t)}},_k={getRequiredSize:null},Ep=(n,e,t,i,r="",s,a=Oe.LastCreatedEngine)=>{if(typeof HTMLImageElement=="undefined"&&!(a!=null&&a._features.forceBitmapOverHTMLImageElement))return t("LoadImage is only supported in web or BabylonNative environments."),null;let o,l=!1;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))if(typeof Blob!="undefined"&&typeof URL!="undefined"){let T;n instanceof ArrayBuffer?T=n:T=AR(n),o=URL.createObjectURL(new Blob([T],{type:r})),l=!0}else o=`data:${r};base64,`+gp(n);else n instanceof Blob?(o=URL.createObjectURL(n),l=!0):(o=Ji.CleanUrl(n),o=Ji.PreprocessUrl(o));let c=T=>{if(t){let A=o||n.toString();t(`Error while trying to load image: ${A.indexOf("http")===0||A.length<=128?A:A.slice(0,128)+"..."}`,T)}};if(a!=null&&a._features.forceBitmapOverHTMLImageElement)return Bl(o,T=>{a.createImageBitmap(new Blob([T],{type:r}),{premultiplyAlpha:"none",colorSpaceConversion:"none",...s}).then(A=>{e(A),l&&URL.revokeObjectURL(o)}).catch(A=>{t&&t("Error while trying to load image: "+n,A)})},void 0,i||void 0,!0,(T,A)=>{c(A)}),null;let f=new Image;if(_k.getRequiredSize){let T=_k.getRequiredSize(n);T.width&&(f.width=T.width),T.height&&(f.height=T.height)}RR(o,f);let d=[],u=()=>{for(let T of d)T.target.addEventListener(T.name,T.handler)},h=()=>{for(let T of d)T.target.removeEventListener(T.name,T.handler);d.length=0},m=()=>{h(),e(f),l&&f.src&&URL.revokeObjectURL(f.src)},g=T=>{h(),c(T),l&&f.src&&URL.revokeObjectURL(f.src)},p=T=>{if(T.blockedURI!==f.src||T.disposition==="report")return;h();let A=new Error(`CSP violation of policy ${T.effectiveDirective} ${T.blockedURI}. Current policy is ${T.originalPolicy}`);Oe.UseFallbackTexture=!1,c(A),l&&f.src&&URL.revokeObjectURL(f.src),f.src=""};d.push({target:f,name:"load",handler:m}),d.push({target:f,name:"error",handler:g}),d.push({target:document,name:"securitypolicyviolation",handler:p}),u();let _=o.substring(0,5)==="blob:",v=o.substring(0,5)==="data:",E=()=>{_||v||!Ur.IsCustomRequestAvailable?f.src=o:Bl(o,(T,A,R)=>{let M=!r&&R?R:r,I=new Blob([T],{type:M}),C=URL.createObjectURL(I);l=!0,f.src=C},void 0,i||void 0,!0,(T,A)=>{c(A)})},S=()=>{i&&i.loadImage(o,f)};if(!_&&!v&&i&&i.enableTexturesOffline)i.open(S,E);else{if(o.indexOf("file:")!==-1){let T=decodeURIComponent(o.substring(5).toLowerCase());if($f.FilesToLoad[T]&&typeof URL!="undefined"){try{let A;try{A=URL.createObjectURL($f.FilesToLoad[T])}catch(R){A=URL.createObjectURL($f.FilesToLoad[T])}f.src=A,l=!0}catch(A){f.src=""}return f}}E()}return f},Xu=(n,e,t,i,r)=>{let s=new FileReader,a={onCompleteObservable:new re,abort:()=>s.abort()};return s.onloadend=()=>a.onCompleteObservable.notifyObservers(a),r&&(s.onerror=()=>{r(new gL(`Unable to read ${n.name}`,n))}),s.onload=o=>{e(o.target.result)},t&&(s.onprogress=t),i?s.readAsArrayBuffer(n):s.readAsText(n),a},Bl=(n,e,t,i,r,s,a)=>{if(n.name)return Xu(n,e,t,r,s?f=>{s(void 0,f)}:void 0);let o=n;if(o.indexOf("file:")!==-1){let f=decodeURIComponent(o.substring(5).toLowerCase());f.indexOf("./")===0&&(f=f.substring(2));let d=$f.FilesToLoad[f];if(d)return Xu(d,e,t,r,s?u=>s(void 0,new vp(u.message,u.file)):void 0)}let{match:l,type:c}=Tk(o);if(l){let f={onCompleteObservable:new re,abort:()=>()=>{}};try{let d=r?ed(o):Ak(o);e(d,void 0,c)}catch(d){s?s(void 0,d):te.Error(d.message||"Failed to parse the Data URL")}return Fo.SetImmediate(()=>{f.onCompleteObservable.notifyObservers(f)}),f}return bR(o,(f,d)=>{e(f,d==null?void 0:d.responseURL,d==null?void 0:d.getResponseHeader("content-type"))},t,i,r,s?f=>{s(f.request,new vp(f.message,f.request))}:void 0,a)},bR=(n,e,t,i,r,s,a)=>{var d;i!==null&&(i!=null||(i=(d=Oe.LastCreatedScene)==null?void 0:d.offlineProvider)),n=Ji.CleanUrl(n),n=Ji.PreprocessUrl(n);let o=Ji.BaseUrl+n,l=!1,c={onCompleteObservable:new re,abort:()=>l=!0},f=()=>{let u=new Ur,h=null,m,g=()=>{u&&(t&&u.removeEventListener("progress",t),m&&u.removeEventListener("readystatechange",m),u.removeEventListener("loadend",p))},p=()=>{g(),c.onCompleteObservable.notifyObservers(c),c.onCompleteObservable.clear(),t=void 0,m=null,p=null,s=void 0,a=void 0,e=void 0};c.abort=()=>{l=!0,p&&p(),u&&u.readyState!==(XMLHttpRequest.DONE||4)&&u.abort(),h!==null&&(clearTimeout(h),h=null),u=null};let _=E=>{let S=E.message||"Unknown error";s&&u?s(new xR(S,u)):te.Error(S)},v=E=>{if(u){if(u.open("GET",o),a)try{a(u)}catch(S){_(S);return}r&&(u.responseType="arraybuffer"),t&&u.addEventListener("progress",t),p&&u.addEventListener("loadend",p),m=()=>{if(!(l||!u)&&u.readyState===(XMLHttpRequest.DONE||4)){if(m&&u.removeEventListener("readystatechange",m),u.status>=200&&u.status<300||u.status===0&&(!Ar()||Sk())){let A=r?u.response:u.responseText;if(A!==null){try{e&&e(A,u)}catch(R){_(R)}return}}let S=Ji.DefaultRetryStrategy;if(S){let A=S(o,u,E);if(A!==-1){g(),u=new Ur,h=setTimeout(()=>v(E+1),A);return}}let T=new xR("Error status: "+u.status+" "+u.statusText+" - Unable to load "+o,u);s&&s(T)}},u.addEventListener("readystatechange",m),u.send()}};v(0)};if(i&&i.enableSceneOffline&&!n.startsWith("blob:")){let u=m=>{m&&m.status>400?s&&s(m):f()},h=()=>{i&&i.loadFile(Ji.BaseUrl+n,m=>{!l&&e&&e(m),c.onCompleteObservable.notifyObservers(c)},t?m=>{!l&&t&&t(m)}:void 0,u,r)};i.open(h,u)}else f();return c},Ek=n=>{let{match:e,type:t}=Tk(n);if(e)return t||void 0;let i=n.lastIndexOf(".");switch(n.substring(i+1).toLowerCase()){case"glb":return"model/gltf-binary";case"bin":return"application/octet-stream";case"gltf":return"model/gltf+json";case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"ktx":return"image/ktx";case"ktx2":return"image/ktx2";case"avif":return"image/avif";default:return}},Sk=()=>typeof location!="undefined"&&location.protocol==="file:",Jf=n=>vk.test(n),Tk=n=>{let e=vk.exec(n);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace(";base64,","")}};Ak=n=>hL(n.split(",")[1]),Sde=()=>{ye._FileToolsLoadImage=Ep,$m.loadFile=Bl,qP.loadFile=Bl};Sde();Tde=(n,e,t,i,r,s,a,o,l,c)=>{xv={DecodeBase64UrlToBinary:n,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:r,LoadFile:s,LoadImage:a,ReadFile:o,RequestFile:l,SetCorsBehavior:c},Object.defineProperty(xv,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(f){t.DefaultRetryStrategy=f}}),Object.defineProperty(xv,"BaseUrl",{get:function(){return t.BaseUrl},set:function(f){t.BaseUrl=f}}),Object.defineProperty(xv,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(f){t.PreprocessUrl=f}}),Object.defineProperty(xv,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(f){t.CorsBehavior=f}})};Tde(ed,Ak,Ji,Jf,Sk,Bl,Ep,Xu,bR,RR)});var MR,xk=y(()=>{gR();MR=class n{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return this._texture?this._texture.isCube:!1}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return(e==null?void 0:e.shareDepth)!==void 0}constructor(e){var t,i,r;this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=bc.Zero(),this._cachedBaseSize=bc.Zero(),this._initialSamplingMode=2,this._texture=n._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine(),this.wrapU=(t=this._texture._cachedWrapU)!=null?t:this.wrapU,this.wrapV=(i=this._texture._cachedWrapV)!=null?i:this.wrapV,this.wrapR=(r=this._texture._cachedWrapR)!=null?r:this.wrapR)}isReady(){return this.delayLoadState===4?(this.delayLoad(),!1):this._texture?this._texture.isReady:!1}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return!this.isReady()||!this._texture?(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize):this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e,t=!1){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture,this._texture.generateMipMaps&&t)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}});var yR,Rk=y(()=>{yR=class n{static Eval(e,t){return e.match(/\([^()]*\)/g)?e=e.replace(/\([^()]*\)/g,i=>(i=i.slice(1,i.length-1),n._HandleParenthesisContent(i,t))):e=n._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:n.Eval(e,t)}static _HandleParenthesisContent(e,t){t=t||(s=>s==="true");let i,r=e.split("||");for(let s in r)if(Object.prototype.hasOwnProperty.call(r,s)){let a=n._SimplifyNegation(r[s].trim()),o=a.split("&&");if(o.length>1)for(let l=0;l<o.length;++l){let c=n._SimplifyNegation(o[l].trim());if(c!=="true"&&c!=="false"?c[0]==="!"?i=!t(c.substring(1)):i=t(c):i=c==="true",!i){a="false";break}}if(i||a==="true"){i=!0;break}a!=="true"&&a!=="false"?a[0]==="!"?i=!t(a.substring(1)):i=t(a):i=a==="true"}return i?"true":"false"}static _SimplifyNegation(e){return e=e.replace(/^[\s!]+/,t=>(t=t.replace(/[\s]/g,()=>""),t.length%2?"!":"")),e=e.trim(),e==="!true"?e="false":e==="!false"&&(e="true"),e}}});var ni,td=y(()=>{Rk();ni=class n{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>n.HasTags(e),e.addTags=t=>n.AddTagsTo(e,t),e.removeTags=t=>n.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>n.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;let t=e._tags;for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){let i=[];for(let r in e._tags)Object.prototype.hasOwnProperty.call(e._tags,r)&&e._tags[r]===!0&&i.push(r);return i.join(" ")}else return e._tags}static AddTagsTo(e,t){if(!t||typeof t!="string")return;let i=t.split(" ");for(let r of i)n._AddTagTo(e,r)}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(n.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!n.HasTags(e))return;let i=t.split(" ");for(let r in i)n._RemoveTagFrom(e,i[r])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?n.HasTags(e):yR.Eval(t,i=>n.HasTags(e)&&e._tags[i])}}});var bk,at,Or=y(()=>{Mn();td();$t();He();uL();bk=function(n,e,t,i={}){let r=n();ni&&ni.HasTags(e)&&ni.AddTagsTo(r,ni.GetTags(e,!0));let s=ER(r),a={};for(let o in s){let l=s[o],c=e[o],f=l.type;if(c!=null&&(o!=="uniqueId"||at.AllowLoadingUniqueId))switch(f){case 0:case 6:case 9:case 11:typeof c.slice=="function"?r[o]=c.slice():r[o]=c;break;case 1:i.cloneTexturesOnlyOnce&&a[c.uniqueId]?r[o]=a[c.uniqueId]:(r[o]=t||c.isRenderTarget?c:c.clone(),a[c.uniqueId]=r[o]);break;case 2:case 3:case 4:case 5:case 7:case 8:case 10:case 12:r[o]=t?c:c.clone();break}}return r},at=class n{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i<e.animations.length;i++){let r=e.animations[i];t.animations.push(r.serialize())}}}static Serialize(e,t){t||(t={}),ni&&(t.tags=ni.GetTags(e));let i=ER(e);for(let r in i){let s=i[r],a=s.sourceName||r,o=s.type,l=e[r];if(l!=null&&(r!=="uniqueId"||n.AllowLoadingUniqueId))switch(o){case 0:Array.isArray(l)?t[a]=l.slice():t[a]=l;break;case 1:t[a]=l.serialize();break;case 2:t[a]=l.asArray();break;case 3:t[a]=l.serialize();break;case 4:t[a]=l.asArray();break;case 5:t[a]=l.asArray();break;case 6:t[a]=l.id;break;case 7:t[a]=l.serialize();break;case 8:t[a]=l.asArray();break;case 9:t[a]=l.serialize();break;case 10:t[a]=l.asArray();break;case 11:t[a]=l.id;break;case 12:t[a]=l.asArray();break}}return t}static ParseProperties(e,t,i,r){r||(r="");let s=ER(t);for(let a in s){let o=s[a],l=e[o.sourceName||a],c=o.type;if(l!=null&&(a!=="uniqueId"||n.AllowLoadingUniqueId)){let f=t;switch(c){case 0:f[a]=l;break;case 1:i&&(f[a]=n._TextureParser(l,i,r));break;case 2:f[a]=he.FromArray(l);break;case 3:f[a]=n._FresnelParametersParser(l);break;case 4:f[a]=Fe.FromArray(l);break;case 5:f[a]=b.FromArray(l);break;case 6:i&&(f[a]=i.getLastMeshById(l));break;case 7:f[a]=n._ColorCurvesParser(l);break;case 8:f[a]=ht.FromArray(l);break;case 9:f[a]=n._ImageProcessingConfigurationParser(l);break;case 10:f[a]=je.FromArray(l);break;case 11:i&&(f[a]=i.getCameraById(l));break;case 12:f[a]=Q.FromArray(l);break}}}}static Parse(e,t,i,r=null){let s=e();return ni&&ni.AddTagsTo(s,t.tags),n.ParseProperties(t,s,i,r),s}static Clone(e,t,i={}){return bk(e,t,!1,i)}static Instanciate(e,t){return bk(e,t,!0)}};at.AllowLoadingUniqueId=!1;at._ImageProcessingConfigurationParser=n=>{throw $e("ImageProcessingConfiguration")};at._FresnelParametersParser=n=>{throw $e("FresnelParameters")};at._ColorCurvesParser=n=>{throw $e("ColorCurves")};at._TextureParser=(n,e,t)=>{throw $e("Texture")}});var Ri,Rv=y(()=>{jt();Yt();Si();He();Yi();Sv();Cc();xk();Or();Ri=class n extends MR{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){if(this._texture)this._texture._gammaSpace===null&&(this._texture._gammaSpace=this._gammaSpace);else return this._gammaSpace;return this._texture._gammaSpace&&!this._texture._useSRGBBuffer}set gammaSpace(e){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this))}get isRGBD(){return this._texture!=null&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return this._texture?this._texture._linearSpecularLOD:!1}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=Qf()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=n.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this._dominantDirection=null,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new re,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?n._IsScene(e)?this._scene=e:this._engine=e:this._scene=Oe.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return Q.IdentityReadOnly}getReflectionTextureMatrix(){return Q.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,s,a){let o=this._getEngine();if(!o)return null;let l=o._getUseSRGBBuffer(!!s,t),c=o.getLoadedTexturesCache();for(let f=0;f<c.length;f++){let d=c[f];if((s===void 0||l===d._useSRGBBuffer)&&(r===void 0||r===d.invertY)&&d.url===e&&d.generateMipMaps===!t&&(!i||i===d.samplingMode)&&(a===void 0||a===d.isCube))return d.incrementReferences(),d}return null}_rebuild(e=!1){}clone(){return null}get textureType(){return this._texture&&this._texture.type!==void 0?this._texture.type:0}get textureFormat(){return this._texture&&this._texture.format!==void 0?this._texture.format:5}_markAllSubMeshesAsTexturesDirty(){let e=this.getScene();e&&e.markAllMaterialsAsDirty(1)}readPixels(e=0,t=0,i=null,r=!0,s=!1,a=0,o=0,l=Number.MAX_VALUE,c=Number.MAX_VALUE){if(!this._texture)return null;let f=this._getEngine();if(!f)return null;let d=this.getSize(),u=d.width,h=d.height;t!==0&&(u=u/Math.pow(2,t),h=h/Math.pow(2,t),u=Math.round(u),h=Math.round(h)),l=Math.min(u,l),c=Math.min(h,c);try{return this._texture.isCube||this._texture.is2DArray?f._readTexturePixels(this._texture,l,c,e,t,i,r,s,a,o):f._readTexturePixels(this._texture,l,c,-1,t,i,r,s,a,o)}catch(m){return null}}_readPixelsSync(e=0,t=0,i=null,r=!0,s=!1){if(!this._texture)return null;let a=this.getSize(),o=a.width,l=a.height,c=this._getEngine();if(!c)return null;t!=0&&(o=o/Math.pow(2,t),l=l/Math.pow(2,t),o=Math.round(o),l=Math.round(l));try{return this._texture.isCube?c._readTexturePixelsSync(this._texture,o,l,e,t,i,r,s):c._readTexturePixelsSync(this._texture,o,l,-1,t,i,r,s)}catch(f){return null}}get _lodTextureHigh(){return this._texture?this._texture._lodTextureHigh:null}get _lodTextureMid(){return this._texture?this._texture._lodTextureMid:null}get _lodTextureLow(){return this._texture?this._texture._lodTextureLow:null}dispose(){if(this._scene){this._scene.stopAnimation&&this._scene.stopAnimation(this),this._scene.removePendingData(this);let e=this._scene.textures.indexOf(this);if(e>=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){let t=this._parentContainer.textures.indexOf(this);t>-1&&this._parentContainer.textures.splice(t,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;let t=at.Serialize(this);return at.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(i===0){t();return}for(let r=0;r<e.length;r++){let s=e[r];if(s.isReady())--i===0&&t();else{let a=s.onLoadObservable;a?a.addOnce(()=>{--i===0&&t()}):--i===0&&t()}}}static _IsScene(e){return e.getClassName()==="Scene"}};Ri.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;P([F()],Ri.prototype,"uniqueId",void 0);P([F()],Ri.prototype,"name",void 0);P([F()],Ri.prototype,"displayName",void 0);P([F()],Ri.prototype,"metadata",void 0);P([F("hasAlpha")],Ri.prototype,"_hasAlpha",void 0);P([F("getAlphaFromRGB")],Ri.prototype,"_getAlphaFromRGB",void 0);P([F()],Ri.prototype,"level",void 0);P([F("coordinatesIndex")],Ri.prototype,"_coordinatesIndex",void 0);P([F()],Ri.prototype,"optimizeUVAllocation",void 0);P([F("coordinatesMode")],Ri.prototype,"_coordinatesMode",void 0);P([F()],Ri.prototype,"wrapU",null);P([F()],Ri.prototype,"wrapV",null);P([F()],Ri.prototype,"wrapR",void 0);P([F()],Ri.prototype,"anisotropicFilteringLevel",void 0);P([F()],Ri.prototype,"isCube",null);P([F()],Ri.prototype,"is3D",null);P([F()],Ri.prototype,"is2DArray",null);P([F()],Ri.prototype,"gammaSpace",null);P([F()],Ri.prototype,"invertZ",void 0);P([F()],Ri.prototype,"lodLevelInAlpha",void 0);P([F()],Ri.prototype,"lodGenerationOffset",null);P([F()],Ri.prototype,"lodGenerationScale",null);P([F()],Ri.prototype,"linearSpecularLOD",null);P([Xt()],Ri.prototype,"irradianceTexture",null);P([F()],Ri.prototype,"isRenderTarget",void 0)});var id,Pc,_L=y(()=>{He();ts();Ev();es();$t();id=class{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}},Pc=class{static _NearestPow2Floor(e){return e<=1?1:1<<Math.floor(Math.log2(e))}static ConvertCubeMapTextureToSphericalPolynomial(e){var v,E;if(!e.isCube)return null;(v=e.getScene())==null||v.getEngine().flushFramebuffer();let t=e.getSize().width,i=e._sphericalPolynomialTargetSize,r=i>0?this._NearestPow2Floor(i):0,s=!e.noMipmap&&((E=e._texture)==null?void 0:E.generateMipMaps)===!0,a=r>0&&r<t&&s,o=a?Math.max(0,Math.round(Math.log2(t/r))):0,l=a?Math.max(1,Math.floor(t/Math.pow(2,o))):t,c=e.readPixels(0,o,void 0,!1),f=e.readPixels(1,o,void 0,!1),d,u;e.isRenderTarget?(d=e.readPixels(3,o,void 0,!1),u=e.readPixels(2,o,void 0,!1)):(d=e.readPixels(2,o,void 0,!1),u=e.readPixels(3,o,void 0,!1));let h=e.readPixels(4,o,void 0,!1),m=e.readPixels(5,o,void 0,!1),g=e.gammaSpace,p=5,_=r>0&&r<t&&!a;return new Promise(S=>{Promise.all([f,c,d,u,h,m]).then(([T,A,R,M,I,C])=>{let L=l;_&&(T=this._DownsampleFace(T,t,r,4),A=this._DownsampleFace(A,t,r,4),R=this._DownsampleFace(R,t,r,4),M=this._DownsampleFace(M,t,r,4),I=this._DownsampleFace(I,t,r,4),C=this._DownsampleFace(C,t,r,4),L=r);let w={size:L,right:A,left:T,up:R,down:M,front:I,back:C,format:p,type:T instanceof Float32Array?1:0,gammaSpace:g};S(this.ConvertCubeMapToSphericalPolynomial(w))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static _DownsampleFace(e,t,i,r){let s=e instanceof Float32Array?e:Float32Array.from(e),a=i*i*r,o=new Float32Array(a),l=t/i,c=1/(l*l);for(let u=0;u<i;u++){let h=Math.floor(u*l),m=Math.floor((u+1)*l);for(let g=0;g<i;g++){let p=Math.floor(g*l),_=Math.floor((g+1)*l),v=(u*i+g)*r;for(let E=0;E<r;E++){let S=0;for(let T=h;T<m;T++)for(let A=p;A<_;A++)S+=s[(T*t+A)*r+E];o[v+E]=S*c}}}if(e instanceof Float32Array)return o;let f=e.constructor,d=new f(a);for(let u=0;u<a;u++)d[u]=o[u]+.5|0;return d}static ConvertCubeMapToSphericalPolynomial(e,t=0){let i=t>0?this._NearestPow2Floor(t):0;if(i>0&&e.size>i){let m=e.format===5?4:3,g=["right","left","up","down","front","back"],p={};for(let _ of g)p[_]=this._DownsampleFace(e[_],e.size,i,m);e={...e,...p,size:i}}let r=new vv,s=0,a=2/e.size,o=a,l=.5*a,c=l-1;for(let m=0;m<6;m++){let g=this._FileFaces[m],p=e[g.name],_=c,v=e.format===5?4:3;for(let E=0;E<e.size;E++){let S=c;for(let T=0;T<e.size;T++){let A=g.worldAxisForFileX.scale(S).add(g.worldAxisForFileY.scale(_)).add(g.worldAxisForNormal);A.normalize();let R=this._AreaElement(S-l,_-l)-this._AreaElement(S-l,_+l)-this._AreaElement(S+l,_-l)+this._AreaElement(S+l,_+l),M=p[E*e.size*v+T*v+0],I=p[E*e.size*v+T*v+1],C=p[E*e.size*v+T*v+2];isNaN(M)&&(M=0),isNaN(I)&&(I=0),isNaN(C)&&(C=0),e.type===0&&(M/=255,I/=255,C/=255),e.gammaSpace&&(M=Math.pow(Gt(M),rp),I=Math.pow(Gt(I),rp),C=Math.pow(Gt(C),rp));let L=this.MAX_HDRI_VALUE;if(this.PRESERVE_CLAMPED_COLORS){let G=Math.max(M,I,C);if(G>L){let O=L/G;M*=O,I*=O,C*=O}}else M=Gt(M,0,L),I=Gt(I,0,L),C=Gt(C,0,L);let w=new he(M,I,C);r.addLight(A,w,R),s+=R,S+=a}_+=o}}let h=4*Math.PI*6/6/s;return r.scaleInPlace(h),r.convertIncidentRadianceToIrradiance(),r.convertIrradianceToLambertianRadiance(),wl.FromHarmonics(r)}};Pc._FileFaces=[new id("right",new b(1,0,0),new b(0,0,-1),new b(0,-1,0)),new id("left",new b(-1,0,0),new b(0,0,1),new b(0,-1,0)),new id("up",new b(0,1,0),new b(1,0,0),new b(0,0,1)),new id("down",new b(0,-1,0),new b(1,0,0),new b(0,0,-1)),new id("front",new b(0,0,1),new b(1,0,0),new b(0,-1,0)),new id("back",new b(0,0,-1),new b(-1,0,0),new b(0,-1,0))];Pc.MAX_HDRI_VALUE=4096;Pc.PRESERVE_CLAMPED_COLORS=!1});var Lc,vL=y(()=>{wt();ir();Lc=class{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];let t=Vn(e);if(t)return t;te.Warn(e+" not found, you may have missed an import.");let i=e.split("."),r=window||this;for(let s=0,a=i.length;s<a;s++)r=r[i[s]];return typeof r!="function"?null:r}};Lc.RegisteredExternalClasses={}});function Mk(n,e,t=!1){let i=e.width,r=e.height;if(n instanceof Float32Array){let c=n.byteLength/n.BYTES_PER_ELEMENT,f=new Uint8Array(c);for(;--c>=0;){let d=n[c];d<0?d=0:d>1&&(d=1),f[c]=d*255}n=f}let s=document.createElement("canvas");s.width=i,s.height=r;let a=s.getContext("2d");if(!a)return null;let o=a.createImageData(i,r);if(o.data.set(n),a.putImageData(o,0,0),t){let c=document.createElement("canvas");c.width=i,c.height=r;let f=c.getContext("2d");return f?(f.translate(0,r),f.scale(1,-1),f.drawImage(s,0,0),c.toDataURL("image/png")):null}return s.toDataURL("image/png")}function yk(n,e=0,t=0){let i=n.getInternalTexture();if(!i)return null;let r=n._readPixelsSync(e,t);return r?Mk(r,n.getSize(),i.invertY):null}async function Ik(n,e=0,t=0){let i=n.getInternalTexture();if(!i)return null;let r=await n.readPixels(e,t);return r?Mk(r,n.getSize(),i.invertY):null}var Ck=y(()=>{});var Ot,vn=y(()=>{Ot=!1});var _e,Kr=y(()=>{jt();Yt();Si();He();Rv();ir();Mn();Ll();vL();Gu();Av();Ck();vn();Or();_e=class n extends Ri{static _CreateVideoTexture(e,t,i,r=!1,s=!1,a=n.TRILINEAR_SAMPLINGMODE,o={},l,c=5){throw $e("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,r,s=n.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=null,c=!1,f,d,u,h,m){var R,M,I,C,L,w,G,O,N,B,V;super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new re,this._isBlocking=!0,this.name=e||"",this.url=e;let g,p=!1,_=null,v=!0;typeof i=="object"&&i!==null?(g=(R=i.noMipmap)!=null?R:!1,r=(M=i.invertY)!=null?M:!Ot,s=(I=i.samplingMode)!=null?I:n.TRILINEAR_SAMPLINGMODE,a=(C=i.onLoad)!=null?C:null,o=(L=i.onError)!=null?L:null,l=(w=i.buffer)!=null?w:null,c=(G=i.deleteBuffer)!=null?G:!1,f=i.format,d=i.mimeType,u=i.loaderOptions,h=i.creationFlags,p=(O=i.useSRGBBuffer)!=null?O:!1,_=(N=i.internalTexture)!=null?N:null,v=(B=i.gammaSpace)!=null?B:v,m=(V=i.forcedExtension)!=null?V:m):g=!!i,this._gammaSpace=v,this._noMipmap=g,this._invertY=r===void 0?!Ot:r,this._initialSamplingMode=s,this._buffer=l,this._deleteBuffer=c,this._mimeType=d,this._loaderOptions=u,this._creationFlags=h,this._useSRGBBuffer=p,this._forcedExtension=m,f!==void 0&&(this._format=f);let E=this.getScene(),S=this._getEngine();if(!S)return;S.onBeforeTextureInitObservable.notifyObservers(this);let T=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),this._texture._cachedWrapU!==null&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),this._texture._cachedWrapV!==null&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),this._texture._cachedWrapR!==null&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),a&&a(),!this.isBlocking&&E&&E.resetCachedMaterial()},A=(q,K)=>{this._loadingError=!0,this._errorObject={message:q,exception:K},o&&o(q,K),n.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!_){this._delayedOnLoad=T,this._delayedOnError=A;return}if(this._texture=_!=null?_:this._getFromCache(this.url,g,s,this._invertY,p,this.isCube),this._texture)if(this._texture.isReady)Fo.SetImmediate(()=>T());else{let q=this._texture.onLoadedObservable.add(T);this._texture.onErrorObservable.add(K=>{var J;A(K.message,K.exception),(J=this._texture)==null||J.onLoadedObservable.remove(q)})}else if(!E||!E.useDelayedTextureLoading){try{this._texture=S.createTexture(this.url,g,this._invertY,E,s,T,A,this._buffer,void 0,this._format,this._forcedExtension,d,u,h,p)}catch(q){throw A("error loading",q),q}c&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=T,this._delayedOnError=A}updateURL(e,t=null,i,r){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,o=>o.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=4;let s=this._delayedOnLoad,a=()=>{s?s():this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),i&&i()};this._delayedOnLoad=a,this.delayLoad()}delayLoad(){if(this.delayLoadState!==4)return;let e=this.getScene();if(!e)return;let t=this.url;!t&&(this.name.indexOf("://")>0||this.name.startsWith("data:"))&&(t=this.name),this.delayLoadState=1,this._texture=this._getFromCache(t,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?Fo.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(t,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null}_prepareRowForTextureGeneration(e,t,i,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,b.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,(!this._cachedTextureMatrix||!this._rowGenerationMatrix)&&(this._cachedTextureMatrix=Q.Zero(),this._rowGenerationMatrix=new Q,this._t0=b.Zero(),this._t1=b.Zero(),this._t2=b.Zero()),Q.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(Q.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,ee.Matrix[0]),Q.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,ee.Matrix[1]),Q.ScalingToRef(this._cachedUScale,this._cachedVScale,0,ee.Matrix[2]),Q.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,ee.Matrix[3]),ee.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ee.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ee.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ee.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),Q.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));let t=this.getScene();if(!t)return this._cachedTextureMatrix;let i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(1,r=>r.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){let e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode)if(this.coordinatesMode===n.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=Q.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=Q.Zero());let t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case n.PLANAR_MODE:{Q.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break}case n.PROJECTION_MODE:{Q.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);let i=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=i.updateFlag,i.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:Q.IdentityToRef(this._cachedReflectionTextureMatrix);break}return t&&e.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){let e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return at.Clone(()=>new n(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var i,r;let e=this.name;n.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");let t=super.serialize(n._SerializeInternalTextureUniqueId);if(!t)return null;if(n.SerializeBuffers||n.ForceSerializeBuffers)if(typeof this._buffer=="string"&&this._buffer.startsWith("data:"))t.base64String=this._buffer,t.name=t.name.replace("data:","");else if(this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array){let s=this.mimeType||"image/png";t.base64String=`data:${s};base64,${gp(this._buffer)}`}else(n.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?yk(this):Ik(this));return t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,n._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=(i=this._texture)==null?void 0:i.uniqueId),t.internalTextureLabel=(r=this._texture)==null?void 0:r.label,t.noMipmap=this._noMipmap,this.name=e,t}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){let c=Lc.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&c.updateSamplingMode&&c._samplingMode&&c._samplingMode!==e.samplingMode&&c.updateSamplingMode(e.samplingMode),c}if(e.isCube&&!e.isRenderTarget)return n._CubeTextureParser(e,t,i);let r=e.internalTextureUniqueId!==void 0;if(!e.name&&!e.isRenderTarget&&!r)return null;let s;if(r){let l=t.getEngine().getLoadedTexturesCache();for(let c of l)if(c.uniqueId===e.internalTextureUniqueId){s=c;break}}let a=l=>{if(l&&l._texture&&(l._texture._cachedWrapU=null,l._texture._cachedWrapV=null,l._texture._cachedWrapR=null),e.samplingMode){let c=e.samplingMode;l&&l.samplingMode!==c&&l.updateSamplingMode(c)}if(l&&e.animations)for(let c=0;c<e.animations.length;c++){let f=e.animations[c],d=Vn("BABYLON.Animation");d&&l.animations.push(d.Parse(f))}l&&l._texture&&(r&&!s&&l._texture._setUniqueId(e.internalTextureUniqueId),l._texture.label=e.internalTextureLabel)};return at.Parse(()=>{var c,f,d,u,h;let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){let m=n._CreateMirror(e.name,e.renderTargetSize,t,l);return m._waitingRenderList=e.renderList,m.mirrorPlane=Da.FromArray(e.mirrorPlane),a(m),m}else if(e.isRenderTarget&&!e.base64String){let m=null;if(e.isCube){if(t.reflectionProbes)for(let g=0;g<t.reflectionProbes.length;g++){let p=t.reflectionProbes[g];if(p.name===e.name)return p.cubeTexture}}else m=n._CreateRenderTargetTexture(e.name,e.renderTargetSize,t,l,(c=e._creationFlags)!=null?c:0),m._waitingRenderList=e.renderList;return a(m),m}else if(e.isVideo){let m=n._CreateVideoTexture(i+(e.url||e.name),i+(e.src||e.url),t,l,e.invertY,e.samplingMode,e.settings||{});return a(m),m}else{let m;if(typeof e.base64String=="string"&&e.base64String&&!s){let g={buffer:e.base64String,noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,useSRGBBuffer:(f=e._useSRGBBuffer)!=null?f:!1,creationFlags:(d=e._creationFlags)!=null?d:0,onLoad:()=>{a(m)}},p=e.base64String,_=p.startsWith("data:")?p.substring(5):p;m=n.CreateFromBase64String("",_,t,g),m.name=e.name}else{let g;e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?g=e.name:g=i+e.name,e.url&&(e.url.startsWith("data:")||n.UseSerializedUrlIfAny)&&(g=e.url);let p={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,useSRGBBuffer:(u=e._useSRGBBuffer)!=null?u:!1,creationFlags:(h=e._creationFlags)!=null?h:0,onLoad:()=>{a(m)},internalTexture:s};m=new n(g,t,p)}return m}},e,t)}static CreateFromBase64String(e,t,i,r,s,a=n.TRILINEAR_SAMPLINGMODE,o=null,l=null,c=5,f,d){return new n("data:"+t,i,r,s,a,o,l,e,!1,c,void 0,void 0,f,d)}static LoadFromDataString(e,t,i,r=!1,s,a=!0,o=n.TRILINEAR_SAMPLINGMODE,l=null,c=null,f=5,d,u){return e.substring(0,5)!=="data:"&&(e="data:"+e),new n(e,i,s,a,o,l,c,t,r,f,void 0,void 0,d,u)}};_e.SerializeBuffers=!0;_e.ForceSerializeBuffers=!1;_e.OnTextureLoadErrorObservable=new re;_e._SerializeInternalTextureUniqueId=!1;_e._CubeTextureParser=(n,e,t)=>{throw $e("CubeTexture")};_e._CreateMirror=(n,e,t,i)=>{throw $e("MirrorTexture")};_e._CreateRenderTargetTexture=(n,e,t,i,r)=>{throw $e("RenderTargetTexture")};_e.NEAREST_SAMPLINGMODE=1;_e.NEAREST_NEAREST_MIPLINEAR=8;_e.BILINEAR_SAMPLINGMODE=2;_e.LINEAR_LINEAR_MIPNEAREST=11;_e.TRILINEAR_SAMPLINGMODE=3;_e.LINEAR_LINEAR_MIPLINEAR=3;_e.NEAREST_NEAREST_MIPNEAREST=4;_e.NEAREST_LINEAR_MIPNEAREST=5;_e.NEAREST_LINEAR_MIPLINEAR=6;_e.NEAREST_LINEAR=7;_e.NEAREST_NEAREST=1;_e.LINEAR_NEAREST_MIPNEAREST=9;_e.LINEAR_NEAREST_MIPLINEAR=10;_e.LINEAR_LINEAR=2;_e.LINEAR_NEAREST=12;_e.EXPLICIT_MODE=0;_e.SPHERICAL_MODE=1;_e.PLANAR_MODE=2;_e.CUBIC_MODE=3;_e.PROJECTION_MODE=4;_e.SKYBOX_MODE=5;_e.INVCUBIC_MODE=6;_e.EQUIRECTANGULAR_MODE=7;_e.FIXED_EQUIRECTANGULAR_MODE=8;_e.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;_e.CLAMP_ADDRESSMODE=0;_e.WRAP_ADDRESSMODE=1;_e.MIRROR_ADDRESSMODE=2;_e.UseSerializedUrlIfAny=!1;P([F()],_e.prototype,"url",void 0);P([F()],_e.prototype,"uOffset",void 0);P([F()],_e.prototype,"vOffset",void 0);P([F()],_e.prototype,"uScale",void 0);P([F()],_e.prototype,"vScale",void 0);P([F()],_e.prototype,"uAng",void 0);P([F()],_e.prototype,"vAng",void 0);P([F()],_e.prototype,"wAng",void 0);P([F()],_e.prototype,"uRotationCenter",void 0);P([F()],_e.prototype,"vRotationCenter",void 0);P([F()],_e.prototype,"wRotationCenter",void 0);P([F()],_e.prototype,"homogeneousRotationInUVTransform",void 0);P([F()],_e.prototype,"isBlocking",null);zt("BABYLON.Texture",_e);at._TextureParser=_e.Parse});var ko,D,qi=y(()=>{tL();wt();_p();ko=class{get isDisposed(){return this._isDisposed}constructor(e,t,i,r=0,s=!1,a=!1,o=!1,l,c){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=a,this._divisor=l||1,this._label=c,t instanceof Fu?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=o?r:r*Float32Array.BYTES_PER_ELEMENT,s||this.create()}createVertexBuffer(e,t,i,r,s,a=!1,o){let l=a?t:t*Float32Array.BYTES_PER_ELEMENT,c=r?a?r:r*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new D(this._engine,this,e,this._updatable,!0,c,s===void 0?this._instanced:s,l,i,void 0,void 0,!0,this._divisor||o)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data,e&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label)))}_rebuild(){if(this._data)this._buffer=null,this.create(this._data);else{if(!this._buffer)return;if(this._buffer.capacity>0){this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label);return}te.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,r=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,r?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),t===0&&i===void 0?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}},D=class n{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){let t=e!=0;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){let e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,r,s,a,o,l,c,f,d=!1,u=!1,h=1,m=!1){var _,v,E,S,T;this._isDisposed=!1;let g;if(this.engine=e,typeof r=="object"&&r!==null?(g=(_=r.updatable)!=null?_:!1,s=r.postponeInternalCreation,a=r.stride,o=r.instanced,l=r.offset,c=r.size,f=r.type,d=(v=r.normalized)!=null?v:!1,u=(E=r.useBytes)!=null?E:!1,h=(S=r.divisor)!=null?S:1,m=(T=r.takeBufferOwnership)!=null?T:!1,this._label=r.label):g=!!r,t instanceof ko?(this._buffer=t,this._ownsBuffer=m):(this._buffer=new ko(e,t,g,a,s,o,u,h,this._label),this._ownsBuffer=!0),this.uniqueId=n._Counter++,this._kind=i,f===void 0){let A=this.getData();this.type=A?n.GetDataType(A):n.FLOAT}else this.type=f;let p=Fl(this.type);u?(this._size=c||(a?a/p:n.DeduceStride(i)),this.byteStride=a||this._buffer.byteStride||this._size*p,this.byteOffset=l||0):(this._size=c||a||n.DeduceStride(i),this.byteStride=a?a*p:this._buffer.byteStride||this._size*p,this.byteOffset=(l||0)*p),this.normalized=d,this._instanced=o!==void 0?o:!1,this._instanceDivisor=o?h:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){var e;(e=this._buffer)==null||e._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){let i=this.getData();return i?pL(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Fl(this.type)}getOffset(){return this.byteOffset/Fl(this.type)}getSize(e=!1){return e?this._size*Fl(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){Hu(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,(i,r)=>{for(let s=0;s<this._size;s++)t(i[s],r+s)})}_alignBuffer(){}static DeduceStride(e){switch(e){case n.UVKind:case n.UV2Kind:case n.UV3Kind:case n.UV4Kind:case n.UV5Kind:case n.UV6Kind:return 2;case n.NormalKind:case n.PositionKind:return 3;case n.ColorKind:case n.ColorInstanceKind:case n.MatricesIndicesKind:case n.MatricesIndicesExtraKind:case n.MatricesWeightsKind:case n.MatricesWeightsExtraKind:case n.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?n.BYTE:e instanceof Uint8Array?n.UNSIGNED_BYTE:e instanceof Int16Array?n.SHORT:e instanceof Uint16Array?n.UNSIGNED_SHORT:e instanceof Int32Array?n.INT:e instanceof Uint32Array?n.UNSIGNED_INT:n.FLOAT}static GetTypeByteLength(e){return Fl(e)}static ForEach(e,t,i,r,s,a,o,l){Hu(e,t,i,r,s,a,o,(c,f)=>{for(let d=0;d<r;d++)l(c[d],f+d)})}static GetFloatData(e,t,i,r,s,a,o,l){return pL(e,t,i,r,s,a,o,l)}};D._Counter=0;D.BYTE=5120;D.UNSIGNED_BYTE=5121;D.SHORT=5122;D.UNSIGNED_SHORT=5123;D.INT=5124;D.UNSIGNED_INT=5125;D.FLOAT=5126;D.PositionKind="position";D.NormalKind="normal";D.TangentKind="tangent";D.UVKind="uv";D.UV2Kind="uv2";D.UV3Kind="uv3";D.UV4Kind="uv4";D.UV5Kind="uv5";D.UV6Kind="uv6";D.ColorKind="color";D.ColorInstanceKind="instanceColor";D.MatricesIndicesKind="matricesIndices";D.MatricesWeightsKind="matricesWeights";D.MatricesIndicesExtraKind="matricesIndicesExtra";D.MatricesWeightsExtraKind="matricesWeightsExtra"});var Dc,IR=y(()=>{qi();Si();Dc=class{constructor(e){this._vertexBuffers={},this._activePostProcesses=[],this.onBeforeRenderObservable=new re,this._scene=e}_prepareBuffers(){if(this._vertexBuffers[D.PositionKind])return;let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[D.PositionKind]=new D(this._scene.getEngine(),e,D.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){let e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_getActivePostProcesses(e){let t=this._activePostProcesses;t.length=0;for(let i=0;i<e.length;i++){let r=e[i];r&&t.push(r)}return t}_rebuild(){let e=this._vertexBuffers[D.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){let i=this._scene.activeCamera;return!i||(t=t||this._getActivePostProcesses(i._postProcesses),!t||t.length===0||!this._scene.postProcessesEnabled)?!1:(t[0].activate(i,e,t!=null),!0)}directRender(e,t=null,i=!1,r=0,s=0,a=!1,o=e.length){var c;let l=this._scene.getEngine();for(let f=0;f<o;f++){f<e.length-1?e[f+1].activate(this._scene.activeCamera||this._scene,t==null?void 0:t.texture):(t?l.bindFramebuffer(t,r,void 0,void 0,i,s):a||l.restoreDefaultFramebuffer(),(c=l._debugInsertMarker)==null||c.call(l,`post process ${e[f].name} output`));let d=e[f],u=d.apply();u&&(d.onBeforeRenderObservable.notifyObservers(u),this._prepareBuffers(),l.bindBuffers(this._vertexBuffers,this._indexBuffer,u),l.drawElementsType(0,0,6),d.onAfterRenderObservable.notifyObservers(u))}l.setDepthBuffer(!0),l.setDepthWrite(!0)}_finalizeFrame(e,t,i,r,s=!1){var l;let a=this._scene.activeCamera;if(!a||(this.onBeforeRenderObservable.notifyObservers(this),r=r||this._getActivePostProcesses(a._postProcesses),r.length===0||!this._scene.postProcessesEnabled))return;let o=this._scene.getEngine();for(let c=0,f=r.length;c<f;c++){let d=r[c];if(c<f-1?d._outputTexture=r[c+1].activate(a,t==null?void 0:t.texture):(t?(o.bindFramebuffer(t,i,void 0,void 0,s),d._outputTexture=t):(o.restoreDefaultFramebuffer(),d._outputTexture=null),(l=o._debugInsertMarker)==null||l.call(o,`post process ${r[c].name} output`)),e)break;let u=d.apply();u&&(d.onBeforeRenderObservable.notifyObservers(u),this._prepareBuffers(),o.bindBuffers(this._vertexBuffers,this._indexBuffer,u),o.drawElementsType(0,0,6),d.onAfterRenderObservable.notifyObservers(u))}o.setDepthBuffer(!0),o.setDepthWrite(!0),o.setAlphaMode(0)}dispose(){let e=this._vertexBuffers[D.PositionKind];e&&(e.dispose(),this._vertexBuffers[D.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)}}});function Ade(n){let e=[];do{let t=Object.getOwnPropertyNames(n);for(let i of t)e.indexOf(i)===-1&&e.push(i)}while(n=Object.getPrototypeOf(n));return e}var Pk,Ul,bv=y(()=>{wt();Pk=(n,e,t)=>!n||n.getClassName&&n.getClassName()==="Mesh"?null:n.getClassName&&(n.getClassName()==="SubMesh"||n.getClassName()==="PhysicsBody")?n.clone(e):n.clone?n.clone():Array.isArray(n)?n.slice():t&&typeof n=="object"?{...n}:null;Ul=class{static DeepCopy(e,t,i,r,s=!1){let a=Ade(e);for(let o of a){if(o[0]==="_"&&(!r||r.indexOf(o)===-1)||o.endsWith("Observable")||i&&i.indexOf(o)!==-1)continue;let l=e[o],c=typeof l;if(c!=="function")try{if(c==="object")if(l instanceof Uint8Array)t[o]=Uint8Array.from(l);else if(l instanceof Array){if(t[o]=[],l.length>0)if(typeof l[0]=="object")for(let f=0;f<l.length;f++){let d=Pk(l[f],t,s);t[o].indexOf(d)===-1&&t[o].push(d)}else t[o]=l.slice(0)}else t[o]=Pk(l,t,s);else t[o]=l}catch(f){te.Warn(f.message)}}}}});var xt,pe,CR,Gi=y(()=>{Si();qa();wt();bv();Ac();Mn();Wu();Yi();Cc();Ll();vL();Sv();Bo();pe=class{static get BaseUrl(){return Ji.BaseUrl}static set BaseUrl(e){Ji.BaseUrl=e}static get CleanUrl(){return Ji.CleanUrl}static set CleanUrl(e){Ji.CleanUrl=e}static IsAbsoluteUrl(e){return e.indexOf("//")===0?!0:e.indexOf("://")===-1||e.indexOf(".")===-1||e.indexOf("/")===-1||e.indexOf(":")>e.indexOf("/")?!1:e.indexOf("://")<e.indexOf(".")||e.indexOf("data:")===0||e.indexOf("blob:")===0}static set ScriptBaseUrl(e){Ji.ScriptBaseUrl=e}static get ScriptBaseUrl(){return Ji.ScriptBaseUrl}static set CDNBaseUrl(e){xt.ScriptBaseUrl=e,xt.AssetBaseUrl=e}static set ScriptPreprocessUrl(e){Ji.ScriptPreprocessUrl=e}static get ScriptPreprocessUrl(){return Ji.ScriptPreprocessUrl}static get DefaultRetryStrategy(){return Ji.DefaultRetryStrategy}static set DefaultRetryStrategy(e){Ji.DefaultRetryStrategy=e}static get CorsBehavior(){return Ji.CorsBehavior}static set CorsBehavior(e){Ji.CorsBehavior=e}static get UseFallbackTexture(){return Oe.UseFallbackTexture}static set UseFallbackTexture(e){Oe.UseFallbackTexture=e}static get RegisteredExternalClasses(){return Lc.RegisteredExternalClasses}static set RegisteredExternalClasses(e){Lc.RegisteredExternalClasses=e}static get fallbackTexture(){return Oe.FallbackTexture}static set fallbackTexture(e){Oe.FallbackTexture=e}static FetchToRef(e,t,i,r,s,a){let o=Math.abs(e)*i%i|0,l=Math.abs(t)*r%r|0,c=(o+l*i)*4;a.r=s[c]/255,a.g=s[c+1]/255,a.b=s[c+2]/255,a.a=s[c+3]/255}static Mix(e,t,i){return 0}static Instantiate(e){return Lc.Instantiate(e)}static SetImmediate(e){Fo.SetImmediate(e)}static IsExponentOfTwo(e){return!0}static FloatRound(e){return Math.fround(e)}static GetFilename(e){let t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)}static GetFolderPath(e,t=!1){let i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)}static ToDegrees(e){return e*180/Math.PI}static ToRadians(e){return e*Math.PI/180}static SmoothAngleChange(e,t,i=.9){let r=this.ToRadians(e),s=this.ToRadians(t);return this.ToDegrees(Math.atan2((1-i)*Math.sin(s)+i*Math.sin(r),(1-i)*Math.cos(s)+i*Math.cos(r)))}static MakeArray(e,t){return t!==!0&&(e===void 0||e==null)?null:Array.isArray(e)?e:[e]}static GetPointerPrefix(e){return Ar()&&!window.PointerEvent?"mouse":"pointer"}static SetCorsBehavior(e,t){RR(e,t)}static SetReferrerPolicyBehavior(e,t){t.referrerPolicy=e}static get PreprocessUrl(){return Ji.PreprocessUrl}static set PreprocessUrl(e){Ji.PreprocessUrl=e}static LoadImage(e,t,i,r,s,a){return Ep(e,t,i,r,s,a)}static LoadFile(e,t,i,r,s,a){return Bl(e,t,i,r,s,a)}static async LoadFileAsync(e,t=!0){return await new Promise((i,r)=>{Bl(e,s=>{i(s)},void 0,void 0,t,(s,a)=>{r(a)})})}static GetAssetUrl(e){if(!e)return"";if(xt.AssetBaseUrl&&e.startsWith(xt._DefaultAssetsUrl)){let t=xt.AssetBaseUrl.endsWith("/")?xt.AssetBaseUrl.slice(0,-1):xt.AssetBaseUrl;return e.replace(xt._DefaultAssetsUrl,t)}return e}static GetBabylonScriptURL(e,t){if(!e)return"";if(e.startsWith(xt._DefaultCdnUrl)){if(xt.ScriptBaseUrl){let i=xt.ScriptBaseUrl.endsWith("/")?xt.ScriptBaseUrl.slice(0,-1):xt.ScriptBaseUrl;e=e.replace(xt._DefaultCdnUrl,i)}else if(xt._CdnVersion){let i=`${xt._DefaultCdnUrl}/v${xt._CdnVersion}`;e.startsWith(i)||(e=e.replace(xt._DefaultCdnUrl,i))}}return e=xt.ScriptPreprocessUrl(e),t&&!xt.IsAbsoluteUrl(e)&&(e=xt.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,r){e=xt.GetBabylonScriptURL(e),xt.LoadScript(e,t,i)}static async LoadBabylonScriptAsync(e){return e=xt.GetBabylonScriptURL(e),await xt.LoadScriptAsync(e)}static _LoadScriptNative(e,t,i){let r=new Error(`[AI3D] Babylon script loading is disabled in this plugin build. Refused script URL: ${e}`);i==null||i(r.message,r)}static _LoadScriptWeb(e,t,i,r,s=!1){let a=new Error(`[AI3D] Babylon script loading is disabled in this plugin build. Refused script URL: ${e}`);i==null||i(a.message,a)}static async LoadScriptAsync(e,t){return await new Promise((i,r)=>{this.LoadScript(e,()=>{i()},(s,a)=>{r(a||new Error(s))},t)})}static ReadFileAsDataURL(e,t,i){let r=new FileReader,s={onCompleteObservable:new re,abort:()=>r.abort()};return r.onloadend=()=>{s.onCompleteObservable.notifyObservers(s)},r.onload=a=>{t(a.target.result)},r.onprogress=i,r.readAsDataURL(e),s}static ReadFile(e,t,i,r,s){return Xu(e,t,i,r,s)}static FileAsURL(e){let t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){Ul.DeepCopy(e,t,i,r)}static IsEmpty(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){let r=t[i];e.addEventListener(r.name,r.handler,!1);try{window.parent&&window.parent.addEventListener(r.name,r.handler,!1)}catch(s){}}}static UnregisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){let r=t[i];e.removeEventListener(r.name,r.handler);try{e.parent&&e.parent.removeEventListener(r.name,r.handler)}catch(s){}}}static async DumpFramebuffer(e,t,i,r,s="image/png",a,o){throw $e("DumpTools")}static DumpData(e,t,i,r,s="image/png",a,o=!1,l=!1,c){throw $e("DumpTools")}static async DumpDataAsync(e,t,i,r="image/png",s,a=!1,o=!1,l){throw $e("DumpTools")}static _IsOffScreenCanvas(e){return e.convertToBlob!==void 0}static ToBlob(e,t,i="image/png",r){!xt._IsOffScreenCanvas(e)&&!e.toBlob&&(e.toBlob=function(s,a,o){setTimeout(()=>{let l=atob(this.toDataURL(a,o).split(",")[1]),c=l.length,f=new Uint8Array(c);for(let d=0;d<c;d++)f[d]=l.charCodeAt(d);s(new Blob([f]))})}),xt._IsOffScreenCanvas(e)?e.convertToBlob({type:i,quality:r}).then(s=>t(s)):e.toBlob(function(s){t(s)},i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){let i=new Date;t="screenshot_"+((i.getFullYear()+"-"+(i.getMonth()+1)).slice(2)+"-"+i.getDate()+"_"+i.getHours()+"-"+("0"+i.getMinutes()).slice(-2))+".png"}xt.Download(e,t)}else if(e&&typeof URL!="undefined"){let i=URL.createObjectURL(e),r=window.open("");if(!r)return;let s=r.document.createElement("img");s.onload=function(){URL.revokeObjectURL(i)},s.src=i,r.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,s){if(typeof r=="string"||!t)this.ToBlob(e,function(a){a&&xt.DownloadBlob(a,r),t&&t("")},i,s);else if(t){if(xt._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:s}).then(o=>{let l=new FileReader;l.readAsDataURL(o),l.onloadend=()=>{let c=l.result;t(c)}});return}let a=e.toDataURL(i,s);t(a)}}static Download(e,t){if(typeof URL=="undefined")return;let i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",()=>{r.parentElement&&r.parentElement.removeChild(r)}),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return typeof e[0]=="boolean"?e[0]:typeof e[1]=="boolean"?e[1]:!1}static CreateScreenshot(e,t,i,r,s="image/png",a=!1,o){throw $e("ScreenshotTools")}static async CreateScreenshotAsync(e,t,i,r="image/png",s){throw $e("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",a=1,o=!1,l,c=!1,f=!1,d=!0,u,h){throw $e("ScreenshotTools")}static async CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,a=!1,o,l=!1,c=!1,f=!0,d,u){throw $e("ScreenshotTools")}static RandomId(){return Qf()}static IsBase64(e){return Jf(e)}static DecodeBase64(e){return ed(e)}static get errorsCount(){return te.errorsCount}static Log(e){te.Log(e)}static Warn(e){te.Warn(e)}static Error(e){te.Error(e)}static get LogCache(){return te.LogCache}static ClearLogCache(){te.ClearLogCache()}static set LogLevels(e){te.LogLevels=e}static set PerformanceLogLevel(e){var t;if((e&xt.PerformanceUserMarkLogLevel)===xt.PerformanceUserMarkLogLevel){_native!=null&&_native.enablePerformanceLogging?(_native.enablePerformanceLogging(1),xt.StartPerformanceCounter=xt._StartMarkNative,xt.EndPerformanceCounter=xt._EndMarkNative):(xt.StartPerformanceCounter=xt._StartUserMark,xt.EndPerformanceCounter=xt._EndUserMark);return}if((e&xt.PerformanceConsoleLogLevel)===xt.PerformanceConsoleLogLevel){_native!=null&&_native.enablePerformanceLogging?(_native.enablePerformanceLogging(2),xt.StartPerformanceCounter=xt._StartMarkNative,xt.EndPerformanceCounter=xt._EndMarkNative):(xt.StartPerformanceCounter=xt._StartPerformanceConsole,xt.EndPerformanceCounter=xt._EndPerformanceConsole);return}xt.StartPerformanceCounter=xt._StartPerformanceCounterDisabled,xt.EndPerformanceCounter=xt._EndPerformanceCounterDisabled,(t=_native==null?void 0:_native.disablePerformanceLogging)==null||t.call(_native)}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!xt._Performance){if(!Ar())return;xt._Performance=window.performance}!t||!xt._Performance.mark||xt._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!xt._Performance.mark||(xt._Performance.mark(e+"-End"),xt._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(xt._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(xt._EndUserMark(e,t),console.timeEnd(e))}static _StartMarkNative(e,t=!0){if(t&&(_native!=null&&_native.startPerformanceCounter))if(xt._NativePerformanceCounterHandles.has(e))xt.Warn(`Performance counter with name ${e} is already started.`);else{let i=_native.startPerformanceCounter(e);xt._NativePerformanceCounterHandles.set(e,i)}}static _EndMarkNative(e,t=!0){if(t&&(_native!=null&&_native.endPerformanceCounter)){let i=xt._NativePerformanceCounterHandles.get(e);i?(_native.endPerformanceCounter(i),xt._NativePerformanceCounterHandles.delete(e)):xt.Warn(`Performance counter with name ${e} was not started.`)}}static get Now(){return br.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(let i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,r=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(r!=null?r+".":"")+i:null}static async DelayAsync(e){await new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return Tc()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}};xt=pe;pe.AssetBaseUrl="";pe.UseCustomRequestHeaders=!1;pe.CustomRequestHeaders=Ur.CustomRequestHeaders;pe.GetDOMTextContent=Ux;pe._DefaultCdnUrl="https://cdn.babylonjs.com";pe._CdnVersion="9.6.0";pe._DefaultAssetsUrl="https://assets.babylonjs.com/core";pe.LoadScript=typeof _native=="undefined"?xt._LoadScriptWeb:xt._LoadScriptNative;pe.GetAbsoluteUrl=typeof document=="object"?n=>{let e=document.createElement("a");return e.href=n,e.href}:typeof URL=="function"&&typeof location=="object"?n=>new URL(n,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")};pe.NoneLogLevel=te.NoneLogLevel;pe.MessageLogLevel=te.MessageLogLevel;pe.WarningLogLevel=te.WarningLogLevel;pe.ErrorLogLevel=te.ErrorLogLevel;pe.AllLogLevel=te.AllLogLevel;pe.IsWindowObjectExist=Ar;pe.PerformanceNoneLogLevel=0;pe.PerformanceUserMarkLogLevel=1;pe.PerformanceConsoleLogLevel=2;pe._NativePerformanceCounterHandles=new Map;pe.StartPerformanceCounter=xt._StartPerformanceCounterDisabled;pe.EndPerformanceCounter=xt._EndPerformanceCounterDisabled;CR=class n{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())}breakLoop(){this._done=!0,this._successCallback()}static Run(e,t,i,r=0){let s=new n(e,t,i,r);return s.executeNext(),s}static SyncAsyncForLoop(e,t,i,r,s,a=0){return n.Run(Math.ceil(e/t),o=>{s&&s()?o.breakLoop():setTimeout(()=>{for(let l=0;l<t;++l){let c=o.index*t+l;if(c>=e)break;if(i(c),s&&s()){o.breakLoop();break}}o.executeNext()},a)},r)}};pe.Mix=pv;pe.IsExponentOfTwo=Bu;Oe.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z"});var xr,rd=y(()=>{wt();Gi();xr=class n{constructor(e,t,i=!1,r,s=!1,a){this._uniformNames=[],this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=r!=null?r:"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._trackUBOsInFrame=!1,(a===void 0&&this._engine._features.trackUbosInFrame||a===!0)&&(this._buffers=[],this._bufferIndex=-1,this._bufferUpdatedLastFrame=!1,this._createBufferOnWrite=!1,this._currentFrameId=0,this._trackUBOsInFrame=!0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}getUniformNames(){return this._uniformNames}_fillAlignment(e){let t;if(e<=2?t=e:t=4,this._uniformLocationPointer%t!==0){let i=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;let r=this._uniformLocationPointer-i;for(let s=0;s<r;s++)this._data.push(0)}}addUniform(e,t,i=0){if(i>0&&typeof t=="number"&&(this._uniformArraySizes[e]={strideSize:t,arraySize:i}),this._uniformLocations[e]!==void 0||(this._uniformNames.push(e),this._noUBO))return;let r;if(i>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),t==16)t=t*i;else{let a=(4-t)*i;t=t*i+a}r=[];for(let s=0;s<t;s++)r.push(0)}else{if(t instanceof Array)r=t,t=r.length;else{r=[];for(let s=0;s<t;s++)r.push(0)}this._fillAlignment(t)}this._uniformSizes[e]=t,this._uniformLocations[e]=this._uniformLocationPointer,this._uniformLocationPointer+=t;for(let s=0;s<t;s++)this._data.push(r[s]);this._needSync=!0}addMatrix(e,t){this.addUniform(e,Array.prototype.slice.call(t.asArray()))}addFloat2(e,t,i){let r=[t,i];this.addUniform(e,r)}addFloat3(e,t,i,r){let s=[t,i,r];this.addUniform(e,s)}addColor3(e,t){let i=[t.r,t.g,t.b];this.addUniform(e,i)}addColor4(e,t,i){let r=[t.r,t.g,t.b,i];this.addUniform(e,r)}addVector3(e,t){let i=[t.x,t.y,t.z];this.addUniform(e,i)}addMatrix3x3(e){this.addUniform(e,12)}addMatrix2x2(e){this.addUniform(e,8)}create(){this._noUBO||this._buffer||(this._fillAlignment(4),this._bufferData=new Float32Array(this._data),this._rebuild(),this._needSync=!0)}_getNamesDebug(){let e=[],t=0;for(let i in this._uniformLocations)if(e.push(i),++t===10)break;return e.join(",")}_rebuild(){this._noUBO||!this._bufferData||(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNamesDebug()):this._buffer=this._engine.createUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNamesDebug()),this._trackUBOsInFrame&&(this._buffers.push([this._buffer,this._engine._features.checkUbosContentBeforeUpload?this._bufferData.slice():void 0]),this._bufferIndex=this._buffers.length-1,this._createBufferOnWrite=!1))}_rebuildAfterContextLost(){this._trackUBOsInFrame&&(this._buffers=[],this._currentFrameId=0),this._rebuild()}get _numBuffers(){return this._buffers.length}get _indexBuffer(){return this._bufferIndex}get name(){return this._name}set name(e){this._name=e}get currentEffect(){return this._currentEffect}_buffersEqual(e,t){for(let i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0}_copyBuffer(e,t){for(let i=0;i<e.length;++i)t[i]=e[i]}update(){if(!this._noUBO){if(this.bindUniformBuffer(),!this._buffer){this.create();return}if(!this._dynamic&&!this._needSync){this._createBufferOnWrite=this._trackUBOsInFrame;return}if(this._buffers&&this._buffers.length>1&&this._buffers[this._bufferIndex][1])if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._trackUBOsInFrame;return}else this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1]);this._bufferUpdatedLastFrame=!0,this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._needSync=!1,this._createBufferOnWrite=this._trackUBOsInFrame}}_createNewBuffer(){this._bufferIndex+1<this._buffers.length?(this._bufferIndex++,this._buffer=this._buffers[this._bufferIndex][0],this._createBufferOnWrite=!1,this._needSync=!0):this._rebuild()}_checkNewFrame(){this._trackUBOsInFrame&&this._currentFrameId!==this._engine.frameId&&(this._currentFrameId=this._engine.frameId,this._createBufferOnWrite=!1,this._buffers&&this._buffers.length>0?(this._buffers.length===1?this._needSync=!this._bufferUpdatedLastFrame:this._needSync=this._bufferIndex!==0,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let r=this._uniformLocations[e];if(r===void 0){if(this._buffer){te.Error("Cannot add an uniform after UBO has been created. uniformName="+e);return}this.addUniform(e,i),r=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let s=0;s<i;s++)this._bufferData[r+s]=t[s];else{let s=!1;for(let a=0;a<i;a++)(i===16&&!this._engine._features.uniformBufferHardCheckMatrix||this._bufferData[r+a]!==Math.fround(t[a]))&&(s=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[r+a]=t[a]);this._needSync=this._needSync||s}}updateUniformArray(e,t,i){this._checkNewFrame();let r=this._uniformLocations[e];if(r===void 0){te.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine.");return}this._buffer||this.create();let s=this._uniformArraySizes[e];if(this._dynamic)for(let a=0;a<i;a++)this._bufferData[r+a]=t[a];else{let a=!1,o=0,l=0;for(let c=0;c<i;c++)if(this._bufferData[r+l*4+o]!==pe.FloatRound(t[c])&&(a=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[r+l*4+o]=t[c]),o++,o===s.strideSize){for(;o<4;o++)this._bufferData[r+l*4+o]=0;o=0,l++}this._needSync=this._needSync||a}}_cacheMatrix(e,t){this._checkNewFrame();let i=this._valueCache[e],r=t.updateFlag;return i!==void 0&&i===r?!1:(this._valueCache[e]=r,!0)}_updateMatrix3x3ForUniform(e,t){for(let i=0;i<3;i++)n._TempBuffer[i*4]=t[i*3],n._TempBuffer[i*4+1]=t[i*3+1],n._TempBuffer[i*4+2]=t[i*3+2],n._TempBuffer[i*4+3]=0;this.updateUniform(e,n._TempBuffer,12)}_updateMatrix3x3ForEffect(e,t){this._currentEffect.setMatrix3x3(e,t)}_updateMatrix2x2ForEffect(e,t){this._currentEffect.setMatrix2x2(e,t)}_updateMatrix2x2ForUniform(e,t){for(let i=0;i<2;i++)n._TempBuffer[i*4]=t[i*2],n._TempBuffer[i*4+1]=t[i*2+1],n._TempBuffer[i*4+2]=0,n._TempBuffer[i*4+3]=0;this.updateUniform(e,n._TempBuffer,8)}_updateFloatForEffect(e,t,i=""){this._currentEffect.setFloat(e+i,t)}_updateFloatForUniform(e,t){n._TempBuffer[0]=t,this.updateUniform(e,n._TempBuffer,1)}_updateFloat2ForEffect(e,t,i,r=""){this._currentEffect.setFloat2(e+r,t,i)}_updateFloat2ForUniform(e,t,i){n._TempBuffer[0]=t,n._TempBuffer[1]=i,this.updateUniform(e,n._TempBuffer,2)}_updateFloat3ForEffect(e,t,i,r,s=""){this._currentEffect.setFloat3(e+s,t,i,r)}_updateFloat3ForUniform(e,t,i,r){n._TempBuffer[0]=t,n._TempBuffer[1]=i,n._TempBuffer[2]=r,this.updateUniform(e,n._TempBuffer,3)}_updateFloat4ForEffect(e,t,i,r,s,a=""){this._currentEffect.setFloat4(e+a,t,i,r,s)}_updateFloat4ForUniform(e,t,i,r,s){n._TempBuffer[0]=t,n._TempBuffer[1]=i,n._TempBuffer[2]=r,n._TempBuffer[3]=s,this.updateUniform(e,n._TempBuffer,4)}_updateFloatArrayForEffect(e,t,i=""){var r;switch((r=this._uniformArraySizes[e])==null?void 0:r.strideSize){case 2:this._currentEffect.setFloatArray2(e+i,t);break;case 3:this._currentEffect.setFloatArray3(e+i,t);break;case 4:this._currentEffect.setFloatArray4(e+i,t);break;default:this._currentEffect.setFloatArray(e+i,t);break}}_updateFloatArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateArrayForEffect(e,t){this._currentEffect.setArray(e,t)}_updateArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateIntArrayForEffect(e,t){this._currentEffect.setIntArray(e,t)}_updateIntArrayForUniform(e,t){n._TempBufferInt32View.set(t),this.updateUniformArray(e,n._TempBuffer,t.length)}_updateUIntArrayForEffect(e,t){this._currentEffect.setUIntArray(e,t)}_updateUIntArrayForUniform(e,t){n._TempBufferUInt32View.set(t),this.updateUniformArray(e,n._TempBuffer,t.length)}_updateMatrixForEffect(e,t){this._currentEffect.setMatrix(e,t)}_updateMatrixForUniform(e,t){this._cacheMatrix(e,t)&&this.updateUniform(e,t.asArray(),16)}_updateMatricesForEffect(e,t){this._currentEffect.setMatrices(e,t)}_updateMatricesForUniform(e,t){this.updateUniform(e,t,t.length)}_updateVector3ForEffect(e,t){this._currentEffect.setVector3(e,t)}_updateVector3ForUniform(e,t){n._TempBuffer[0]=t.x,n._TempBuffer[1]=t.y,n._TempBuffer[2]=t.z,this.updateUniform(e,n._TempBuffer,3)}_updateVector4ForEffect(e,t){this._currentEffect.setVector4(e,t)}_updateVector4ForUniform(e,t){n._TempBuffer[0]=t.x,n._TempBuffer[1]=t.y,n._TempBuffer[2]=t.z,n._TempBuffer[3]=t.w,this.updateUniform(e,n._TempBuffer,4)}_updateColor3ForEffect(e,t,i=""){this._currentEffect.setColor3(e+i,t)}_updateColor3ForUniform(e,t){n._TempBuffer[0]=t.r,n._TempBuffer[1]=t.g,n._TempBuffer[2]=t.b,this.updateUniform(e,n._TempBuffer,3)}_updateColor4ForEffect(e,t,i,r=""){this._currentEffect.setColor4(e+r,t,i)}_updateDirectColor4ForEffect(e,t,i=""){this._currentEffect.setDirectColor4(e+i,t)}_updateColor4ForUniform(e,t,i){n._TempBuffer[0]=t.r,n._TempBuffer[1]=t.g,n._TempBuffer[2]=t.b,n._TempBuffer[3]=i,this.updateUniform(e,n._TempBuffer,4)}_updateDirectColor4ForUniform(e,t){n._TempBuffer[0]=t.r,n._TempBuffer[1]=t.g,n._TempBuffer[2]=t.b,n._TempBuffer[3]=t.a,this.updateUniform(e,n._TempBuffer,4)}_updateIntForEffect(e,t,i=""){this._currentEffect.setInt(e+i,t)}_updateIntForUniform(e,t){n._TempBufferInt32View[0]=t,this.updateUniform(e,n._TempBuffer,1)}_updateInt2ForEffect(e,t,i,r=""){this._currentEffect.setInt2(e+r,t,i)}_updateInt2ForUniform(e,t,i){n._TempBufferInt32View[0]=t,n._TempBufferInt32View[1]=i,this.updateUniform(e,n._TempBuffer,2)}_updateInt3ForEffect(e,t,i,r,s=""){this._currentEffect.setInt3(e+s,t,i,r)}_updateInt3ForUniform(e,t,i,r){n._TempBufferInt32View[0]=t,n._TempBufferInt32View[1]=i,n._TempBufferInt32View[2]=r,this.updateUniform(e,n._TempBuffer,3)}_updateInt4ForEffect(e,t,i,r,s,a=""){this._currentEffect.setInt4(e+a,t,i,r,s)}_updateInt4ForUniform(e,t,i,r,s){n._TempBufferInt32View[0]=t,n._TempBufferInt32View[1]=i,n._TempBufferInt32View[2]=r,n._TempBufferInt32View[3]=s,this.updateUniform(e,n._TempBuffer,4)}_updateUIntForEffect(e,t,i=""){this._currentEffect.setUInt(e+i,t)}_updateUIntForUniform(e,t){n._TempBufferUInt32View[0]=t,this.updateUniform(e,n._TempBuffer,1)}_updateUInt2ForEffect(e,t,i,r=""){this._currentEffect.setUInt2(e+r,t,i)}_updateUInt2ForUniform(e,t,i){n._TempBufferUInt32View[0]=t,n._TempBufferUInt32View[1]=i,this.updateUniform(e,n._TempBuffer,2)}_updateUInt3ForEffect(e,t,i,r,s=""){this._currentEffect.setUInt3(e+s,t,i,r)}_updateUInt3ForUniform(e,t,i,r){n._TempBufferUInt32View[0]=t,n._TempBufferUInt32View[1]=i,n._TempBufferUInt32View[2]=r,this.updateUniform(e,n._TempBuffer,3)}_updateUInt4ForEffect(e,t,i,r,s,a=""){this._currentEffect.setUInt4(e+a,t,i,r,s)}_updateUInt4ForUniform(e,t,i,r,s){n._TempBufferUInt32View[0]=t,n._TempBufferUInt32View[1]=i,n._TempBufferUInt32View[2]=r,n._TempBufferUInt32View[3]=s,this.updateUniform(e,n._TempBuffer,4)}setTexture(e,t){this._currentEffect.setTexture(e,t)}setTextureArray(e,t){this._currentEffect.setTextureArray(e,t)}bindTexture(e,t){this._currentEffect._bindTexture(e,t)}updateUniformDirectly(e,t){this.updateUniform(e,t,t.length),this.update()}bindToEffect(e,t){this._currentEffect=e,this._currentEffectName=t}bindUniformBuffer(){!this._noUBO&&this._buffer&&this._currentEffect&&this._currentEffect.bindUniformBuffer(this._buffer,this._currentEffectName)}unbindEffect(){this._currentEffect=void 0,this._currentEffectName=void 0}setDataBuffer(e){if(!this._buffers)return this._buffer===e;for(let t=0;t<this._buffers.length;++t)if(this._buffers[t][0]===e)return this._bufferIndex=t,this._buffer=e,this._createBufferOnWrite=!1,this._currentEffect=void 0,this._buffers.length>1&&this._buffers[t][1]&&this._bufferData.set(this._buffers[t][1]),this._valueCache={},this._currentFrameId=this._engine.frameId,!0;return!1}has(e){return this._uniformLocations[e]!==void 0}dispose(){if(this._noUBO)return;let e=this._engine._uniformBuffers,t=e.indexOf(this);if(t!==-1&&(e[t]=e[e.length-1],e.pop()),this._trackUBOsInFrame&&this._buffers)for(let i=0;i<this._buffers.length;++i){let r=this._buffers[i][0];this._engine._releaseBuffer(r)}else this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)}};xr._MAX_UNIFORM_SIZE=256;xr._TempBuffer=new Float32Array(xr._MAX_UNIFORM_SIZE);xr._TempBufferInt32View=new Int32Array(xr._TempBuffer.buffer);xr._TempBufferUInt32View=new Uint32Array(xr._TempBuffer.buffer)});var Qi,zo,Wo=y(()=>{Qi=class n{constructor(e){this.length=0,this.data=new Array(e),this._id=n._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;t<this.length;t++)e(this.data[t])}sort(e){this.data.sort(e)}reset(){this.length=0}dispose(){this.reset(),this.data&&(this.data.length=0)}concat(e){if(e.length!==0){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}}indexOf(e){let t=this.data.indexOf(e);return t>=this.length?-1:t}contains(e){return this.indexOf(e)!==-1}};Qi._GlobalId=0;zo=class extends Qi{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId?!1:(this.push(e),!0)}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(e.length!==0){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t<e.length;t++){let i=(e.data||e)[t];this.pushNoDuplicate(i)}}}}});var Mv,Lk=y(()=>{Wo();He();Mv=class n{set opaqueSortCompareFn(e){e?this._opaqueSortCompareFn=e:this._opaqueSortCompareFn=n.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){e?this._alphaTestSortCompareFn=e:this._alphaTestSortCompareFn=n.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){e?this._transparentSortCompareFn=e:this._transparentSortCompareFn=n.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,r=null,s=null){this.index=e,this._opaqueSubMeshes=new Qi(256),this._transparentSubMeshes=new Qi(256),this._alphaTestSubMeshes=new Qi(256),this._depthOnlySubMeshes=new Qi(256),this._particleSystems=new Qi(256),this._spriteManagers=new Qi(256),this._empty=!0,this._edgesRenderers=new zo(16),this.disableDepthPrePass=!1,this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=r,this.transparentSortCompareFn=s}render(e,t,i,r,s=!0,a=!0,o=!0,l=!0,c){if(e){e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);return}let f=this._scene.getEngine();s&&this._depthOnlySubMeshes.length!==0&&(f.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),f.setColorWrite(!0)),a&&this._opaqueSubMeshes.length!==0&&this._renderOpaque(this._opaqueSubMeshes),o&&this._alphaTestSubMeshes.length!==0&&this._renderAlphaTest(this._alphaTestSubMeshes);let d=f.getStencilBuffer();if(f.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(r),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),l&&(c||this._transparentSubMeshes.length!==0||this._scene.useOrderIndependentTransparency)){if(f.setStencilBuffer(d),c)c(this._transparentSubMeshes,this);else if(this._scene.useOrderIndependentTransparency){let u=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);u.length&&this._renderTransparent(u)}else this._renderTransparent(this._transparentSubMeshes);f.setAlphaMode(0)}if(f.setStencilBuffer(!1),a&&this._edgesRenderers.length){for(let u=0;u<this._edgesRenderers.length;u++)this._edgesRenderers.data[u].render();f.setAlphaMode(0)}f.setStencilBuffer(d)}_renderOpaqueSorted(e){n._RenderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera,!1,this.disableDepthPrePass)}_renderAlphaTestSorted(e){n._RenderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera,!1,this.disableDepthPrePass)}_renderTransparentSorted(e){n._RenderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera,!0,this.disableDepthPrePass)}static _RenderSorted(e,t,i,r,s){let a=0,o,l=i?i.globalPosition:n._ZeroVector;if(r)for(;a<e.length;a++)o=e.data[a],o._alphaIndex=o.getMesh().alphaIndex,o._distanceToCamera=b.Distance(o.getBoundingInfo().boundingSphere.centerWorld,l);let c=e.length===e.data.length?e.data:e.data.slice(0,e.length);t&&c.sort(t);let f=c[0].getMesh().getScene();for(a=0;a<c.length;a++)if(o=c[a],!(f._activeMeshesFrozenButKeepClipping&&!o.isInFrustum(f._frustumPlanes))){if(r){let d=o.getMaterial();if(d&&d.needDepthPrePass&&!s){let u=d.getScene().getEngine();u.setColorWrite(!1),u.setAlphaMode(0),o.render(!1),u.setColorWrite(!0)}}o.render(r)}}static defaultTransparentSortCompare(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:n.backToFrontSortCompare(e,t)}static backToFrontSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0}static PainterSortCompare(e,t){let i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){t===void 0&&(t=e.getMesh()),i===void 0&&(i=e.getMaterial()),i!=null&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTestingForMesh(t)?(i.needDepthPrePass&&!this.disableDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&!this.disableDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(this._particleSystems.length===0)return;let t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i<this._particleSystems.length;i++){let r=this._particleSystems.data[i];if((t&&t.layerMask&r.layerMask)===0)continue;let s=r.emitter;(!s.position||!e||e.indexOf(s)!==-1)&&this._scene._activeParticles.addCount(r.render(),!1)}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}_renderSprites(){if(!this._scene.spritesEnabled||this._spriteManagers.length===0)return;let e=this._scene.activeCamera;this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);for(let t=0;t<this._spriteManagers.length;t++){let i=this._spriteManagers.data[t];(e&&e.layerMask&i.layerMask)!==0&&i.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}};Mv._ZeroVector=b.Zero()});var EL,Ja,PR=y(()=>{Lk();EL=class{},Ja=class n{get disableDepthPrePass(){return this._disableDepthPrePass}set disableDepthPrePass(e){this._disableDepthPrePass=e;for(let t of this._renderingGroups)t.disableDepthPrePass=e}get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,this._maintainStateBetweenFrames||this.restoreDispachedFlags())}restoreDispachedFlags(){for(let e of this._scene.meshes)if(e.subMeshes)for(let t of e.subMeshes)t._wasDispatched=!1;if(this._scene.spriteManagers)for(let e of this._scene.spriteManagers)e._wasDispatched=!1;for(let e of this._scene.particleSystems)e._wasDispatched=!1}constructor(e){this._useSceneAutoClearSetup=!1,this._disableDepthPrePass=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new EL,this._maintainStateBetweenFrames=!1,this._scene=e;for(let t=n.MIN_RENDERINGGROUPS;t<n.MAX_RENDERINGGROUPS;t++)this._autoClearDepthStencil[t]={autoClear:!0,depth:!0,stencil:!0}}get renderingGroups(){return this._renderingGroups}getRenderingGroup(e){let t=e||0;return this._prepareRenderingGroup(t),this._renderingGroups[t]}_clearDepthStencilBuffer(e=!0,t=!0){this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(null,!1,e,t),this._depthStencilBufferAlreadyCleaned=!0)}render(e,t,i,r,s=!0,a=!0,o=!0,l=!0,c){let f=this._renderingGroupInfo;if(f.scene=this._scene,f.camera=this._scene.activeCamera,f.renderingManager=this,this._scene.spriteManagers&&r)for(let d=0;d<this._scene.spriteManagers.length;d++){let u=this._scene.spriteManagers[d];this.dispatchSprites(u)}for(let d=n.MIN_RENDERINGGROUPS;d<n.MAX_RENDERINGGROUPS;d++){this._depthStencilBufferAlreadyCleaned=d===n.MIN_RENDERINGGROUPS;let u=this._renderingGroups[d];if(!u||u._empty)continue;let h=1<<d;if(f.renderingGroupId=d,this._scene.onBeforeRenderingGroupObservable.notifyObservers(f,h),n.AUTOCLEAR){let m=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(d):this._autoClearDepthStencil[d];m&&m.autoClear&&this._clearDepthStencilBuffer(m.depth,m.stencil)}for(let m of this._scene._beforeRenderingGroupDrawStage)m.action(d);u.render(e,r,i,t,s,a,o,l,c);for(let m of this._scene._afterRenderingGroupDrawStage)m.action(d);this._scene.onAfterRenderingGroupObservable.notifyObservers(f,h)}}reset(){if(!this.maintainStateBetweenFrames)for(let e=n.MIN_RENDERINGGROUPS;e<n.MAX_RENDERINGGROUPS;e++){let t=this._renderingGroups[e];t&&t.prepare()}}resetSprites(){if(!this.maintainStateBetweenFrames)for(let e=n.MIN_RENDERINGGROUPS;e<n.MAX_RENDERINGGROUPS;e++){let t=this._renderingGroups[e];t&&t.prepareSprites()}}dispose(){this.freeRenderingGroups(),this._renderingGroups.length=0,this._renderingGroupInfo=null}freeRenderingGroups(){for(let e=n.MIN_RENDERINGGROUPS;e<n.MAX_RENDERINGGROUPS;e++){let t=this._renderingGroups[e];t&&t.dispose()}}_prepareRenderingGroup(e){this._renderingGroups[e]===void 0&&(this._renderingGroups[e]=new Mv(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]),this._renderingGroups[e].disableDepthPrePass=this._disableDepthPrePass)}dispatchSprites(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchSprites(e))}dispatchParticles(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchParticles(e))}dispatch(e,t,i){t===void 0&&(t=e.getMesh()),!(this.maintainStateBetweenFrames&&e._wasDispatched)&&(e._wasDispatched=!0,this.getRenderingGroup(t.renderingGroupId).dispatch(e,t,i))}setRenderingOrder(e,t=null,i=null,r=null){if(this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=r,this._renderingGroups[e]){let s=this._renderingGroups[e];s.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],s.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],s.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._autoClearDepthStencil[e]={autoClear:t,depth:i,stencil:r}}getAutoClearDepthStencilSetup(e){return this._autoClearDepthStencil[e]}};Ja.MAX_RENDERINGGROUPS=4;Ja.MIN_RENDERINGGROUPS=0;Ja.AUTOCLEAR=!0});var ti,yv=y(()=>{ti=class{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}};ti.FALLOFF_DEFAULT=0;ti.FALLOFF_PHYSICAL=1;ti.FALLOFF_GLTF=2;ti.FALLOFF_STANDARD=3;ti.LIGHTMAP_DEFAULT=0;ti.LIGHTMAP_SPECULAR=1;ti.LIGHTMAP_SHADOWSONLY=2;ti.INTENSITYMODE_AUTOMATIC=0;ti.INTENSITYMODE_LUMINOUSPOWER=1;ti.INTENSITYMODE_LUMINOUSINTENSITY=2;ti.INTENSITYMODE_ILLUMINANCE=3;ti.INTENSITYMODE_LUMINANCE=4;ti.LIGHTTYPEID_POINTLIGHT=0;ti.LIGHTTYPEID_DIRECTIONALLIGHT=1;ti.LIGHTTYPEID_SPOTLIGHT=2;ti.LIGHTTYPEID_HEMISPHERICLIGHT=3;ti.LIGHTTYPEID_RECT_AREALIGHT=4;ti.LIGHTTYPEID_CLUSTERED_CONTAINER=5});var eo,SL=y(()=>{rd();Si();PR();Ol();Ll();wt();Wo();yv();eo=class n{get renderList(){return this._renderList}set renderList(e){this._renderList!==e&&(this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=hR(e,this._renderListHasChanged)),this._renderList=e)}get disableImageProcessing(){return this._disableImageProcessing}set disableImageProcessing(e){e!==this._disableImageProcessing&&(this._disableImageProcessing=e,this._scene.markAllMaterialsAsDirty(64))}get disableDepthPrePass(){return this._disableDepthPrePass}set disableDepthPrePass(e){this._disableDepthPrePass=e,this._renderingManager.disableDepthPrePass=e}get name(){return this._name}set name(e){if(this._name!==e){if(this._name=e,this._sceneUBOs)for(let t=0;t<this._sceneUBOs.length;++t)this._sceneUBOs[t].name=`Scene ubo #${t} for ${this.name}`;if(this._scene)for(let t=0;t<this._renderPassIds.length;++t){let i=this._renderPassIds[t];this._engine._renderPassNames[i]=`${this._name}#${t}`}}}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}getActiveMeshes(){return this._activeMeshes}setMaterialForRendering(e,t){let i;Array.isArray(e)?i=e:i=[e];for(let r=0;r<i.length;++r)for(let s=0;s<this.options.numPasses;++s){let a=i[r];i[r].isAnInstance&&(a=i[r].sourceMesh),a.setMaterialForRenderPass(this._renderPassIds[s],t!==void 0?Array.isArray(t)?t[s]:t:void 0)}}_freezeActiveMeshes(e){this._freezeActiveMeshesCancel=Pl(()=>this._checkReadiness(),()=>{if(this._freezeActiveMeshesCancel=null,e)for(let t=0;t<this._activeMeshes.length;t++)this._activeMeshes.data[t]._freeze();this._prepareRenderingManager(0,!0),this._isFrozen=!0},(t,i)=>{this._freezeActiveMeshesCancel=null,i?(te.Error("ObjectRenderer: Timeout while waiting for the renderer to be ready."),t&&te.Error(t)):(te.Error("ObjectRenderer: An unexpected error occurred while waiting for the renderer to be ready."),t&&(te.Error(t),t.stack&&te.Error(t.stack)))})}_unfreezeActiveMeshes(){var e;(e=this._freezeActiveMeshesCancel)==null||e.call(this),this._freezeActiveMeshesCancel=null;for(let t=0;t<this._activeMeshes.length;t++)this._activeMeshes.data[t]._unFreeze();this._isFrozen=!1}constructor(e,t,i){this._unObserveRenderList=null,this._renderListHasChanged=(r,s)=>{let a=this._renderList?this._renderList.length:0;if(s===0&&a>0||a===0)for(let o of this._scene.meshes)o._markSubMeshesAsLightDirty()},this.particleSystemList=null,this.getCustomRenderList=null,this.renderMeshes=!0,this.renderDepthOnlyMeshes=!0,this.renderOpaqueMeshes=!0,this.renderAlphaTestMeshes=!0,this.renderTransparentMeshes=!0,this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.enableBoundingBoxRendering=!1,this.enableOutlineRendering=!0,this._disableImageProcessing=!1,this.dontSetTransformationMatrix=!1,this._disableDepthPrePass=!1,this.onBeforeRenderObservable=new re,this.onAfterRenderObservable=new re,this.onBeforeRenderingManagerRenderObservable=new re,this.onAfterRenderingManagerRenderObservable=new re,this.onInitRenderingObservable=new re,this.onFinishRenderingObservable=new re,this.onFastPathRenderObservable=new re,this._currentRefreshId=-1,this._refreshRate=1,this._currentApplyByPostProcessSetting=!1,this._activeMeshes=new Qi(256),this._activeBoundingBoxes=new Qi(32),this._currentFrameId=-1,this._currentSceneUBOIndex=0,this._isFrozen=!1,this._freezeActiveMeshesCancel=null,this._currentSceneCamera=null,this.name=e,this._scene=t,this._engine=this._scene.getEngine(),this._useUBO=this._engine.supportsUniformBuffers,this.renderList=[],this._renderPassIds=[],this.options={numPasses:1,doNotChangeAspectRatio:!0,enableClusteredLights:!1,...i},this._createRenderPassId(),this.renderPassId=this._renderPassIds[0],this._renderingManager=new Ja(t),this._renderingManager._useSceneAutoClearSetup=!0,this.options.enableClusteredLights&&this.onInitRenderingObservable.add(()=>{for(let r of this._scene.lights)r.getTypeID()===ti.LIGHTTYPEID_CLUSTERED_CONTAINER&&r.isSupported&&r._updateBatches(this.activeCamera).render()}),this._scene.addObjectRenderer(this)}_releaseRenderPassId(){for(let e=0;e<this.options.numPasses;++e)this._engine.releaseRenderPassId(this._renderPassIds[e]);this._renderPassIds.length=0}_createRenderPassId(){this._releaseRenderPassId();for(let e=0;e<this.options.numPasses;++e)this._renderPassIds[e]=this._engine.createRenderPassId(`${this.name}#${e}`)}_createSceneUBO(e,t){let i=this._scene.getEngine(),r=new xr(i,void 0,t,e,void 0,!1);return r.addUniform("viewProjection",16),t&&r.addUniform("viewProjectionR",16),r.addUniform("view",16),r.addUniform("projection",16),r.addUniform("vEyePosition",4),r.addUniform("inverseProjection",16),r}_getSceneUBO(){var r;this._currentFrameId!==this._engine.frameId&&(this._currentSceneUBOIndex=0,this._currentFrameId=this._engine.frameId),this._sceneUBOs||(this._sceneUBOs=[],this._sceneUBOIsMultiview=[]);let e=this._engine._currentRenderTarget,t=!!(e&&((r=e.texture)!=null&&r.isMultiview))||!!this._scene._multiviewSceneUboIsActive;if(this._currentSceneUBOIndex>=this._sceneUBOs.length){let s=this._sceneUBOs.length;this._sceneUBOs.push(this._createSceneUBO(`Scene ubo #${s} for ${this.name}`,t)),this._sceneUBOIsMultiview.push(t)}else this._sceneUBOIsMultiview[this._currentSceneUBOIndex]!==t&&(this._sceneUBOs[this._currentSceneUBOIndex].dispose(),this._sceneUBOs[this._currentSceneUBOIndex]=this._createSceneUBO(`Scene ubo #${this._currentSceneUBOIndex} for ${this.name}`,t),this._sceneUBOIsMultiview[this._currentSceneUBOIndex]=t);let i=this._sceneUBOs[this._currentSceneUBOIndex++];return i.unbindEffect(),i}resetRefreshCounter(){this._currentRefreshId=-1}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}shouldRender(){return this._engine.snapshotRendering?!0:this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}isReadyForRendering(e,t){this.prepareRenderList(),this.initRender(e,t);let i=this._checkReadiness();return this.finishRender(),i}prepareRenderList(){let e=this._scene;if(this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let t=0;t<this._waitingRenderList.length;t++){let i=this._waitingRenderList[t],r=e.getMeshById(i);r&&this.renderList.push(r)}}this._waitingRenderList=void 0}if(this.renderListPredicate){this.renderList?this.renderList.length=0:this.renderList=[];let t=this._scene.meshes;for(let i=0;i<t.length;i++){let r=t[i];this.renderListPredicate(r)&&this.renderList.push(r)}}this._currentApplyByPostProcessSetting=this._scene.imageProcessingConfiguration.applyByPostProcess,this._disableImageProcessing&&(this._scene.imageProcessingConfiguration._applyByPostProcess=this._disableImageProcessing)}initRender(e,t){var r;let i=(r=this.activeCamera)!=null?r:this._scene.activeCamera;this._currentSceneCamera=this._scene.activeCamera,this._useUBO&&(this._currentSceneUBO=this._scene.getSceneUniformBuffer(),this._currentSceneUBO.unbindEffect(),this._scene.setSceneUniformBuffer(this._getSceneUBO())),this.onInitRenderingObservable.notifyObservers(this),i&&(this.dontSetTransformationMatrix||this._scene.setTransformMatrix(i.getViewMatrix(),i.getProjectionMatrix(!0)),this._scene.activeCamera=i,this._engine.setViewport(i.rigParent?i.rigParent.viewport:i.viewport,e,t)),this._useUBO&&this._scene.finalizeSceneUbo(),this._defaultRenderListPrepared=!1}finishRender(){let e=this._scene;this._useUBO&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._disableImageProcessing&&(e.imageProcessingConfiguration._applyByPostProcess=this._currentApplyByPostProcessSetting),e.activeCamera=this._currentSceneCamera,this._currentSceneCamera&&(this.activeCamera&&this.activeCamera!==e.activeCamera&&e.setTransformMatrix(this._currentSceneCamera.getViewMatrix(),this._currentSceneCamera.getProjectionMatrix(!0)),this._engine.setViewport(this._currentSceneCamera.viewport)),e.resetCachedMaterial(),this.onFinishRenderingObservable.notifyObservers(this)}render(e=0,t=!1){var s,a;let i=this._engine.currentRenderPassId;if(this._engine.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e),this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1)this.onFastPathRenderObservable.notifyObservers(e);else{let o=this._prepareRenderingManager(e),l=(a=(s=this._scene).getOutlineRenderer)==null?void 0:a.call(s),c=l==null?void 0:l.enabled;l&&(l.enabled=this.enableOutlineRendering),this.onBeforeRenderingManagerRenderObservable.notifyObservers(e),this._renderingManager.render(this.customRenderFunction,o,this.renderParticles,this.renderSprites,this.renderDepthOnlyMeshes,this.renderOpaqueMeshes,this.renderAlphaTestMeshes,this.renderTransparentMeshes,this.customRenderTransparentSubMeshes),this.onAfterRenderingManagerRenderObservable.notifyObservers(e),l&&(l.enabled=c)}t||this.onAfterRenderObservable.notifyObservers(e),this._engine.currentRenderPassId=i}_checkReadiness(){let e=this._scene,t=this._engine.currentRenderPassId,i=!0;e.getViewMatrix()||e.updateTransformMatrix();let r=this.options.numPasses;for(let a=0;a<r&&i;a++){let o=this.renderList?this.renderList:e.frameGraph?e.meshes:e.getActiveMeshes().data,l=this.renderList||e.frameGraph?o.length:e.getActiveMeshes().length;this._engine.currentRenderPassId=this._renderPassIds[a],this.onBeforeRenderObservable.notifyObservers(a);let c=null,f=l;this.getCustomRenderList&&(c=this.getCustomRenderList(a,o,l),c&&(f=c.length)),c||(c=o),this.options.doNotChangeAspectRatio||e.updateTransformMatrix(!0);for(let d=0;d<f&&i;++d){let u=c[d];if(!(!u.isEnabled()||u.isBlocked||!u.isVisible||!u.subMeshes)){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(u,this.refreshRate,!0)){i=!1;continue}}else if(!u.isReady(!0)){i=!1;continue}}}this.onAfterRenderObservable.notifyObservers(a),r>1&&(e.incrementRenderId(),e.resetCachedMaterial())}let s=this.particleSystemList||e.particleSystems;for(let a of s)a.isReady()||(i=!1);return this._engine.currentRenderPassId=t,i}_prepareRenderingManager(e=0,t=!1){var u,h;let i=this._scene,r=null,s,a,o=this.renderList?this.renderList:i.frameGraph?i.meshes:i.getActiveMeshes().data,l=this.renderList||i.frameGraph?o.length:i.getActiveMeshes().length;if(this.getCustomRenderList&&(r=this.getCustomRenderList(e,o,l)),r)s=r.length,a=this.forceLayerMaskCheck;else{if(this._defaultRenderListPrepared&&!t&&!this._engine.isWebGPU)return o;this._defaultRenderListPrepared=!0,r=o,s=l,a=!this.renderList||this.forceLayerMaskCheck}let c=i.activeCamera,f=(u=this.cameraForLOD)!=null?u:c,d=(h=i.getBoundingBoxRenderer)==null?void 0:h.call(i);if(i._activeMeshesFrozen&&this._isFrozen){if(this._renderingManager.resetSprites(),this.enableBoundingBoxRendering&&d){d.reset();for(let m=0;m<this._activeBoundingBoxes.length;m++){let g=this._activeBoundingBoxes.data[m];d.renderList.push(g)}}return r}if(this._renderingManager.reset(),this._activeMeshes.reset(),this._activeBoundingBoxes.reset(),d&&d.reset(),this.renderMeshes){let m=i.getRenderId(),g=i.getFrameId();for(let p=0;p<s;p++){let _=r[p];if(_&&!_.isBlocked){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(_,this.refreshRate,!1)){this.resetRefreshCounter();continue}}else if(!_.isReady(this.refreshRate===0)){this.resetRefreshCounter();continue}let v;if(f){let S=_._internalAbstractMeshDataInfo._currentLOD.get(f);!S||S[1]!==g?(v=i.customLODSelector?i.customLODSelector(_,f):_.getLOD(f),S?(S[0]=v,S[1]=g):_._internalAbstractMeshDataInfo._currentLOD.set(f,[v,g])):v=S[0]}else v=_;if(!v)continue;v!==_&&v.billboardMode!==0&&v.computeWorldMatrix(),v._preActivateForIntermediateRendering(m);let E;if(a&&c?E=(_.layerMask&c.layerMask)===0:E=!1,_.isEnabled()&&_.isVisible&&_.subMeshes&&!E){if(this._activeMeshes.push(_),v._internalAbstractMeshDataInfo._wasActiveLastFrame=!0,v!==_&&v._activate(m,!0),this.enableBoundingBoxRendering&&d&&d._preActiveMesh(_),_._activate(m,!0)&&_.subMeshes.length){_.isAnInstance?_._internalAbstractMeshDataInfo._actAsRegularMesh&&(v=_):v._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,v._internalAbstractMeshDataInfo._isActiveIntermediate=!0,i._prepareSkeleton(v);for(let S=0;S<v.subMeshes.length;S++){let T=v.subMeshes[S];this.enableBoundingBoxRendering&&d&&d._evaluateSubMesh(_,T),this._renderingManager.dispatch(T,v)}}_._postActivate()}}}}if(this.enableBoundingBoxRendering&&d&&t)for(let m=0;m<d.renderList.length;m++){let g=d.renderList.data[m];this._activeBoundingBoxes.push(g)}if(this._scene.particlesEnabled&&this.renderParticles){this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);let m=this.particleSystemList||i.particleSystems;for(let g=0;g<m.length;g++){let p=m[g],_=p.emitter;!p.isStarted()||!_||_.position&&!_.isEnabled()||this._renderingManager.dispatchParticles(p)}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}return r}get renderingManager(){return this._renderingManager}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,r),this._renderingManager._useSceneAutoClearSetup=!1}clone(){let e=new n(this.name,this._scene,this.options);return this.renderList&&(e.renderList=this.renderList.slice(0)),e}dispose(){let e=this.renderList?this.renderList:this._scene.getActiveMeshes().data,t=this.renderList?this.renderList.length:this._scene.getActiveMeshes().length;for(let i=0;i<t;i++){let r=e[i];r&&r.getMaterialForRenderPass(this.renderPassId)!==void 0&&r.setMaterialForRenderPass(this.renderPassId,void 0)}if(this.onInitRenderingObservable.clear(),this.onFinishRenderingObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderingManagerRenderObservable.clear(),this.onAfterRenderingManagerRenderObservable.clear(),this.onFastPathRenderObservable.clear(),this._releaseRenderPassId(),this.renderList=null,this._sceneUBOs)for(let i of this._sceneUBOs)i.dispose();this._sceneUBOs=void 0,this._scene.removeObjectRenderer(this)}_rebuild(){this.refreshRate===n.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=n.REFRESHRATE_RENDER_ONCE)}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}};eo.REFRESHRATE_RENDER_ONCE=0;eo.REFRESHRATE_RENDER_ONEVERYFRAME=1;eo.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2});var Ps,Yu=y(()=>{Ll();Ps=class{static GetEffect(e){return e.getPipelineContext===void 0?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var r;this.effect=e,t!==void 0&&(this.defines=t),i&&((r=this.drawContext)==null||r.reset())}dispose(e=!1){var t;if(this.effect){let i=this.effect;e?i.dispose():Fo.SetImmediate(()=>{i.getEngine().onEndFrameObservable.addOnce(()=>{i.dispose()})}),this.effect=null}(t=this.drawContext)==null||t.dispose()}}});var Ok={};Be(Ok,{postprocessVertexShader:()=>xde});var TL,Dk,xde,AL=y(()=>{k();TL="postprocessVertexShader",Dk=`attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;x.ShadersStore[TL]||(x.ShadersStore[TL]=Dk);xde={name:TL,shader:Dk}});var wk={};Be(wk,{postprocessVertexShaderWGSL:()=>Rde});var xL,Nk,Rde,RL=y(()=>{k();xL="postprocessVertexShader",Nk=`attribute position: vec2<f32>;uniform scale: vec2<f32>;varying vUV: vec2<f32>;const madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}
`;x.ShadersStoreWGSL[xL]||(x.ShadersStoreWGSL[xL]=Nk);Rde={name:xL,shader:Nk}});var bL,LR,sn,Ku=y(()=>{qi();up();Si();Nu();Yu();AL();RL();bL={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]},LR=class{constructor(e,t=bL){var s,a;this._fullscreenViewport=new Go(0,0,1,1);let i=(s=t.positions)!=null?s:bL.positions,r=(a=t.indices)!=null?a:bL.indices;this.engine=e,this._vertexBuffers={[D.PositionKind]:new D(e,i,D.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(r),this._indexBufferLength=r.length,this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(r);for(let o in this._vertexBuffers)this._vertexBuffers[o]._rebuild()})}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e,t=!1,i=!1){this.engine.setState(!0),this.engine.depthCullingState.depthTest=t,this.engine.stencilState.stencilTest=i,this.engine.enableEffect(e.drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,this._indexBufferLength)}_isRenderTargetTexture(e){return e.renderTarget!==void 0}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();let i=t===null?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){let e=this._vertexBuffers[D.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[D.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}},sn=class n{static RegisterShaderCodeProcessing(e,t){if(!t){delete n._CustomShaderCodeProcessing[e!=null?e:""];return}n._CustomShaderCodeProcessing[e!=null?e:""]=t}static _GetShaderCodeProcessing(e){var t;return(t=n._CustomShaderCodeProcessing[e])!=null?t:n._CustomShaderCodeProcessing[""]}get name(){return this.options.name}set name(e){this.options.name=e}isReady(){var e,t;return(t=(e=this._drawWrapper.effect)==null?void 0:e.isReady())!=null?t:!1}get drawWrapper(){return this._drawWrapper}get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){var i,r;this.alphaMode=0,this.onEffectCreatedObservable=new re(void 0,!0),this.onApplyObservable=new re,this._shadersLoaded=!1,this._webGPUReady=!1,this._importPromises=[],this.options={...e,name:e.name||"effectWrapper",engine:e.engine,uniforms:e.uniforms||e.uniformNames||[],uniformNames:void 0,samplers:e.samplers||e.samplerNames||[],samplerNames:void 0,attributeNames:e.attributeNames||["position"],uniformBuffers:e.uniformBuffers||[],defines:e.defines||"",useShaderStore:e.useShaderStore||!1,vertexUrl:e.vertexUrl||e.vertexShader||"postprocess",vertexShader:void 0,fragmentShader:e.fragmentShader||"pass",indexParameters:e.indexParameters,blockCompilation:e.blockCompilation||!1,shaderLanguage:e.shaderLanguage||0,onCompiled:e.onCompiled||void 0,extraInitializations:e.extraInitializations||void 0,extraInitializationsAsync:e.extraInitializationsAsync||void 0,useAsPostProcess:(i=e.useAsPostProcess)!=null?i:!1,allowEmptySourceTexture:(r=e.allowEmptySourceTexture)!=null?r:!1},this.options.uniformNames=this.options.uniforms,this.options.samplerNames=this.options.samplers,this.options.vertexShader=this.options.vertexUrl,this.options.useAsPostProcess&&(!this.options.allowEmptySourceTexture&&this.options.samplers.indexOf("textureSampler")===-1&&this.options.samplers.push("textureSampler"),this.options.uniforms.indexOf("scale")===-1&&this.options.uniforms.push("scale")),e.vertexUrl||e.vertexShader?this._shaderPath={vertexSource:this.options.vertexShader}:(this.options.useAsPostProcess||(this.options.uniforms.push("scale"),this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)})),this._shaderPath={vertex:this.options.vertexShader}),this._shaderPath.fragmentSource=this.options.fragmentShader,this._shaderPath.spectorName=this.options.name,this.options.useShaderStore&&(this._shaderPath.fragment=this._shaderPath.fragmentSource,this._shaderPath.vertex||(this._shaderPath.vertex=this._shaderPath.vertexSource),delete this._shaderPath.fragmentSource,delete this._shaderPath.vertexSource),this.onApplyObservable.add(()=>{this.bind()}),this.options.useShaderStore||(this._onContextRestoredObserver=this.options.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})),this._drawWrapper=new Ps(this.options.engine),this._webGPUReady=this.options.shaderLanguage===1;let t=Array.isArray(this.options.defines)?this.options.defines.join(`
`):this.options.defines;this._postConstructor(this.options.blockCompilation,t,this.options.extraInitializations)}_gatherImports(e=!1,t){}_postConstructor(e,t=null,i,r){this._importPromises.length=0,r&&this._importPromises.push(...r);let s=this.options.engine.isWebGPU&&!n.ForceGLSL;this._gatherImports(s,this._importPromises),i!==void 0&&i(s,this._importPromises),s&&this._webGPUReady&&(this.options.shaderLanguage=1),e||this.updateEffect(t)}updateEffect(e=null,t=null,i=null,r,s,a,o,l){var u,h;let c=n._GetShaderCodeProcessing(this.name);if(c!=null&&c.defineCustomBindings){let m=(u=t==null?void 0:t.slice())!=null?u:[];m.push(...this.options.uniforms);let g=(h=i==null?void 0:i.slice())!=null?h:[];g.push(...this.options.samplers),e=c.defineCustomBindings(this.name,e,m,g),t=m,i=g}this.options.defines=e||"";let f=this._shadersLoaded||this._importPromises.length===0?void 0:async()=>{await Promise.all(this._importPromises),this._shadersLoaded=!0},d;this.options.extraInitializationsAsync?d=async()=>{f==null||f(),await this.options.extraInitializationsAsync()}:d=f,this.options.useShaderStore?this._drawWrapper.effect=this.options.engine.createEffect({vertex:o!=null?o:this._shaderPath.vertex,fragment:l!=null?l:this._shaderPath.fragment},{attributes:this.options.attributeNames,uniformsNames:t||this.options.uniforms,uniformBuffersNames:this.options.uniformBuffers,samplers:i||this.options.samplers,defines:e!==null?e:"",fallbacks:null,onCompiled:s!=null?s:this.options.onCompiled,onError:a!=null?a:null,indexParameters:r||this.options.indexParameters,processCodeAfterIncludes:c!=null&&c.processCodeAfterIncludes?(m,g)=>c.processCodeAfterIncludes(this.name,m,g):null,processFinalCode:c!=null&&c.processFinalCode?(m,g)=>c.processFinalCode(this.name,m,g):null,shaderLanguage:this.options.shaderLanguage,extraInitializationsAsync:d},this.options.engine):this._drawWrapper.effect=new pr(this._shaderPath,this.options.attributeNames,t||this.options.uniforms,i||this.options.samplerNames,this.options.engine,e,void 0,s||this.options.onCompiled,void 0,void 0,void 0,this.options.shaderLanguage,d),this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect)}bind(e=!1){var t,i;this.options.useAsPostProcess&&!e&&(this.options.engine.setAlphaMode(this.alphaMode),this.drawWrapper.effect.setFloat2("scale",1,1)),(i=(t=n._GetShaderCodeProcessing(this.name))==null?void 0:t.bindCustomBindings)==null||i.call(t,this.name,this._drawWrapper.effect)}dispose(e=!1){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.onEffectCreatedObservable.clear(),this._drawWrapper.dispose(!0)}};sn.ForceGLSL=!1;sn._CustomShaderCodeProcessing={}});var yL={};Be(yL,{passPixelShader:()=>bde});var ML,Fk,bde,IL=y(()=>{k();ML="passPixelShader",Fk=`varying vec2 vUV;uniform sampler2D textureSampler;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=texture2D(textureSampler,vUV);}`;x.ShadersStore[ML]||(x.ShadersStore[ML]=Fk);bde={name:ML,shader:Fk}});var Bk={};Be(Bk,{Dispose:()=>PL,DumpData:()=>DR,DumpDataAsync:()=>Cv,DumpFramebuffer:()=>CL,DumpTools:()=>Cde,EncodeImageAsync:()=>Ide});async function Mde(){var o,l;let n=(l=(o=Oe.LastCreatedEngine)==null?void 0:o.createCanvas(100,100))!=null?l:new OffscreenCanvas(100,100);n instanceof OffscreenCanvas&&te.Warn("DumpData: OffscreenCanvas will be used for dumping data. This may result in lossy alpha values.");let{ThinEngine:e}=await Promise.resolve().then(()=>(Is(),OG));if(!e.IsSupported)throw new Error("DumpData: No WebGL context available. Cannot dump data.");let t={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1},i=new e(n,!1,t);Oe.Instances.pop(),Oe.OnEnginesDisposedObservable.add(c=>{i&&c!==i&&!i.isDisposed&&Oe.Instances.length===0&&PL()}),i.getCaps().parallelShaderCompile=void 0;let r=new LR(i),{passPixelShader:s}=await Promise.resolve().then(()=>(IL(),yL)),a=new sn({engine:i,name:s.name,fragmentShader:s.shader,samplerNames:["textureSampler"]});return{canvas:n,dumpEngine:{engine:i,renderer:r,wrapper:a}}}async function yde(){return nd||(nd=Mde()),await nd}async function CL(n,e,t,i,r="image/png",s,a){let o=await t.readPixels(0,0,n,e),l=new Uint8Array(o.buffer);DR(n,e,l,i,r,s,!0,void 0,a)}async function Cv(n,e,t,i="image/png",r,s=!1,a=!1,o){if(t instanceof Float32Array){let f=new Uint8Array(t.length),d=t.length;for(;d--;){let u=t[d];f[d]=Math.round(Gt(u)*255)}t=f}let l=await Iv.EncodeImageAsync(t,n,e,i,s,o);r!==void 0&&pe.DownloadBlob(l,r),l.type!==i&&te.Warn(`DumpData: The requested mimeType '${i}' is not supported. The result has mimeType '${l.type}' instead.`);let c=await l.arrayBuffer();return a?c:`data:${i};base64,${gp(c)}`}function DR(n,e,t,i,r="image/png",s,a=!1,o=!1,l){s===void 0&&!i&&(s=""),Cv(n,e,t,r,s,a,o,l).then(c=>{i&&i(c)})}function PL(){nd&&(nd==null||nd.then(n=>{n.canvas instanceof HTMLCanvasElement&&n.canvas.remove(),n.dumpEngine&&(n.dumpEngine.engine.dispose(),n.dumpEngine.renderer.dispose(),n.dumpEngine.wrapper.dispose())}),nd=null)}var nd,Iv,Ide,Cde,Pde,LL=y(()=>{jt();Ku();Gi();ts();Yi();wt();Av();Yt();nd=null;Iv=class{static async EncodeImageAsync(e,t,i,r,s,a){let o=await yde(),l=o.dumpEngine;l.engine.setSize(t,i,!0);let c=l.engine.createRawTexture(e,t,i,5,!1,!s,1);return l.renderer.setViewport(),l.renderer.applyEffectWrapper(l.wrapper),l.wrapper.effect._bindTexture("textureSampler",c),l.renderer.draw(),c.dispose(),await new Promise((f,d)=>{pe.ToBlob(o.canvas,u=>{u?f(u):d(new Error("EncodeImageAsync: Failed to convert canvas to blob."))},r,a)})}};P([ia],Iv,"EncodeImageAsync",null);Ide=Iv.EncodeImageAsync;Cde={DumpData:DR,DumpDataAsync:Cv,DumpFramebuffer:CL,Dispose:PL},Pde=()=>{pe.DumpData=DR,pe.DumpDataAsync=Cv,pe.DumpFramebuffer=CL};Pde()});var jr,sd=y(()=>{Si();He();Kr();IR();Bo();Nu();wt();SL();pr.prototype.setDepthStencilTexture=function(n,e){this._engine.setDepthStencilTexture(this._samplers[n],this._uniforms[n],e,n)};jr=class n extends _e{get renderListPredicate(){return this._objectRenderer.renderListPredicate}set renderListPredicate(e){this._objectRenderer.renderListPredicate=e}get renderList(){return this._objectRenderer.renderList}set renderList(e){this._objectRenderer.renderList=e}get particleSystemList(){return this._objectRenderer.particleSystemList}set particleSystemList(e){this._objectRenderer.particleSystemList=e}get getCustomRenderList(){return this._objectRenderer.getCustomRenderList}set getCustomRenderList(e){this._objectRenderer.getCustomRenderList=e}get renderParticles(){return this._objectRenderer.renderParticles}set renderParticles(e){this._objectRenderer.renderParticles=e}get renderSprites(){return this._objectRenderer.renderSprites}set renderSprites(e){this._objectRenderer.renderSprites=e}get enableBoundingBoxRendering(){return this._objectRenderer.enableBoundingBoxRendering}set enableBoundingBoxRendering(e){this._objectRenderer.enableBoundingBoxRendering=e}get enableOutlineRendering(){return this._objectRenderer.enableOutlineRendering}set enableOutlineRendering(e){this._objectRenderer.enableOutlineRendering=e}get forceLayerMaskCheck(){return this._objectRenderer.forceLayerMaskCheck}set forceLayerMaskCheck(e){this._objectRenderer.forceLayerMaskCheck=e}get activeCamera(){return this._objectRenderer.activeCamera}set activeCamera(e){this._objectRenderer.activeCamera=e}get cameraForLOD(){return this._objectRenderer.cameraForLOD}set cameraForLOD(e){this._objectRenderer.cameraForLOD=e}get disableImageProcessing(){return this._objectRenderer.disableImageProcessing}set disableImageProcessing(e){this._objectRenderer.disableImageProcessing=e}get customIsReadyFunction(){return this._objectRenderer.customIsReadyFunction}set customIsReadyFunction(e){this._objectRenderer.customIsReadyFunction=e}get customRenderFunction(){return this._objectRenderer.customRenderFunction}set customRenderFunction(e){this._objectRenderer.customRenderFunction=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}get onBeforeRenderObservable(){return this._objectRenderer.onBeforeRenderObservable}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}get onAfterRenderObservable(){return this._objectRenderer.onAfterRenderObservable}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get _waitingRenderList(){return this._objectRenderer._waitingRenderList}set _waitingRenderList(e){this._objectRenderer._waitingRenderList=e}get renderPassId(){return this._objectRenderer.renderPassId}get renderPassIds(){return this._objectRenderer.renderPassIds}get currentRefreshId(){return this._objectRenderer.currentRefreshId}setMaterialForRendering(e,t){this._objectRenderer.setMaterialForRendering(e,t)}get isMulti(){var e,t;return(t=(e=this._renderTarget)==null?void 0:e.isMulti)!=null?t:!1}get renderTargetOptions(){return this._renderTargetOptions}get renderTarget(){return this._renderTarget}_onRatioRescale(){this._sizeRatio&&this.resize(this._initialSizeParameter)}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}get depthStencilTexture(){var e,t;return(t=(e=this._renderTarget)==null?void 0:e._depthStencilTexture)!=null?t:null}constructor(e,t,i,r=!1,s=!0,a=0,o=!1,l=_e.TRILINEAR_SAMPLINGMODE,c=!0,f=!1,d=!1,u=5,h=!1,m,g,p=!1,_=!1){var R,M,I,C,L,w,G;let v,E=!0,S,T=!1;if(typeof r=="object"){let O=r;r=!!O.generateMipMaps,s=(R=O.doNotChangeAspectRatio)!=null?R:!0,a=(M=O.type)!=null?M:0,o=!!O.isCube,l=(I=O.samplingMode)!=null?I:_e.TRILINEAR_SAMPLINGMODE,c=(C=O.generateDepthBuffer)!=null?C:!0,f=!!O.generateStencilBuffer,d=!!O.isMulti,u=(L=O.format)!=null?L:5,h=!!O.delayAllocation,m=O.samples,g=O.creationFlags,p=!!O.noColorAttachment,_=!!O.useSRGBBuffer,v=O.colorAttachment,E=(w=O.gammaSpace)!=null?w:E,S=O.existingObjectRenderer,T=!!O.enableClusteredLights}if(super(null,i,!r,void 0,l,void 0,void 0,void 0,void 0,u),this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new re,this.onAfterUnbindObservable=new re,this.onClearObservable=new re,this.onResizeObservable=new re,this._cleared=!1,this.skipInitialClear=!1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this._dontDisposeObjectRenderer=!1,this.boundingBoxPosition=b.Zero(),this._disableEngineStages=!1,this._dumpToolsLoading=!1,i=this.getScene(),!i)return;let A=this.getScene().getEngine();this._gammaSpace=E,this._coordinatesMode=_e.PROJECTION_MODE,this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._dontDisposeObjectRenderer=!!S,this._processSizeParameter(t),this._objectRenderer=S!=null?S:new eo(e,i,{numPasses:o?6:this.getRenderLayers()||1,doNotChangeAspectRatio:s,enableClusteredLights:T}),this._onBeforeRenderingManagerRenderObserver=this._objectRenderer.onBeforeRenderingManagerRenderObservable.add(()=>{var N;let O=this._scene;if(!this._disableEngineStages)for(let B of O._beforeRenderTargetClearStage)B.action(this,this._currentFaceIndex,this._currentLayer);if(this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(A):this.skipInitialClear||A.clear((N=this.clearColor)!=null?N:O.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||O.updateTransformMatrix(!0),!this._disableEngineStages)for(let B of O._beforeRenderTargetDrawStage)B.action(this,this._currentFaceIndex,this._currentLayer);A._debugPushGroup&&A._debugPushGroup(`Render to ${this.name} (face #${this._currentFaceIndex} layer #${this._currentLayer})`)}),this._onAfterRenderingManagerRenderObserver=this._objectRenderer.onAfterRenderingManagerRenderObservable.add(()=>{var N,B,V,q;if(A._debugPopGroup&&A._debugPopGroup(),!this._disableEngineStages)for(let K of this._scene._afterRenderTargetDrawStage)K.action(this,this._currentFaceIndex,this._currentLayer);let O=(B=(N=this._texture)==null?void 0:N.generateMipMaps)!=null?B:!1;if(this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,(V=this._renderTarget)!=null?V:void 0,this._currentFaceIndex,this._postProcesses,this.ignoreCameraViewport):this._currentUseCameraPostProcess&&this._scene.postProcessManager._finalizeFrame(!1,(q=this._renderTarget)!=null?q:void 0,this._currentFaceIndex),!this._disableEngineStages)for(let K of this._scene._afterRenderTargetPostProcessStage)K.action(this,this._currentFaceIndex,this._currentLayer);this._texture&&(this._texture.generateMipMaps=O),this._doNotChangeAspectRatio||this._scene.updateTransformMatrix(!0),this._currentDumpForDebug&&(this._dumpTools?this._dumpTools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),A):te.Error("dumpTools module is still being loaded. To speed up the process import dump tools directly in your project"))}),this._onFastPathRenderObserver=this._objectRenderer.onFastPathRenderObservable.add(()=>{this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(A):this.skipInitialClear||A.clear(this.clearColor||this._scene.clearColor,!0,!0,!0)}),this._resizeObserver=A.onResizeObservable.add(()=>{}),this._generateMipMaps=!!r,this._doNotChangeAspectRatio=s,!d&&(this._renderTargetOptions={generateMipMaps:r,type:a,format:(G=this._format)!=null?G:void 0,samplingMode:this.samplingMode,generateDepthBuffer:c,generateStencilBuffer:f,samples:m,creationFlags:g,noColorAttachment:p,useSRGBBuffer:_,colorAttachment:v,label:this.name},this.samplingMode===_e.NEAREST_SAMPLINGMODE&&(this.wrapU=_e.CLAMP_ADDRESSMODE,this.wrapV=_e.CLAMP_ADDRESSMODE),h||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=_e.INVCUBIC_MODE,this._textureMatrix=Q.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,m!==void 0&&(this.samples=m)))}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,a){var o;(o=this._renderTarget)==null||o.createDepthStencilTexture(e,t,i,r,s,a)}_processSizeParameter(e){if(e.ratio){this._sizeRatio=e.ratio;let t=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(t.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(t.getRenderHeight(),this._sizeRatio)}}else this._size=e}get samples(){var e,t;return(t=(e=this._renderTarget)==null?void 0:e.samples)!=null?t:this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}addPostProcess(e){if(!this._postProcessManager){let t=this.getScene();if(!t)return;this._postProcessManager=new Dc(t),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(let t of this._postProcesses)t.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;let t=this._postProcesses.indexOf(e);t!==-1&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}resetRefreshCounter(){this._objectRenderer.resetRefreshCounter()}get refreshRate(){return this._objectRenderer.refreshRate}set refreshRate(e){this._objectRenderer.refreshRate=e}_shouldRender(){return this._objectRenderer.shouldRender()}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){let e=this._size.layers;if(e)return e;let t=this._size.depth;return t||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){let t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var r;let t=this.isCube;(r=this._renderTarget)==null||r.dispose(),this._renderTarget=null;let i=this.getScene();i&&(this._processSizeParameter(e),t?this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,this._renderTargetOptions.samples!==void 0&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){this._dumpToolsLoading||(this._dumpToolsLoading=!0,Promise.resolve().then(()=>(LL(),Bk)).then(t=>this._dumpTools=t)),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight());let e=this._objectRenderer._checkReadiness();return this.onAfterUnbindObservable.notifyObservers(this),this._objectRenderer.finishRender(),e}_render(e=!1,t=!1){let i=this.getScene();if(!i)return;this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses);let r=i.getEngine();if(r._debugPushGroup&&r._debugPushGroup(`Render to ${this.name}`),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight()),(this.is2DArray||this.is3D)&&!this.isMulti)for(let s=0;s<this.getRenderLayers();s++)this._renderToTarget(0,e,t,s),i.incrementRenderId(),i.resetCachedMaterial();else if(this.isCube&&!this.isMulti)for(let s=0;s<6;s++)this._renderToTarget(s,e,t),i.incrementRenderId(),i.resetCachedMaterial();else this._renderToTarget(0,e,t);this.onAfterUnbindObservable.notifyObservers(this),this._objectRenderer.finishRender(),r._debugPopGroup&&r._debugPopGroup()}_bestReflectionRenderTargetDimension(e,t){let r=e*t,s=iL(r+16384/(128+r));return Math.min(cR(e),s)}_bindFrameBuffer(e=0,t=0){let i=this.getScene();if(!i)return;let r=i.getEngine();this._renderTarget&&r.bindFramebuffer(this._renderTarget,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,t)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindFramebuffer(this._renderTarget,this.isCube,()=>{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses)||this._bindFrameBuffer(t,i):(!r||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0){let s=this.getScene();if(!s)return;let a=s.getEngine();this._currentFaceIndex=e,this._currentLayer=r,this._currentUseCameraPostProcess=t,this._currentDumpForDebug=i,this._prepareFrame(s,e,r,t),this._objectRenderer.render(e+r,!0),this._unbindFrameBuffer(a,e),this._texture&&this.isCube&&e===5&&a.generateMipMapsForCubemap(this._texture,!0)}setRenderingOrder(e,t=null,i=null,r=null){this._objectRenderer.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._objectRenderer.setRenderingAutoClearDepthStencil(e,t)}clone(){let e=this.getSize(),t=new n(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;let e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t<this.renderList.length;t++)e.renderList.push(this.renderList[t].id);return e}disposeFramebufferObjects(){var e;(e=this._renderTarget)==null||e.dispose(!0)}releaseInternalTexture(){var e;(e=this._renderTarget)==null||e.releaseTextures(),this._texture=null}dispose(){var i;this.onResizeObservable.clear(),this.onClearObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this._prePassRenderTarget&&this._prePassRenderTarget.dispose(),this._objectRenderer.onBeforeRenderingManagerRenderObservable.remove(this._onBeforeRenderingManagerRenderObserver),this._objectRenderer.onAfterRenderingManagerRenderObservable.remove(this._onAfterRenderingManagerRenderObserver),this._objectRenderer.onFastPathRenderObservable.remove(this._onFastPathRenderObserver),this._dontDisposeObjectRenderer||this._objectRenderer.dispose(),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null);let e=this.getScene();if(!e)return;let t=e.customRenderTargets.indexOf(this);t>=0&&e.customRenderTargets.splice(t,1);for(let r of e.cameras)t=r.customRenderTargets.indexOf(this),t>=0&&r.customRenderTargets.splice(t,1);(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this._objectRenderer._rebuild(),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._objectRenderer.freeRenderingGroups()}getViewCount(){return 1}};jr.REFRESHRATE_RENDER_ONCE=eo.REFRESHRATE_RENDER_ONCE;jr.REFRESHRATE_RENDER_ONEVERYFRAME=eo.REFRESHRATE_RENDER_ONEVERYFRAME;jr.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=eo.REFRESHRATE_RENDER_ONEVERYTWOFRAMES;_e._CreateRenderTargetTexture=(n,e,t,i,r)=>new jr(n,e,t,i)});var Ni,Oc=y(()=>{jt();Wo();Si();He();Nu();Yt();Or();ir();Yr();Bo();Ku();ye.prototype.setTextureFromPostProcess=function(n,e,t){var r;let i=null;e&&(e._forcedOutputTexture?i=e._forcedOutputTexture:e._textures.data[e._currentRenderTextureInd]&&(i=e._textures.data[e._currentRenderTextureInd])),this._bindTexture(n,(r=i==null?void 0:i.texture)!=null?r:null,t)};ye.prototype.setTextureFromPostProcessOutput=function(n,e,t){var i,r;this._bindTexture(n,(r=(i=e==null?void 0:e._outputTexture)==null?void 0:i.texture)!=null?r:null,t)};pr.prototype.setTextureFromPostProcess=function(n,e){this._engine.setTextureFromPostProcess(this._samplers[n],e,n)};pr.prototype.setTextureFromPostProcessOutput=function(n,e){this._engine.setTextureFromPostProcessOutput(this._samplers[n],e,n)};Ni=class n{static get ForceGLSL(){return sn.ForceGLSL}static set ForceGLSL(e){sn.ForceGLSL=e}static RegisterShaderCodeProcessing(e,t){sn.RegisterShaderCodeProcessing(e,t)}get name(){return this._effectWrapper.name}set name(e){this._effectWrapper.name=e}get alphaMode(){return this._effectWrapper.alphaMode}set alphaMode(e){this._effectWrapper.alphaMode=e}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach(t=>{t.setSamples(this._samples)})}get shaderLanguage(){return this._shaderLanguage}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,r,s,a,o=1,l,c,f=null,d=0,u="postprocess",h,m=!1,g=5,p,_){var T,A,R,M,I,C,L,w,G,O,N,B;this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this.doNotSerialize=!1,this._webGPUReady=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Qi(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new Fe(1,1),this._texelSize=Fe.Zero(),this.onActivateObservable=new re,this.onSizeChangedObservable=new re,this.onApplyObservable=new re,this.onBeforeRenderObservable=new re,this.onAfterRenderObservable=new re,this.onDisposeObservable=new re;let v=1,E=null,S;if(i&&!Array.isArray(i)){let V=i;i=(T=V.uniforms)!=null?T:null,r=(A=V.samplers)!=null?A:null,v=(R=V.size)!=null?R:1,a=(M=V.camera)!=null?M:null,o=(I=V.samplingMode)!=null?I:1,l=V.engine,c=V.reusable,f=Array.isArray(V.defines)?V.defines.join(`
`):(C=V.defines)!=null?C:null,d=(L=V.textureType)!=null?L:0,u=(w=V.vertexUrl)!=null?w:"postprocess",h=V.indexParameters,m=(G=V.blockCompilation)!=null?G:!1,g=(O=V.textureFormat)!=null?O:5,p=(N=V.shaderLanguage)!=null?N:0,E=(B=V.uniformBuffers)!=null?B:null,_=V.extraInitializations,S=V.effectWrapper}else s&&(typeof s=="number"?v=s:v={width:s.width,height:s.height});if(this._useExistingThinPostProcess=!!S,this._effectWrapper=S!=null?S:new sn({name:e,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:t,engine:l||(a==null?void 0:a.getScene().getEngine()),uniforms:i,samplers:r,uniformBuffers:E,defines:f,vertexUrl:u,indexParameters:h,blockCompilation:!0,shaderLanguage:p,extraInitializations:void 0}),this.name=e,this.onEffectCreatedObservable=this._effectWrapper.onEffectCreatedObservable,a!=null?(this._camera=a,this._scene=a.getScene(),a.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.addPostProcess(this),this.uniqueId=this._scene.getUniqueId()):l&&(this._engine=l,this._engine.postProcesses.push(this)),this._options=v,this.renderTargetSamplingMode=o||1,this._reusable=c||!1,this._textureType=d,this._textureFormat=g,this._shaderLanguage=p||0,this._samplers=r||[],this._samplers.indexOf("textureSampler")===-1&&this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=u,this._parameters=i||[],this._parameters.indexOf("scale")===-1&&this._parameters.push("scale"),this._uniformBuffers=E||[],this._indexParameters=h,!this._useExistingThinPostProcess){this._webGPUReady=this._shaderLanguage===1;let V=[];this._gatherImports(this._engine.isWebGPU&&!n.ForceGLSL,V),this._effectWrapper._webGPUReady=this._webGPUReady,this._effectWrapper._postConstructor(m,f,_,V)}}_gatherImports(e=!1,t){e&&this._webGPUReady?t.push(Promise.all([Promise.resolve().then(()=>(RL(),wk))])):t.push(Promise.all([Promise.resolve().then(()=>(AL(),Ok))]))}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._effectWrapper.drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){this._textures.length==0&&(this._textures=new Qi(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,s,a,o,l){this._effectWrapper.updateEffect(e,t,i,r,s,a,o,l),this._postProcessDefines=Array.isArray(this._effectWrapper.options.defines)?this._effectWrapper.options.defines.join(`
`):this._effectWrapper.options.defines}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s<this._textureCache.length;s++)if(this._textureCache[s].texture.width===e.width&&this._textureCache[s].texture.height===e.height&&this._textureCache[s].postProcessChannel===i&&this._textureCache[s].texture._generateDepthBuffer===t.generateDepthBuffer&&this._textureCache[s].texture.samples===t.samples)return this._textureCache[s].texture;let r=this._engine.createRenderTargetTexture(e,t);return this._textureCache.push({texture:r,postProcessChannel:i,lastUsedRenderId:-1}),r}_flushTextureCache(){let e=this._renderId;for(let t=this._textureCache.length-1;t>=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let i=!1;for(let r=0;r<this._textures.length;r++)if(this._textures.data[r]===this._textureCache[t].texture){i=!0;break}i||(this._textureCache[t].texture.dispose(),this._textureCache.splice(t,1))}}resize(e,t,i=null,r=!1,s=!1){this._textures.length>0&&this._textures.reset(),this.width=e,this.height=t;let a=null;if(i){for(let c=0;c<i._postProcesses.length;c++)if(i._postProcesses[c]!==null){a=i._postProcesses[c];break}}let o={width:this.width,height:this.height},l={generateMipMaps:r,generateDepthBuffer:s||a===this,generateStencilBuffer:(s||a===this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType,format:this._textureFormat,samples:this._samples,label:"PostProcessRTT-"+this.name};this._textures.push(this._createRenderTargetTexture(o,l,0)),this._reusable&&this._textures.push(this._createRenderTargetTexture(o,l,1)),this._texelSize.copyFromFloats(1/this.width,1/this.height),this.onSizeChangedObservable.notifyObservers(this)}_getTarget(){let e;if(this._shareOutputWithPostProcess)e=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)e=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{e=this.inputTexture;let t;for(let i=0;i<this._textureCache.length;i++)if(this._textureCache[i].texture===e){t=this._textureCache[i];break}t&&(t.lastUsedRenderId=this._renderId)}return e}activate(e,t=null,i){var m,g,p;let r=e===null||e.cameraRigMode!==void 0?e||this._camera:null,s=(m=r==null?void 0:r.getScene())!=null?m:e,a=s.getEngine(),o=a.getCaps().maxTextureSize,l=(t?t.width:this._engine.getRenderWidth(!0))*this._options|0,c=(t?t.height:this._engine.getRenderHeight(!0))*this._options|0,f=this._options.width||l,d=this._options.height||c,u=this.renderTargetSamplingMode!==7&&this.renderTargetSamplingMode!==1&&this.renderTargetSamplingMode!==2,h=null;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){let _=a.currentViewport;_&&(f*=_.width,d*=_.height)}(u||this.alwaysForcePOT)&&(this._options.width||(f=a.needPOTTextures?Un(f,o,this.scaleMode):f),this._options.height||(d=a.needPOTTextures?Un(d,o,this.scaleMode):d)),(this.width!==f||this.height!==d||!(h=this._getTarget()))&&this.resize(f,d,r,u,i),this._textures.forEach(_=>{_.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(_,this.samples)}),this._flushTextureCache(),this._renderId++}return h||(h=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(l/f,c/d),this._engine.bindFramebuffer(h,0,l,c,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(h,0,void 0,void 0,this.forceFullscreenViewport)),(p=(g=this._engine)._debugInsertMarker)==null||p.call(g,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(r),this.autoClear&&(this.alphaMode===0||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),h}get isSupported(){return this._effectWrapper.drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._effectWrapper.isReady()}apply(){if(!this._effectWrapper.isReady())return null;this._engine.enableEffect(this._effectWrapper.drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),this._engine.setAlphaMode(this.alphaMode);let e;return this._shareOutputWithPostProcess?e=this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?e=this._forcedOutputTexture:e=this.inputTexture,this.externalTextureSamplerBinding||this._effectWrapper.drawWrapper.effect._bindTexture("textureSampler",e==null?void 0:e.texture),this._effectWrapper.drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._effectWrapper.drawWrapper.effect),this._effectWrapper.bind(!0),this._effectWrapper.drawWrapper.effect}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}this._disposeTextureCache(),this._textures.dispose()}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return this._prePassEffectConfiguration?(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0):!1}dispose(e){e=e||this._camera,this._useExistingThinPostProcess||this._effectWrapper.dispose(),this._disposeTextures(),this._scene&&this._scene.removePostProcess(this);let t;if(this._parentContainer&&(t=this._parentContainer.postProcesses.indexOf(this),t>-1&&this._parentContainer.postProcesses.splice(t,1),this._parentContainer=null),t=this._engine.postProcesses.indexOf(this),t!==-1&&this._engine.postProcesses.splice(t,1),this.onDisposeObservable.notifyObservers(),!!e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),t===0&&e._postProcesses.length>0){let i=this._camera._getFirstPostProcess();i&&i.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear(),this.onEffectCreatedObservable.clear()}}serialize(){let e=at.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.uniformBuffers=this._uniformBuffers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){let e=this.serialize();e._engine=this._engine,e.cameraId=null;let t=n.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){let r=Vn(e.customType);if(!r||!r._Parse)return null;let s=t?t.getCameraById(e.cameraId):null;return r._Parse(e,s,t,i)}static _Parse(e,t,i,r){return at.Parse(()=>new n(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat),e,i,r)}};P([F()],Ni.prototype,"uniqueId",void 0);P([F()],Ni.prototype,"name",null);P([F()],Ni.prototype,"width",void 0);P([F()],Ni.prototype,"height",void 0);P([F()],Ni.prototype,"renderTargetSamplingMode",void 0);P([pp()],Ni.prototype,"clearColor",void 0);P([F()],Ni.prototype,"autoClear",void 0);P([F()],Ni.prototype,"forceAutoClearInAlphaMode",void 0);P([F()],Ni.prototype,"alphaMode",null);P([F()],Ni.prototype,"alphaConstants",void 0);P([F()],Ni.prototype,"enablePixelPerfectMode",void 0);P([F()],Ni.prototype,"forceFullscreenViewport",void 0);P([F()],Ni.prototype,"scaleMode",void 0);P([F()],Ni.prototype,"alwaysForcePOT",void 0);P([F("samples")],Ni.prototype,"_samples",void 0);P([F()],Ni.prototype,"adaptScaleToCurrentViewport",void 0);zt("BABYLON.PostProcess",Ni)});var Vk={};Be(Vk,{passPixelShaderWGSL:()=>Lde});var DL,Uk,Lde,Gk=y(()=>{k();DL="passPixelShader",Uk=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);}`;x.ShadersStoreWGSL[DL]||(x.ShadersStoreWGSL[DL]=Uk);Lde={name:DL,shader:Uk}});var zk={};Be(zk,{passCubePixelShaderWGSL:()=>Dde});var OL,kk,Dde,Wk=y(()=>{k();OL="passCubePixelShader",kk=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube<f32>;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f=input.vUV*2.0-1.0;
#ifdef POSITIVEX
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(1.001,uv.y,uv.x));
#endif
#ifdef NEGATIVEX
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(-1.001,uv.y,uv.x));
#endif
#ifdef POSITIVEY
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,1.001,uv.x));
#endif
#ifdef NEGATIVEY
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,-1.001,uv.x));
#endif
#ifdef POSITIVEZ
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,1.001));
#endif
#ifdef NEGATIVEZ
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,-1.001));
#endif
}`;x.ShadersStoreWGSL[OL]||(x.ShadersStoreWGSL[OL]=kk);Dde={name:OL,shader:kk}});var Xk={};Be(Xk,{passCubePixelShader:()=>Ode});var NL,Hk,Ode,Yk=y(()=>{k();NL="passCubePixelShader",Hk=`varying vec2 vUV;uniform samplerCube textureSampler;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec2 uv=vUV*2.0-1.0;
#ifdef POSITIVEX
gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));
#endif
#ifdef NEGATIVEX
gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));
#endif
#ifdef POSITIVEY
gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));
#endif
#ifdef NEGATIVEY
gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));
#endif
#ifdef POSITIVEZ
gl_FragColor=textureCube(textureSampler,vec3(uv,1.001));
#endif
#ifdef NEGATIVEZ
gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));
#endif
}`;x.ShadersStore[NL]||(x.ShadersStore[NL]=Hk);Ode={name:NL,shader:Hk}});var Nc,Pv,wL=y(()=>{Ku();Yi();Nc=class n extends sn{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(()=>(Gk(),Vk))]))):t.push(Promise.all([Promise.resolve().then(()=>(IL(),yL))])),super._gatherImports(e,t)}constructor(e,t=null,i){let r={name:e,engine:t||Oe.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,...i};r.engine||(r.engine=Oe.LastCreatedEngine),super(r)}};Nc.FragmentUrl="pass";Pv=class n extends sn{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(()=>(Wk(),zk))]))):t.push(Promise.all([Promise.resolve().then(()=>(Yk(),Xk))])),super._gatherImports(e,t)}constructor(e,t=null,i){super({...i,name:e,engine:t||Oe.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,defines:"#define POSITIVEX"}),this._face=0}get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ");break}}};Pv.FragmentUrl="passCube"});var ju,FL,BL=y(()=>{jt();Oc();Yr();ir();Or();wL();Yt();ju=class n extends Ni{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,s,a,o=0,l=!1){let c={size:typeof t=="number"?t:void 0,camera:i,samplingMode:r,engine:s,reusable:a,textureType:o,blockCompilation:l,...t};super(e,Nc.FragmentUrl,{effectWrapper:typeof t=="number"||!t.effectWrapper?new Nc(e,s,c):void 0,...c})}static _Parse(e,t,i,r){return at.Parse(()=>new n(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}};zt("BABYLON.PassPostProcess",ju);FL=class n extends Ni{get face(){return this._effectWrapper.face}set face(e){this._effectWrapper.face=e}getClassName(){return"PassCubePostProcess"}constructor(e,t,i=null,r,s,a,o=0,l=!1){let c={size:typeof t=="number"?t:void 0,camera:i,samplingMode:r,engine:s,reusable:a,textureType:o,blockCompilation:l,...t};super(e,Nc.FragmentUrl,{effectWrapper:typeof t=="number"||!t.effectWrapper?new Pv(e,s,c):void 0,...c})}static _Parse(e,t,i,r){return at.Parse(()=>new n(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}};P([F()],FL.prototype,"face",null);ye._RescalePostProcessFactory=n=>new ju("rescale",1,null,2,n,!1,0)});function jk(n,e,t,i,r,s,a,o){let l=e.getEngine();return e.isReady=!1,r=r!=null?r:e.samplingMode,i=i!=null?i:e.type,s=s!=null?s:e.format,a=a!=null?a:e.width,o=o!=null?o:e.height,i===-1&&(i=0),new Promise(c=>{let f=new Ni("postprocess",n,null,null,1,null,r,l,!1,void 0,i,void 0,null,!1,s);f.externalTextureSamplerBinding=!0;let d=l.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:i,format:s});f.onEffectCreatedObservable.addOnce(u=>{u.executeWhenCompiled(()=>{f.onApply=h=>{h._bindTexture("textureSampler",e),h.setFloat2("scale",1,1)},t.postProcessManager.directRender([f],d,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(e),f&&f.dispose(),d._swapAndDie(e),e.type=i,e.format=5,e.isReady=!0,c(e)})})})}function Zu(n){OR||(OR=new Float32Array(1),Kk=new Int32Array(OR.buffer)),OR[0]=n;let e=Kk[0],t=e>>16&32768,i=e>>12&2047,r=e>>23&255;return r<103?t:r>142?(t|=31744,t|=(r==255?0:1)&&e&8388607,t):r<113?(i|=2048,t|=(i>>114-r)+(i>>113-r&1),t):(t|=r-112<<10|i>>1,t+=i&1,t)}function wc(n){let e=(n&32768)>>15,t=(n&31744)>>10,i=n&1023;return t===0?(e?-1:1)*Math.pow(2,-14)*(i/Math.pow(2,10)):t==31?i?NaN:(e?-1:1)*(1/0):(e?-1:1)*Math.pow(2,t-15)*(1+i/Math.pow(2,10))}var OR,Kk,UL=y(()=>{Kr();sd();BL();Oc();ts()});function GL(n){return n.split(" ").filter(e=>e!=="").map(e=>parseFloat(e))}function VL(n,e,t){for(;t.length!==e;){let i=GL(n.lines[n.index++]);t.push(...i)}}function Nde(n,e,t){let i=0,r=0,s=0,a=0,o=0,l=0;for(let _=0;_<n.numberOfHorizontalAngles-1;_++)if(t<n.horizontalAngles[_+1]||_===n.numberOfHorizontalAngles-2){r=_,s=n.horizontalAngles[_],a=n.horizontalAngles[_+1];break}for(let _=0;_<n.numberOfVerticalAngles-1;_++)if(e<n.verticalAngles[_+1]||_===n.numberOfVerticalAngles-2){i=_,o=n.verticalAngles[_],l=n.verticalAngles[_+1];break}let c=a-s,f=l-o;if(f===0)return 0;let d=c===0?0:(t-s)/c,u=(e-o)/f,h=c===0?r:r+1,m=Uo(n.candelaValues[r][i],n.candelaValues[h][i],d),g=Uo(n.candelaValues[r][i+1],n.candelaValues[h][i+1],d);return Uo(m,g,u)}function Zk(n){let i={lines:new TextDecoder("utf-8").decode(n).split(`
`),index:0},r={version:i.lines[0],candelaValues:[],horizontalAngles:[],verticalAngles:[],numberOfHorizontalAngles:0,numberOfVerticalAngles:0};for(i.index=1;i.lines.length>0&&!i.lines[i.index].includes("TILT=");)i.index++;i.lines[i.index].includes("INCLUDE"),i.index++;let s=GL(i.lines[i.index++]);r.numberOfLights=s[0],r.lumensPerLamp=s[1],r.candelaMultiplier=s[2],r.numberOfVerticalAngles=s[3],r.numberOfHorizontalAngles=s[4],r.photometricType=s[5],r.unitsType=s[6],r.width=s[7],r.length=s[8],r.height=s[9];let a=GL(i.lines[i.index++]);r.ballastFactor=a[0],r.fileGenerationType=a[1],r.inputWatts=a[2];for(let m=0;m<r.numberOfHorizontalAngles;m++)r.candelaValues[m]=[];VL(i,r.numberOfVerticalAngles,r.verticalAngles),VL(i,r.numberOfHorizontalAngles,r.horizontalAngles);for(let m=0;m<r.numberOfHorizontalAngles;m++)VL(i,r.numberOfVerticalAngles,r.candelaValues[m]);let o=-1;for(let m=0;m<r.numberOfHorizontalAngles;m++)for(let g=0;g<r.numberOfVerticalAngles;g++)r.candelaValues[m][g]*=r.candelaValues[m][g]*r.candelaMultiplier*r.ballastFactor*r.fileGenerationType,o=Math.max(o,r.candelaValues[m][g]);if(o>0)for(let m=0;m<r.numberOfHorizontalAngles;m++)for(let g=0;g<r.numberOfVerticalAngles;g++)r.candelaValues[m][g]/=o;let l=180,c=l*2,f=c*l,d=new Float32Array(c*l),u=r.horizontalAngles[0],h=r.horizontalAngles[r.numberOfHorizontalAngles-1];for(let m=0;m<f;m++){let g=m%c,p=Math.floor(m/c);h-u!==0&&(g<u||g>=h)&&(g%=h*2,g>h&&(g=h*2-g)),d[p+g*l]=Nde(r,p,g)}return{width:c/2,height:1,data:d}}var qk=y(()=>{ts()});var Qk={};Be(Qk,{_IESTextureLoader:()=>kL});var kL,$k=y(()=>{qk();kL=class{constructor(){this.supportCascades=!1}loadCubeData(){throw".ies not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=Zk(r);i(s.width,s.height,!!t.useMipMaps,!1,()=>{let a=t.getEngine();t.type=1,t.format=6,t._gammaSpace=!1,a._uploadDataToTextureDirectly(t,s.data)})}}});var Jk={};Be(Jk,{_DDSTextureLoader:()=>zL});var zL,ez=y(()=>{Ev();WL();zL=class{constructor(){this.supportCascades=!0}loadCubeData(e,t,i,r){let s=t.getEngine(),a,o=!1,l=1e3;if(Array.isArray(e))for(let c=0;c<e.length;c++){let f=e[c];a=Ho.GetDDSInfo(f),t.width=a.width,t.height=a.height,o=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&t.generateMipMaps,s._unpackFlipY(a.isCompressed),Ho.UploadDDSLevels(s,t,f,a,o,6,-1,c),!a.isFourCC&&a.mipmapCount===1?s.generateMipMapsForCubemap(t):l=a.mipmapCount-1}else{let c=e;a=Ho.GetDDSInfo(c),t.width=a.width,t.height=a.height,i&&(a.sphericalPolynomial=new wl),o=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&t.generateMipMaps,s._unpackFlipY(a.isCompressed),Ho.UploadDDSLevels(s,t,c,a,o,6),!a.isFourCC&&a.mipmapCount===1?s.generateMipMapsForCubemap(t,!1):l=a.mipmapCount-1}s._setCubeMapTextureParams(t,o,l),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r({isDDS:!0,width:t.width,info:a,data:e,texture:t})}loadData(e,t,i){let r=Ho.GetDDSInfo(e),s=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&Math.max(r.width,r.height)>>r.mipmapCount-1===1;i(r.width,r.height,s,r.isFourCC,()=>{Ho.UploadDDSLevels(t.getEngine(),t,e,r,s,1)})}}});function tz(){let n={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFBC4:4,cTFBC5:5,cTFBC7:6,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFATC_RGB:11,cTFATC_RGBA_INTERPOLATED_ALPHA:12,cTFRGBA32:13,cTFRGB565:14,cTFBGR565:15,cTFRGBA4444:16,cTFFXT1_RGB:17,cTFPVRTC2_4_RGB:18,cTFPVRTC2_4_RGBA:19,cTFETC2_EAC_R11:20,cTFETC2_EAC_RG11:21},e=null;onmessage=a=>{if(a.data.action==="init"){if(a.data.url)try{importScripts(a.data.url)}catch(o){postMessage({action:"error",error:o})}e||(e=BASIS({wasmBinary:a.data.wasmBinary})),e!==null&&e.then(o=>{BASIS=o,o.initializeBasis(),postMessage({action:"init"})})}else if(a.data.action==="transcode"){let o=a.data.config,l=a.data.imageData,c=new BASIS.BasisFile(l),f=i(c),d=a.data.ignoreSupportedFormats?null:t(a.data.config,f),u=!1;d===null&&(u=!0,d=f.hasAlpha?n.cTFBC3:n.cTFBC1);let h=!0;c.startTranscoding()||(h=!1);let m=[];for(let g=0;g<f.images.length&&h;g++){let p=f.images[g];if(o.loadSingleImage===void 0||o.loadSingleImage===g){let _=p.levels.length;o.loadMipmapLevels===!1&&(_=1);for(let v=0;v<_;v++){let E=p.levels[v],S=r(c,g,v,d,u);if(!S){h=!1;break}E.transcodedPixels=S,m.push(E.transcodedPixels.buffer)}}}c.close(),c.delete(),u&&(d=-1),h?postMessage({action:"transcode",success:h,id:a.data.id,fileInfo:f,format:d},m):postMessage({action:"transcode",success:h,id:a.data.id})}};function t(a,o){let l=null;return a.supportedCompressionFormats&&(a.supportedCompressionFormats.astc?l=n.cTFASTC_4x4:a.supportedCompressionFormats.bc7?l=n.cTFBC7:a.supportedCompressionFormats.s3tc?l=o.hasAlpha?n.cTFBC3:n.cTFBC1:a.supportedCompressionFormats.pvrtc?l=o.hasAlpha?n.cTFPVRTC1_4_RGBA:n.cTFPVRTC1_4_RGB:a.supportedCompressionFormats.etc2?l=n.cTFETC2:a.supportedCompressionFormats.etc1?l=n.cTFETC1:l=n.cTFRGB565),l}function i(a){let o=a.getHasAlpha(),l=a.getNumImages(),c=[];for(let d=0;d<l;d++){let u={levels:[]},h=a.getNumLevels(d);for(let m=0;m<h;m++){let g={width:a.getImageWidth(d,m),height:a.getImageHeight(d,m)};u.levels.push(g)}c.push(u)}return{hasAlpha:o,images:c}}function r(a,o,l,c,f){let d=a.getImageTranscodedSizeInBytes(o,l,c),u=new Uint8Array(d);if(!a.transcodeImage(u,o,l,c,1,0))return null;if(f){let h=a.getImageWidth(o,l)+3&-4,m=a.getImageHeight(o,l)+3&-4;u=s(u,0,h,m)}return u}function s(a,o,l,c){let f=new Uint16Array(4),d=new Uint16Array(l*c),u=l/4,h=c/4;for(let m=0;m<h;m++)for(let g=0;g<u;g++){let p=o+8*(m*u+g);f[0]=a[p]|a[p+1]<<8,f[1]=a[p+2]|a[p+3]<<8,f[2]=(2*(f[0]&31)+1*(f[1]&31))/3|(2*(f[0]&2016)+1*(f[1]&2016))/3&2016|(2*(f[0]&63488)+1*(f[1]&63488))/3&63488,f[3]=(2*(f[1]&31)+1*(f[0]&31))/3|(2*(f[1]&2016)+1*(f[0]&2016))/3&2016|(2*(f[1]&63488)+1*(f[0]&63488))/3&63488;for(let _=0;_<4;_++){let v=a[p+4+_],E=(m*4+_)*l+g*4;d[E++]=f[v&3],d[E++]=f[v>>2&3],d[E++]=f[v>>4&3],d[E]=f[v>>6&3]}}return d}}async function iz(n,e,t){return await new Promise((i,r)=>{let s=a=>{a.data.action==="init"?(n.removeEventListener("message",s),i(n)):a.data.action==="error"&&r(a.data.error||"error initializing worker")};n.addEventListener("message",s),n.postMessage({action:"init",url:t?pe.GetBabylonScriptURL(t):void 0,wasmBinary:e},[e])})}var rz=y(()=>{Gi()});var Fc,ad,wde,HL,qu,Fde,Bde,Ude,wR,NR,FR,XL,nz=y(()=>{Gi();Kr();ea();rz();(function(n){n[n.cTFETC1=0]="cTFETC1",n[n.cTFETC2=1]="cTFETC2",n[n.cTFBC1=2]="cTFBC1",n[n.cTFBC3=3]="cTFBC3",n[n.cTFBC4=4]="cTFBC4",n[n.cTFBC5=5]="cTFBC5",n[n.cTFBC7=6]="cTFBC7",n[n.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",n[n.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",n[n.cTFASTC_4x4=10]="cTFASTC_4x4",n[n.cTFATC_RGB=11]="cTFATC_RGB",n[n.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",n[n.cTFRGBA32=13]="cTFRGBA32",n[n.cTFRGB565=14]="cTFRGB565",n[n.cTFBGR565=15]="cTFBGR565",n[n.cTFRGBA4444=16]="cTFRGBA4444",n[n.cTFFXT1_RGB=17]="cTFFXT1_RGB",n[n.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",n[n.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",n[n.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",n[n.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"})(Fc||(Fc={}));ad={JSModuleURL:`${pe._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${pe._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},wde=(n,e)=>{let t;switch(n){case Fc.cTFETC1:t=36196;break;case Fc.cTFBC1:t=33776;break;case Fc.cTFBC4:t=33779;break;case Fc.cTFASTC_4x4:t=37808;break;case Fc.cTFETC2:t=37496;break;case Fc.cTFBC7:t=36492;break}if(t===void 0)throw"The chosen Basis transcoder format is not currently supported";return t},HL=null,qu=null,Fde=0,Bde=!1,Ude=async()=>(HL||(HL=new Promise((n,e)=>{qu?n(qu):pe.LoadFileAsync(pe.GetBabylonScriptURL(ad.WasmModuleURL)).then(t=>{if(typeof URL!="function")return e("Basis transcoder requires an environment with a URL constructor");let i=URL.createObjectURL(new Blob([`(${tz})()`],{type:"application/javascript"}));qu=new Worker(i),iz(qu,t,ad.JSModuleURL).then(n,e)}).catch(e)})),await HL),wR=async(n,e)=>{let t=n instanceof ArrayBuffer?new Uint8Array(n):n;return await new Promise((i,r)=>{Ude().then(()=>{let s=Fde++,a=l=>{l.data.action==="transcode"&&l.data.id===s&&(qu.removeEventListener("message",a),l.data.success?i(l.data):r("Transcode is not supported on this device"))};qu.addEventListener("message",a);let o=new Uint8Array(t.byteLength);o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),qu.postMessage({action:"transcode",id:s,imageData:o,config:e,ignoreSupportedFormats:Bde},[o.buffer])},s=>{r(s)})})},NR=(n,e)=>{var i,r;let t=(i=e._gl)==null?void 0:i.TEXTURE_2D;n.isCube&&(t=(r=e._gl)==null?void 0:r.TEXTURE_CUBE_MAP),e._bindTextureDirectly(t,n,!0)},FR=(n,e)=>{let t=n.getEngine();for(let i=0;i<e.fileInfo.images.length;i++){let r=e.fileInfo.images[i].levels[0];if(n._invertVScale=n.invertY,e.format===-1||e.format===Fc.cTFRGB565)if(n.type=10,n.format=4,t._features.basisNeedsPOT&&(Math.log2(r.width)%1!==0||Math.log2(r.height)%1!==0)){let s=new Xi(t,2);n._invertVScale=n.invertY,s.type=10,s.format=4,s.width=r.width+3&-4,s.height=r.height+3&-4,NR(s,t),t._uploadDataToTextureDirectly(s,new Uint16Array(r.transcodedPixels.buffer),i,0,4,!0),t._rescaleTexture(s,n,t.scenes[0],t._getInternalFormat(4),()=>{t._releaseTexture(s),NR(n,t)})}else n._invertVScale=!n.invertY,n.width=r.width+3&-4,n.height=r.height+3&-4,n.samplingMode=2,NR(n,t),t._uploadDataToTextureDirectly(n,new Uint16Array(r.transcodedPixels.buffer),i,0,4,!0);else{n.width=r.width,n.height=r.height,n.generateMipMaps=e.fileInfo.images[i].levels.length>1;let s=XL.GetInternalFormatFromBasisFormat(e.format,t);n.format=s,NR(n,t);let a=e.fileInfo.images[i].levels;for(let o=0;o<a.length;o++){let l=a[o];t._uploadCompressedDataToTextureDirectly(n,s,l.width,l.height,l.transcodedPixels,i,o)}t._features.basisNeedsPOT&&(Math.log2(n.width)%1!==0||Math.log2(n.height)%1!==0)&&(pe.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),n._cachedWrapU=_e.CLAMP_ADDRESSMODE,n._cachedWrapV=_e.CLAMP_ADDRESSMODE)}}},XL={JSModuleURL:ad.JSModuleURL,WasmModuleURL:ad.WasmModuleURL,GetInternalFormatFromBasisFormat:wde,TranscodeAsync:wR,LoadTextureFromTranscodeResult:FR};Object.defineProperty(XL,"JSModuleURL",{get:function(){return ad.JSModuleURL},set:function(n){ad.JSModuleURL=n}});Object.defineProperty(XL,"WasmModuleURL",{get:function(){return ad.WasmModuleURL},set:function(n){ad.WasmModuleURL=n}})});var sz={};Be(sz,{_BasisTextureLoader:()=>YL});var YL,az=y(()=>{nz();Gi();YL=class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let a=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!a.etc1,s3tc:!!a.s3tc,pvrtc:!!a.pvrtc,etc2:!!a.etc2,astc:!!a.astc,bc7:!!a.bptc}};wR(e,o).then(l=>{let c=l.fileInfo.images[0].levels.length>1&&t.generateMipMaps;FR(t,l),t.getEngine()._setCubeMapTextureParams(t,c),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}).catch(l=>{pe.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,s&&s(l)})}loadData(e,t,i){let r=t.getEngine().getCaps(),s={supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}};wR(e,s).then(a=>{let o=a.fileInfo.images[0].levels[0],l=a.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(o.width,o.height,l,a.format!==-1,()=>{FR(t,a)})}).catch(a=>{pe.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),pe.Warn(`Failed to transcode Basis file: ${a}`),i(0,0,!1,!1,()=>{},!0)})}}});var Lv,oz=y(()=>{Lv=class{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach((t,i)=>this.add(t,i))}get(e){let t=this._data[e];if(t!==void 0)return t}getOrAddWithFactory(e,t){let i=this.get(e);return i!==void 0||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){let i=this.get(e);return i!==void 0?i:(this.add(e,t),t)}contains(e){return this._data[e]!==void 0}add(e,t){return this._data[e]!==void 0?!1:(this._data[e]=t,++this._count,!0)}set(e,t){return this._data[e]===void 0?!1:(this._data[e]=t,!0)}getAndRemove(e){let t=this.get(e);return t!==void 0?(delete this._data[e],--this._count,t):null}remove(e){return this.contains(e)?(delete this._data[e],--this._count,!0):!1}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(let t in this._data){let i=this._data[t];e(t,i)}}first(e){for(let t in this._data){let i=this._data[t],r=e(t,i);if(r)return r}return null}}});function BR(n){n.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}var KL=y(()=>{});var En,lz=y(()=>{jt();Yt();$t();Or();KL();En=class n{constructor(){this._dirty=!0,this._tempColor=new ht(0,0,0,0),this._globalCurve=new ht(0,0,0,0),this._highlightsCurve=new ht(0,0,0,0),this._midtonesCurve=new ht(0,0,0,0),this._shadowsCurve=new ht(0,0,0,0),this._positiveCurve=new ht(0,0,0,0),this._negativeCurve=new ht(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",r="vCameraColorCurveNeutral",s="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,r,s){e!=null&&(e=n._Clamp(e,0,360),t=n._Clamp(t,-100,100),i=n._Clamp(i,-100,100),r=n._Clamp(r,-100,100),t=n._ApplyColorGradingSliderNonlinear(t),t*=.5,r=n._ApplyColorGradingSliderNonlinear(r),t<0&&(t*=-1,e=(e+180)%360),n._FromHSBToRef(e,t,50+.25*r,s),s.scaleToRef(2,s),s.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,r){let s=n._Clamp(e,0,360),a=n._Clamp(t/100,0,1),o=n._Clamp(i/100,0,1);if(a===0)r.r=o,r.g=o,r.b=o;else{s/=60;let l=Math.floor(s),c=s-l,f=o*(1-a),d=o*(1-a*c),u=o*(1-a*(1-c));switch(l){case 0:r.r=o,r.g=u,r.b=f;break;case 1:r.r=d,r.g=o,r.b=f;break;case 2:r.r=f,r.g=o,r.b=u;break;case 3:r.r=f,r.g=d,r.b=o;break;case 4:r.r=u,r.g=f,r.b=o;break;default:r.r=o,r.g=f,r.b=d;break}}r.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return at.Clone(()=>new n,this)}serialize(){return at.Serialize(this)}static Parse(e){return at.Parse(()=>new n,e,null,null)}};En.PrepareUniforms=BR;P([F()],En.prototype,"_globalHue",void 0);P([F()],En.prototype,"_globalDensity",void 0);P([F()],En.prototype,"_globalSaturation",void 0);P([F()],En.prototype,"_globalExposure",void 0);P([F()],En.prototype,"_highlightsHue",void 0);P([F()],En.prototype,"_highlightsDensity",void 0);P([F()],En.prototype,"_highlightsSaturation",void 0);P([F()],En.prototype,"_highlightsExposure",void 0);P([F()],En.prototype,"_midtonesHue",void 0);P([F()],En.prototype,"_midtonesDensity",void 0);P([F()],En.prototype,"_midtonesSaturation",void 0);P([F()],En.prototype,"_midtonesExposure",void 0);at._ColorCurvesParser=En.Parse});function cz(n,e){e.EXPOSURE&&n.push("exposureLinear"),e.CONTRAST&&n.push("contrast"),e.COLORGRADING&&n.push("colorTransformSettings"),(e.VIGNETTE||e.DITHER)&&n.push("vInverseScreenSize"),e.VIGNETTE&&(n.push("vignetteSettings1"),n.push("vignetteSettings2")),e.COLORCURVES&&BR(n),e.DITHER&&n.push("ditherIntensity")}function fz(n,e){e.COLORGRADING&&n.push("txColorTransform")}var dz=y(()=>{KL()});var Zt,Dv=y(()=>{jt();Yt();Si();$t();lz();Bo();Or();dz();ir();Zt=class n{constructor(){this.colorCurves=new En,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=n.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new ht(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=n.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.outputTextureWidth=0,this.outputTextureHeight=0,this.onUpdateParameters=new re}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=0,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===n._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,!this._toneMappingEnabled)e.TONEMAPPING=0;else switch(this._toneMappingType){case n.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case n.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1;break}e.CONTRAST=this.contrast!==1,e.EXPOSURE=this.exposure!==1,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||!!e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&En.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){let i=1/(this.outputTextureWidth||e.getEngine().getRenderWidth()),r=1/(this.outputTextureHeight||e.getEngine().getRenderHeight());if(e.setFloat2("vInverseScreenSize",i,r),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){let s=t!=null?t:r/i,a=Math.tan(this.vignetteCameraFov*.5),o=a*s,l=Math.sqrt(o*a);o=pv(o,l,this.vignetteStretch),a=pv(a,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,a,-o*this.vignetteCenterX,-a*this.vignetteCenterY);let c=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,c)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);let i=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(i-1)/i,.5/i,i,this.colorGradingTexture.level)}}clone(){return at.Clone(()=>new n,this)}serialize(){return at.Serialize(this)}static Parse(e){let t=at.Parse(()=>new n,e,null,null);return e.vignetteCentreX!==void 0&&(t.vignetteCenterX=e.vignetteCentreX),e.vignetteCentreY!==void 0&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}};Zt.TONEMAPPING_STANDARD=0;Zt.TONEMAPPING_ACES=1;Zt.TONEMAPPING_KHR_PBR_NEUTRAL=2;Zt.PrepareUniforms=cz;Zt.PrepareSamplers=fz;Zt._VIGNETTEMODE_MULTIPLY=0;Zt._VIGNETTEMODE_OPAQUE=1;P([ok()],Zt.prototype,"colorCurves",void 0);P([F()],Zt.prototype,"_colorCurvesEnabled",void 0);P([Xt("colorGradingTexture")],Zt.prototype,"_colorGradingTexture",void 0);P([F()],Zt.prototype,"_colorGradingEnabled",void 0);P([F()],Zt.prototype,"_colorGradingWithGreenDepth",void 0);P([F()],Zt.prototype,"_colorGradingBGR",void 0);P([F()],Zt.prototype,"_exposure",void 0);P([F()],Zt.prototype,"_toneMappingEnabled",void 0);P([F()],Zt.prototype,"_toneMappingType",void 0);P([F()],Zt.prototype,"_contrast",void 0);P([F()],Zt.prototype,"vignetteStretch",void 0);P([F()],Zt.prototype,"vignetteCenterX",void 0);P([F()],Zt.prototype,"vignetteCenterY",void 0);P([F()],Zt.prototype,"vignetteWeight",void 0);P([pp()],Zt.prototype,"vignetteColor",void 0);P([F()],Zt.prototype,"vignetteCameraFov",void 0);P([F()],Zt.prototype,"_vignetteBlendMode",void 0);P([F()],Zt.prototype,"_vignetteEnabled",void 0);P([F()],Zt.prototype,"_ditheringEnabled",void 0);P([F()],Zt.prototype,"_ditheringIntensity",void 0);P([F()],Zt.prototype,"_skipFinalColorClamp",void 0);P([F()],Zt.prototype,"_applyByPostProcess",void 0);P([F()],Zt.prototype,"_isEnabled",void 0);P([F()],Zt.prototype,"outputTextureWidth",void 0);P([F()],Zt.prototype,"outputTextureHeight",void 0);at._ImageProcessingConfigurationParser=Zt.Parse;zt("BABYLON.ImageProcessingConfiguration",Zt)});var Ls,Ov=y(()=>{He();qi();Ls=class{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(D.NormalKind))return null;let i=this.pickedMesh.getIndices();(i==null?void 0:i.length)===0&&(i=null);let r,s=ee.Vector3[0],a=ee.Vector3[1],o=ee.Vector3[2];if(t){let c=this.pickedMesh.getVerticesData(D.NormalKind),f=i?b.FromArrayToRef(c,i[this.faceId*3]*3,s):s.copyFromFloats(c[this.faceId*3*3],c[this.faceId*3*3+1],c[this.faceId*3*3+2]),d=i?b.FromArrayToRef(c,i[this.faceId*3+1]*3,a):a.copyFromFloats(c[(this.faceId*3+1)*3],c[(this.faceId*3+1)*3+1],c[(this.faceId*3+1)*3+2]),u=i?b.FromArrayToRef(c,i[this.faceId*3+2]*3,o):o.copyFromFloats(c[(this.faceId*3+2)*3],c[(this.faceId*3+2)*3+1],c[(this.faceId*3+2)*3+2]);f=f.scale(this.bu),d=d.scale(this.bv),u=u.scale(1-this.bu-this.bv),r=new b(f.x+d.x+u.x,f.y+d.y+u.y,f.z+d.z+u.z)}else{let c=this.pickedMesh.getVerticesData(D.PositionKind),f=i?b.FromArrayToRef(c,i[this.faceId*3]*3,s):s.copyFromFloats(c[this.faceId*3*3],c[this.faceId*3*3+1],c[this.faceId*3*3+2]),d=i?b.FromArrayToRef(c,i[this.faceId*3+1]*3,a):a.copyFromFloats(c[(this.faceId*3+1)*3],c[(this.faceId*3+1)*3+1],c[(this.faceId*3+1)*3+2]),u=i?b.FromArrayToRef(c,i[this.faceId*3+2]*3,o):o.copyFromFloats(c[(this.faceId*3+2)*3],c[(this.faceId*3+2)*3+1],c[(this.faceId*3+2)*3+2]),h=f.subtract(d),m=u.subtract(d);r=b.Cross(h,m)}let l=(c,f)=>{if(this.thinInstanceIndex!==-1){let u=c._thinInstanceDataStorage.matrixData,h=this.thinInstanceIndex<<4;if(u&&u.length>h){let m=ee.Matrix[0];Q.FromArrayToRef(u,h,m),b.TransformNormalToRef(f,m,f)}}let d=c.getWorldMatrix();c.nonUniformScaling&&(ee.Matrix[0].copyFrom(d),d=ee.Matrix[0],d.setTranslationFromFloats(0,0,0),d.invert(),d.transposeToRef(ee.Matrix[1]),d=ee.Matrix[1]),b.TransformNormalToRef(f,d,f)};if(e&&l(this.pickedMesh,r),this.ray){let c=ee.Vector3[0].copyFrom(r);e||l(this.pickedMesh,c),b.Dot(c,this.ray.direction)>0&&r.negateInPlace()}return r.normalize(),r}getTextureCoordinates(e=D.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;let t=this.pickedMesh.getIndices();if(!t)return null;let i=this.pickedMesh.getVerticesData(e);if(!i)return null;let r=Fe.FromArray(i,t[this.faceId*3]*2),s=Fe.FromArray(i,t[this.faceId*3+1]*2),a=Fe.FromArray(i,t[this.faceId*3+2]*2);return r=r.scale(this.bu),s=s.scale(this.bv),a=a.scale(1-this.bu-this.bv),new Fe(r.x+s.x+a.x,r.y+s.y+a.y)}}});var Sn,jL=y(()=>{Sn=class n{constructor(e,t,i,r,s,a){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=s,this.additionalData=a}static CreateNew(e,t,i){let r=e.getScene();return new n(e,r.pointerX,r.pointerY,r.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,r){return new n(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,r)}static CreateNewFromScene(e,t){return new n(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,r){return new n(e,t.x,t.y,null,i,r)}}});function Nv(n,e,t){let i=t.asArray(),r=e.asArray();for(let s=0;s<16;s++)i[s]=r[s];return i[12]-=n.x,i[13]-=n.y,i[14]-=n.z,t.markAsUpdated(),t}function pz(n,e,t){return _v(e,io),Nv(n,io,ro),_v(ro,t),t}function UR(n,e,t){if(!no.eyeAtCamera)return pz(n,e,t);let i=t.asArray(),r=e.asArray();for(let s=0;s<16;s++)i[s]=r[s];return i[12]=0,i[13]=0,i[14]=0,t.markAsUpdated(),t}function ZL(n,e,t,i){return Uu(UR(n,e,i),t,i),i}function gz(n,e,t,i,r){for(let s=0;s<i;++s)QL(n,e[s],t[s],io),io.copyToArray(r,s*16);return r}function uz(n,e,t,i){return _v(t,io),Uu(e,io,ro),Nv(n,ro,io),UR(n,t,ro),Uu(io,ro,i),i}function QL(n,e,t,i){return pz(n,e,ro),Uu(ro,t,i),i}function hz(n,e,t,i,r,s){return _v(t,io),Uu(e,io,ro),Nv(n,ro,io),ZL(n,i,r,ro),Uu(io,ro,s),s}function mz(n,e){let t=no.getScene();if(!t||to===e)return e;to.updateFlag=e.updateFlag;let i=t.floatingOriginOffset;switch(n){case"world":return Nv(i,e,to);case"view":return UR(i,e,to);case"worldView":return uz(i,e,t.getViewMatrix(),to);case"viewProjection":return ZL(i,t.getViewMatrix(),t.getProjectionMatrix(),to);case"worldViewProjection":return hz(i,e,t.getTransformMatrix(),t.getViewMatrix(),t.getProjectionMatrix(),to);default:if(n.startsWith("u_")){let r=n.toLowerCase();if(r.startsWith("u_worldviewprojection"))return hz(i,e,t.getTransformMatrix(),t.getViewMatrix(),t.getProjectionMatrix(),to);if(r.startsWith("u_viewprojection"))return ZL(i,t.getViewMatrix(),t.getProjectionMatrix(),to);if(r.startsWith("u_worldview"))return uz(i,e,t.getViewMatrix(),to);if(r.startsWith("u_world"))return Nv(i,e,to);if(r.startsWith("u_view"))return UR(i,e,to)}return e}}function Ez(){pr.prototype.setMatrix=vz,qL._setMatrixOverride=void 0,wv.prototype._updateMatrixForUniform=_z,wv.prototype._updateMatrixForUniformOverride=void 0}function Sz(){qL.prototype._setMatrixOverride=vz,qL.prototype.setMatrix=function(n,e){return this._setMatrixOverride(n,mz(n,e)),this},wv.prototype._updateMatrixForUniformOverride=_z,wv.prototype._updateMatrixForUniform=function(n,e){this._updateMatrixForUniformOverride(n,mz(n,e))}}var to,io,ro,no,wv,qL,_z,vz,Fv=y(()=>{Nu();He();fL();rd();to=new Q,io=new Q,ro=new Q,no={getScene:()=>{},eyeAtCamera:!0};wv=xr,qL=pr,_z=wv.prototype._updateMatrixForUniform,vz=pr.prototype.setMatrix});var tt,_r,Sp=y(()=>{tt=class{};tt.NAME_EFFECTLAYER="EffectLayer";tt.NAME_LAYER="Layer";tt.NAME_LENSFLARESYSTEM="LensFlareSystem";tt.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer";tt.NAME_PARTICLESYSTEM="ParticleSystem";tt.NAME_GAMEPAD="Gamepad";tt.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue";tt.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer";tt.NAME_PREPASSRENDERER="PrePassRenderer";tt.NAME_DEPTHRENDERER="DepthRenderer";tt.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer";tt.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager";tt.NAME_SPRITE="Sprite";tt.NAME_SUBSURFACE="SubSurface";tt.NAME_OUTLINERENDERER="Outline";tt.NAME_PROCEDURALTEXTURE="ProceduralTexture";tt.NAME_SHADOWGENERATOR="ShadowGenerator";tt.NAME_OCTREE="Octree";tt.NAME_PHYSICSENGINE="PhysicsEngine";tt.NAME_AUDIO="Audio";tt.NAME_FLUIDRENDERER="FluidRenderer";tt.NAME_IBLCDFGENERATOR="iblCDFGenerator";tt.NAME_CLUSTEREDLIGHTING="ClusteredLighting";tt.STEP_ISREADYFORMESH_EFFECTLAYER=0;tt.STEP_ISREADYFORMESH_DEPTHRENDERER=1;tt.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0;tt.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0;tt.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0;tt.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1;tt.STEP_BEFORECAMERADRAW_PREPASS=0;tt.STEP_BEFORECAMERADRAW_EFFECTLAYER=1;tt.STEP_BEFORECAMERADRAW_LAYER=2;tt.STEP_BEFORERENDERTARGETDRAW_PREPASS=0;tt.STEP_BEFORERENDERTARGETDRAW_LAYER=1;tt.STEP_BEFORERENDERINGMESH_PREPASS=0;tt.STEP_BEFORERENDERINGMESH_OUTLINE=1;tt.STEP_AFTERRENDERINGMESH_PREPASS=0;tt.STEP_AFTERRENDERINGMESH_OUTLINE=1;tt.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0;tt.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1;tt.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0;tt.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0;tt.STEP_BEFORECLEAR_PREPASS=1;tt.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0;tt.STEP_AFTERRENDERTARGETDRAW_PREPASS=0;tt.STEP_AFTERRENDERTARGETDRAW_LAYER=1;tt.STEP_AFTERCAMERADRAW_PREPASS=0;tt.STEP_AFTERCAMERADRAW_EFFECTLAYER=1;tt.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2;tt.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3;tt.STEP_AFTERCAMERADRAW_LAYER=4;tt.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5;tt.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0;tt.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0;tt.STEP_AFTERRENDER_AUDIO=0;tt.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0;tt.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1;tt.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2;tt.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3;tt.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0;tt.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1;tt.STEP_GATHERACTIVECAMERARENDERTARGETS_CLUSTEREDLIGHTING=2;tt.STEP_POINTERMOVE_SPRITE=0;tt.STEP_POINTERDOWN_SPRITE=0;tt.STEP_POINTERUP_SPRITE=0;_r=class n extends Array{constructor(e){super(...e)}static Create(){return Object.create(n.prototype)}registerStep(e,t,i){let r=0,s;for(;r<this.length&&(s=this[r].index,!(e<s));r++);this.splice(r,0,{index:e,component:t,action:i.bind(t)})}clear(){this.length=0}}});var ot,VR,GR,so,Xo=y(()=>{He();ot=class{};ot.POINTERDOWN=1;ot.POINTERUP=2;ot.POINTERMOVE=4;ot.POINTERWHEEL=8;ot.POINTERPICK=16;ot.POINTERTAP=32;ot.POINTERDOUBLETAP=64;VR=class{constructor(e,t){this.type=e,this.event=t}},GR=class extends VR{constructor(e,t,i,r){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new Fe(i,r)}},so=class extends VR{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,r=null){super(e,t),this._pickInfo=i,this._inputManager=r}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}});var Bc,Tz=y(()=>{Bc=class n{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1,this.disposeWhenUnowned=!0}static get HasTriggers(){for(let e in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(let e in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,e)){let t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(let t in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,t)&&parseInt(t)===e)return!0;return!1}};Bc.Triggers={}});var Yo,Tp,Bv,kR=y(()=>{Yo=class{};Yo.KEYDOWN=1;Yo.KEYUP=2;Tp=class{constructor(e,t){this.type=e,this.event=t}},Bv=class extends Tp{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}}});var et,Rt,Az,xz,Rz,bz,Mz,Qu=y(()=>{(function(n){n[n.Generic=0]="Generic",n[n.Keyboard=1]="Keyboard",n[n.Mouse=2]="Mouse",n[n.Touch=3]="Touch",n[n.DualShock=4]="DualShock",n[n.Xbox=5]="Xbox",n[n.Switch=6]="Switch",n[n.DualSense=7]="DualSense"})(et||(et={}));(function(n){n[n.Horizontal=0]="Horizontal",n[n.Vertical=1]="Vertical",n[n.LeftClick=2]="LeftClick",n[n.MiddleClick=3]="MiddleClick",n[n.RightClick=4]="RightClick",n[n.BrowserBack=5]="BrowserBack",n[n.BrowserForward=6]="BrowserForward",n[n.MouseWheelX=7]="MouseWheelX",n[n.MouseWheelY=8]="MouseWheelY",n[n.MouseWheelZ=9]="MouseWheelZ",n[n.Move=12]="Move"})(Rt||(Rt={}));(function(n){n[n.Horizontal=0]="Horizontal",n[n.Vertical=1]="Vertical",n[n.LeftClick=2]="LeftClick",n[n.MiddleClick=3]="MiddleClick",n[n.RightClick=4]="RightClick",n[n.BrowserBack=5]="BrowserBack",n[n.BrowserForward=6]="BrowserForward",n[n.MouseWheelX=7]="MouseWheelX",n[n.MouseWheelY=8]="MouseWheelY",n[n.MouseWheelZ=9]="MouseWheelZ",n[n.DeltaHorizontal=10]="DeltaHorizontal",n[n.DeltaVertical=11]="DeltaVertical"})(Az||(Az={}));(function(n){n[n.Cross=0]="Cross",n[n.Circle=1]="Circle",n[n.Square=2]="Square",n[n.Triangle=3]="Triangle",n[n.L1=4]="L1",n[n.R1=5]="R1",n[n.L2=6]="L2",n[n.R2=7]="R2",n[n.Share=8]="Share",n[n.Options=9]="Options",n[n.L3=10]="L3",n[n.R3=11]="R3",n[n.DPadUp=12]="DPadUp",n[n.DPadDown=13]="DPadDown",n[n.DPadLeft=14]="DPadLeft",n[n.DPadRight=15]="DPadRight",n[n.Home=16]="Home",n[n.TouchPad=17]="TouchPad",n[n.LStickXAxis=18]="LStickXAxis",n[n.LStickYAxis=19]="LStickYAxis",n[n.RStickXAxis=20]="RStickXAxis",n[n.RStickYAxis=21]="RStickYAxis"})(xz||(xz={}));(function(n){n[n.Cross=0]="Cross",n[n.Circle=1]="Circle",n[n.Square=2]="Square",n[n.Triangle=3]="Triangle",n[n.L1=4]="L1",n[n.R1=5]="R1",n[n.L2=6]="L2",n[n.R2=7]="R2",n[n.Create=8]="Create",n[n.Options=9]="Options",n[n.L3=10]="L3",n[n.R3=11]="R3",n[n.DPadUp=12]="DPadUp",n[n.DPadDown=13]="DPadDown",n[n.DPadLeft=14]="DPadLeft",n[n.DPadRight=15]="DPadRight",n[n.Home=16]="Home",n[n.TouchPad=17]="TouchPad",n[n.LStickXAxis=18]="LStickXAxis",n[n.LStickYAxis=19]="LStickYAxis",n[n.RStickXAxis=20]="RStickXAxis",n[n.RStickYAxis=21]="RStickYAxis"})(Rz||(Rz={}));(function(n){n[n.A=0]="A",n[n.B=1]="B",n[n.X=2]="X",n[n.Y=3]="Y",n[n.LB=4]="LB",n[n.RB=5]="RB",n[n.LT=6]="LT",n[n.RT=7]="RT",n[n.Back=8]="Back",n[n.Start=9]="Start",n[n.LS=10]="LS",n[n.RS=11]="RS",n[n.DPadUp=12]="DPadUp",n[n.DPadDown=13]="DPadDown",n[n.DPadLeft=14]="DPadLeft",n[n.DPadRight=15]="DPadRight",n[n.Home=16]="Home",n[n.LStickXAxis=17]="LStickXAxis",n[n.LStickYAxis=18]="LStickYAxis",n[n.RStickXAxis=19]="RStickXAxis",n[n.RStickYAxis=20]="RStickYAxis"})(bz||(bz={}));(function(n){n[n.B=0]="B",n[n.A=1]="A",n[n.Y=2]="Y",n[n.X=3]="X",n[n.L=4]="L",n[n.R=5]="R",n[n.ZL=6]="ZL",n[n.ZR=7]="ZR",n[n.Minus=8]="Minus",n[n.Plus=9]="Plus",n[n.LS=10]="LS",n[n.RS=11]="RS",n[n.DPadUp=12]="DPadUp",n[n.DPadDown=13]="DPadDown",n[n.DPadLeft=14]="DPadLeft",n[n.DPadRight=15]="DPadRight",n[n.Home=16]="Home",n[n.Capture=17]="Capture",n[n.LStickXAxis=18]="LStickXAxis",n[n.LStickYAxis=19]="LStickYAxis",n[n.RStickXAxis=20]="RStickXAxis",n[n.RStickYAxis=21]="RStickYAxis"})(Mz||(Mz={}))});var yz,Ko,zR=y(()=>{(function(n){n[n.PointerMove=0]="PointerMove",n[n.PointerDown=1]="PointerDown",n[n.PointerUp=2]="PointerUp"})(yz||(yz={}));Ko=class{};Ko.DOM_DELTA_PIXEL=0;Ko.DOM_DELTA_LINE=1;Ko.DOM_DELTA_PAGE=2});var jo,$L=y(()=>{zR();Qu();jo=class{static CreateDeviceEvent(e,t,i,r,s,a,o){switch(e){case et.Keyboard:return this._CreateKeyboardEvent(i,r,s,a);case et.Mouse:if(i===Rt.MouseWheelX||i===Rt.MouseWheelY||i===Rt.MouseWheelZ)return this._CreateWheelEvent(e,t,i,r,s,a);case et.Touch:return this._CreatePointerEvent(e,t,i,r,s,a,o);default:throw`Unable to generate event for device ${et[e]}`}}static _CreatePointerEvent(e,t,i,r,s,a,o){let l=this._CreateMouseEvent(e,t,i,r,s,a);e===et.Mouse?(l.deviceType=et.Mouse,l.pointerId=1,l.pointerType="mouse"):(l.deviceType=et.Touch,l.pointerId=o!=null?o:t,l.pointerType="touch");let c=0;return c+=s.pollInput(e,t,Rt.LeftClick),c+=s.pollInput(e,t,Rt.RightClick)*2,c+=s.pollInput(e,t,Rt.MiddleClick)*4,l.buttons=c,i===Rt.Move?l.type="pointermove":i>=Rt.LeftClick&&i<=Rt.RightClick&&(l.type=r===1?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,r,s,a){let o=this._CreateMouseEvent(e,t,i,r,s,a);switch(o.pointerId=1,o.type="wheel",o.deltaMode=Ko.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case Rt.MouseWheelX:o.deltaX=r;break;case Rt.MouseWheelY:o.deltaY=r;break;case Rt.MouseWheelZ:o.deltaZ=r;break}return o}static _CreateMouseEvent(e,t,i,r,s,a){let o=this._CreateEvent(a),l=s.pollInput(e,t,Rt.Horizontal),c=s.pollInput(e,t,Rt.Vertical);return a?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-a.getBoundingClientRect().x,o.offsetY=o.movementY-a.getBoundingClientRect().y):(o.movementX=s.pollInput(e,t,10),o.movementY=s.pollInput(e,t,11),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,s),o.clientX=l,o.clientY=c,o.x=l,o.y=c,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,r){let s=this._CreateEvent(r);return this._CheckNonCharacterKeys(s,i),s.deviceType=et.Keyboard,s.deviceSlot=0,s.inputIndex=e,s.type=t===1?"keydown":"keyup",s.key=String.fromCharCode(e),s.keyCode=e,s}static _CheckNonCharacterKeys(e,t){let i=t.isDeviceAvailable(et.Keyboard),r=i&&t.pollInput(et.Keyboard,0,18)===1,s=i&&t.pollInput(et.Keyboard,0,17)===1,a=i&&(t.pollInput(et.Keyboard,0,91)===1||t.pollInput(et.Keyboard,0,92)===1||t.pollInput(et.Keyboard,0,93)===1),o=i&&t.pollInput(et.Keyboard,0,16)===1;e.altKey=r,e.ctrlKey=s,e.metaKey=a,e.shiftKey=o}static _CreateEvent(e){let t={};return t.preventDefault=()=>{},t.target=e,t}}});var WR,Iz=y(()=>{$L();Qu();WR=class{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(r,s,a,o)=>{let l=jo.CreateDeviceEvent(r,s,a,o,this);i(r,s,l)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===et.Mouse||e===et.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}});var Cz,Pz,HR,Lz=y(()=>{qa();Gi();$L();Qu();Cz=255,Pz=Object.keys(Rt).length/2,HR=class{constructor(e,t,i,r){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=pe.IsSafari(),this._usingMacOs=Tc()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=s=>{},this._keyboardUpEvent=s=>{},this._keyboardBlurEvent=s=>{},this._pointerMoveEvent=s=>{},this._pointerDownEvent=s=>{},this._pointerUpEvent=s=>{},this._pointerCancelEvent=s=>{},this._pointerCancelTouch=s=>{},this._pointerLeaveEvent=s=>{},this._pointerWheelEvent=s=>{},this._pointerBlurEvent=s=>{},this._pointerMacOsChromeOutEvent=s=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=Tc()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=Tc()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=s=>{},this._gamepadDisconnectedEvent=s=>{},this._eventPrefix=pe.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOs&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){let r=this._inputs[e][t];if(!r)throw`Unable to find device ${et[e]}`;e>=et.DualShock&&e<=et.DualSense&&this._updateDevice(e,t,i);let s=r[i];if(s===void 0)throw`Unable to find input ${i} for device ${et[e]} in slot ${t}`;return i===Rt.Move&&pe.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),s}isDeviceAvailable(e){return this._inputs[e]!==void 0}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){let e=this==null?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(let t of this._inputs)if(t)for(let i in t){let r=+i,s=t[r];if(s)for(let a=0;a<s.length;a++)s[a]=0}}this._elementToAttachTo=e,this._elementToAttachTo.tabIndex=this._elementToAttachTo.tabIndex!==-1?this._elementToAttachTo.tabIndex:this._engine.canvasTabIndex,this._handleKeyActions(),this._handlePointerActions(),this._handleGamepadActions(),this._eventsAttached=!0,this._checkForConnectedDevices()}}_disableEvents(){this._elementToAttachTo&&(this._elementToAttachTo.removeEventListener("blur",this._keyboardBlurEvent),this._elementToAttachTo.removeEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.removeEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.removeEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"leave",this._pointerLeaveEvent),this._elementToAttachTo.removeEventListener(this._wheelEventName,this._pointerWheelEvent),this._usingMacOs&&this._isUsingChromium&&this._elementToAttachTo.removeEventListener("lostpointercapture",this._pointerMacOsChromeOutEvent),window.removeEventListener("gamepadconnected",this._gamepadConnectedEvent),window.removeEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)),this._pointerInputClearObserver&&this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver),this._eventsAttached=!1}_checkForConnectedDevices(){if(navigator.getGamepads){let e=navigator.getGamepads();for(let t of e)t&&this._addGamePad(t)}typeof matchMedia=="function"&&matchMedia("(pointer:fine)").matches&&this._addPointerDevice(et.Mouse,0,0,0)}_addGamePad(e){let t=this._getGamepadDeviceType(e.id),i=e.index;this._gamepads=this._gamepads||new Array(e.index+1),this._registerDevice(t,i,e.buttons.length+e.axes.length),this._gamepads[i]=t}_addPointerDevice(e,t,i,r){this._pointerActive||(this._pointerActive=!0),this._registerDevice(e,t,Pz);let s=this._inputs[e][t];s[0]=i,s[1]=r}_registerDevice(e,t,i){if(t===void 0)throw`Unable to register device ${et[e]} to undefined slot.`;if(this._inputs[e]||(this._inputs[e]={}),!this._inputs[e][t]){let r=new Array(i);r.fill(0),this._inputs[e][t]=r,this._onDeviceConnected(e,t)}}_unregisterDevice(e,t){this._inputs[e][t]&&(delete this._inputs[e][t],this._onDeviceDisconnected(e,t))}_handleKeyActions(){this._keyboardDownEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(et.Keyboard,0,Cz));let t=this._inputs[et.Keyboard][0];if(t){t[e.keyCode]=1;let i=e;i.inputIndex=e.keyCode,this._usingMacOs&&e.metaKey&&e.key!=="Meta"&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(et.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(et.Keyboard,0,Cz));let t=this._inputs[et.Keyboard][0];if(t){t[e.keyCode]=0;let i=e;if(i.inputIndex=e.keyCode,this._usingMacOs&&e.key==="Meta"&&this._metaKeys.length>0){for(let r of this._metaKeys){let s=jo.CreateDeviceEvent(et.Keyboard,0,r,0,this,this._elementToAttachTo);t[r]=0,this._onInputChanged(et.Keyboard,0,s)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(et.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){let e=this._inputs[et.Keyboard][0];for(let t=0;t<e.length;t++)if(e[t]!==0){e[t]=0;let i=jo.CreateDeviceEvent(et.Keyboard,0,t,0,this,this._elementToAttachTo);this._onInputChanged(et.Keyboard,0,i)}this._usingMacOs&&this._metaKeys.splice(0,this._metaKeys.length)}},this._elementToAttachTo.addEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.addEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.addEventListener("blur",this._keyboardBlurEvent)}_handlePointerActions(){this._maxTouchPoints=Tc()&&navigator.maxTouchPoints||2,this._activeTouchIds||(this._activeTouchIds=new Array(this._maxTouchPoints));for(let i=0;i<this._maxTouchPoints;i++)this._activeTouchIds[i]=-1;this._pointerMoveEvent=i=>{let r=this._getPointerType(i),s=r===et.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(r===et.Touch&&s===-1){let o=this._activeTouchIds.indexOf(-1);if(o>=0)s=o,this._activeTouchIds[o]=i.pointerId,this._onDeviceConnected(r,s);else{pe.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[r]||(this._inputs[r]={}),this._inputs[r][s]||this._addPointerDevice(r,s,i.clientX,i.clientY);let a=this._inputs[r][s];if(a){let o=i;o.inputIndex=Rt.Move,a[Rt.Horizontal]=i.clientX,a[Rt.Vertical]=i.clientY,r===et.Touch&&a[Rt.LeftClick]===0&&(a[Rt.LeftClick]=1),i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(r,s,o),!this._usingSafari&&i.button!==-1&&(o.inputIndex=i.button+2,a[i.button+2]=a[i.button+2]?0:1,this._onInputChanged(r,s,o))}},this._pointerDownEvent=i=>{let r=this._getPointerType(i),s=r===et.Mouse?0:i.pointerId;if(r===et.Touch){let o=this._activeTouchIds.indexOf(i.pointerId);if(o===-1&&(o=this._activeTouchIds.indexOf(-1)),o>=0)s=o,this._activeTouchIds[o]=i.pointerId;else{pe.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[r]||(this._inputs[r]={}),this._inputs[r][s]?r===et.Touch&&this._onDeviceConnected(r,s):this._addPointerDevice(r,s,i.clientX,i.clientY);let a=this._inputs[r][s];if(a){let o=a[Rt.Horizontal],l=a[Rt.Vertical];if(r===et.Mouse){if(i.pointerId===void 0&&(i.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(f){}}else if(i.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(i.pointerId)}catch(f){}a[Rt.Horizontal]=i.clientX,a[Rt.Vertical]=i.clientY,a[i.button+2]=1;let c=i;c.inputIndex=i.button+2,this._onInputChanged(r,s,c),(o!==i.clientX||l!==i.clientY)&&(c.inputIndex=Rt.Move,this._onInputChanged(r,s,c))}},this._pointerUpEvent=i=>{var c,f,d,u,h;let r=this._getPointerType(i),s=r===et.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(r===et.Touch){if(s===-1)return;this._activeTouchIds[s]=-1}let a=(c=this._inputs[r])==null?void 0:c[s],o=i.button,l=a&&a[o+2]!==0;if(!l&&this._isUsingFirefox&&this._usingMacOs&&a&&(o=o===2?0:2,l=a[o+2]!==0),l){let m=a[Rt.Horizontal],g=a[Rt.Vertical];a[Rt.Horizontal]=i.clientX,a[Rt.Vertical]=i.clientY,a[o+2]=0;let p=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(m!==i.clientX||g!==i.clientY)&&(p.inputIndex=Rt.Move,this._onInputChanged(r,s,p)),p.inputIndex=o+2,r===et.Mouse&&this._mouseId>=0&&((d=(f=this._elementToAttachTo).hasPointerCapture)!=null&&d.call(f,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&((h=(u=this._elementToAttachTo).hasPointerCapture)!=null&&h.call(u,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(r,s,p),r===et.Touch&&this._onDeviceDisconnected(r,s)}},this._pointerCancelTouch=i=>{var a,o;let r=this._activeTouchIds.indexOf(i);if(r===-1)return;(o=(a=this._elementToAttachTo).hasPointerCapture)!=null&&o.call(a,i)&&this._elementToAttachTo.releasePointerCapture(i),this._inputs[et.Touch][r][Rt.LeftClick]=0;let s=jo.CreateDeviceEvent(et.Touch,r,Rt.LeftClick,0,this,this._elementToAttachTo,i);this._onInputChanged(et.Touch,r,s),this._activeTouchIds[r]=-1,this._onDeviceDisconnected(et.Touch,r)},this._pointerCancelEvent=i=>{var r,s;if(i.pointerType==="mouse"){let a=this._inputs[et.Mouse][0];this._mouseId>=0&&((s=(r=this._elementToAttachTo).hasPointerCapture)!=null&&s.call(r,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let o=Rt.LeftClick;o<=Rt.BrowserForward;o++)if(a[o]===1){a[o]=0;let l=jo.CreateDeviceEvent(et.Mouse,0,o,0,this,this._elementToAttachTo);this._onInputChanged(et.Mouse,0,l)}}else this._pointerCancelTouch(i.pointerId)},this._pointerLeaveEvent=i=>{i.pointerType==="pen"&&this._pointerCancelTouch(i.pointerId)},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":document.onmousewheel!==void 0?"mousewheel":"DOMMouseScroll";let e=!1,t=function(){};try{let i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(i){}this._pointerBlurEvent=()=>{var i,r,s,a,o;if(this.isDeviceAvailable(et.Mouse)){let l=this._inputs[et.Mouse][0];this._mouseId>=0&&((r=(i=this._elementToAttachTo).hasPointerCapture)!=null&&r.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let c=Rt.LeftClick;c<=Rt.BrowserForward;c++)if(l[c]===1){l[c]=0;let f=jo.CreateDeviceEvent(et.Mouse,0,c,0,this,this._elementToAttachTo);this._onInputChanged(et.Mouse,0,f)}}if(this.isDeviceAvailable(et.Touch)){let l=this._inputs[et.Touch];for(let c=0;c<this._activeTouchIds.length;c++){let f=this._activeTouchIds[c];if((a=(s=this._elementToAttachTo).hasPointerCapture)!=null&&a.call(s,f)&&this._elementToAttachTo.releasePointerCapture(f),f!==-1&&((o=l[c])==null?void 0:o[Rt.LeftClick])===1){l[c][Rt.LeftClick]=0;let d=jo.CreateDeviceEvent(et.Touch,c,Rt.LeftClick,0,this,this._elementToAttachTo,f);this._onInputChanged(et.Touch,c,d),this._activeTouchIds[c]=-1,this._onDeviceDisconnected(et.Touch,c)}}}},this._pointerWheelEvent=i=>{let r=et.Mouse,s=0;this._inputs[r]||(this._inputs[r]=[]),this._inputs[r][s]||(this._pointerActive=!0,this._registerDevice(r,s,Pz));let a=this._inputs[r][s];if(a){a[Rt.MouseWheelX]=i.deltaX||0,a[Rt.MouseWheelY]=i.deltaY||i.wheelDelta||0,a[Rt.MouseWheelZ]=i.deltaZ||0;let o=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),a[Rt.MouseWheelX]!==0&&(o.inputIndex=Rt.MouseWheelX,this._onInputChanged(r,s,o)),a[Rt.MouseWheelY]!==0&&(o.inputIndex=Rt.MouseWheelY,this._onInputChanged(r,s,o)),a[Rt.MouseWheelZ]!==0&&(o.inputIndex=Rt.MouseWheelZ,this._onInputChanged(r,s,o))}},this._usingMacOs&&this._isUsingChromium&&(this._pointerMacOsChromeOutEvent=i=>{i.buttons>1&&this._pointerCancelEvent(i)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOsChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"leave",this._pointerLeaveEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,e?{passive:!1}:!1),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(()=>{if(this.isDeviceAvailable(et.Mouse)){let i=this._inputs[et.Mouse][0];i[Rt.MouseWheelX]=0,i[Rt.MouseWheelY]=0,i[Rt.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){let t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){let r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){let s=this._inputs[e][t];i>=r.buttons.length?s[i]=r.axes[i-r.buttons.length].valueOf():s[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return e.indexOf("054c")!==-1?e.indexOf("0ce6")!==-1?et.DualSense:et.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?et.Xbox:e.indexOf("057e")!==-1?et.Switch:et.Generic}_getPointerType(e){let t=et.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=et.Touch),t}}});var Uv,Dz=y(()=>{Si();Uv=class{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new re,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}});var XR,Oz=y(()=>{Qu();Iz();Lz();Dz();XR=class{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=a=>{for(let o=0;o<this._devices.length;o++){let l=this._devices[o];for(let c in l){let f=+c;a._addDevice(new Uv(this._deviceInputSystem,o,f))}}this._registeredManagers.push(a)},this.unregisterManager=a=>{let o=this._registeredManagers.indexOf(a);o>-1&&this._registeredManagers.splice(o,1)};let t=Object.keys(et).length/2;this._devices=new Array(t);let i=(a,o)=>{this._devices[a]||(this._devices[a]=new Array),this._devices[a][o]||(this._devices[a][o]=o);for(let l of this._registeredManagers){let c=new Uv(this._deviceInputSystem,a,o);l._addDevice(c)}},r=(a,o)=>{var l;(l=this._devices[a])!=null&&l[o]&&delete this._devices[a][o];for(let c of this._registeredManagers)c._removeDevice(a,o)},s=(a,o,l)=>{if(l)for(let c of this._registeredManagers)c._onInputChanged(a,o,l)};typeof _native!="undefined"?this._deviceInputSystem=new WR(i,r,s):this._deviceInputSystem=new HR(e,i,r,s)}dispose(){this._deviceInputSystem.dispose()}}});var YR,Nz=y(()=>{Qu();Si();Oz();YR=class{getDeviceSource(e,t){if(t===void 0){if(this._firstDevice[e]===void 0)return null;t=this._firstDevice[e]}return!this._devices[e]||this._devices[e][t]===void 0?null:this._devices[e][t]}getDeviceSources(e){return this._devices[e]?this._devices[e].filter(t=>!!t):[]}constructor(e){let t=Object.keys(et).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new XR(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new re(i=>{for(let r of this._devices)if(r)for(let s of r)s&&this.onDeviceConnectedObservable.notifyObserver(i,s)}),this.onDeviceDisconnectedObservable=new re,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=[]),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var r,s;let i=(r=this._devices[e])==null?void 0:r[t];this.onDeviceDisconnectedObservable.notifyObservers(i),(s=this._devices[e])!=null&&s[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var r,s;(s=(r=this._devices[e])==null?void 0:r[t])==null||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case et.Keyboard:case et.Mouse:this._firstDevice[e]=0;break;case et.Touch:case et.DualSense:case et.DualShock:case et.Xbox:case et.Switch:case et.Generic:{delete this._firstDevice[e];let t=this._devices[e];if(t){for(let i=0;i<t.length;i++)if(t[i]){this._firstDevice[e]=i;break}}break}}}}});var $u,JL=y(()=>{$u=class{};$u._IsPickingAvailable=!1});var KR,is,wz=y(()=>{Xo();Tz();Ov();He();jL();kR();Qu();Nz();Yi();JL();KR=class{constructor(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}get singleClick(){return this._singleClick}get doubleClick(){return this._doubleClick}get hasSwiped(){return this._hasSwiped}get ignore(){return this._ignore}set singleClick(e){this._singleClick=e}set doubleClick(e){this._doubleClick=e}set hasSwiped(e){this._hasSwiped=e}set ignore(e){this._ignore=e}},is=class n{constructor(e){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._activePointerIds=new Array,this._activePointerIdsCount=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new Fe(0,0),this._previousStartingPointerPosition=new Fe(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||Oe.LastCreatedScene,this._scene}get meshUnderPointer(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh}getMeshUnderPointerByPointerId(e){return this._meshUnderPointerId[e]||null}get unTranslatedPointer(){return new Fe(this._unTranslatedPointerX,this._unTranslatedPointerY)}get pointerX(){return this._pointerX}set pointerX(e){this._pointerX=e}get pointerY(){return this._pointerY}set pointerY(e){this._pointerY=e}_updatePointerPosition(e){let t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)}_processPointerMove(e,t){let i=this._scene,r=i.getEngine(),s=r.getInputElement();s&&(s.tabIndex=r.canvasTabIndex,i.doNotHandleCursors||(s.style.cursor=i.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,i);for(let l of i._pointerMoveStage){e=e||this._pickMove(t);let c=!!(e!=null&&e.pickedMesh);e=l.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,c,s)}let a=t.inputIndex>=Rt.MouseWheelX&&t.inputIndex<=Rt.MouseWheelZ?ot.POINTERWHEEL:ot.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,a));let o;e?(o=new so(a,t,e),this._setRayOnPointerInfo(e,t)):(o=new so(a,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,a)}_setRayOnPointerInfo(e,t){let i=this._scene;e&&$u._IsPickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,Q.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){let r=this._scene,s=new GR(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(s.originalPickingInfo=e,s.ray=e.ray,t.pointerType==="xr-near"&&e.originMesh&&(s.nearInteractionPickingInfo=e)),r.onPrePointerObservable.notifyObservers(s,i),!!s.skipOnPointerObservable}_pickMove(e){let t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){let s=i.getEngine().getInputElement();if(e!=null&&e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){let a=this._pointerOverMesh._getActionManagerForTrigger();a&&a.hasPointerTriggers&&(s.style.cursor=a.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){let i=new PointerEvent("pointermove",t);i.inputIndex=Rt.Move,!this._checkPrePointerObservable(e,i,ot.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){let i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,ot.POINTERDOWN)&&this._processPointerDown(e,i)}_processPointerDown(e,t){let i=this._scene;if(e!=null&&e.pickedMesh){this._pickedDownMesh=e.pickedMesh;let a=e.pickedMesh._getActionManagerForTrigger();if(a){if(a.hasPickTriggers)switch(a.processTrigger(5,new Sn(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e)),t.button){case 0:a.processTrigger(2,new Sn(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e));break;case 1:a.processTrigger(4,new Sn(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e));break;case 2:a.processTrigger(3,new Sn(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e));break}a.hasSpecificTrigger(8)&&window.setTimeout(()=>{let o=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,l=>l.isPickable&&l.isVisible&&l.isReady()&&l.actionManager&&l.actionManager.hasSpecificTrigger(8)&&l===this._pickedDownMesh,!1,i.cameraToUseForPointers);o!=null&&o.pickedMesh&&a&&this._activePointerIdsCount!==0&&Date.now()-this._startingPointerTime>n.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,a.processTrigger(8,Sn.CreateNew(o.pickedMesh,t)))},n.LongPressDelay)}}else for(let a of i._pointerDownStage)e=a.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let r,s=ot.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,s),r=new so(s,t,e),this._setRayOnPointerInfo(e,t)):r=new so(s,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(r,s)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){let r=new PointerEvent("pointerup",t);r.inputIndex=Rt.Move;let s=new KR;i?s.doubleClick=!0:s.singleClick=!0,!this._checkPrePointerObservable(e,r,ot.POINTERUP)&&this._processPointerUp(e,r,s)}_processPointerUp(e,t,i){let r=this._scene;if(e!=null&&e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(r.onPointerPick&&r.onPointerPick(t,e),i.singleClick&&!i.ignore&&r.onPointerObservable.observers.length>this._cameraObserverCount)){let a=ot.POINTERPICK,o=new so(a,t,e);this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(o,a)}let s=e.pickedMesh._getActionManagerForTrigger();if(s&&!i.ignore){s.processTrigger(7,Sn.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&s.processTrigger(1,Sn.CreateNew(e.pickedMesh,t,e));let a=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&a&&a.processTrigger(6,Sn.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(let s of r._pointerUpStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){let s=this._pickedDownMesh._getActionManagerForTrigger(16);s&&s.processTrigger(16,Sn.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){let s=new so(ot.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,ot.POINTERUP),r.onPointerUp&&r.onPointerUp(t,e,ot.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let a=0;if(i.singleClick?a=ot.POINTERTAP:i.doubleClick&&(a=ot.POINTERDOUBLETAP),a){let o=new so(a,t,e);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(a)&&r.onPointerObservable.notifyObservers(o,a)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,r=null){let s=this._scene,a=s.getEngine();r||(r=a.getInputElement()),this._alreadyAttached&&this.detachControl(),r&&(this._alreadyAttachedTo=r),this._deviceSourceManager=new YR(a),this._initActionManager=o=>{if(!this._meshPickProceed){let l=s.skipPointerUpPicking||s._registeredActions===0&&!this._checkForPicking()&&!s.onPointerUp?null:s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerUpPredicate,s.pointerUpFastCheck,s.cameraToUseForPointers,s.pointerUpTrianglePredicate);this._currentPickResult=l,l&&(o=l.hit&&l.pickedMesh?l.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return o},this._delayedSimpleClick=(o,l,c)=>{if((Date.now()-this._previousStartingPointerTime>n.DoubleClickDelay&&!this._doubleClickOccured||o!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,l.singleClick=!0,l.ignore=!1,this._delayedClicks[o])){let f=this._delayedClicks[o].evt,d=ot.POINTERTAP,u=new so(d,f,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(d)&&s.onPointerObservable.notifyObservers(u,d),this._delayedClicks[o]=null}},this._initClickEvent=(o,l,c,f)=>{var g,p;let d=new KR;this._currentPickResult=null;let u=null,h=o.hasSpecificMask(ot.POINTERPICK)||l.hasSpecificMask(ot.POINTERPICK)||o.hasSpecificMask(ot.POINTERTAP)||l.hasSpecificMask(ot.POINTERTAP)||o.hasSpecificMask(ot.POINTERDOUBLETAP)||l.hasSpecificMask(ot.POINTERDOUBLETAP);!h&&Bc&&(u=this._initActionManager(u,d),u&&(h=u.hasPickTriggers));let m=!1;if(h=h&&!this._isMultiTouchGesture,h){let _=c.button;if(d.hasSwiped=this._isPointerSwiping(),!d.hasSwiped){let v=!n.ExclusiveDoubleClickMode;if(v||(v=!o.hasSpecificMask(ot.POINTERDOUBLETAP)&&!l.hasSpecificMask(ot.POINTERDOUBLETAP),v&&!Bc.HasSpecificTrigger(6)&&(u=this._initActionManager(u,d),u&&(v=!u.hasSpecificTrigger(6)))),v)(Date.now()-this._previousStartingPointerTime>n.DoubleClickDelay||_!==this._previousButtonPressed)&&(d.singleClick=!0,f(d,this._currentPickResult),m=!0);else{let S={evt:c,clickInfo:d,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,_,d,f),n.DoubleClickDelay)};this._delayedClicks[_]=S}let E=o.hasSpecificMask(ot.POINTERDOUBLETAP)||l.hasSpecificMask(ot.POINTERDOUBLETAP);!E&&Bc.HasSpecificTrigger(6)&&(u=this._initActionManager(u,d),u&&(E=u.hasSpecificTrigger(6))),E&&(_===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime<n.DoubleClickDelay&&!this._doubleClickOccured?(!d.hasSwiped&&!this._isPointerSwiping()?(this._previousStartingPointerTime=0,this._doubleClickOccured=!0,d.doubleClick=!0,d.ignore=!1,n.ExclusiveDoubleClickMode&&this._delayedClicks[_]&&(clearTimeout((g=this._delayedClicks[_])==null?void 0:g.timeoutId),this._delayedClicks[_]=null),f(d,this._currentPickResult)):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=_,n.ExclusiveDoubleClickMode?(this._delayedClicks[_]&&(clearTimeout((p=this._delayedClicks[_])==null?void 0:p.timeoutId),this._delayedClicks[_]=null),f(d,this._previousPickResult)):f(d,this._currentPickResult)),m=!0):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=_))}}m||f(d,this._currentPickResult)},this._onPointerMove=o=>{if(this._updatePointerPosition(o),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>n.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>n.DragMovementThreshold),a.isPointerLock&&a._verifyPointerLock(),this._checkPrePointerObservable(null,o,o.inputIndex>=Rt.MouseWheelX&&o.inputIndex<=Rt.MouseWheelZ?ot.POINTERWHEEL:ot.POINTERMOVE)||!s.cameraToUseForPointers&&!s.activeCamera)return;if(s.skipPointerMovePicking){this._processPointerMove(new Ls,o);return}s.pointerMovePredicate||(s.pointerMovePredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(c.enablePointerMoveEvents||s.constantlyUpdateMeshUnderPointer||c._getActionManagerForTrigger()!==null)&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&c.layerMask)!==0));let l=s._registeredActions>0||s.constantlyUpdateMeshUnderPointer?this._pickMove(o):null;this._processPointerMove(l,o)},this._onPointerDown=o=>{var f;let l=this._activePointerIds.indexOf(-1);if(l===-1?this._activePointerIds.push(o.pointerId):this._activePointerIds[l]=o.pointerId,this._activePointerIdsCount++,this._pickedDownMesh=null,this._meshPickProceed=!1,n.ExclusiveDoubleClickMode){for(let d=0;d<this._delayedClicks.length;d++)if(this._delayedClicks[d])if(o.button===d)clearTimeout((f=this._delayedClicks[d])==null?void 0:f.timeoutId);else{let u=this._delayedClicks[d].clickInfo;this._doubleClickOccured=!1,u.singleClick=!0,u.ignore=!1;let h=this._delayedClicks[d].evt,m=ot.POINTERTAP,g=new so(m,h,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(m)&&s.onPointerObservable.notifyObservers(g,m),this._delayedClicks[d]=null}}if(this._updatePointerPosition(o),this._swipeButtonPressed===-1&&(this._swipeButtonPressed=o.button),s.preventDefaultOnPointerDown&&r&&(o.preventDefault(),r.focus()),this._startingPointerPosition.x=this._pointerX,this._startingPointerPosition.y=this._pointerY,this._startingPointerTime=Date.now(),this._checkPrePointerObservable(null,o,ot.POINTERDOWN)||!s.cameraToUseForPointers&&!s.activeCamera)return;this._pointerCaptures[o.pointerId]=!0,s.pointerDownPredicate||(s.pointerDownPredicate=d=>d.isPickable&&d.isVisible&&d.isReady()&&d.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&d.layerMask)!==0)),this._pickedDownMesh=null;let c;s.skipPointerDownPicking||s._registeredActions===0&&!this._checkForPicking()&&!s.onPointerDown?c=new Ls:c=s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerDownPredicate,s.pointerDownFastCheck,s.cameraToUseForPointers,s.pointerDownTrianglePredicate),this._processPointerDown(c,o)},this._onPointerUp=o=>{let l=this._activePointerIds.indexOf(o.pointerId);l!==-1&&(this._activePointerIds[l]=-1,this._activePointerIdsCount--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(o),s.preventDefaultOnPointerUp&&r&&(o.preventDefault(),r.focus()),this._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,o,(c,f)=>{if(s.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!c.ignore)){if(this._checkPrePointerObservable(null,o,ot.POINTERUP)){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1);return}c.hasSwiped||(c.singleClick&&s.onPrePointerObservable.hasSpecificMask(ot.POINTERTAP)&&this._checkPrePointerObservable(null,o,ot.POINTERTAP)&&(this._skipPointerTap=!0),c.doubleClick&&s.onPrePointerObservable.hasSpecificMask(ot.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,o,ot.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[o.pointerId]){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1),!(!s.cameraToUseForPointers&&!s.activeCamera)&&(s.pointerUpPredicate||(s.pointerUpPredicate=d=>d.isPickable&&d.isVisible&&d.isReady()&&d.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&d.layerMask)!==0)),!this._meshPickProceed&&(Bc&&Bc.HasTriggers||this._checkForPicking()||s.onPointerUp)&&this._initActionManager(null,c),f||(f=this._currentPickResult),this._processPointerUp(f,o,c),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=o=>{let l=Yo.KEYDOWN;if(s.onPreKeyboardObservable.hasObservers()){let c=new Bv(l,o);if(s.onPreKeyboardObservable.notifyObservers(c,l),c.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){let c=new Tp(l,o);s.onKeyboardObservable.notifyObservers(c,l)}s.actionManager&&s.actionManager.processTrigger(14,Sn.CreateNewFromScene(s,o))},this._onKeyUp=o=>{let l=Yo.KEYUP;if(s.onPreKeyboardObservable.hasObservers()){let c=new Bv(l,o);if(s.onPreKeyboardObservable.notifyObservers(c,l),c.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){let c=new Tp(l,o);s.onKeyboardObservable.notifyObservers(c,l)}s.actionManager&&s.actionManager.processTrigger(15,Sn.CreateNewFromScene(s,o))},this._deviceSourceManager.onDeviceConnectedObservable.add(o=>{o.deviceType===et.Mouse?o.onInputChangedObservable.add(l=>{this._originMouseEvent=l,l.inputIndex===Rt.LeftClick||l.inputIndex===Rt.MiddleClick||l.inputIndex===Rt.RightClick||l.inputIndex===Rt.BrowserBack||l.inputIndex===Rt.BrowserForward?t&&o.getInput(l.inputIndex)===1?this._onPointerDown(l):e&&o.getInput(l.inputIndex)===0&&this._onPointerUp(l):i&&(l.inputIndex===Rt.Move?this._onPointerMove(l):(l.inputIndex===Rt.MouseWheelX||l.inputIndex===Rt.MouseWheelY||l.inputIndex===Rt.MouseWheelZ)&&this._onPointerMove(l))}):o.deviceType===et.Touch?o.onInputChangedObservable.add(l=>{l.inputIndex===Rt.LeftClick&&(t&&o.getInput(l.inputIndex)===1?(this._onPointerDown(l),this._activePointerIdsCount>1&&(this._isMultiTouchGesture=!0)):e&&o.getInput(l.inputIndex)===0&&(this._onPointerUp(l),this._activePointerIdsCount===0&&(this._isMultiTouchGesture=!1))),i&&l.inputIndex===Rt.Move&&this._onPointerMove(l)}):o.deviceType===et.Keyboard&&o.onInputChangedObservable.add(l=>{l.type==="keydown"?this._onKeyDown(l):l.type==="keyup"&&this._onKeyUp(l)})}),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,r){if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;let s=this._meshUnderPointerId[t],a;s&&(a=s._getActionManagerForTrigger(10),a&&a.processTrigger(10,new Sn(s,this._pointerX,this._pointerY,e,r,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,a=e._getActionManagerForTrigger(9),a&&a.processTrigger(9,new Sn(e,this._pointerX,this._pointerY,e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null),this._scene.onMeshUnderPointerUpdatedObservable.hasObservers()&&this._scene.onMeshUnderPointerUpdatedObservable.notifyObservers({mesh:e,pointerId:t})}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(let t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}};is.DragMovementThreshold=10;is.LongPressDelay=500;is.DoubleClickDelay=300;is.ExclusiveDoubleClickMode=!1});var Vl,eD=y(()=>{Ac();Vl=class n{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){n.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){n.Enabled&&(this._startMonitoringTime=br.Now)}endMonitoring(e=!0){if(!n.Enabled)return;e&&this.fetchNewFrame();let t=br.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;let e=br.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}};Vl.Enabled=!0});var Uc,jR=y(()=>{Uc=class{static get UniqueId(){let e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}};Uc._UniqueIdCounter=1});var ZR,Fz=y(()=>{ZR=class{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}});var Vde,Gde,Bz,ai,na=y(()=>{Gi();Ac();Si();Wo();oz();td();He();Dv();rd();Ov();jL();IR();Fv();PR();Sp();qa();Yi();Mn();wz();eD();$t();pR();jR();Cc();yv();Ol();Fz();wt();ir();Ll();Vde=new Vi,Gde=new Vi;(function(n){n[n.BackwardCompatible=0]="BackwardCompatible",n[n.Intermediate=1]="Intermediate",n[n.Aggressive=2]="Aggressive"})(Bz||(Bz={}));ai=class n{static DefaultMaterialFactory(e){throw $e("StandardMaterial")}static CollisionCoordinatorFactory(){throw $e("DefaultCollisionCoordinator")}get clearColor(){return this._clearColor}set clearColor(e){e!==this._clearColor&&(this._clearColor=e,this.onClearColorChangedObservable.notifyObservers(this._clearColor))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case 0:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case 1:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case 2:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1;break}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.onEnvironmentTextureChangedObservable.notifyObservers(e),this.markAllMaterialsAsDirty(1))}getNodes(){let e=[];e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes);for(let t of this.skeletons)e=e.concat(t.bones);return e}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return is.DragMovementThreshold}static set DragMovementThreshold(e){is.DragMovementThreshold=e}static get LongPressDelay(){return is.LongPressDelay}static set LongPressDelay(e){is.LongPressDelay=e}static get DoubleClickDelay(){return is.DoubleClickDelay}static set DoubleClickDelay(e){is.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return is.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){is.ExclusiveDoubleClickMode=e}get _eyePosition(){var e,t,i;return(i=(t=this._forcedViewPosition)!=null?t:(e=this.activeCamera)==null?void 0:e.globalPosition)!=null?i:b.ZeroReadOnly}bindEyePosition(e,t="vEyePosition",i=!1){let r=this._eyePosition,s=this.useRightHandedSystem===(this._mirroredCameraPosition!=null),a=this.floatingOriginOffset,o=Vde.set(r.x,r.y,r.z,s?-1:1),l=o.subtractFromFloatsToRef(a.x,a.y,a.z,0,Gde);return e&&(i?e.setFloat3(t,l.x,l.y,l.z):e.setVector4(t,l)),o}finalizeSceneUbo(){let e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null),i=this.floatingOriginOffset;return e.updateFloat4("vEyePosition",t.x-i.x,t.y-i.y,t.z-i.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=hR(e,()=>{this.onActiveCamerasChanged.notifyObservers(this)})),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get _hasDefaultMaterial(){return n.DefaultMaterialFactory!==n._OriginalDefaultMaterialFactory}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=n.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}get frameGraph(){return this._frameGraph}set frameGraph(e){if(this._frameGraph){this._frameGraph=e,e||(this.customRenderFunction=this._currentCustomRenderFunction);return}this._frameGraph=e,e&&(this._currentCustomRenderFunction=this.customRenderFunction,this.customRenderFunction=this._renderWithFrameGraph,this.activeCamera=null)}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=n.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(let e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);let t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(let t of this._components)if(t.name===e)return t;return null}get uniqueId(){return this._uniqueId}constructor(e,t){this._inputManager=new is(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this._clearColor=new ht(.2,.2,.3,1),this.onClearColorChangedObservable=new re,this.ambientColor=new he(0,0,0),this.environmentIntensity=1,this.iblIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new re,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.objectRenderers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.effectLayers=[],this.sounds=null,this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new re,this._onDisposeObserver=null,this.onBeforeRenderObservable=new re,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new re,this.onAfterRenderCameraObservable=new re,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new re,this.onAfterAnimationsObservable=new re,this.onBeforeDrawPhaseObservable=new re,this.onAfterDrawPhaseObservable=new re,this.onReadyObservable=new re,this.onBeforeCameraRenderObservable=new re,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new re,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new re,this.onAfterActiveMeshesEvaluationObservable=new re,this.onBeforeParticlesRenderingObservable=new re,this.onAfterParticlesRenderingObservable=new re,this.onDataLoadedObservable=new re,this.onNewCameraAddedObservable=new re,this.onCameraRemovedObservable=new re,this.onNewLightAddedObservable=new re,this.onLightRemovedObservable=new re,this.onNewGeometryAddedObservable=new re,this.onGeometryRemovedObservable=new re,this.onNewTransformNodeAddedObservable=new re,this.onTransformNodeRemovedObservable=new re,this.onNewMeshAddedObservable=new re,this.onMeshRemovedObservable=new re,this.onNewSkeletonAddedObservable=new re,this.onSkeletonRemovedObservable=new re,this.onNewParticleSystemAddedObservable=new re,this.onParticleSystemRemovedObservable=new re,this.onNewAnimationGroupAddedObservable=new re,this.onAnimationGroupRemovedObservable=new re,this.onNewMaterialAddedObservable=new re,this.onNewMultiMaterialAddedObservable=new re,this.onMaterialRemovedObservable=new re,this.onMultiMaterialRemovedObservable=new re,this.onNewTextureAddedObservable=new re,this.onTextureRemovedObservable=new re,this.onNewFrameGraphAddedObservable=new re,this.onFrameGraphRemovedObservable=new re,this.onNewObjectRendererAddedObservable=new re,this.onObjectRendererRemovedObservable=new re,this.onNewPostProcessAddedObservable=new re,this.onPostProcessRemovedObservable=new re,this.onNewEffectLayerAddedObservable=new re,this.onEffectLayerRemovedObservable=new re,this.onBeforeRenderTargetsRenderObservable=new re,this.onAfterRenderTargetsRenderObservable=new re,this.onBeforeStepObservable=new re,this.onAfterStepObservable=new re,this.onActiveCameraChanged=new re,this.onActiveCamerasChanged=new re,this.onBeforeRenderingGroupObservable=new re,this.onAfterRenderingGroupObservable=new re,this.onMeshImportedObservable=new re,this.onAnimationFileImportedObservable=new re,this.onEnvironmentTextureChangedObservable=new re,this.onMeshUnderPointerUpdatedObservable=new re,this._registeredForLateAnimationBindings=new zo(256),this._pointerPickingConfiguration=new ZR,this.onPrePointerObservable=new re,this.onPointerObservable=new re,this.onPreKeyboardObservable=new re,this.onKeyboardObservable=new re,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=n.FOGMODE_NONE,this.fogColor=new he(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this._frameGraph=null,this.frameGraphs=[],this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new b(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new zo(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new Vl,this._activeIndices=new Vl,this._activeParticles=new Vl,this._activeBones=new Vl,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._pendingData=[],this._isDisposed=!1,this._isReadyChecks=[],this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new Qi(256),this._processedMaterials=new Qi(256),this._renderTargets=new zo(256),this._materialsRenderTargets=new zo(256),this._activeParticleSystems=new Qi(256),this._activeSkeletons=new zo(32),this._softwareSkinnedMeshes=new zo(32),this._activeAnimatables=new Array,this._transformMatrix=Q.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=_r.Create(),this._beforeClearStage=_r.Create(),this._beforeRenderTargetClearStage=_r.Create(),this._gatherRenderTargetsStage=_r.Create(),this._gatherActiveCameraRenderTargetsStage=_r.Create(),this._isReadyForMeshStage=_r.Create(),this._beforeEvaluateActiveMeshStage=_r.Create(),this._evaluateSubMeshStage=_r.Create(),this._preActiveMeshStage=_r.Create(),this._cameraDrawRenderTargetStage=_r.Create(),this._beforeCameraDrawStage=_r.Create(),this._beforeRenderTargetDrawStage=_r.Create(),this._beforeRenderingGroupDrawStage=_r.Create(),this._beforeRenderingMeshStage=_r.Create(),this._afterRenderingMeshStage=_r.Create(),this._afterRenderingGroupDrawStage=_r.Create(),this._afterCameraDrawStage=_r.Create(),this._afterCameraPostProcessStage=_r.Create(),this._afterRenderTargetDrawStage=_r.Create(),this._afterRenderTargetPostProcessStage=_r.Create(),this._afterRenderStage=_r.Create(),this._pointerMoveStage=_r.Create(),this._pointerDownStage=_r.Create(),this._pointerUpStage=_r.Create(),this._geometriesByUniqueId=null,this._uniqueId=0,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this.onReadyTimeoutObservable=new re,this.onReadyTimeoutDuration=120*1e3,this._timeoutChecksStartTime=0,this._floatingOriginScene=void 0,this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._freezeActiveMeshesCancel=null,this._useCurrentFrameBuffer=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._getFloatingOriginScene=()=>this._floatingOriginScene,this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[],this._uniqueId=this.getUniqueId();let i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,defaultCameraLayerMask:268435455,defaultRenderableLayerMask:268435455,...t};this.defaultCameraLayerMask=i.defaultCameraLayerMask,this.defaultRenderableLayerMask=i.defaultRenderableLayerMask,e=this._engine=e||Oe.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(Oe._LastCreatedScene=this,e.scenes.push(this)),(e.getCreationOptions().useLargeWorldRendering||t!=null&&t.useFloatingOrigin)&&(Sz(),this._floatingOriginScene=this,no.getScene=this._getFloatingOriginScene),this._uid=null,this._renderingManager=new Ja(this),Dc&&(this.postProcessManager=new Dc(this)),Ar()&&this.attachControl(),this._createUbo(),Zt&&(this._imageProcessingConfiguration=new Zt),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,(!t||!t.virtual)&&e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return this._animationRatio!==void 0?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){var a,o,l;if(this._isDisposed)return!1;let t,i=this.getEngine(),r=i.currentRenderPassId;i.currentRenderPassId=(o=(a=this.activeCamera)==null?void 0:a.renderPassId)!=null?o:r;let s=!0;for(this._pendingData.length>0&&(s=!1),(l=this.prePassRenderer)==null||l.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&s&&(s=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t<this.meshes.length;t++){let c=this.meshes[t];if(!c.subMeshes||c.subMeshes.length===0)continue;if(!c.isReady(!0)){s=!1;continue}let f=c.hasThinInstances||c.getClassName()==="InstancedMesh"||c.getClassName()==="InstancedLinesMesh"||i.getCaps().instancedArrays&&c.instances.length>0;for(let u of this._isReadyForMeshStage)u.action(c,f)||(s=!1);if(!e)continue;let d=c.material||this.defaultMaterial;if(d)if(d._storeEffectOnSubMeshes)for(let u of c.subMeshes){let h=u.getMaterial();h&&h.hasRenderTargetTextures&&h.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(h)===-1&&(this._processedMaterials.push(h),this._materialsRenderTargets.concatWithNoDuplicate(h.getRenderTargetTextures()))}else d.hasRenderTargetTextures&&d.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(d)===-1&&(this._processedMaterials.push(d),this._materialsRenderTargets.concatWithNoDuplicate(d.getRenderTargetTextures()))}if(e){for(t=0;t<this._materialsRenderTargets.length;++t)this._materialsRenderTargets.data[t].isReadyForRendering()||(s=!1);for(t=0;t<this.customRenderTargets.length;++t)this.customRenderTargets[t].isReadyForRendering()||(s=!1)}for(t=0;t<this.geometries.length;t++)this.geometries[t].delayLoadState===2&&(s=!1);if(this.activeCameras&&this.activeCameras.length>0)for(let c of this.activeCameras)c.isReady(!0)||(s=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(s=!1));for(let c of this.particleSystems)c.isReady()||(s=!1);if(this.proceduralTexturesEnabled)for(let c of this.proceduralTextures)c.isReady()||(s=!1);if(this.layers)for(let c of this.layers)c.isReady()||(s=!1);if(this.effectLayers)for(let c of this.effectLayers)c.isLayerReady()||(s=!1);for(let c of this._isReadyChecks)c.isReady()||(s=!1);return i.areAllEffectsReady()||(s=!1),i.currentRenderPassId=r,s}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){let t=()=>{e(),setTimeout(()=>{this.unregisterBeforeRender(t)})};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){t!==void 0?setTimeout(()=>{this._executeOnceBeforeRender(e)},t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){let t=this.isLoading,i=this._pendingData.indexOf(e);i!==-1&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}addIsReadyCheck(e){this._isReadyChecks.indexOf(e)===-1&&this._isReadyChecks.push(e)}removeIsReadyCheck(e){let t=this._isReadyChecks.indexOf(e);t!==-1&&this._isReadyChecks.splice(t,1)}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),this._executeWhenReadyTimeoutId===null&&this._checkIsReady(t)}async whenReadyAsync(e=!1){return await new Promise(t=>{this.executeWhenReady(()=>{t()},e)})}_clearReadynessChecksData(){this._timeoutChecksStartTime=0,this.onReadyTimeoutObservable.clear(),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null}_checkIsReady(e=!1){if(this._registerTransientComponents(),this._timeoutChecksStartTime===0)this._timeoutChecksStartTime=br.Now;else if(this.onReadyTimeoutDuration>0&&br.Now-this._timeoutChecksStartTime>this.onReadyTimeoutDuration){this.onReadyTimeoutObservable.notifyObservers(this),this._clearReadynessChecksData();return}if(this.isReady(e)){this.onReadyObservable.notifyObservers(this),this._clearReadynessChecksData();return}if(this._isDisposed){this._clearReadynessChecksData();return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=br.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getInverseProjectionMatrix(){return this._inverseProjectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,r){this._multiviewSceneUboIsActive=!!(i&&r&&this._multiviewSceneUbo),!(this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag)&&(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._inverseProjectionMatrix||(this._inverseProjectionMatrix=new Q),this._projectionMatrix.invertToRef(this._inverseProjectionMatrix),this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?qf.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=qf.GetPlanes(this._transformMatrix),this._multiviewSceneUboIsActive&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,r):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix),this._sceneUbo.updateMatrix("inverseProjection",this._inverseProjectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUboIsActive&&this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e,t){let i=typeof t=="boolean"?t:t==null?void 0:t.trackUBOsInFrame,r=new xr(this._engine,void 0,!1,e!=null?e:"scene",void 0,i);return r.addUniform("viewProjection",16),r.addUniform("view",16),r.addUniform("projection",16),r.addUniform("vEyePosition",4),r.addUniform("inverseProjection",16),r}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}get floatingOriginMode(){return this._floatingOriginScene!==void 0}get floatingOriginOffset(){return this.floatingOriginMode?this._eyePosition:b.ZeroReadOnly}getUniqueId(){return Uc.UniqueId}addMesh(e,t=!1){if(!this._blockEntityCollection&&(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),pe.SetImmediate(()=>{this.onNewMeshAddedObservable.notifyObservers(e)}),t)){let i=e.getChildMeshes();for(let r of i)this.addMesh(r)}}removeMesh(e,t=!1){let i=this.meshes.indexOf(e);if(i!==-1&&(this.meshes.splice(i,1),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t){let r=e.getChildMeshes();for(let s of r)this.removeMesh(s)}return i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneTransformNodesArray!==-1||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){let t=e._indexInSceneTransformNodesArray;if(t!==-1){if(t!==this.transformNodes.length-1){let i=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=i,i._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){let t=this.skeletons.indexOf(e);return t!==-1&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){let t=this.morphTargetManagers.indexOf(e);return t!==-1&&this.morphTargetManagers.splice(t,1),t}removeLight(e){let t=this.lights.indexOf(e);if(t!==-1){for(let i of this.meshes)i._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes(),this.onLightRemovedObservable.notifyObservers(e)}return t}removeCamera(e){let t=this.cameras.indexOf(e);if(t!==-1&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){let i=this.activeCameras.indexOf(e);i!==-1&&this.activeCameras.splice(i,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){let t=this.particleSystems.indexOf(e);return t!==-1&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),this.onParticleSystemRemovedObservable.notifyObservers(e),t}removeAnimation(e){let t=this.animations.indexOf(e);return t!==-1&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){let t=this.animationGroups.indexOf(e);return t!==-1&&this.animationGroups.splice(t,1),this.onAnimationGroupRemovedObservable.notifyObservers(e),t}removeMultiMaterial(e){let t=this.multiMaterials.indexOf(e);return t!==-1&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){let t=e._indexInSceneMaterialArray;if(t!==-1&&t<this.materials.length){if(t!==this.materials.length-1){let i=this.materials[this.materials.length-1];this.materials[t]=i,i._indexInSceneMaterialArray=t}e._indexInSceneMaterialArray=-1,this.materials.pop()}return this.onMaterialRemovedObservable.notifyObservers(e),t}removeActionManager(e){let t=this.actionManagers.indexOf(e);return t!==-1&&this.actionManagers.splice(t,1),t}removeTexture(e){let t=this.textures.indexOf(e);return t!==-1&&this.textures.splice(t,1),this.onTextureRemovedObservable.notifyObservers(e),t}removeFrameGraph(e){let t=this.frameGraphs.indexOf(e);return t!==-1&&this.frameGraphs.splice(t,1),this.onFrameGraphRemovedObservable.notifyObservers(e),t}removeObjectRenderer(e){let t=this.objectRenderers.indexOf(e);return t!==-1&&this.objectRenderers.splice(t,1),this.onObjectRendererRemovedObservable.notifyObservers(e),t}removePostProcess(e){let t=this.postProcesses.indexOf(e);return t!==-1&&this.postProcesses.splice(t,1),this.onPostProcessRemovedObservable.notifyObservers(e),t}removeEffectLayer(e){let t=this.effectLayers.indexOf(e);return t!==-1&&this.effectLayers.splice(t,1),this.onEffectLayerRemovedObservable.notifyObservers(e),t}addLight(e){if(!this._blockEntityCollection){this.lights.push(e),this.sortLightsByPriority(),e.parent||e._addToSceneRootNodes();for(let t of this.meshes)t.lightSources.indexOf(e)===-1&&(t.lightSources.push(e),t._resyncLightSources());pe.SetImmediate(()=>{this.onNewLightAddedObservable.notifyObservers(e)})}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(ti.CompareLightsPriority)}addCamera(e){this._blockEntityCollection||(this.cameras.push(e),pe.SetImmediate(()=>{this.onNewCameraAddedObservable.notifyObservers(e)}),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),pe.SetImmediate(()=>{this.onNewSkeletonAddedObservable.notifyObservers(e)}))}addParticleSystem(e){this._blockEntityCollection||(this.particleSystems.push(e),pe.SetImmediate(()=>{this.onNewParticleSystemAddedObservable.notifyObservers(e)}))}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||(this.animationGroups.push(e),pe.SetImmediate(()=>{this.onNewAnimationGroupAddedObservable.notifyObservers(e)}))}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),pe.SetImmediate(()=>{this.onNewMultiMaterialAddedObservable.notifyObservers(e)}))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneMaterialArray!==-1||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),pe.SetImmediate(()=>{this.onNewMaterialAddedObservable.notifyObservers(e)}))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}addFrameGraph(e){this.frameGraphs.push(e),pe.SetImmediate(()=>{this.onNewFrameGraphAddedObservable.notifyObservers(e)})}addObjectRenderer(e){this.objectRenderers.push(e),pe.SetImmediate(()=>{this.onNewObjectRendererAddedObservable.notifyObservers(e)})}addPostProcess(e){this._blockEntityCollection||(this.postProcesses.push(e),pe.SetImmediate(()=>{this.onNewPostProcessAddedObservable.notifyObservers(e)}))}addEffectLayer(e){this._blockEntityCollection||(this.effectLayers.push(e),pe.SetImmediate(()=>{this.onNewEffectLayerAddedObservable.notifyObservers(e)}))}switchActiveCamera(e,t=!0){this._engine.getInputElement()&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){let t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){let t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;t<this.animationGroups.length;t++)if(this.animationGroups[t].name===e)return this.animationGroups[t];return null}_getMaterial(e,t){for(let i=0;i<this.materials.length;i++){let r=this.materials[i];if(t(r))return r}if(e)for(let i=0;i<this.multiMaterials.length;i++){let r=this.multiMaterials[i];if(t(r))return r}return null}getMaterialByUniqueID(e,t=!1){return this.getMaterialByUniqueId(e,t)}getMaterialByUniqueId(e,t=!1){return this._getMaterial(t,i=>i.uniqueId===e)}getMaterialById(e,t=!1){return this._getMaterial(t,i=>i.id===e)}getMaterialByName(e,t=!1){return this._getMaterial(t,i=>i.name===e)}getLastMaterialById(e,t=!1){for(let i=this.materials.length-1;i>=0;i--)if(this.materials[i].id===e)return this.materials[i];if(t){for(let i=this.multiMaterials.length-1;i>=0;i--)if(this.multiMaterials[i].id===e)return this.multiMaterials[i]}return null}getTextureByUniqueId(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].uniqueId===e)return this.textures[t];return null}getTextureByName(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].name===e)return this.textures[t];return null}getCameraById(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null}getCameraByUniqueId(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null}getCameraByName(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null}getBoneById(e){for(let t=0;t<this.skeletons.length;t++){let i=this.skeletons[t];for(let r=0;r<i.bones.length;r++)if(i.bones[r].id===e)return i.bones[r]}return null}getBoneByName(e){for(let t=0;t<this.skeletons.length;t++){let i=this.skeletons[t];for(let r=0;r<i.bones.length;r++)if(i.bones[r].name===e)return i.bones[r]}return null}getLightByName(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null}getLightById(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null}getLightByUniqueId(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];return null}getParticleSystemById(e){for(let t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null}getGeometryById(e){for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].id===e)return this.geometries[t];return null}_getGeometryByUniqueId(e){if(this._geometriesByUniqueId){let t=this._geometriesByUniqueId[e];if(t!==void 0)return this.geometries[t]}else for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].uniqueId===e)return this.geometries[t];return null}getFrameGraphByName(e){for(let t=0;t<this.frameGraphs.length;t++)if(this.frameGraphs[t].name===e)return this.frameGraphs[t];return null}pushGeometry(e,t){return!t&&this._getGeometryByUniqueId(e.uniqueId)?!1:(this.addGeometry(e),pe.SetImmediate(()=>{this.onNewGeometryAddedObservable.notifyObservers(e)}),!0)}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(t=this._geometriesByUniqueId[e.uniqueId],t===void 0)return!1}else if(t=this.geometries.indexOf(e),t<0)return!1;if(t!==this.geometries.length-1){let i=this.geometries[this.geometries.length-1];i&&(this.geometries[t]=i,this._geometriesByUniqueId&&(this._geometriesByUniqueId[i.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null}getMeshesById(e){return this.meshes.filter(function(t){return t.id===e})}getTransformNodeById(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getTransformNodeByUniqueId(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].uniqueId===e)return this.transformNodes[t];return null}getTransformNodesById(e){return this.transformNodes.filter(function(t){return t.id===e})}getMeshByUniqueId(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null}getLastMeshById(e){for(let t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];for(t=this.skeletons.length-1;t>=0;t--){let i=this.skeletons[t];for(let r=i.bones.length-1;r>=0;r--)if(i.bones[r].id===e)return i.bones[r]}return null}getNodeById(e){let t=this.getMeshById(e);if(t)return t;let i=this.getTransformNodeById(e);if(i)return i;let r=this.getLightById(e);if(r)return r;let s=this.getCameraById(e);if(s)return s;let a=this.getBoneById(e);return a||null}getNodeByName(e){let t=this.getMeshByName(e);if(t)return t;let i=this.getTransformNodeByName(e);if(i)return i;let r=this.getLightByName(e);if(r)return r;let s=this.getCameraByName(e);if(s)return s;let a=this.getBoneByName(e);return a||null}getMeshByName(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null}getTransformNodeByName(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].name===e)return this.transformNodes[t];return null}getLastSkeletonById(e){for(let t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].uniqueId===e)return this.skeletons[t];return null}getSkeletonById(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByName(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null}getMorphTargetManagerById(e){for(let t=0;t<this.morphTargetManagers.length;t++)if(this.morphTargetManagers[t].uniqueId===e)return this.morphTargetManagers[t];return null}getMorphTargetById(e){for(let t=0;t<this.morphTargetManagers.length;++t){let i=this.morphTargetManagers[t];for(let r=0;r<i.numTargets;++r){let s=i.getTarget(r);if(s.id===e)return s}}return null}getMorphTargetByName(e){for(let t=0;t<this.morphTargetManagers.length;++t){let i=this.morphTargetManagers[t];for(let r=0;r<i.numTargets;++r){let s=i.getTarget(r);if(s.name===e)return s}}return null}getPostProcessByName(e){for(let t=0;t<this.postProcesses.length;++t){let i=this.postProcesses[t];if(i.name===e)return i}return null}isActiveMesh(e){return this._activeMeshes.indexOf(e)!==-1}get uid(){return this._uid||(this._uid=pe.RandomId()),this._uid}addExternalData(e,t){return this._externalData||(this._externalData=new Lv),this._externalData.add(e,t)}getExternalData(e){return this._externalData?this._externalData.get(e):null}getOrAddExternalDataWithFactory(e,t){return this._externalData||(this._externalData=new Lv),this._externalData.getOrAddWithFactory(e,t)}removeExternalData(e){return this._externalData.remove(e)}_evaluateSubMesh(e,t,i,r){if(r||e.isInFrustum(this._frustumPlanes)){for(let a of this._evaluateSubMeshStage)a.action(t,e);let s=e.getMaterial();s!=null&&(s.hasRenderTargetTextures&&s.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(s)===-1&&(this._processedMaterials.push(s),this._materialsRenderTargets.concatWithNoDuplicate(s.getRenderTargetTextures())),this._renderingManager.dispatch(e,t,s))}}freeProcessedMaterials(){this._processedMaterials.dispose()}get blockfreeActiveMeshesAndRenderingGroups(){return this._preventFreeActiveMeshesAndRenderingGroups}set blockfreeActiveMeshesAndRenderingGroups(e){this._preventFreeActiveMeshesAndRenderingGroups!==e&&(e&&(this.freeActiveMeshes(),this.freeRenderingGroups()),this._preventFreeActiveMeshesAndRenderingGroups=e)}freeActiveMeshes(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._activeMeshes.dispose(),this.activeCamera&&this.activeCamera._activeMeshes&&this.activeCamera._activeMeshes.dispose(),this.activeCameras))for(let e=0;e<this.activeCameras.length;e++){let t=this.activeCameras[e];t&&t._activeMeshes&&t._activeMeshes.dispose()}}freeRenderingGroups(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._renderingManager&&this._renderingManager.freeRenderingGroups(),this.textures))for(let e=0;e<this.textures.length;e++){let t=this.textures[e];t&&t.renderList&&t.freeRenderingGroups()}}_isInIntermediateRendering(){return this._intermediateRendering}freezeActiveMeshes(e=!1,t,i,r=!0,s=!1){if(this.frameGraph){this._renderWithFrameGraph(!0,!1,!0);let a=this.frameGraph.getTasksByClassName(["FrameGraphObjectRendererTask","FrameGraphGeometryRendererTask"]);for(let o of a)o.objectRenderer._freezeActiveMeshes(r);return this._freezeActiveMeshesCancel=Pl(()=>{let o=!0,l=!0;for(let c of a)o&&(o=c.objectRenderer._isFrozen),l&&(l=c.objectRenderer._freezeActiveMeshesCancel!==null);if(o)return!0;if(!l)throw new Error("Freezing active meshes was cancelled");return!1},()=>{this._freezeActiveMeshesCancel=null,this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,t==null||t()},(o,l)=>{if(this._freezeActiveMeshesCancel=null,this.unfreezeActiveMeshes(),l){let c="Scene: Timeout while waiting for meshes to be frozen.";i?i(c):(te.Error(c),o&&te.Error(o))}else{let c="Scene: An unexpected error occurred while trying to freeze active meshes.";i?i(c):(te.Error(c),o&&(te.Error(o),o.stack&&te.Error(o.stack)))}}),this}return this.executeWhenReady(()=>{if(!this.activeCamera){i&&i("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,r)for(let a=0;a<this._activeMeshes.length;a++)this._activeMeshes.data[a]._freeze();t&&t()}),this}unfreezeActiveMeshes(){var e;for(let t=0;t<this.meshes.length;t++){let i=this.meshes[t];i._internalAbstractMeshDataInfo&&(i._internalAbstractMeshDataInfo._isActive=!1)}if((e=this._freezeActiveMeshesCancel)==null||e.call(this),this._freezeActiveMeshesCancel=null,this.frameGraph){let t=this.frameGraph.getTasksByClassName(["FrameGraphObjectRendererTask","FrameGraphGeometryRendererTask"]);for(let i of t)i.objectRenderer._unfreezeActiveMeshes()}else for(let t=0;t<this._activeMeshes.length;t++)this._activeMeshes.data[t]._unFreeze();return this._activeMeshesFrozen=!1,this}_executeActiveContainerCleanup(e){!(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1)&&this._activeMeshesFrozen&&this._activeMeshes.length||this.onBeforeRenderObservable.addOnce(()=>e.dispose())}_evaluateActiveMeshes(){var i;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&((i=this.activeCamera)==null||i._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){let r=this._activeMeshes.length;for(let s=0;s<r;s++)this._activeMeshes.data[s].computeWorldMatrix()}if(this._activeParticleSystems){let r=this._activeParticleSystems.length;for(let s=0;s<r;s++)this._activeParticleSystems.data[s].animate()}this._renderingManager.resetSprites();return}if(!this.activeCamera)return;this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this),this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._materialsRenderTargets.reset();for(let r of this._beforeEvaluateActiveMeshStage)r.action();let e=this.getActiveMeshCandidates(),t=e.length;for(let r=0;r<t;r++){let s=e.data[r],a=s._internalAbstractMeshDataInfo._currentLOD.get(this.activeCamera);if(a?a[1]=-1:(a=[s,-1],s._internalAbstractMeshDataInfo._currentLOD.set(this.activeCamera,a)),s.isBlocked||(this._totalVertices.addCount(s.getTotalVertices(),!1),!s.isReady()||!s.isEnabled()||s.scaling.hasAZeroComponent))continue;s.computeWorldMatrix(),s.actionManager&&s.actionManager.hasSpecificTriggers2(12,13)&&this._meshesForIntersections.pushNoDuplicate(s);let o=this.customLODSelector?this.customLODSelector(s,this.activeCamera):s.getLOD(this.activeCamera);if(a[0]=o,a[1]=this._frameId,o!=null&&(o!==s&&o.billboardMode!==0&&o.computeWorldMatrix(),s._preActivate(),s.isVisible&&s.visibility>0&&(s.layerMask&this.activeCamera.layerMask)!==0&&(this._skipFrustumClipping||s.alwaysSelectAsActiveMesh||s.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(s),this.activeCamera._activeMeshes.push(s),o!==s&&o._activate(this._renderId,!1);for(let l of this._preActiveMeshStage)l.action(s);s._activate(this._renderId,!1)&&(s.isAnInstance?s._internalAbstractMeshDataInfo._actAsRegularMesh&&(o=s):o._internalAbstractMeshDataInfo._onlyForInstances=!1,o._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(s,o)),s._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let r=0;r<this.particleSystems.length;r++){let s=this.particleSystems[r];if(!s.isStarted()||!s.emitter)continue;let a=s.emitter;(!a.position||a.isEnabled())&&(this._activeParticleSystems.push(s),s.animate(),this._renderingManager.dispatchParticles(s))}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}_prepareSkeleton(e){!this._skeletonsEnabled||!e.skeleton||(this._activeSkeletons.pushNoDuplicate(e.skeleton)&&(e.skeleton.prepare(),this._activeBones.addCount(e.skeleton.bones.length,!1)),e.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(e)&&this.frameGraph&&e.applySkeleton(e.skeleton))}_activeMesh(e,t){this._prepareSkeleton(t);let i=e.hasInstances||e.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||t.alwaysSelectAsActiveMesh;if(t&&t.subMeshes&&t.subMeshes.length>0){let r=this.getActiveSubMeshCandidates(t),s=r.length;i=i||s===1;for(let a=0;a<s;a++){let o=r.data[a];this._evaluateSubMesh(o,t,e,i)}}}updateTransformMatrix(e){let t=this.activeCamera;if(t)if(t._renderingMultiview){let i=t._rigCameras[0],r=t._rigCameras[1];this.setTransformMatrix(i.getViewMatrix(),i.getProjectionMatrix(e),r.getViewMatrix(),r.getProjectionMatrix(e))}else this.setTransformMatrix(t.getViewMatrix(),t.getProjectionMatrix(e))}_bindFrameBuffer(e,t=!0){this._useCurrentFrameBuffer||(e&&e._multiviewTexture?e._multiviewTexture._bindFrameBuffer():e&&e.outputRenderTarget?e.outputRenderTarget._bindFrameBuffer():this._engine._currentFrameBufferIsDefaultFrameBuffer()||this._engine.restoreDefaultFramebuffer()),t&&this._clearFrameBuffer(e)}_clearFrameBuffer(e){if(!(e&&e._multiviewTexture))if(e&&e.outputRenderTarget&&!e._renderingMultiview){let t=e.outputRenderTarget;t.onClearObservable.hasObservers()?t.onClearObservable.notifyObservers(this._engine):!t.skipInitialClear&&!e.isRightCamera&&(this.autoClear&&this._engine.clear(t.clearColor||this._clearColor,!t._cleared,!0,!0),t._cleared=!0)}else this._defaultFrameBufferCleared?this._engine.clear(null,!1,!0,!0):(this._defaultFrameBufferCleared=!0,this._clear())}_renderForCamera(e,t,i=!0){var o,l,c,f,d;if(e&&e._skipRendering)return;let r=this._engine;if(this._activeCamera=e,!this.activeCamera)throw new Error("Active camera not set");if(r.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&i){let u=!0;e._renderingMultiview&&e.outputRenderTarget&&(u=e.outputRenderTarget.skipInitialClear,this.autoClear&&(this._defaultFrameBufferCleared=!1,e.outputRenderTarget.skipInitialClear=!1)),this._bindFrameBuffer(this._activeCamera),e._renderingMultiview&&e.outputRenderTarget&&(e.outputRenderTarget.skipInitialClear=u)}this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._engine.currentRenderPassId=(c=(l=(o=e.outputRenderTarget)==null?void 0:o.renderPassId)!=null?l:e.renderPassId)!=null?c:0,this._evaluateActiveMeshes();for(let u=0;u<this._softwareSkinnedMeshes.length;u++){let h=this._softwareSkinnedMeshes.data[u];h.applySkeleton(h.skeleton)}this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets),e.customRenderTargets&&e.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(let u of this._gatherActiveCameraRenderTargetsStage)u.action(this._renderTargets);let s=!1;if(this.renderTargetsEnabled){this._intermediateRendering=!0;let u;if(this._renderTargets.length>0){pe.StartPerformanceCounter("Render targets",this._renderTargets.length>0);let h=(f=this.getBoundingBoxRenderer)==null?void 0:f.call(this);for(let m=0;m<this._renderTargets.length;m++){let g=this._renderTargets.data[m];if(g._shouldRender()){this._renderId++;let p=g.activeCamera&&g.activeCamera!==this.activeCamera;h&&!u&&(u=h.renderList.length>0?h.renderList.data.slice():[],u.length=h.renderList.length),g.render(p,this.dumpNextRenderTargets),s=!0}}h&&u&&(h.renderList.data=u,h.renderList.length=u.length),pe.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}if(this._cameraDrawRenderTargetStage.length>0){let h=(d=this.getBoundingBoxRenderer)==null?void 0:d.call(this);h&&!u&&(u=h.renderList.length>0?h.renderList.data.slice():[],u.length=h.renderList.length);for(let m of this._cameraDrawRenderTargetStage)s=m.action(this.activeCamera)||s;h&&u&&(h.renderList.data=u,h.renderList.length=u.length)}this._intermediateRendering=!1}s&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(let u of this._beforeCameraDrawStage)u.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this);let a=r.snapshotRendering&&r.snapshotRenderingMode===1;a&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!a),this.onAfterDrawPhaseObservable.notifyObservers(this);for(let u of this._afterCameraDrawStage)u.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){let u=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,u)}for(let u of this._afterCameraPostProcessStage)u.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(e.cameraRigMode===0||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let i=0;i<e._rigCameras.length;i++)this._renderForCamera(e._rigCameras[i],e)}this._activeCamera=e,this.updateTransformMatrix(),this.onAfterRenderCameraObservable.notifyObservers(e)}_checkIntersections(){for(let e=0;e<this._meshesForIntersections.length;e++){let t=this._meshesForIntersections.data[e];if(t.actionManager)for(let i=0;t.actionManager&&i<t.actionManager.actions.length;i++){let r=t.actionManager.actions[i];if(r.trigger===12||r.trigger===13){let s=r.getTriggerParameter(),a=s.mesh?s.mesh:s,o=a.intersectsMesh(t,s.usePreciseIntersection),l=t._intersectionsInProgress.indexOf(a);o&&l===-1?r.trigger===12?(r._executeCurrent(Sn.CreateNew(t,void 0,a)),t._intersectionsInProgress.push(a)):r.trigger===13&&t._intersectionsInProgress.push(a):!o&&l>-1&&(r.trigger===13&&r._executeCurrent(Sn.CreateNew(t,void 0,a)),(!t.actionManager.hasSpecificTrigger(13,c=>{let f=c.mesh?c.mesh:c;return a===f})||r.trigger===13)&&t._intersectionsInProgress.splice(l,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(n.MinDeltaTime,Math.min(this._engine.getDeltaTime(),n.MaxDeltaTime))+this._timeAccumulator,t=this._engine.getTimeStep(),i=1e3/t/1e3,r=0,s=this._engine.getLockstepMaxSteps(),a=Math.floor(e/t);for(a=Math.min(a,s);e>0&&r<a;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=t*i,this._animate(t),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(t),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,r++,e-=t;this._timeAccumulator=e<0?0:e}else{let e=this.useConstantAnimationDeltaTime?16:Math.max(n.MinDeltaTime,Math.min(this._engine.getDeltaTime(),n.MaxDeltaTime));this._animationRatio=e*(60/1e3),this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(e)}}_clear(){(this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this._clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil)}_checkCameraRenderTarget(e){var t;if(e!=null&&e.outputRenderTarget&&!(e!=null&&e.isRigCamera)&&(e.outputRenderTarget._cleared=!1),(t=e==null?void 0:e.rigCameras)!=null&&t.length)for(let i=0;i<e.rigCameras.length;++i){let r=e.rigCameras[i].outputRenderTarget;r&&(r._cleared=!1)}}resetDrawCache(e){if(this.meshes)for(let t of this.meshes)t.resetDrawCache(e)}_renderWithFrameGraph(e=!0,t=!1,i=!1){var s,a,o;if(this.activeCamera=null,this.activeCameras=null,e){for(let l of this.cameras)if(l.update(),l.cameraRigMode!==0)for(let c=0;c<l._rigCameras.length;c++)l._rigCameras[c].update()}this.onBeforeRenderObservable.notifyObservers(this),this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.reset();let r=(a=(s=this._frameGraph)==null?void 0:s.findMainCamera())!=null?a:null;if(this.renderTargetsEnabled){this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture),this._renderTargets.concatWithNoDuplicate(this.customRenderTargets),pe.StartPerformanceCounter("Custom render targets",this._renderTargets.length>0);for(let l=0;l<this._renderTargets.length;l++){let c=this._renderTargets.data[l],f=c.activeCamera||r;this._renderRenderTarget(c,f,!0,this.dumpNextRenderTargets)}pe.EndPerformanceCounter("Custom render targets",this._renderTargets.length>0),this._renderId++}this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(let l of this._beforeClearStage)l.action();if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1)this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset();else{let l=this.getActiveMeshCandidates(),c=l.length;if(this._activeMeshesFrozen){if(!this._skipEvaluateActiveMeshesCompletely)for(let f=0;f<c;f++){let d=l.data[f];d._internalAbstractMeshDataInfo._wasActiveLastFrame&&d.computeWorldMatrix()}if(this.particlesEnabled){let f=this._activeParticleSystems.length;for(let d=0;d<f;d++)this._activeParticleSystems.data[d].animate()}}else{this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset();for(let f=0;f<c;f++){let d=l.data[f];d._internalAbstractMeshDataInfo._wasActiveLastFrame=!1,!d.isBlocked&&(this._totalVertices.addCount(d.getTotalVertices(),!1),!(!d.isReady()||!d.isEnabled()||d.scaling.hasAZeroComponent)&&(d.computeWorldMatrix(i),d.actionManager&&d.actionManager.hasSpecificTriggers2(12,13)&&this._meshesForIntersections.pushNoDuplicate(d)))}if(this.particlesEnabled)for(let f=0;f<this.particleSystems.length;f++){let d=this.particleSystems[f];if(!d.isStarted()||!d.emitter)continue;let u=d.emitter;(!u.position||u.isEnabled())&&(this._activeParticleSystems.push(d),d.animate())}}}(o=this.frameGraph)==null||o.execute()}_renderRenderTarget(e,t,i=!1,r=!1){if(this._intermediateRendering=!0,e._shouldRender()){if(this._renderId++,this.activeCamera=t,!this.activeCamera)throw new Error("Active camera not set");this._engine.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),e.render(i,r)}this._intermediateRendering=!1}render(e=!0,t=!1){var i,r,s;if(!this.isDisposed){if(this.onReadyObservable.hasObservers()&&this._executeWhenReadyTimeoutId===null&&this._checkIsReady(),no.getScene=this._getFloatingOriginScene,this._frameId++,this._defaultFrameBufferCleared=!1,this._checkCameraRenderTarget(this.activeCamera),(i=this.activeCameras)!=null&&i.length)for(let a of this.activeCameras)this._checkCameraRenderTarget(a);this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(11),t||this.animate();for(let a of this._beforeCameraUpdateStage)a.action();if(e){if(this.activeCameras&&this.activeCameras.length>0)for(let a=0;a<this.activeCameras.length;a++){let o=this.activeCameras[a];if(o.update(),o.cameraRigMode!==0)for(let l=0;l<o._rigCameras.length;l++)o._rigCameras[l].update()}else if(this.activeCamera&&(this.activeCamera.update(),this.activeCamera.cameraRigMode!==0))for(let a=0;a<this.activeCamera._rigCameras.length;a++)this.activeCamera._rigCameras[a].update()}if(this.customRenderFunction)this._renderId++,this._engine.currentRenderPassId=0,this.customRenderFunction(e,t);else{this.onBeforeRenderObservable.notifyObservers(this),this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);let a=(r=this.activeCameras)!=null&&r.length?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){pe.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0);for(let o=0;o<this.customRenderTargets.length;o++){let l=this.customRenderTargets[o],c=l.activeCamera||this.activeCamera;this._renderRenderTarget(l,c,a!==c,this.dumpNextRenderTargets)}pe.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._renderId++}this._engine.currentRenderPassId=(s=a==null?void 0:a.renderPassId)!=null?s:0,this.activeCamera=a,this._activeCamera&&this._activeCamera.cameraRigMode!==22&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(let o of this._beforeClearStage)o.action();this._clearFrameBuffer(this.activeCamera);for(let o of this._gatherRenderTargetsStage)o.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let o=0;o<this.activeCameras.length;o++)this._processSubCameras(this.activeCameras[o],o>0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}}this._checkIntersections();for(let a of this._afterRenderStage)a.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let a=0;a<this._toBeDisposed.length;a++){let o=this._toBeDisposed[a];o&&o.dispose()}this._toBeDisposed.length=0}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0),this._engine.restoreDefaultFramebuffer()}}freezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].freeze()}unfreezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].unfreeze()}dispose(){if(this.isDisposed)return;if(this.beforeRender=null,this.afterRender=null,this.metadata=null,this.skeletons.length=0,this.morphTargetManagers.length=0,this._transientComponents.length=0,this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._preActiveMeshStage.clear(),this._cameraDrawRenderTargetStage.clear(),this._beforeCameraDrawStage.clear(),this._beforeRenderTargetDrawStage.clear(),this._beforeRenderingGroupDrawStage.clear(),this._beforeRenderingMeshStage.clear(),this._afterRenderingMeshStage.clear(),this._afterRenderingGroupDrawStage.clear(),this._afterCameraDrawStage.clear(),this._afterRenderTargetDrawStage.clear(),this._afterRenderStage.clear(),this._beforeCameraUpdateStage.clear(),this._beforeClearStage.clear(),this._gatherRenderTargetsStage.clear(),this._gatherActiveCameraRenderTargetsStage.clear(),this._pointerMoveStage.clear(),this._pointerDownStage.clear(),this._pointerUpStage.clear(),this._isReadyChecks.length=0,this.importedMeshesFiles=[],this._activeAnimatables&&this.stopAllAnimations){for(let s of this._activeAnimatables)s.onAnimationEndObservable.clear(),s.onAnimationEnd=null;this.stopAllAnimations()}this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;let e=this._activeRequests.slice();for(let s of e)s.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(s){te.Error("An error occurred while calling onDisposeObservable!",s)}if(this.detachControl(),this._engine.getInputElement())for(let s=0;s<this.cameras.length;s++)this.cameras[s].detachControl();this._disposeList(this.animationGroups),this._disposeList(this.lights),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.meshes,s=>s.dispose(!0)),this._disposeList(this.transformNodes,s=>s.dispose(!0));let i=this.cameras;this._disposeList(i),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._disposeList(this.frameGraphs),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let r=this._engine.scenes.indexOf(this);if(r>-1&&this._engine.scenes.splice(r,1),this._floatingOriginScene=void 0,this._engine.scenes.length===0&&Ez(),Oe._LastCreatedScene===this){Oe._LastCreatedScene=null;let s=Oe.Instances.length-1;for(;s>=0;){let a=Oe.Instances[s];if(a.scenes.length>0){Oe._LastCreatedScene=a.scenes[this._engine.scenes.length-1];break}s--}}r=this._engine._virtualScenes.indexOf(this),r>-1&&this._engine._virtualScenes.splice(r,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onNewFrameGraphAddedObservable.clear(),this.onFrameGraphRemovedObservable.clear(),this.onNewObjectRendererAddedObservable.clear(),this.onObjectRendererRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this.onClearColorChangedObservable.clear(),this.onEnvironmentTextureChangedObservable.clear(),this.onMeshUnderPointerUpdatedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){let i=e.slice(0);t=t!=null?t:(r=>r.dispose());for(let r of i)t(r);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e<this.meshes.length;e++){let i=this.meshes[e].geometry;i&&i.clearCachedData()}}cleanCachedTextureBuffer(){for(let e of this.textures)e._buffer&&(e._buffer=null)}getWorldExtends(e){let t=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);e=e||(()=>!0);let r=this.meshes.filter(e);for(let s of r){if(s.computeWorldMatrix(!0),!s.subMeshes||s.subMeshes.length===0||s.infiniteDistance)continue;let a=s.getBoundingInfo(),o=a.boundingBox.minimumWorld,l=a.boundingBox.maximumWorld;b.CheckExtends(o,t,i),b.CheckExtends(l,t,i)}return t.x===Number.MAX_VALUE?{min:b.Zero(),max:b.Zero()}:{min:t,max:i}}createPickingRay(e,t,i,r,s=!1){throw $e("Ray")}createPickingRayToRef(e,t,i,r,s,a=!1,o=!1){throw $e("Ray")}createPickingRayInCameraSpace(e,t,i){throw $e("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,r){throw $e("Ray")}pick(e,t,i,r,s,a){let o=$e("Ray",!0);return o&&te.Warn(o),new Ls}pickWithBoundingInfo(e,t,i,r,s){let a=$e("Ray",!0);return a&&te.Warn(a),new Ls}pickWithRay(e,t,i,r){throw $e("Ray")}multiPick(e,t,i,r,s){throw $e("Ray")}multiPickWithRay(e,t,i){throw $e("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(let e of this._components)e.rebuild();for(let e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(let e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(let e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(t===void 0)return e;let r=[];for(let s in e){let a=e[s];ni&&ni.MatchesQuery(a,t)&&(!i||i(a))&&r.push(a)}return r}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,r)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(127))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(let i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,r,s,a,o){let l=Bl(e,t,i,r?this.offlineProvider:void 0,s,a,o);return this._activeRequests.push(l),l.onCompleteObservable.add(c=>{this._activeRequests.splice(this._activeRequests.indexOf(c),1)}),l}async _loadFileAsync(e,t,i,r,s){return await new Promise((a,o)=>{this._loadFile(e,l=>{a(l)},t,i,r,(l,c)=>{o(c)},s)})}_requestFile(e,t,i,r,s,a,o){let l=bR(e,t,i,r?this.offlineProvider:void 0,s,a,o);return this._activeRequests.push(l),l.onCompleteObservable.add(c=>{this._activeRequests.splice(this._activeRequests.indexOf(c),1)}),l}async _requestFileAsync(e,t,i,r,s){return await new Promise((a,o)=>{this._requestFile(e,l=>{a(l)},t,i,r,l=>{o(l)},s)})}_readFile(e,t,i,r,s){let a=Xu(e,t,i,r,s);return this._activeRequests.push(a),a.onCompleteObservable.add(o=>{this._activeRequests.splice(this._activeRequests.indexOf(o),1)}),a}async _readFileAsync(e,t,i){return await new Promise((r,s)=>{this._readFile(e,a=>{r(a)},t,i,a=>{s(a)})})}getPerfCollector(){throw $e("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}};ai.FOGMODE_NONE=0;ai.FOGMODE_EXP=1;ai.FOGMODE_EXP2=2;ai.FOGMODE_LINEAR=3;ai.MinDeltaTime=1;ai.MaxDeltaTime=1e3;ai._OriginalDefaultMaterialFactory=ai.DefaultMaterialFactory;zt("BABYLON.Scene",ai)});var Uz,kde,ao=y(()=>{k();Uz="helperFunctions",kde=`const PI: f32=3.141592653589793;const TWO_PI: f32=6.283185307179586;const HALF_PI: f32=1.5707963267948966;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const RECIPROCAL_PI4: f32=0.07957747154594767;const HALF_MIN: f32=5.96046448e-08;
const LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3f=vec3f(0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;fn square(x: f32)->f32 {return x*x;}
fn saturate(x: f32)->f32 {return clamp(x,0.0,1.0);}
fn saturateVec3(x: vec3f)->vec3f {return clamp(x,vec3f(),vec3f(1.0));}
fn saturateEps(x: f32)->f32 {return clamp(x,Epsilon,1.0);}
fn maxEps(x: f32)->f32 {return max(x,Epsilon);}
fn maxEpsVec3(x: vec3f)->vec3f {return max(x,vec3f(Epsilon));}
fn absEps(x: f32)->f32 {return abs(x)+Epsilon;}
fn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3f=inMatrix[0];let i1: vec3f=inMatrix[1];let i2: vec3f=inMatrix[2];let outMatrix:mat3x3f=mat3x3f(
vec3(i0.x,i1.x,i2.x),
vec3(i0.y,i1.y,i2.y),
vec3(i0.z,i1.z,i2.z)
);return outMatrix;}
fn inverseMat3(inMatrix: mat3x3f)->mat3x3f {let a00: f32=inMatrix[0][0];let a01: f32=inMatrix[0][1];let a02: f32=inMatrix[0][2];let a10: f32=inMatrix[1][0];let a11: f32=inMatrix[1][1];let a12: f32=inMatrix[1][2];let a20: f32=inMatrix[2][0];let a21: f32=inMatrix[2][1];let a22: f32=inMatrix[2][2];let b01: f32=a22*a11-a12*a21;let b11: f32=-a22*a10+a12*a20;let b21: f32=a21*a10-a11*a20;let det: f32=a00*b01+a01*b11+a02*b21;return mat3x3f(b01/det,(-a22*a01+a02*a21)/det,(a12*a01-a02*a11)/det,
b11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det,
b21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);}
#if USE_EXACT_SRGB_CONVERSIONS
fn toLinearSpaceExact(color: vec3f)->vec3f
{let nearZeroSection: vec3f=0.0773993808*color;let remainingSection: vec3f=pow(0.947867299*(color+vec3f(0.055)),vec3f(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3f(0.04045)));}
fn toGammaSpaceExact(color: vec3f)->vec3f
{let nearZeroSection: vec3f=12.92*color;let remainingSection: vec3f=1.055*pow(color,vec3f(0.41666))-vec3f(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3f(0.0031308)));}
#endif
fn toLinearSpace(color: f32)->f32
{
#if USE_EXACT_SRGB_CONVERSIONS
var nearZeroSection=0.0773993808*color;var remainingSection=pow(0.947867299*(color+0.055),2.4);return select(remainingSection,nearZeroSection,color<=0.04045);
#else
return pow(color,LinearEncodePowerApprox);
#endif
}
fn toLinearSpaceVec3(color: vec3f)->vec3f
{
#if USE_EXACT_SRGB_CONVERSIONS
return toLinearSpaceExact(color);
#else
return pow(color,vec3f(LinearEncodePowerApprox));
#endif
}
fn toLinearSpaceVec4(color: vec4<f32>)->vec4<f32>
{
#if USE_EXACT_SRGB_CONVERSIONS
return vec4f(toLinearSpaceExact(color.rgb),color.a);
#else
return vec4f(pow(color.rgb,vec3f(LinearEncodePowerApprox)),color.a);
#endif
}
fn toGammaSpace(color: vec4<f32>)->vec4<f32>
{
#if USE_EXACT_SRGB_CONVERSIONS
return vec4<f32>(toGammaSpaceExact(color.rgb),color.a);
#else
return vec4<f32>(pow(color.rgb,vec3f(GammaEncodePowerApprox)),color.a);
#endif
}
fn toGammaSpaceVec3(color: vec3f)->vec3f
{
#if USE_EXACT_SRGB_CONVERSIONS
return toGammaSpaceExact(color);
#else
return pow(color,vec3f(GammaEncodePowerApprox));
#endif
}
fn squareVec3(value: vec3f)->vec3f
{return value*value;}
fn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;}
fn double_refract(I: vec3f,N: vec3f,eta: f32)->vec3f {let Tfront: vec3f=refract(I,N,1.0/eta);let Nback: vec3f=normalize(reflect(N,Tfront));return refract(Tfront,-Nback,eta);}
fn getLuminanceUnclamped(color: vec3f)->f32
{return dot(color,LuminanceEncodeApprox);}
fn getLuminance(color: vec3f)->f32
{return saturate(getLuminanceUnclamped(color));}
fn getRand(seed: vec2<f32>)->f32 {return fract(sin(dot(seed.xy ,vec2<f32>(12.9898,78.233)))*43758.5453);}
fn dither(seed: vec2<f32>,varianceAmount: f32)->f32 {let rand: f32=getRand(seed);let normVariance: f32=varianceAmount/255.0;let dither: f32=mix(-normVariance,normVariance,rand);return dither;}
const rgbdMaxRange: f32=255.0;fn toRGBD(color: vec3f)->vec4<f32> {let maxRGB: f32=max(max(color.r,max(color.g,color.b)),Epsilon);var D: f32 =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);var rgb: vec3f =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4<f32>(saturateVec3(rgb),D);}
fn fromRGBD(rgbd: vec4<f32>)->vec3f {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;}
fn parallaxCorrectNormal(vertexPos: vec3f,origVec: vec3f,cubeSize: vec3f,cubePos: vec3f)->vec3f {let invOrigVec: vec3f=vec3f(1.)/origVec;let halfSize: vec3f=cubeSize*0.5;let intersecAtMaxPlane: vec3f=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3f=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3f=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3f=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}
fn equirectangularToCubemapDirection(uv : vec2f)->vec3f {var longitude : f32=uv.x*TWO_PI-PI;var latitude : f32=HALF_PI-uv.y*PI;var direction : vec3f;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}
fn sqrtClamped(value: f32)->f32 {return sqrt(max(value,0.));}
fn avg(value: vec3f)->f32 {return dot(value,vec3f(0.333333333));}
fn singleScatterToMultiScatterAlbedo(rho_ss: vec3f)->vec3f {let s: vec3f=sqrt(max(vec3f(1.0)-rho_ss,vec3f(0.0)));return (vec3f(1.0)-s)*(vec3f(1.0)-vec3f(0.139)*s)/(vec3f(1.0)+vec3f(1.17)*s);}
fn multiScatterToSingleScatterAlbedo(rho_ms: vec3f)->vec3f {let s: vec3f=4.09712f+4.20863f*rho_ms-sqrt(9.59217f+41.6808f*rho_ms+17.7126f*rho_ms*rho_ms);return 1.0f-s*s;}
fn multiScatterToSingleScatterAlbedoWithAniso(rho_ms: vec3f,aniso: f32)->vec3f {let s: vec3f=4.09712+4.20863f*rho_ms-sqrt(9.59217f+41.6808f*rho_ms+17.7126f*rho_ms*rho_ms);return (vec3f(1.0f)-s*s)/maxEpsVec3(vec3f(1.0f)-vec3f(aniso)*s*s);}
fn min3(v: vec3f)->f32 {return min(v.x,min(v.y,v.z));}
fn max3(v: vec3f)->f32 {return max(v.x,max(v.y,v.z));}
fn uint2float(i: u32)->f32 {return bitcast<f32>(0x3F800000u | (i>>9u))-1.0;}
fn plasticSequence(rstate: u32)->vec2f {return vec2f(uint2float(rstate*3242174889u),
uint2float(rstate*2447445414u));}
`;x.IncludesShadersStoreWGSL[Uz]||(x.IncludesShadersStoreWGSL[Uz]=kde)});var iD={};Be(iD,{rgbdDecodePixelShaderWGSL:()=>zde});var tD,Vz,zde,rD=y(()=>{k();ao();tD="rgbdDecodePixelShader",Vz=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;
#include<helperFunctions>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(fromRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV)),1.0);}`;x.ShadersStoreWGSL[tD]||(x.ShadersStoreWGSL[tD]=Vz);zde={name:tD,shader:Vz}});var Gz,Wde,oo=y(()=>{k();Gz="helperFunctions",Wde=`const float PI=3.141592653589793;const float TWO_PI=6.283185307179586;const float HALF_PI=1.5707963267948966;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float RECIPROCAL_PI4=0.07957747154594767;const float HALF_MIN=5.96046448e-08;
const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001;
#define saturate(x) clamp(x,0.0,1.0)
#define absEps(x) abs(x)+Epsilon
#define maxEps(x) max(x,Epsilon)
#define saturateEps(x) clamp(x,Epsilon,1.0)
mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(
vec3(i0.x,i1.x,i2.x),
vec3(i0.y,i1.y,i2.y),
vec3(i0.z,i1.z,i2.z)
);return outMatrix;}
mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),
b11,(a22*a00-a02*a20),(-a12*a00+a02*a10),
b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}
#if USE_EXACT_SRGB_CONVERSIONS
vec3 toLinearSpaceExact(vec3 color)
{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));
#else
return
vec3(
color.r<=0.04045 ? nearZeroSection.r : remainingSection.r,
color.g<=0.04045 ? nearZeroSection.g : remainingSection.g,
color.b<=0.04045 ? nearZeroSection.b : remainingSection.b);
#endif
}
vec3 toGammaSpaceExact(vec3 color)
{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));
#else
return
vec3(
color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,
color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,
color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);
#endif
}
#endif
float toLinearSpace(float color)
{
#if USE_EXACT_SRGB_CONVERSIONS
float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;
#else
return pow(color,LinearEncodePowerApprox);
#endif
}
vec3 toLinearSpace(vec3 color)
{
#if USE_EXACT_SRGB_CONVERSIONS
return toLinearSpaceExact(color);
#else
return pow(color,vec3(LinearEncodePowerApprox));
#endif
}
vec4 toLinearSpace(vec4 color)
{
#if USE_EXACT_SRGB_CONVERSIONS
return vec4(toLinearSpaceExact(color.rgb),color.a);
#else
return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);
#endif
}
float toGammaSpace(float color)
{
#if USE_EXACT_SRGB_CONVERSIONS
float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;
#else
return pow(color,GammaEncodePowerApprox);
#endif
}
vec3 toGammaSpace(vec3 color)
{
#if USE_EXACT_SRGB_CONVERSIONS
return toGammaSpaceExact(color);
#else
return pow(color,vec3(GammaEncodePowerApprox));
#endif
}
vec4 toGammaSpace(vec4 color)
{
#if USE_EXACT_SRGB_CONVERSIONS
return vec4(toGammaSpaceExact(color.rgb),color.a);
#else
return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);
#endif
}
float square(float value)
{return value*value;}
vec3 square(vec3 value)
{return value*value;}
float pow5(float value) {float sq=value*value;return sq*sq*value;}
vec3 double_refract(vec3 I,vec3 N,float eta) {vec3 Tfront=refract(I,N,1.0/eta);vec3 Nback=normalize(reflect(N,Tfront));return refract(Tfront,-Nback,eta);}
float getLuminanceUnclamped(vec3 color)
{return dot(color,LuminanceEncodeApprox);}
float getLuminance(vec3 color)
{return saturate(getLuminanceUnclamped(color));}
float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}
float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}
const float rgbdMaxRange=255.;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =saturate(floor(D)/255.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(saturate(rgb),D);}
vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}
vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}
vec3 equirectangularToCubemapDirection(vec2 uv) {float longitude=uv.x*TWO_PI-PI;float latitude=HALF_PI-uv.y*PI;vec3 direction;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}
float sqrtClamped(float value) {return sqrt(max(value,0.));}
float avg(vec3 value) {return dot(value,vec3(0.333333333));}
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
uint extractBits(uint value,int offset,int width) {return (value>>offset) & ((1u<<width)-1u);}
int onlyBitPosition(uint value) {return (floatBitsToInt(float(value))>>23)-0x7f;}
vec3 singleScatterToMultiScatterAlbedo(vec3 rho_ss) {vec3 s=sqrt(max(vec3(1.0)-rho_ss,vec3(0.0)));return (vec3(1.0)-s)*(vec3(1.0)-vec3(0.139)*s)/(vec3(1.0)+vec3(1.17)*s);}
vec3 multiScatterToSingleScatterAlbedo(vec3 rho_ms) {vec3 s=4.09712+4.20863*rho_ms-sqrt(9.59217+41.6808*rho_ms+17.7126*rho_ms*rho_ms);return 1.0-s*s;}
vec3 multiScatterToSingleScatterAlbedo(vec3 rho_ms,float aniso) {vec3 s=4.09712+4.20863*rho_ms-sqrt(9.59217+41.6808*rho_ms+17.7126*rho_ms*rho_ms);return (1.0-s*s)/maxEps(1.0-aniso*s*s);}
float min3(vec3 v) {return min(v.x,min(v.y,v.z));}
float max3(vec3 v) {return max(v.x,max(v.y,v.z));}
float uint2float(uint i) {return uintBitsToFloat(0x3F800000u | (i>>9u))-1.0;}
vec2 plasticSequence(const uint rstate) {return vec2(uint2float(rstate*3242174889u),
uint2float(rstate*2447445414u));}
#endif
`;x.IncludesShadersStore[Gz]||(x.IncludesShadersStore[Gz]=Wde)});var sD={};Be(sD,{rgbdDecodePixelShader:()=>Hde});var nD,kz,Hde,aD=y(()=>{k();oo();nD="rgbdDecodePixelShader",kz=`varying vec2 vUV;uniform sampler2D textureSampler;
#include<helperFunctions>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;x.ShadersStore[nD]||(x.ShadersStore[nD]=kz);Hde={name:nD,shader:kz}});var Wz={};Be(Wz,{rgbdEncodePixelShader:()=>Xde});var oD,zz,Xde,Hz=y(()=>{k();oo();oD="rgbdEncodePixelShader",zz=`varying vec2 vUV;uniform sampler2D textureSampler;
#include<helperFunctions>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;x.ShadersStore[oD]||(x.ShadersStore[oD]=zz);Xde={name:oD,shader:zz}});var Yz={};Be(Yz,{rgbdEncodePixelShaderWGSL:()=>Yde});var lD,Xz,Yde,Kz=y(()=>{k();ao();lD="rgbdEncodePixelShader",Xz=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;
#include<helperFunctions>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=toRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb);}`;x.ShadersStoreWGSL[lD]||(x.ShadersStoreWGSL[lD]=Xz);Yde={name:lD,shader:Xz}});var Ap,cD=y(()=>{Oc();UL();Ap=class{static ExpandRGBDTexture(e){let t=e._texture;if(!t||!e.isRGBD)return;let i=t.getEngine(),r=i.getCaps(),s=t.isReady,a=!1;r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?(a=!0,t.type=2):r.textureFloatRender&&r.textureFloatLinearFiltering&&(a=!0,t.type=1),a&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);let o=async()=>{let l=i.isWebGPU,c=l?1:0;t.isReady=!1,l?await Promise.resolve().then(()=>(rD(),iD)):await Promise.resolve().then(()=>(aD(),sD));let f=new Ni("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1,void 0,c);f.externalTextureSamplerBinding=!0;let d=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});f.onEffectCreatedObservable.addOnce(u=>{u.executeWhenCompiled(()=>{f.onApply=h=>{h._bindTexture("textureSampler",t),h.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([f],d,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),f&&f.dispose(),d._swapAndDie(t),t.isReady=!0})})};a&&(s?o():e.onLoadObservable.addOnce(o))}static async EncodeTextureToRGBD(e,t,i=0){return t.getEngine().isWebGPU?await Promise.resolve().then(()=>(Kz(),Yz)):await Promise.resolve().then(()=>(Hz(),Wz)),await jk("rgbdEncode",e,t,i,1,5)}}});var fD=y(()=>{_L();Rv();Ri.prototype._sphericalPolynomialTargetSize=0;Ri.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)};Object.defineProperty(Ri.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=Pc.ConvertCubeMapTextureToSphericalPolynomial(this),this._texture._sphericalPolynomialPromise===null?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(n=>{this._texture._sphericalPolynomial=n,this._texture._sphericalPolynomialComputed=!0})),null}return null},set:function(n){this._texture&&(this._texture._sphericalPolynomial=n)},enumerable:!0,configurable:!0})});function Qz(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=0;for(let a=0;a<Zz.length;a++)if(e.getUint8(t++)!==Zz[a])return te.Error("Not a babylon environment map"),null;let i="",r;for(;r=e.getUint8(t++);)i+=String.fromCharCode(r);let s=JSON.parse(i);return s=Vv(s),s.binaryDataPosition=t,s.specular&&(s.specular.lodGenerationScale=s.specular.lodGenerationScale||.8),s}function Vv(n){if(n.version>jz)throw new Error(`Unsupported babylon environment map version "${n.version}". Latest supported version is "${jz}".`);return n.version===2||(n={...n,version:2,imageType:qR}),n}function Kde(n,e){e=Vv(e);let t=e.specular,i=Math.log2(e.width);if(i=Math.round(i)+1,t.mipmaps.length!==6*i)throw new Error(`Unsupported specular mipmaps number "${t.mipmaps.length}"`);let r=new Array(i);for(let s=0;s<i;s++){r[s]=new Array(6);for(let a=0;a<6;a++){let o=t.mipmaps[s*6+a];r[s][a]=new Uint8Array(n.buffer,n.byteOffset+e.binaryDataPosition+o.position,o.length)}}return r}function jde(n,e){var r;e=Vv(e);let t=new Array(6),i=(r=e.irradiance)==null?void 0:r.irradianceTexture;if(i){if(i.faces.length!==6)throw new Error(`Incorrect irradiance texture faces number "${i.faces.length}"`);for(let s=0;s<6;s++){let a=i.faces[s];t[s]=new Uint8Array(n.buffer,n.byteOffset+e.binaryDataPosition+a.position,a.length)}}return t}function $z(n,e,t){var o,l,c;t=Vv(t);let i=t.specular;if(!i)return Promise.resolve([]);n._lodGenerationScale=i.lodGenerationScale;let r=[],s=Kde(e,t);r.push(Zde(n,s,t.imageType));let a=(o=t.irradiance)==null?void 0:o.irradianceTexture;if(a){let f=jde(e,t),d=null;(c=(l=t.irradiance)==null?void 0:l.irradianceTexture)!=null&&c.dominantDirection&&(d=b.FromArray(t.irradiance.irradianceTexture.dominantDirection)),r.push(qde(n,f,a.size,t.imageType,d))}return Promise.all(r)}async function qz(n,e,t,i,r,s,a,o,l,c,f){return await new Promise((d,u)=>{if(t){let h=e.createTexture(null,!0,!0,null,1,null,m=>{u(m)},n);i==null||i.onEffectCreatedObservable.addOnce(m=>{m.executeWhenCompiled(()=>{i.externalTextureSamplerBinding=!0,i.onApply=g=>{g._bindTexture("textureSampler",h),g.setFloat2("scale",1,e._features.needsInvertingBitmap&&n instanceof ImageBitmap?-1:1)},e.scenes.length&&(e.scenes[0].postProcessManager.directRender([i],c,!0,s,a),e.restoreDefaultFramebuffer(),h.dispose(),URL.revokeObjectURL(r),d())})})}else{if(e._uploadImageToTexture(f,n,s,a),o){let h=l[a];h&&e._uploadImageToTexture(h._texture,n,s,0)}d()}})}async function Zde(n,e,t=qR){let i=n.getEngine();n.format=5,n.type=0,n.generateMipMaps=!0,n._cachedAnisotropicFilteringLevel=null,i.updateTextureSamplingMode(3,n),await Jz(n,e,!0,t),n.isReady=!0}async function qde(n,e,t,i=qR,r=null){let s=n.getEngine(),a=new Xi(s,5),o=new Ri(s,a);n._irradianceTexture=o,o._dominantDirection=r,a.isCube=!0,a.format=5,a.type=0,a.generateMipMaps=!0,a._cachedAnisotropicFilteringLevel=null,a.generateMipMaps=!0,a.width=t,a.height=t,s.updateTextureSamplingMode(3,a),await Jz(a,[e],!1,i),s.generateMipMapsForCubemap(a),a.isReady=!0}async function Jz(n,e,t,i=qR){if(!pe.IsExponentOfTwo(n.width))throw new Error("Texture size must be a power of two");let r=$G(n.width)+1,s=n.getEngine(),a=!1,o=!1,l=null,c=null,f=null,d=s.getCaps();d.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?d.textureHalfFloatRender&&d.textureHalfFloatLinearFiltering?(a=!0,n.type=2):d.textureFloatRender&&d.textureFloatLinearFiltering&&(a=!0,n.type=1):a=!1:(a=!1,o=t);let u=0;if(a)s.isWebGPU?(u=1,await Promise.resolve().then(()=>(rD(),iD))):await Promise.resolve().then(()=>(aD(),sD)),l=new Ni("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,n.type,void 0,null,!1,void 0,u),n._isRGBD=!1,n.invertY=!1,c=s.createRenderTargetCubeTexture(n.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:n.type,format:5});else if(n._isRGBD=!0,n.invertY=!0,o){f={};let g=n._lodGenerationScale,p=n._lodGenerationOffset;for(let _=0;_<3;_++){let E=1-_/2,S=p,T=(r-1)*g+p,A=S+(T-S)*E,R=Math.round(Math.min(Math.max(A,0),T)),M=new Xi(s,2);M.isCube=!0,M.invertY=!0,M.generateMipMaps=!1,s.updateTextureSamplingMode(2,M);let I=new Ri(null);switch(I._isCube=!0,I._texture=M,f[R]=I,_){case 0:n._lodTextureLow=I;break;case 1:n._lodTextureMid=I;break;case 2:n._lodTextureHigh=I;break}}}let h=[];for(let m=0;m<e.length;m++)for(let g=0;g<6;g++){let p=e[m][g],_=AR(p),v=new Blob([_],{type:i}),E=URL.createObjectURL(v),S;if(s._features.forceBitmapOverHTMLImageElement)S=s.createImageBitmap(v,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(async T=>await qz(T,s,a,l,E,g,m,o,f,c,n));else{let T=new Image;T.src=E,S=new Promise((A,R)=>{T.onload=()=>{qz(T,s,a,l,E,g,m,o,f,c,n).then(()=>A()).catch(M=>{R(M)})},T.onerror=M=>{R(M)}})}h.push(S)}if(await Promise.all(h),e.length<r){let m,g=Math.pow(2,r-1-e.length),p=g*g*4;switch(n.type){case 0:{m=new Uint8Array(p);break}case 2:{m=new Uint16Array(p);break}case 1:{m=new Float32Array(p);break}}for(let _=e.length;_<r;_++)for(let v=0;v<6;v++)s._uploadArrayBufferViewToTexture((c==null?void 0:c.texture)||n,m,v,_)}if(c){let m=n._irradianceTexture;n._irradianceTexture=null,s._releaseTexture(n),c._swapAndDie(n),n._irradianceTexture=m}l&&l.dispose(),o&&(n._lodTextureHigh&&n._lodTextureHigh._texture&&(n._lodTextureHigh._texture.isReady=!0),n._lodTextureMid&&n._lodTextureMid._texture&&(n._lodTextureMid._texture.isReady=!0),n._lodTextureLow&&n._lodTextureLow._texture&&(n._lodTextureLow._texture.isReady=!0))}function eW(n,e){e=Vv(e);let t=e.irradiance;if(!t)return;let i=new wl;b.FromArrayToRef(t.x,0,i.x),b.FromArrayToRef(t.y,0,i.y),b.FromArrayToRef(t.z,0,i.z),b.FromArrayToRef(t.xx,0,i.xx),b.FromArrayToRef(t.yy,0,i.yy),b.FromArrayToRef(t.zz,0,i.zz),b.FromArrayToRef(t.yz,0,i.yz),b.FromArrayToRef(t.zx,0,i.zx),b.FromArrayToRef(t.xy,0,i.xy),n._sphericalPolynomial=i}var qR,jz,Zz,tW=y(()=>{Gi();He();ts();Ev();ea();Rv();na();Oc();wt();cD();LL();fD();_p();qR="image/png",jz=2,Zz=[134,22,135,150,246,214,150,54]});var iW={};Be(iW,{_ENVTextureLoader:()=>dD});var dD,rW=y(()=>{tW();dD=class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let a=Qz(e);if(a){t.width=a.width,t.height=a.width;try{eW(t,a),$z(t,e,a).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()},o=>{s==null||s("Can not upload environment levels",o)})}catch(o){s==null||s("Can not upload environment file",o)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}});var Vc,nW=y(()=>{He();Vc=class{static ConvertPanoramaToCubemap(e,t,i,r,s=!1,a=!0){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";let o;if(e.length!=t*i*3){if(e.length!=t*i*4)throw"ConvertPanoramaToCubemap: input size is wrong";o=4}else o=3;let l=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,s,a,o),c=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,s,a,o),f=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,s,a,o),d=this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,s,a,o),u=this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,s,a,o),h=this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,s,a,o);return{front:l,back:c,left:f,right:d,up:u,down:h,size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,s,a,o,l){let c=new ArrayBuffer(e*e*4*3),f=new Float32Array(c),d=a?Math.max(1,Math.round(r/4/e)):1,u=1/d,h=u*u,m=t[1].subtract(t[0]).scale(u/e),g=t[3].subtract(t[2]).scale(u/e),p=1/e,_=0;for(let v=0;v<e;v++)for(let E=0;E<d;E++){let S=t[0],T=t[2];for(let A=0;A<e;A++)for(let R=0;R<d;R++){let M=T.subtract(S).scale(_).add(S);M.normalize();let I=this.CalcProjectionSpherical(M,i,r,s,l,o);f[v*e*3+A*3+0]+=I.r*h,f[v*e*3+A*3+1]+=I.g*h,f[v*e*3+A*3+2]+=I.b*h,S=S.add(m),T=T.add(g)}_+=p*u}return f}static CalcProjectionSpherical(e,t,i,r,s,a){let o=Math.atan2(e.z,e.x),l=Math.acos(e.y);for(;o<-Math.PI;)o+=2*Math.PI;for(;o>Math.PI;)o-=2*Math.PI;let c=o/Math.PI,f=l/Math.PI;c=c*.5+.5;let d=Math.round(c*i);d<0?d=0:d>=i&&(d=i-1);let u=Math.round(f*r);u<0?u=0:u>=r&&(u=r-1);let h=a?r-u-1:u,m=t[h*i*s+d*s+0],g=t[h*i*s+d*s+1],p=t[h*i*s+d*s+2];return{r:m,g,b:p}}};Vc.FACE_LEFT=[new b(-1,-1,-1),new b(1,-1,-1),new b(-1,1,-1),new b(1,1,-1)];Vc.FACE_RIGHT=[new b(1,-1,1),new b(-1,-1,1),new b(1,1,1),new b(-1,1,1)];Vc.FACE_FRONT=[new b(1,-1,-1),new b(1,-1,1),new b(1,1,-1),new b(1,1,1)];Vc.FACE_BACK=[new b(-1,-1,1),new b(-1,-1,-1),new b(-1,1,1),new b(-1,1,-1)];Vc.FACE_DOWN=[new b(1,1,-1),new b(1,1,1),new b(-1,1,-1),new b(-1,1,1)];Vc.FACE_UP=[new b(-1,-1,-1),new b(-1,-1,1),new b(1,-1,-1),new b(1,-1,1)]});function Qde(n,e){return e>1023?n*Math.pow(2,1023)*Math.pow(2,e-1023):e<-1074?n*Math.pow(2,-1074)*Math.pow(2,e+1074):n*Math.pow(2,e)}function sW(n,e,t,i,r,s){r>0?(r=Qde(1,r-136),n[s+0]=e*r,n[s+1]=t*r,n[s+2]=i*r):(n[s+0]=0,n[s+1]=0,n[s+2]=0)}function uD(n,e){let t="",i;for(let r=e;r<n.length-e&&(i=String.fromCharCode(n[r]),i!=`
`);r++)t+=i;return t}function aW(n){let e=uD(n,0);if(e[0]!="#"||e[1]!="?")throw"Bad HDR Format.";let t=!1,i=!1,r=0;do r+=e.length+1,e=uD(n,r),e=="FORMAT=32-bit_rle_rgbe"?i=!0:e.length==0&&(t=!0);while(!t);if(!i)throw"HDR Bad header format, unsupported FORMAT";r+=e.length+1,e=uD(n,r);let a=/^-Y (.*) \+X (.*)$/g.exec(e);if(!a||a.length<3)throw"HDR Bad header format, no size";let o=parseInt(a[2]),l=parseInt(a[1]);if(o<8||o>32767)throw"HDR Bad header format, unsupported size";return r+=e.length+1,{height:l,width:o,dataPosition:r}}function oW(n,e){return $de(n,e)}function $de(n,e){let t=e.height,i=e.width,r,s,a,o,l,c=e.dataPosition,f,d,u,h=new ArrayBuffer(i*4),m=new Uint8Array(h),g=new ArrayBuffer(e.width*e.height*4*3),p=new Float32Array(g);for(;t>0;){if(r=n[c++],s=n[c++],a=n[c++],o=n[c++],r!=2||s!=2||a&128||e.width<8||e.width>32767)return Jde(n,e);if((a<<8|o)!=i)throw"HDR Bad header format, wrong scan line width";for(f=0,u=0;u<4;u++)for(d=(u+1)*i;f<d;)if(r=n[c++],s=n[c++],r>128){if(l=r-128,l==0||l>d-f)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)m[f++]=s}else{if(l=r,l==0||l>d-f)throw"HDR Bad Format, bad scanline data (non-run)";if(m[f++]=s,--l>0)for(let _=0;_<l;_++)m[f++]=n[c++]}for(u=0;u<i;u++)r=m[u],s=m[u+i],a=m[u+2*i],o=m[u+3*i],sW(p,r,s,a,o,(e.height-t)*i*3+u*3);t--}return p}function Jde(n,e){let t=e.height,i=e.width,r,s,a,o,l,c=e.dataPosition,f=new ArrayBuffer(e.width*e.height*4*3),d=new Float32Array(f);for(;t>0;){for(l=0;l<e.width;l++)r=n[c++],s=n[c++],a=n[c++],o=n[c++],sW(d,r,s,a,o,(e.height-t)*i*3+l*3);t--}return d}var lW=y(()=>{nW()});var cW={};Be(cW,{_HDRTextureLoader:()=>hD});var hD,fW=y(()=>{lW();hD=class{constructor(){this.supportCascades=!1}loadCubeData(){throw".hdr not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=aW(r),a=oW(r,s),o=s.width*s.height,l=new Float32Array(o*4);for(let c=0;c<o;c+=1)l[c*4]=a[c*3],l[c*4+1]=a[c*3+1],l[c*4+2]=a[c*3+2],l[c*4+3]=1;i(s.width,s.height,t.generateMipMaps,!1,()=>{let c=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,c._uploadDataToTextureDirectly(t,l)})}}});var Zo,dW=y(()=>{wt();Zo=class n{constructor(e,t){if(this.data=e,this.isInvalid=!1,!n.IsValid(e)){this.isInvalid=!0,te.Error("texture missing KTX identifier");return}let i=Uint32Array.BYTES_PER_ELEMENT,r=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),a=r.getUint32(0,!0)===67305985;if(this.glType=r.getUint32(1*i,a),this.glTypeSize=r.getUint32(2*i,a),this.glFormat=r.getUint32(3*i,a),this.glInternalFormat=r.getUint32(4*i,a),this.glBaseInternalFormat=r.getUint32(5*i,a),this.pixelWidth=r.getUint32(6*i,a),this.pixelHeight=r.getUint32(7*i,a),this.pixelDepth=r.getUint32(8*i,a),this.numberOfArrayElements=r.getUint32(9*i,a),this.numberOfFaces=r.getUint32(10*i,a),this.numberOfMipmapLevels=r.getUint32(11*i,a),this.bytesOfKeyValueData=r.getUint32(12*i,a),this.glType!==0){te.Error("only compressed formats currently supported"),this.isInvalid=!0;return}else this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels);if(this.pixelHeight===0||this.pixelDepth!==0){te.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(this.numberOfArrayElements!==0){te.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){te.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=n.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case n.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);break;case n.TEX_2D:case n.COMPRESSED_3D:case n.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=n.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,s=this.pixelHeight,a=t?this.numberOfMipmapLevels:1;for(let o=0;o<a;o++){let l=new Int32Array(this.data.buffer,this.data.byteOffset+i,1)[0];i+=4;for(let c=0;c<this.numberOfFaces;c++){let f=new Uint8Array(this.data.buffer,this.data.byteOffset+i,l);e.getEngine()._uploadCompressedDataToTextureDirectly(e,e.format,r,s,f,c,o),i+=l,i+=3-(l+3)%4}r=Math.max(1,r*.5),s=Math.max(1,s*.5)}}static IsValid(e){if(e.byteLength>=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(t[0]===171&&t[1]===75&&t[2]===84&&t[3]===88&&t[4]===32&&t[5]===49&&t[6]===49&&t[7]===187&&t[8]===13&&t[9]===10&&t[10]===26&&t[11]===10)return!0}return!1}};Zo.HEADER_LEN=64;Zo.COMPRESSED_2D=0;Zo.COMPRESSED_3D=1;Zo.TEX_2D=2;Zo.TEX_3D=3});var mD,Gv,uW=y(()=>{mD=class{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map(t=>({workerPromise:Promise.resolve(t),idle:!0}))}dispose(){for(let e of this._workerInfos)e.workerPromise.then(t=>{t.terminate()});this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(let t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then(i=>{t(i,()=>{let r=this._pendingActions.shift();r?this._execute(e,r):e.idle=!0})})}},Gv=class n extends mD{constructor(e,t,i=n.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length<this._maxWorkers){let t={workerPromise:this._createWorkerAsync(),idle:!1};this._workerInfos.push(t),this._execute(t,e)}else this._pendingActions.push(e)}_execute(e,t){e.timeoutId&&(clearTimeout(e.timeoutId),delete e.timeoutId),super._execute(e,(i,r)=>{t(i,()=>{r(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(a=>{a.terminate()});let s=this._workerInfos.indexOf(e);s!==-1&&this._workerInfos.splice(s,1)},this._options.idleTimeElapsedBeforeRelease))})})}};Gv.DefaultOptions={idleTimeElapsedBeforeRelease:1e3}});var hW,xp,mW,pW=y(()=>{(function(n){n[n.ETC1S=0]="ETC1S",n[n.UASTC4x4=1]="UASTC4x4"})(hW||(hW={}));(function(n){n[n.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",n[n.ASTC_4x4_RGBA=0]="ASTC_4x4_RGBA",n[n.BC7_RGBA=1]="BC7_RGBA",n[n.BC3_RGBA=2]="BC3_RGBA",n[n.BC1_RGB=3]="BC1_RGB",n[n.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",n[n.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",n[n.ETC2_RGBA=6]="ETC2_RGBA",n[n.ETC1_RGB=7]="ETC1_RGB",n[n.RGBA32=8]="RGBA32",n[n.R8=9]="R8",n[n.RG8=10]="RG8"})(xp||(xp={}));(function(n){n[n.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",n[n.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",n[n.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",n[n.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",n[n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",n[n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",n[n.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",n[n.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",n[n.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",n[n.RGBA8Format=32856]="RGBA8Format",n[n.R8Format=33321]="R8Format",n[n.RG8Format=33323]="RG8Format"})(mW||(mW={}))});function kv(n,e){let t=(e==null?void 0:e.jsDecoderModule)||KTX2DECODER;n&&(n.wasmBaseUrl&&(t.Transcoder.WasmBaseUrl=n.wasmBaseUrl),n.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmModuleURL=n.wasmUASTCToASTC),n.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmModuleURL=n.wasmUASTCToBC7),n.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=n.wasmUASTCToRGBA_UNORM),n.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=n.wasmUASTCToRGBA_SRGB),n.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=n.wasmUASTCToR8_UNORM),n.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=n.wasmUASTCToRG8_UNORM),n.jsMSCTranscoder&&(t.MSCTranscoder.JSModuleURL=n.jsMSCTranscoder),n.wasmMSCTranscoder&&(t.MSCTranscoder.WasmModuleURL=n.wasmMSCTranscoder),n.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmModuleURL=n.wasmZSTDDecoder)),e&&(e.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmBinary=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmBinary=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(t.MSCTranscoder.JSModule=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(t.MSCTranscoder.WasmBinary=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmBinary=e.wasmZSTDDecoder))}function gW(n){typeof n=="undefined"&&typeof KTX2DECODER!="undefined"&&(n=KTX2DECODER);let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{let i=t.data.urls;i&&(i.jsDecoderModule&&typeof n=="undefined"&&(importScripts(i.jsDecoderModule),n=KTX2DECODER),kv(i)),t.data.wasmBinaries&&kv(void 0,{...t.data.wasmBinaries,jsDecoderModule:n}),e=new n.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":{n.KTX2Decoder.DefaultDecoderOptions=t.data.options;break}case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then(i=>{let r=[];for(let s=0;s<i.mipmaps.length;++s){let a=i.mipmaps[s];a&&a.data&&r.push(a.data.buffer)}postMessage({action:"decoded",success:!0,decodedData:i},r)}).catch(i=>{postMessage({action:"decoded",success:!1,msg:i})});break}}}async function _W(n,e,t){return await new Promise((i,r)=>{let s=o=>{n.removeEventListener("error",s),n.removeEventListener("message",a),r(o)},a=o=>{o.data.action==="init"&&(n.removeEventListener("error",s),n.removeEventListener("message",a),i(n))};n.addEventListener("error",s),n.addEventListener("message",a),n.postMessage({action:"init",urls:t,wasmBinaries:e})})}var vW=y(()=>{});var pD,Gc,EW=y(()=>{uW();Gi();pW();vW();pD=class{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;let e={};return this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==void 0&&(e.useRGBAIfASTCBC7NotAvailableWhenUASTC=this._useRGBAIfASTCBC7NotAvailableWhenUASTC),this._forceRGBA!==void 0&&(e.forceRGBA=this._forceRGBA),this._forceR8!==void 0&&(e.forceR8=this._forceR8),this._forceRG8!==void 0&&(e.forceRG8=this._forceRG8),this._bypassTranscoders!==void 0&&(e.bypassTranscoders=this._bypassTranscoders),this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[xp.BC1_RGB,xp.BC3_RGBA],yes:{transcodeFormat:xp.RGBA32,engineFormat:32856,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}},Gc=class n{static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static _Initialize(e){if(n._WorkerPoolPromise||n._DecoderModulePromise)return;let t={wasmBaseUrl:pe.ScriptBaseUrl,jsDecoderModule:pe.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:pe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:pe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:pe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:pe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:pe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:pe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:pe.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:pe.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:pe.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&typeof Worker=="function"&&typeof URL!="undefined"?n._WorkerPoolPromise=new Promise(i=>{let r=`${kv}(${gW})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));i(new Gv(e,async()=>await _W(new Worker(s),void 0,t)))}):typeof n._KTX2DecoderModule=="undefined"?n._DecoderModulePromise=pe.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(n._KTX2DecoderModule=KTX2DECODER,n._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,n._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,kv(t,n._KTX2DecoderModule),new n._KTX2DecoderModule.KTX2Decoder)):(n._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,n._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,n._DecoderModulePromise=Promise.resolve(new n._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=n.DefaultNumWorkers){var r,s;this._engine=e;let i=typeof t=="object"&&t.workerPool||n.WorkerPool;if(i)n._WorkerPoolPromise=Promise.resolve(i);else{typeof t=="object"?n._KTX2DecoderModule=(r=t==null?void 0:t.binariesAndModulesContainer)==null?void 0:r.jsDecoderModule:typeof KTX2DECODER!="undefined"&&(n._KTX2DecoderModule=KTX2DECODER);let a=typeof t=="number"?t:(s=t.numWorkers)!=null?s:n.DefaultNumWorkers;n._Initialize(a)}}async _uploadAsync(e,t,i){let r=this._engine.getCaps(),s={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(n._WorkerPoolPromise){let a=await n._WorkerPoolPromise;return await new Promise((o,l)=>{a.push((c,f)=>{let d=m=>{c.removeEventListener("error",d),c.removeEventListener("message",u),l(m),f()},u=m=>{if(m.data.action==="decoded"){if(c.removeEventListener("error",d),c.removeEventListener("message",u),!m.data.success)l({message:m.data.msg});else try{this._createTexture(m.data.decodedData,t,i),o()}catch(g){l({message:g})}f()}};c.addEventListener("error",d),c.addEventListener("message",u),c.postMessage({action:"setDefaultDecoderOptions",options:n.DefaultDecoderOptions._getKTX2DecoderOptions()});let h=new Uint8Array(e.byteLength);h.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),c.postMessage({action:"decode",data:h,caps:s,options:i},[h.buffer])})})}else if(n._DecoderModulePromise){let a=await n._DecoderModulePromise;return n.DefaultDecoderOptions.isDirty&&(n._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=n.DefaultDecoderOptions._getKTX2DecoderOptions()),await new Promise((o,l)=>{a.decode(e,r).then(c=>{this._createTexture(c,t),o()}).catch(c=>{l({message:c})})})}throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let s=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,s=!1;break}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,t.width=e.mipmaps[0].width,t.height=e.mipmaps[0].height,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let a=0;a<e.mipmaps.length;++a){let o=e.mipmaps[a];if(!o||!o.data)throw new Error("KTX2 container - could not transcode one of the image");s?(t.width=o.width,t.height=o.height,this._engine._uploadDataToTextureDirectly(t,o.data,0,a,void 0,!0)):this._engine._uploadCompressedDataToTextureDirectly(t,e.transcodedFormat,o.width,o.height,o.data,0,a)}t._extension=".ktx2",t.isReady=!0,this._engine._bindTextureDirectly(3553,null)}static IsValid(e){if(e.byteLength>=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(t[0]===171&&t[1]===75&&t[2]===84&&t[3]===88&&t[4]===32&&t[5]===50&&t[6]===48&&t[7]===187&&t[8]===13&&t[9]===10&&t[10]===26&&t[11]===10)return!0}return!1}};Gc.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null};Gc.DefaultNumWorkers=Gc.GetDefaultNumWorkers();Gc.DefaultDecoderOptions=new pD});var _D={};Be(_D,{_KTXTextureLoader:()=>gD});function eue(n){switch(n){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 37841:return 37809;case 37842:return 37810;case 37843:return 37811;case 37844:return 37812;case 37845:return 37813;case 37846:return 37814;case 37847:return 37815;case 37848:return 37816;case 37849:return 37817;case 37850:return 37818;case 37851:return 37819;case 37852:return 37820;case 37853:return 37821;case 36493:return 36492}return null}var gD,vD=y(()=>{dW();EW();wt();gD=class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r){if(Array.isArray(e))return;t._invertVScale=!t.invertY;let s=t.getEngine(),a=new Zo(e,6),o=a.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),a.uploadLevels(t,t.generateMipMaps),t.width=a.pixelWidth,t.height=a.pixelHeight,s._setCubeMapTextureParams(t,o,a.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}loadData(e,t,i,r){if(Zo.IsValid(e)){t._invertVScale=!t.invertY;let s=new Zo(e,1),a=eue(s.glInternalFormat);a?(t.format=a,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=s.glInternalFormat,i(s.pixelWidth,s.pixelHeight,t.generateMipMaps,!0,()=>{s.uploadLevels(t,t.generateMipMaps)},s.isInvalid)}else Gc.IsValid(e)?new Gc(t.getEngine())._uploadAsync(e,t,r).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},a=>{te.Warn(`Failed to load KTX2 texture data: ${a.message}`),i(0,0,!1,!1,()=>{},!0)}):(te.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0))}}});function QR(n){let e=0;return{id_length:n[e++],colormap_type:n[e++],image_type:n[e++],colormap_index:n[e++]|n[e++]<<8,colormap_length:n[e++]|n[e++]<<8,colormap_size:n[e++],origin:[n[e++]|n[e++]<<8,n[e++]|n[e++]<<8],width:n[e++]|n[e++]<<8,height:n[e++]|n[e++]<<8,pixel_size:n[e++],flags:n[e]}}function ED(n,e){if(e.length<19){te.Error("Unable to load TGA file - Not enough data to contain header");return}let t=18,i=QR(e);if(i.id_length+t>e.length){te.Error("Unable to load TGA file - Not enough data");return}t+=i.id_length;let r=!1,s=!1,a=!1;switch(i.image_type){case nue:r=!0;case tue:s=!0;break;case sue:r=!0;case iue:break;case aue:r=!0;case rue:a=!0;break}let o,l=i.pixel_size>>3,c=i.width*i.height*l,f;if(s&&(f=e.subarray(t,t+=i.colormap_length*(i.colormap_size>>3))),r){o=new Uint8Array(c);let S,T,A,R=0,M=new Uint8Array(l);for(;t<c&&R<c;)if(S=e[t++],T=(S&127)+1,S&128){for(A=0;A<l;++A)M[A]=e[t++];for(A=0;A<T;++A)o.set(M,R+A*l);R+=l*T}else{for(T*=l,A=0;A<T;++A)o[R+A]=e[t++];R+=T}}else o=e.subarray(t,t+(s?i.width*i.height:c));let d,u,h,m,g,p;switch((i.flags&oue)>>lue){default:case due:d=0,h=1,p=i.width,u=0,m=1,g=i.height;break;case cue:d=0,h=1,p=i.width,u=i.height-1,m=-1,g=-1;break;case uue:d=i.width-1,h=-1,p=-1,u=0,m=1,g=i.height;break;case fue:d=i.width-1,h=-1,p=-1,u=i.height-1,m=-1,g=-1;break}let _="_getImageData"+(a?"Grey":"")+i.pixel_size+"bits",v=Eue[_](i,f,o,u,m,g,d,h,p);n.getEngine()._uploadDataToTextureDirectly(n,v)}function hue(n,e,t,i,r,s,a,o,l){let c=t,f=e,d=n.width,u=n.height,h,m=0,g,p,_=new Uint8Array(d*u*4);for(p=i;p!==s;p+=r)for(g=a;g!==l;g+=o,m++)h=c[m],_[(g+d*p)*4+3]=255,_[(g+d*p)*4+2]=f[h*3+0],_[(g+d*p)*4+1]=f[h*3+1],_[(g+d*p)*4+0]=f[h*3+2];return _}function mue(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,d=n.height,u,h=0,m,g,p=new Uint8Array(f*d*4);for(g=i;g!==s;g+=r)for(m=a;m!==l;m+=o,h+=2){u=c[h+0]+(c[h+1]<<8);let _=((u&31744)>>10)*255/31|0,v=((u&992)>>5)*255/31|0,E=(u&31)*255/31|0;p[(m+f*g)*4+0]=_,p[(m+f*g)*4+1]=v,p[(m+f*g)*4+2]=E,p[(m+f*g)*4+3]=u&32768?0:255}return p}function pue(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,d=n.height,u=0,h,m,g=new Uint8Array(f*d*4);for(m=i;m!==s;m+=r)for(h=a;h!==l;h+=o,u+=3)g[(h+f*m)*4+3]=255,g[(h+f*m)*4+2]=c[u+0],g[(h+f*m)*4+1]=c[u+1],g[(h+f*m)*4+0]=c[u+2];return g}function gue(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,d=n.height,u=0,h,m,g=new Uint8Array(f*d*4);for(m=i;m!==s;m+=r)for(h=a;h!==l;h+=o,u+=4)g[(h+f*m)*4+2]=c[u+0],g[(h+f*m)*4+1]=c[u+1],g[(h+f*m)*4+0]=c[u+2],g[(h+f*m)*4+3]=c[u+3];return g}function _ue(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,d=n.height,u,h=0,m,g,p=new Uint8Array(f*d*4);for(g=i;g!==s;g+=r)for(m=a;m!==l;m+=o,h++)u=c[h],p[(m+f*g)*4+0]=u,p[(m+f*g)*4+1]=u,p[(m+f*g)*4+2]=u,p[(m+f*g)*4+3]=255;return p}function vue(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,d=n.height,u=0,h,m,g=new Uint8Array(f*d*4);for(m=i;m!==s;m+=r)for(h=a;h!==l;h+=o,u+=2)g[(h+f*m)*4+0]=c[u+0],g[(h+f*m)*4+1]=c[u+0],g[(h+f*m)*4+2]=c[u+0],g[(h+f*m)*4+3]=c[u+1];return g}var tue,iue,rue,nue,sue,aue,oue,lue,cue,fue,due,uue,Eue,SW=y(()=>{wt();tue=1,iue=2,rue=3,nue=9,sue=10,aue=11,oue=48,lue=4,cue=0,fue=1,due=2,uue=3;Eue={GetTGAHeader:QR,UploadContent:ED,_getImageData8bits:hue,_getImageData16bits:mue,_getImageData24bits:pue,_getImageData32bits:gue,_getImageDataGrey8bits:_ue,_getImageDataGrey16bits:vue}});var TW={};Be(TW,{_TGATextureLoader:()=>SD});var SD,AW=y(()=>{SW();SD=class{constructor(){this.supportCascades=!1}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=QR(r);i(s.width,s.height,t.generateMipMaps,!1,()=>{ED(t,r)})}}});var zv=y(()=>{});function Tue(){let n=new ArrayBuffer(4),e=new Float32Array(n),t=new Uint32Array(n),i=new Uint32Array(512),r=new Uint32Array(512);for(let l=0;l<256;++l){let c=l-127;c<-27?(i[l]=0,i[l|256]=32768,r[l]=24,r[l|256]=24):c<-14?(i[l]=1024>>-c-14,i[l|256]=1024>>-c-14|32768,r[l]=-c-1,r[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,r[l]=13,r[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,r[l]=24,r[l|256]=24):(i[l]=31744,i[l|256]=64512,r[l]=13,r[l|256]=13)}let s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,f=0;for(;(c&8388608)===0;)c<<=1,f-=8388608;c&=-8388609,f+=947912704,s[l]=c|f}for(let l=1024;l<2048;++l)s[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function eb(n,e){let t=new Uint8Array(n),i=0;for(;t[e.value+i]!=0;)i+=1;let r=new TextDecoder().decode(t.slice(e.value,e.value+i));return e.value=e.value+i+1,r}function qo(n,e){let t=n.getInt32(e.value,!0);return e.value+=4,t}function Oa(n,e){let t=n.getUint32(e.value,!0);return e.value+=4,t}function Wv(n,e){let t=n.getUint8(e.value);return e.value+=1,t}function Rp(n,e){let t=n.getUint16(e.value,!0);return e.value+=2,t}function AD(n,e){let t=n[e.value];return e.value+=1,t}function bW(n,e){let t;return"getBigInt64"in DataView.prototype?t=Number(n.getBigInt64(e.value,!0)):t=n.getUint32(e.value+4,!0)+Number(n.getUint32(e.value,!0)<<32),e.value+=8,t}function kn(n,e){let t=n.getFloat32(e.value,!0);return e.value+=4,t}function MW(n,e){return Aue(Rp(n,e))}function Aue(n){let e=(n&31744)>>10,t=n&1023;return(n>>15?-1:1)*(e?e===31?t?NaN:1/0:Math.pow(2,e-15)*(1+t/1024):6103515625e-14*(t/1024))}function xue(n){if(Math.abs(n)>65504)throw new Error("Value out of range.Consider using float instead of half-float.");n=Gt(n,-65504,65504),$R.floatView[0]=n;let e=$R.uint32View[0],t=e>>23&511;return $R.baseTable[t]+((e&8388607)>>$R.shiftTable[t])}function yW(n,e){return xue(kn(n,e))}function Rue(n,e,t){let i=new TextDecoder().decode(new Uint8Array(n).slice(e.value,e.value+t));return e.value=e.value+t,i}function bue(n,e){let t=qo(n,e),i=Oa(n,e);return[t,i]}function Mue(n,e){let t=Oa(n,e),i=Oa(n,e);return[t,i]}function yue(n,e){let t=kn(n,e),i=kn(n,e);return[t,i]}function Iue(n,e){let t=kn(n,e),i=kn(n,e),r=kn(n,e);return[t,i,r]}function Cue(n,e,t){let i=e.value,r=[];for(;e.value<i+t-1;){let s=eb(n.buffer,e),a=qo(n,e),o=Wv(n,e);e.value+=3;let l=qo(n,e),c=qo(n,e);r.push({name:s,pixelType:a,pLinear:o,xSampling:l,ySampling:c})}return e.value+=1,r}function Pue(n,e){let t=kn(n,e),i=kn(n,e),r=kn(n,e),s=kn(n,e),a=kn(n,e),o=kn(n,e),l=kn(n,e),c=kn(n,e);return{redX:t,redY:i,greenX:r,greenY:s,blueX:a,blueY:o,whiteX:l,whiteY:c}}function Lue(n,e){return Wv(n,e)}function Due(n,e){let t=qo(n,e),i=qo(n,e),r=qo(n,e),s=qo(n,e);return{xMin:t,yMin:i,xMax:r,yMax:s}}function Oue(n,e){let t=Wv(n,e);return TD[t]}function IW(n,e,t,i){switch(t){case"string":case"stringvector":case"iccProfile":return Rue(n.buffer,e,i);case"chlist":return Cue(n,e,i);case"chromaticities":return Pue(n,e);case"compression":return Lue(n,e);case"box2i":return Due(n,e);case"lineOrder":return Oue(n,e);case"float":return kn(n,e);case"v2f":return yue(n,e);case"v3f":return Iue(n,e);case"int":return qo(n,e);case"rational":return bue(n,e);case"timecode":return Mue(n,e);case"preview":return e.value+=i,"skipped";default:e.value+=i;return}}function xD(n){for(let e=1;e<n.length;e++){let t=n[e-1]+n[e]-128;n[e]=t}}function RD(n,e){let t=0,i=Math.floor((n.length+1)/2),r=0,s=n.length-1;for(;!(r>s||(e[r++]=n[t++],r>s));)e[r++]=n[i++]}var Gl,TD,$R,Hv=y(()=>{ts();zv();(function(n){n[n.NO_COMPRESSION=0]="NO_COMPRESSION",n[n.RLE_COMPRESSION=1]="RLE_COMPRESSION",n[n.ZIPS_COMPRESSION=2]="ZIPS_COMPRESSION",n[n.ZIP_COMPRESSION=3]="ZIP_COMPRESSION",n[n.PIZ_COMPRESSION=4]="PIZ_COMPRESSION",n[n.PXR24_COMPRESSION=5]="PXR24_COMPRESSION"})(Gl||(Gl={}));(function(n){n[n.INCREASING_Y=0]="INCREASING_Y",n[n.DECREASING_Y=1]="DECREASING_Y"})(TD||(TD={}));$R=Tue()});function bD(n,e){if(n.getUint32(0,!0)!=Nue)throw new Error("Incorrect OpenEXR format");let t=n.getUint8(4),i=n.getUint8(5),r={singleTile:!!(i&2),longName:!!(i&4),deepFormat:!!(i&8),multiPart:!!(i&16)};e.value=8;let s={},a=!0;for(;a;){let o=eb(n.buffer,e);if(!o)a=!1;else{let l=eb(n.buffer,e),c=Oa(n,e),f=IW(n,e,l,c);f===void 0?te.Warn(`Unknown header attribute type ${l}'.`):s[o]=f}}if((i&-5)!=0)throw new Error("Unsupported file format");return{version:t,spec:r,...s}}var Nue,CW=y(()=>{wt();Hv();Nue=20000630});function BW(n,e){let t=0;for(let r=0;r<65536;++r)(r==0||n[r>>3]&1<<(r&7))&&(e[t++]=r);let i=t-1;for(;t<65536;)e[t++]=0;return i}function Uue(n){for(let e=0;e<16384;e++)n[e]={},n[e].len=0,n[e].lit=0,n[e].p=null}function OW(n,e,t,i,r){for(;t<n;)e=e<<8|AD(i,r),t+=8;return t-=n,{l:e>>t&(1<<n)-1,c:e,lc:t}}function yD(n,e,t,i){return n=n<<8|AD(t,i),e+=8,{c:n,lc:e}}function MD(n,e,t,i,r,s,a,o,l){if(n==e){if(i<8){let d=yD(t,i,r,s);t=d.c,i=d.lc}i-=8;let c=t>>i;if(c=new Uint8Array([c])[0],o.value+c>l)return null;let f=a[o.value-1];for(;c-- >0;)a[o.value++]=f}else if(o.value<l)a[o.value++]=n;else return null;return{c:t,lc:i}}function Vue(n){for(let t=0;t<=58;++t)Xv[t]=0;for(let t=0;t<65537;++t)Xv[n[t]]+=1;let e=0;for(let t=58;t>0;--t){let i=e+Xv[t]>>1;Xv[t]=e,e=i}for(let t=0;t<65537;++t){let i=n[t];i>0&&(n[t]=i|Xv[i]++<<6)}}function Gue(n,e,t,i,r,s){let a=e,o=0,l=0;for(;i<=r;i++){if(a.value-e.value>t)return;let c=OW(6,o,l,n,a),f=c.l;if(o=c.c,l=c.lc,s[i]=f,f==63){if(a.value-e.value>t)throw new Error("Error in HufUnpackEncTable");c=OW(8,o,l,n,a);let d=c.l+6;if(o=c.c,l=c.lc,i+d>r+1)throw new Error("Error in HufUnpackEncTable");for(;d--;)s[i++]=0;i--}else if(f>=59){let d=f-59+2;if(i+d>r+1)throw new Error("Error in HufUnpackEncTable");for(;d--;)s[i++]=0;i--}}Vue(s)}function UW(n){return n&63}function VW(n){return n>>6}function kue(n,e,t,i){for(;e<=t;e++){let r=VW(n[e]),s=UW(n[e]);if(r>>s)throw new Error("Invalid table entry");if(s>14){let a=i[r>>s-14];if(a.len)throw new Error("Invalid table entry");if(a.lit++,a.p){let o=a.p;a.p=new Array(a.lit);for(let l=0;l<a.lit-1;++l)a.p[l]=o[l]}else a.p=new Array(1);a.p[a.lit-1]=e}else if(s){let a=0;for(let o=1<<14-s;o>0;o--){let l=i[(r<<14-s)+a];if(l.len||l.p)throw new Error("Invalid table entry");l.len=s,l.lit=e,a++}}}return!0}function zue(n,e,t,i,r,s,a,o,l){let c=0,f=0,d=a,u=Math.trunc(i.value+(r+7)/8);for(;i.value<u;){let m=yD(c,f,t,i);for(c=m.c,f=m.lc;f>=14;){let g=c>>f-14&16383,p=e[g];if(p.len){f-=p.len;let _=MD(p.lit,s,c,f,t,i,o,l,d);_&&(c=_.c,f=_.lc)}else{if(!p.p)throw new Error("hufDecode issues");let _;for(_=0;_<p.lit;_++){let v=UW(n[p.p[_]]);for(;f<v&&i.value<u;)m=yD(c,f,t,i),c=m.c,f=m.lc;if(f>=v&&VW(n[p.p[_]])==(c>>f-v&(1<<v)-1)){f-=v;let E=MD(p.p[_],s,c,f,t,i,o,l,d);E&&(c=E.c,f=E.lc);break}}if(_==p.lit)throw new Error("HufDecode issues")}}}let h=8-r&7;for(c>>=h,f-=h;f>0;){let m=e[c<<14-f&16383];if(m.len){f-=m.len;let g=MD(m.lit,s,c,f,t,i,o,l,d);g&&(c=g.c,f=g.lc)}else throw new Error("HufDecode issues")}return!0}function GW(n,e,t,i,r,s){let a={value:0},o=t.value,l=Oa(e,t),c=Oa(e,t);t.value+=4;let f=Oa(e,t);if(t.value+=4,l<0||l>=65537||c<0||c>=65537)throw new Error("Wrong HUF_ENCSIZE");let d=new Array(65537),u=new Array(16384);Uue(u);let h=i-(t.value-o);if(Gue(n,t,h,l,c,d),f>8*(i-(t.value-o)))throw new Error("Wrong hufUncompress");kue(d,l,c,u),zue(d,u,n,t,f,c,s,r,a)}function ID(n){return n&65535}function NW(n){let e=ID(n);return e>32767?e-65536:e}function bp(n,e){let t=NW(n),r=NW(e),s=t+(r&1)+(r>>1),a=s,o=s-r;return{a,b:o}}function Mp(n,e){let t=ID(n),i=ID(e),r=t-(i>>1)&DW;return{a:i+r-Bue&DW,b:r}}function kW(n,e,t,i,r,s,a){let o=a<16384,l=t>r?r:t,c=1,f,d;for(;c<=l;)c<<=1;for(c>>=1,f=c,c>>=1;c>=1;){d=0;let u=d+s*(r-f),h=s*c,m=s*f,g=i*c,p=i*f,_,v,E,S;for(;d<=u;d+=m){let T=d,A=d+i*(t-f);for(;T<=A;T+=p){let R=T+g,M=T+h,I=M+g;if(o){let C=bp(n[T+e],n[M+e]);_=C.a,E=C.b,C=bp(n[R+e],n[I+e]),v=C.a,S=C.b,C=bp(_,v),n[T+e]=C.a,n[R+e]=C.b,C=bp(E,S),n[M+e]=C.a,n[I+e]=C.b}else{let C=Mp(n[T+e],n[M+e]);_=C.a,E=C.b,C=Mp(n[R+e],n[I+e]),v=C.a,S=C.b,C=Mp(_,v),n[T+e]=C.a,n[R+e]=C.b,C=Mp(E,S),n[M+e]=C.a,n[I+e]=C.b}}if(t&c){let R=T+h,M;o?M=bp(n[T+e],n[R+e]):M=Mp(n[T+e],n[R+e]),_=M.a,n[R+e]=M.b,n[T+e]=_}}if(r&c){let T=d,A=d+i*(t-f);for(;T<=A;T+=p){let R=T+g,M;o?M=bp(n[T+e],n[R+e]):M=Mp(n[T+e],n[R+e]),_=M.a,n[R+e]=M.b,n[T+e]=_}}f=c,c>>=1}return d}function zW(n,e,t){for(let i=0;i<t;++i)e[i]=n[e[i]]}var FW,Bue,DW,Xv,WW=y(()=>{Hv();zv();FW=16,Bue=1<<FW-1,DW=(1<<FW)-1;Xv=new Array(59)});function HW(n){let e=n.byteLength,t=[],i=0,r=new DataView(n);for(;e>0;){let s=r.getInt8(i++);if(s<0){let a=-s;e-=a+1;for(let o=0;o<a;o++)t.push(r.getUint8(i++))}else{let a=s;e-=2;let o=r.getUint8(i++);for(let l=0;l<a+1;l++)t.push(o)}}return t}var XW=y(()=>{});function CD(n){return new DataView(n.array.buffer,n.offset.value,n.size)}function KW(n){let e=n.viewer.buffer.slice(n.offset.value,n.offset.value+n.size),t=new Uint8Array(HW(e)),i=new Uint8Array(t.length);return xD(t),RD(t,i),new DataView(i.buffer)}function PD(n){let e=n.array.slice(n.offset.value,n.offset.value+n.size),t=fflate.unzlibSync(e),i=new Uint8Array(t.length);return xD(t),RD(t,i),new DataView(i.buffer)}function jW(n){let e=n.array.slice(n.offset.value,n.offset.value+n.size),t=fflate.unzlibSync(e),i=n.lines*n.channels*n.width,r=n.type==1?new Uint16Array(i):new Uint32Array(i),s=0,a=0,o=new Array(4);for(let l=0;l<n.lines;l++)for(let c=0;c<n.channels;c++){let f=0;switch(n.type){case 1:o[0]=s,o[1]=o[0]+n.width,s=o[1]+n.width;for(let d=0;d<n.width;++d){let u=t[o[0]++]<<8|t[o[1]++];f+=u,r[a]=f,a++}break;case 2:o[0]=s,o[1]=o[0]+n.width,o[2]=o[1]+n.width,s=o[2]+n.width;for(let d=0;d<n.width;++d){let u=t[o[0]++]<<24|t[o[1]++]<<16|t[o[2]++]<<8;f+=u,r[a]=f,a++}break}}return new DataView(r.buffer)}function ZW(n){let e=n.viewer,t={value:n.offset.value},i=new Uint16Array(n.width*n.scanlineBlockSize*(n.channels*n.type)),r=new Uint8Array(8192),s=0,a=new Array(n.channels);for(let m=0;m<n.channels;m++)a[m]={},a[m].start=s,a[m].end=a[m].start,a[m].nx=n.width,a[m].ny=n.lines,a[m].size=n.type,s+=a[m].nx*a[m].ny*a[m].size;let o=Rp(e,t),l=Rp(e,t);if(l>=8192)throw new Error("Wrong PIZ_COMPRESSION BITMAP_SIZE");if(o<=l)for(let m=0;m<l-o+1;m++)r[m+o]=Wv(e,t);let c=new Uint16Array(65536),f=BW(r,c),d=Oa(e,t);GW(n.array,e,t,d,i,s);for(let m=0;m<n.channels;++m){let g=a[m];for(let p=0;p<a[m].size;++p)kW(i,g.start+p,g.nx,g.size,g.ny,g.nx*g.size,f)}zW(c,i,s);let u=0,h=new Uint8Array(i.buffer.byteLength);for(let m=0;m<n.lines;m++)for(let g=0;g<n.channels;g++){let p=a[g],_=p.nx*p.size,v=new Uint8Array(i.buffer,p.end*2,_*2);h.set(v,u),u+=_*2,p.end+=_}return new DataView(h.buffer)}var qW=y(()=>{WW();XW();Hv();zv()});var lo,kl,LD=y(()=>{(function(n){n[n.Float=0]="Float",n[n.HalfFloat=1]="HalfFloat"})(lo||(lo={}));kl=class{};kl.DefaultOutputType=lo.HalfFloat;kl.FFLATEUrl="https://unpkg.com/fflate@0.8.2"});async function DD(n,e,t,i){let r={size:0,viewer:e,array:new Uint8Array(e.buffer),offset:t,width:n.dataWindow.xMax-n.dataWindow.xMin+1,height:n.dataWindow.yMax-n.dataWindow.yMin+1,channels:n.channels.length,channelLineOffsets:{},scanOrder:()=>0,bytesPerLine:0,outLineWidth:0,lines:0,scanlineBlockSize:0,inputSize:null,type:0,uncompress:null,getter:()=>0,format:5,outputChannels:0,decodeChannels:{},blockCount:null,byteArray:null,linearSpace:!1,textureType:0};switch(n.compression){case Gl.NO_COMPRESSION:r.lines=1,r.uncompress=CD;break;case Gl.RLE_COMPRESSION:r.lines=1,r.uncompress=KW;break;case Gl.ZIPS_COMPRESSION:r.lines=1,r.uncompress=PD,await pe.LoadScriptAsync(kl.FFLATEUrl);break;case Gl.ZIP_COMPRESSION:r.lines=16,r.uncompress=PD,await pe.LoadScriptAsync(kl.FFLATEUrl);break;case Gl.PIZ_COMPRESSION:r.lines=32,r.uncompress=ZW;break;case Gl.PXR24_COMPRESSION:r.lines=16,r.uncompress=jW,await pe.LoadScriptAsync(kl.FFLATEUrl);break;default:throw new Error(Gl[n.compression]+" is unsupported")}r.scanlineBlockSize=r.lines;let s={};for(let c of n.channels)switch(c.name){case"R":case"G":case"B":case"A":s[c.name]=!0,r.type=c.pixelType;break;case"Y":s[c.name]=!0,r.type=c.pixelType;break;default:break}let a=!1;if(s.R&&s.G&&s.B&&s.A)r.outputChannels=4,r.decodeChannels={R:0,G:1,B:2,A:3};else if(s.R&&s.G&&s.B)a=!0,r.outputChannels=4,r.decodeChannels={R:0,G:1,B:2,A:3};else if(s.R&&s.G)r.outputChannels=2,r.decodeChannels={R:0,G:1};else if(s.R)r.outputChannels=1,r.decodeChannels={R:0};else if(s.Y)r.outputChannels=1,r.decodeChannels={Y:0};else throw new Error("EXRLoader.parse: file contains unsupported data channels.");if(r.type===1)switch(i){case lo.Float:r.getter=MW,r.inputSize=2;break;case lo.HalfFloat:r.getter=Rp,r.inputSize=2;break}else if(r.type===2)switch(i){case lo.Float:r.getter=kn,r.inputSize=4;break;case lo.HalfFloat:r.getter=yW,r.inputSize=4}else throw new Error("Unsupported pixelType "+r.type+" for "+n.compression);r.blockCount=r.height/r.scanlineBlockSize;for(let c=0;c<r.blockCount;c++)bW(e,t);let o=r.width*r.height*r.outputChannels;switch(i){case lo.Float:r.byteArray=new Float32Array(o),r.textureType=1,a&&r.byteArray.fill(1,0,o);break;case lo.HalfFloat:r.byteArray=new Uint16Array(o),r.textureType=2,a&&r.byteArray.fill(15360,0,o);break;default:throw new Error("Unsupported type: "+i)}let l=0;for(let c of n.channels)r.decodeChannels[c.name]!==void 0&&(r.channelLineOffsets[c.name]=l*r.width),l+=c.pixelType*2;return r.bytesPerLine=r.width*l,r.outLineWidth=r.width*r.outputChannels,n.lineOrder==="INCREASING_Y"?r.scanOrder=c=>c:r.scanOrder=c=>r.height-1-c,r.outputChannels==4?(r.format=5,r.linearSpace=!0):(r.format=6,r.linearSpace=!1),r}function OD(n,e,t,i){let r={value:0};for(let s=0;s<n.height/n.scanlineBlockSize;s++){let a=qo(t,i)-e.dataWindow.yMin;n.size=Oa(t,i),n.lines=a+n.scanlineBlockSize>n.height?n.height-a:n.scanlineBlockSize;let l=n.size<n.lines*n.bytesPerLine&&n.uncompress?n.uncompress(n):CD(n);i.value+=n.size;for(let c=0;c<n.scanlineBlockSize;c++){let f=s*n.scanlineBlockSize,d=c+n.scanOrder(f);if(d>=n.height)continue;let u=c*n.bytesPerLine,h=(n.height-1-d)*n.outLineWidth;for(let m=0;m<n.channels;m++){let g=e.channels[m].name,p=n.channelLineOffsets[g],_=n.decodeChannels[g];if(_!==void 0){r.value=u+p;for(let v=0;v<n.width;v++){let E=h+v*n.outputChannels+_;n.byteArray&&(n.byteArray[E]=n.getter(l,r))}}}}}}var QW=y(()=>{Hv();qW();zv();Gi();LD()});var $W={};Be($W,{ReadExrDataAsync:()=>Wue,_ExrTextureLoader:()=>ND});async function Wue(n){let e=new DataView(n),t={value:0},i=bD(e,t);try{let r=await DD(i,e,t,lo.Float);return OD(r,i,e,t),r.byteArray?{width:i.dataWindow.xMax-i.dataWindow.xMin+1,height:i.dataWindow.yMax-i.dataWindow.yMin+1,data:new Float32Array(r.byteArray)}:(te.Error("Failed to decode EXR data: No byte array available."),{width:0,height:0,data:null})}catch(r){te.Error("Failed to load EXR data: ",r)}return{width:0,height:0,data:null}}var ND,JW=y(()=>{CW();QW();LD();wt();ND=class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r,s){throw".exr not supported in Cube."}loadData(e,t,i){let r=new DataView(e.buffer),s={value:0},a=bD(r,s);DD(a,r,s,kl.DefaultOutputType).then(o=>{OD(o,a,r,s);let l=a.dataWindow.xMax-a.dataWindow.xMin+1,c=a.dataWindow.yMax-a.dataWindow.yMin+1;i(l,c,t.generateMipMaps,!1,()=>{let f=t.getEngine();t.format=a.format,t.type=o.textureType,t.invertY=!1,t._gammaSpace=!a.linearSpace,o.byteArray&&f._uploadDataToTextureDirectly(t,o.byteArray,0,0,void 0,!0)})}).catch(o=>{te.Error("Failed to load EXR texture: ",o)})}}});function kc(n,e){Hue(n)&&te.Warn(`Extension with the name '${n}' already exists`),ib.set(n,e)}function Hue(n){return ib.delete(n)}function rb(n,e){(e==="image/ktx"||e==="image/ktx2")&&(n=".ktx"),ib.has(n)||(n.endsWith(".ies")&&kc(".ies",async()=>await Promise.resolve().then(()=>($k(),Qk)).then(i=>new i._IESTextureLoader)),n.endsWith(".dds")&&kc(".dds",async()=>await Promise.resolve().then(()=>(ez(),Jk)).then(i=>new i._DDSTextureLoader)),n.endsWith(".basis")&&kc(".basis",async()=>await Promise.resolve().then(()=>(az(),sz)).then(i=>new i._BasisTextureLoader)),n.endsWith(".env")&&kc(".env",async()=>await Promise.resolve().then(()=>(rW(),iW)).then(i=>new i._ENVTextureLoader)),n.endsWith(".hdr")&&kc(".hdr",async()=>await Promise.resolve().then(()=>(fW(),cW)).then(i=>new i._HDRTextureLoader)),(n.endsWith(".ktx")||n.endsWith(".ktx2"))&&(kc(".ktx",async()=>await Promise.resolve().then(()=>(vD(),_D)).then(i=>new i._KTXTextureLoader)),kc(".ktx2",async()=>await Promise.resolve().then(()=>(vD(),_D)).then(i=>new i._KTXTextureLoader))),n.endsWith(".tga")&&kc(".tga",async()=>await Promise.resolve().then(()=>(AW(),TW)).then(i=>new i._TGATextureLoader)),n.endsWith(".exr")&&kc(".exr",async()=>await Promise.resolve().then(()=>(JW(),$W)).then(i=>new i._ExrTextureLoader)));let t=ib.get(n);return t?Promise.resolve(t(e)):null}var ib,wD=y(()=>{wt();ib=new Map});function eH(n){let e=n.split("?")[0],t=e.lastIndexOf(".");return t>-1?e.substring(t).toLowerCase():""}var tH=y(()=>{});var iH=y(()=>{ea();wt();Cc();Sv();Yr();wD();tH();ye.prototype._partialLoadFile=function(n,e,t,i,r=null){let s=o=>{t[e]=o,t._internalCount++,t._internalCount===6&&i(t)},a=(o,l)=>{r&&o&&r(o.status+" "+o.statusText,l)};this._loadFile(n,s,void 0,void 0,!0,a)};ye.prototype._cascadeLoadFiles=function(n,e,t,i=null){let r=[];r._internalCount=0;for(let s=0;s<6;s++)this._partialLoadFile(t[s],s,r,e,i)};ye.prototype._cascadeLoadImgs=function(n,e,t,i,r=null,s){let a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(i[o],o,a,n,e,t,r,s)};ye.prototype._partialLoadImg=function(n,e,t,i,r,s,a=null,o){let l=Qf();Ep(n,d=>{t[e]=d,t._internalCount++,i&&i.removePendingData(l),t._internalCount===6&&s&&s(r,t)},(d,u)=>{i&&i.removePendingData(l),a&&a(d,u)},i?i.offlineProvider:null,o),i&&i.addPendingData(l)};ye.prototype.createCubeTextureBase=function(n,e,t,i,r=null,s=null,a,o=null,l=!1,c=0,f=0,d=null,u=null,h=null,m=!1,g=null){let p=d||new Xi(this,7);p.isCube=!0,p.url=n,p.generateMipMaps=!i,p._lodGenerationScale=c,p._lodGenerationOffset=f,p._useSRGBBuffer=!!m&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!i),p!==d&&(p.label=n.substring(0,60)),this._doNotHandleContextLost||(p._extension=o,p._files=t,p._buffer=g);let _=n;this._transformTextureUrl&&!d&&(n=this._transformTextureUrl(n));let v=o!=null?o:eH(n),E=rb(v),S=(A,R)=>{p.dispose(),s?s(A,R):A&&te.Warn(A)},T=(A,R)=>{n===_?A&&S(A.status+" "+A.statusText,R):(te.Warn(`Failed to load ${n}, falling back to the ${_}`),this.createCubeTextureBase(_,e,t,!!i,r,S,a,o,l,c,f,p,u,h,m,g))};if(E)E.then(A=>{let R=M=>{u&&u(p,M),A.loadCubeData(M,p,l,r,(I,C)=>{S(I,C)})};g?R(g):t&&t.length===6?A.supportCascades?this._cascadeLoadFiles(e,M=>R(M.map(I=>new Uint8Array(I))),t,S):S("Textures type does not support cascades."):this._loadFile(n,M=>R(new Uint8Array(M)),void 0,e?e.offlineProvider||null:void 0,!0,T)});else{if(!t||t.length===0)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(e,p,(A,R)=>{h&&h(A,R)},t,S)}return this._internalTexturesCache.push(p),p}});var EH={};Be(EH,{DDSTools:()=>Ho});function nb(n){return n.charCodeAt(0)+(n.charCodeAt(1)<<8)+(n.charCodeAt(2)<<16)+(n.charCodeAt(3)<<24)}function Yue(n){return String.fromCharCode(n&255,n>>8&255,n>>16&255,n>>24&255)}var Xue,rH,nH,sH,aH,oH,lH,cH,fH,FD,dH,uH,hH,mH,Kue,BD,jue,Zue,pH,gH,UD,_H,VD,vH,que,Que,$ue,Jue,ehe,the,ihe,Ho,WL=y(()=>{ts();wt();_L();UL();iH();Xue=542327876,rH=131072,nH=512,sH=4,aH=64,oH=131072;lH=nb("DXT1"),cH=nb("DXT3"),fH=nb("DXT5"),FD=nb("DX10"),dH=113,uH=116,hH=2,mH=10,Kue=88,BD=31,jue=0,Zue=1,pH=2,gH=3,UD=4,_H=7,VD=20,vH=21,que=22,Que=23,$ue=24,Jue=25,ehe=26,the=28,ihe=32,Ho=class n{static GetDDSInfo(e){let t=new Int32Array(e.buffer,e.byteOffset,BD),i=new Int32Array(e.buffer,e.byteOffset,BD+4),r=1;t[pH]&rH&&(r=Math.max(1,t[_H]));let s=t[vH],a=s===FD?i[ihe]:0,o=0;switch(s){case dH:o=2;break;case uH:o=1;break;case FD:if(a===mH){o=2;break}if(a===hH){o=1;break}}return{width:t[UD],height:t[gH],mipmapCount:r,isFourCC:(t[VD]&sH)===sH,isRGB:(t[VD]&aH)===aH,isLuminance:(t[VD]&oH)===oH,isCube:(t[the]&nH)===nH,isCompressed:s===lH||s===cH||s===fH,dxgiFormat:a,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,s,a){let o=new Float32Array(r),l=new Uint16Array(s,i),c=0;for(let f=0;f<t;f++)for(let d=0;d<e;d++){let u=(d+f*e)*4;o[c]=wc(l[u]),o[c+1]=wc(l[u+1]),o[c+2]=wc(l[u+2]),n.StoreLODInAlphaChannel?o[c+3]=a:o[c+3]=wc(l[u+3]),c+=4}return o}static _GetHalfFloatRGBAArrayBuffer(e,t,i,r,s,a){if(n.StoreLODInAlphaChannel){let o=new Uint16Array(r),l=new Uint16Array(s,i),c=0;for(let f=0;f<t;f++)for(let d=0;d<e;d++){let u=(d+f*e)*4;o[c]=l[u],o[c+1]=l[u+1],o[c+2]=l[u+2],o[c+3]=Zu(a),c+=4}return o}return new Uint16Array(s,i,r)}static _GetFloatRGBAArrayBuffer(e,t,i,r,s,a){if(n.StoreLODInAlphaChannel){let o=new Float32Array(r),l=new Float32Array(s,i),c=0;for(let f=0;f<t;f++)for(let d=0;d<e;d++){let u=(d+f*e)*4;o[c]=l[u],o[c+1]=l[u+1],o[c+2]=l[u+2],o[c+3]=a,c+=4}return o}return new Float32Array(s,i,r)}static _GetFloatAsHalfFloatRGBAArrayBuffer(e,t,i,r,s,a){let o=new Uint16Array(r),l=new Float32Array(s,i),c=0;for(let f=0;f<t;f++)for(let d=0;d<e;d++)o[c]=Zu(l[c]),o[c+1]=Zu(l[c+1]),o[c+2]=Zu(l[c+2]),n.StoreLODInAlphaChannel?o[c+3]=Zu(a):o[c+3]=Zu(l[c+3]),c+=4;return o}static _GetFloatAsUIntRGBAArrayBuffer(e,t,i,r,s,a){let o=new Uint8Array(r),l=new Float32Array(s,i),c=0;for(let f=0;f<t;f++)for(let d=0;d<e;d++){let u=(d+f*e)*4;o[c]=Gt(l[u])*255,o[c+1]=Gt(l[u+1])*255,o[c+2]=Gt(l[u+2])*255,n.StoreLODInAlphaChannel?o[c+3]=a:o[c+3]=Gt(l[u+3])*255,c+=4}return o}static _GetHalfFloatAsUIntRGBAArrayBuffer(e,t,i,r,s,a){let o=new Uint8Array(r),l=new Uint16Array(s,i),c=0;for(let f=0;f<t;f++)for(let d=0;d<e;d++){let u=(d+f*e)*4;o[c]=Gt(wc(l[u]))*255,o[c+1]=Gt(wc(l[u+1]))*255,o[c+2]=Gt(wc(l[u+2]))*255,n.StoreLODInAlphaChannel?o[c+3]=a:o[c+3]=Gt(wc(l[u+3]))*255,c+=4}return o}static _GetRGBAArrayBuffer(e,t,i,r,s,a,o,l,c){let f=new Uint8Array(r),d=new Uint8Array(s,i),u=0;for(let h=0;h<t;h++)for(let m=0;m<e;m++){let g=(m+h*e)*4;f[u]=d[g+a],f[u+1]=d[g+o],f[u+2]=d[g+l],f[u+3]=d[g+c],u+=4}return f}static _ExtractLongWordOrder(e){return e===0||e===255||e===-16777216?0:1+n._ExtractLongWordOrder(e>>8)}static _GetRGBArrayBuffer(e,t,i,r,s,a,o,l){let c=new Uint8Array(r),f=new Uint8Array(s,i),d=0;for(let u=0;u<t;u++)for(let h=0;h<e;h++){let m=(h+u*e)*3;c[d]=f[m+a],c[d+1]=f[m+o],c[d+2]=f[m+l],d+=3}return c}static _GetLuminanceArrayBuffer(e,t,i,r,s){let a=new Uint8Array(r),o=new Uint8Array(s,i),l=0;for(let c=0;c<t;c++)for(let f=0;f<e;f++){let d=f+c*e;a[l]=o[d],l++}return a}static UploadDDSLevels(e,t,i,r,s,a,o=-1,l,c=!0){let f=null;r.sphericalPolynomial&&(f=[]);let d=!!e.getCaps().s3tc;t.generateMipMaps=s;let u=new Int32Array(i.buffer,i.byteOffset,BD),h,m,g,p=0,_,v,E,S,T=0,A=1;if(u[jue]!==Xue){te.Error("Invalid magic number in DDS header");return}if(!r.isFourCC&&!r.isRGB&&!r.isLuminance){te.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");return}if(r.isCompressed&&!d){te.Error("Compressed textures are not supported on this platform.");return}let R=u[que];_=u[Zue]+4;let M=!1;if(r.isFourCC)switch(h=u[vH],h){case lH:A=8,T=33777;break;case cH:A=16,T=33778;break;case fH:A=16,T=33779;break;case dH:M=!0,R=64;break;case uH:M=!0,R=128;break;case FD:{_+=20;let N=!1;switch(r.dxgiFormat){case mH:M=!0,R=64,N=!0;break;case hH:M=!0,R=128,N=!0;break;case Kue:r.isRGB=!0,r.isFourCC=!1,R=32,N=!0;break}if(N)break}default:te.Error(["Unsupported FourCC code:",Yue(h)]);return}let I=n._ExtractLongWordOrder(u[Que]),C=n._ExtractLongWordOrder(u[$ue]),L=n._ExtractLongWordOrder(u[Jue]),w=n._ExtractLongWordOrder(u[ehe]);M&&(T=e._getRGBABufferInternalSizedFormat(r.textureType)),E=1,u[pH]&rH&&s!==!1&&(E=Math.max(1,u[_H]));let G=l||0,O=e.getCaps();for(let N=G;N<a;N++){for(m=u[UD],g=u[gH],S=0;S<E;++S){if(o===-1||o===S){let B=o===-1?S:0;if(!r.isCompressed&&r.isFourCC){t.format=5,p=m*g*4;let V=null;if(e._badOS||e._badDesktopOS||!O.textureHalfFloat&&!O.textureFloat)R===128?(V=n._GetFloatAsUIntRGBAArrayBuffer(m,g,i.byteOffset+_,p,i.buffer,B),f&&B==0&&f.push(n._GetFloatRGBAArrayBuffer(m,g,i.byteOffset+_,p,i.buffer,B))):R===64&&(V=n._GetHalfFloatAsUIntRGBAArrayBuffer(m,g,i.byteOffset+_,p,i.buffer,B),f&&B==0&&f.push(n._GetHalfFloatAsFloatRGBAArrayBuffer(m,g,i.byteOffset+_,p,i.buffer,B))),t.type=0;else{let q=O.textureFloat&&(c&&O.textureFloatLinearFiltering||!c),K=O.textureHalfFloat&&(c&&O.textureHalfFloatLinearFiltering||!c),J=(R===128||R===64&&!K)&&q?1:(R===64||R===128&&!q)&&K?2:0,Y,j=null;switch(R){case 128:{switch(J){case 1:Y=n._GetFloatRGBAArrayBuffer,j=null;break;case 2:Y=n._GetFloatAsHalfFloatRGBAArrayBuffer,j=n._GetFloatRGBAArrayBuffer;break;case 0:Y=n._GetFloatAsUIntRGBAArrayBuffer,j=n._GetFloatRGBAArrayBuffer;break}break}default:{switch(J){case 1:Y=n._GetHalfFloatAsFloatRGBAArrayBuffer,j=null;break;case 2:Y=n._GetHalfFloatRGBAArrayBuffer,j=n._GetHalfFloatAsFloatRGBAArrayBuffer;break;case 0:Y=n._GetHalfFloatAsUIntRGBAArrayBuffer,j=n._GetHalfFloatAsFloatRGBAArrayBuffer;break}break}}t.type=J,V=Y(m,g,i.byteOffset+_,p,i.buffer,B),f&&B==0&&f.push(j?j(m,g,i.byteOffset+_,p,i.buffer,B):V)}V&&e._uploadDataToTextureDirectly(t,V,N,B)}else if(r.isRGB)t.type=0,R===24?(t.format=4,p=m*g*3,v=n._GetRGBArrayBuffer(m,g,i.byteOffset+_,p,i.buffer,I,C,L),e._uploadDataToTextureDirectly(t,v,N,B)):(t.format=5,p=m*g*4,v=n._GetRGBAArrayBuffer(m,g,i.byteOffset+_,p,i.buffer,I,C,L,w),e._uploadDataToTextureDirectly(t,v,N,B));else if(r.isLuminance){let V=e._getUnpackAlignement(),q=m;p=Math.floor((m+V-1)/V)*V*(g-1)+q,v=n._GetLuminanceArrayBuffer(m,g,i.byteOffset+_,p,i.buffer),t.format=1,t.type=0,e._uploadDataToTextureDirectly(t,v,N,B)}else p=Math.max(4,m)/4*Math.max(4,g)/4*A,v=new Uint8Array(i.buffer,i.byteOffset+_,p),t.type=0,e._uploadCompressedDataToTextureDirectly(t,T,m,g,v,N,B)}_+=R?m*g*(R/8):p,m*=.5,g*=.5,m=Math.max(1,m),g=Math.max(1,g)}if(l!==void 0)break}f&&f.length>0?r.sphericalPolynomial=Pc.ConvertCubeMapToSphericalPolynomial({size:u[UD],right:f[0],left:f[1],up:f[2],down:f[3],front:f[4],back:f[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}};Ho.StoreLODInAlphaChannel=!1});var SH=y(()=>{Is();ea();wt();Ev();Rv();Pt.prototype.createPrefilteredCubeTexture=function(n,e,t,i,r=null,s=null,a,o=null,l=!0){let c=async f=>{var _;if(!f){r&&r(null);return}let d=f.texture;if(l?f.info.sphericalPolynomial&&(d._sphericalPolynomial=f.info.sphericalPolynomial):d._sphericalPolynomial=(_=d._sphericalPolynomial)!=null?_:new wl,d._source=9,this.getCaps().textureLOD){r&&r(d);return}let u=3,h=this._gl,m=f.width;if(!m)return;let{DDSTools:g}=await Promise.resolve().then(()=>(WL(),EH)),p=[];for(let v=0;v<u;v++){let S=1-v/(u-1),T=i,A=Math.log2(m)*t+i,R=T+(A-T)*S,M=Math.round(Math.min(Math.max(R,0),A)),I=new Xi(this,2);if(I.type=d.type,I.format=d.format,I.width=Math.pow(2,Math.max(Math.log2(m)-M,0)),I.height=I.width,I.isCube=!0,I._cachedWrapU=0,I._cachedWrapV=0,this._bindTextureDirectly(h.TEXTURE_CUBE_MAP,I,!0),I.samplingMode=2,h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_MAG_FILTER,h.LINEAR),h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_MIN_FILTER,h.LINEAR),h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),f.isDDS){let L=f.info,w=f.data;this._unpackFlipY(L.isCompressed),g.UploadDDSLevels(this,I,w,L,!0,6,M)}else te.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(h.TEXTURE_CUBE_MAP,null);let C=new Ri(e);C._isCube=!0,C._texture=I,I.isReady=!0,p.push(C)}d._lodTextureHigh=p[2],d._lodTextureMid=p[1],d._lodTextureLow=p[0],r&&r(d)};return this.createCubeTexture(n,e,null,!1,c,s,a,o,l,t,i)}});var TH=y(()=>{Is();lR();Pt.prototype.createUniformBuffer=function(n,e){let t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");let i=new Dl(t);return this.bindUniformBuffer(i),n instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,n,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(n),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};Pt.prototype.createDynamicUniformBuffer=function(n,e){let t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");let i=new Dl(t);return this.bindUniformBuffer(i),n instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,n,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(n),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};Pt.prototype.updateUniformBuffer=function(n,e,t,i){this.bindUniformBuffer(n),t===void 0&&(t=0),i===void 0?e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,e):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,new Float32Array(e)):e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,e.subarray(t,t+i)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(e).subarray(t,t+i)),this.bindUniformBuffer(null)};Pt.prototype.bindUniformBuffer=function(n){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,n?n.underlyingResource:null)};Pt.prototype.bindUniformBufferBase=function(n,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,n?n.underlyingResource:null)};Pt.prototype.bindUniformBlock=function(n,e,t){let i=n.program,r=this._gl.getUniformBlockIndex(i,e);r!==4294967295&&this._gl.uniformBlockBinding(i,r,t)}});var AH=y(()=>{qa();Yr();ye.prototype.displayLoadingUI=function(){if(!Ar())return;let n=this.loadingScreen;n&&n.displayLoadingUI()};ye.prototype.hideLoadingUI=function(){if(!Ar())return;let n=this._loadingScreen;n&&n.hideLoadingUI()};Object.defineProperty(ye.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=ye.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(n){this._loadingScreen=n},enumerable:!0,configurable:!0});Object.defineProperty(ye.prototype,"loadingUIText",{set:function(n){this.loadingScreen.loadingUIText=n},enumerable:!0,configurable:!0});Object.defineProperty(ye.prototype,"loadingUIBackgroundColor",{set:function(n){this.loadingScreen.loadingUIBackgroundColor=n},enumerable:!0,configurable:!0})});var xH=y(()=>{Yr();ye.prototype.getInputElement=function(){return this._renderingCanvas};ye.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null};ye.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null};ye.prototype.getAspectRatio=function(n,e=!1){let t=n.viewport;return this.getRenderWidth(e)*t.width/(this.getRenderHeight(e)*t.height)};ye.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)};ye.prototype._verifyPointerLock=function(){var n;(n=this._onPointerLockChange)==null||n.call(this)}});var GD=y(()=>{Yr();ye.prototype.setAlphaEquation=function(n,e=0){if(this._alphaEquation[e]!==n){switch(n){case 0:this._alphaState.setAlphaEquationParameters(32774,32774,e);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778,e);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779,e);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776,e);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775,e);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774,e);break}this._alphaEquation[e]=n}}});var RH=y(()=>{Yr();GD();ye.prototype.getInputElement=function(){return this._renderingCanvas};ye.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc};ye.prototype.setDepthFunction=function(n){this._depthCullingState.depthFunc=n};ye.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)};ye.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)};ye.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)};ye.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)};ye.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask};ye.prototype.setDepthWrite=function(n){this._depthCullingState.depthMask=n};ye.prototype.setAlphaConstants=function(n,e,t,i){this._alphaState.setAlphaBlendConstants(n,e,t,i)};ye.prototype.getAlphaMode=function(n=0){return this._alphaMode[n]};ye.prototype.getAlphaEquation=function(n=0){return this._alphaEquation[n]}});var bH=y(()=>{Yr();GD();ye.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest};ye.prototype.setStencilBuffer=function(n){this._stencilState.stencilTest=n};ye.prototype.getStencilMask=function(){return this._stencilState.stencilMask};ye.prototype.setStencilMask=function(n){this._stencilState.stencilMask=n};ye.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc};ye.prototype.getStencilBackFunction=function(){return this._stencilState.stencilBackFunc};ye.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef};ye.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask};ye.prototype.setStencilFunction=function(n){this._stencilState.stencilFunc=n};ye.prototype.setStencilBackFunction=function(n){this._stencilState.stencilBackFunc=n};ye.prototype.setStencilFunctionReference=function(n){this._stencilState.stencilFuncRef=n};ye.prototype.setStencilFunctionMask=function(n){this._stencilState.stencilFuncMask=n};ye.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail};ye.prototype.getStencilBackOperationFail=function(){return this._stencilState.stencilBackOpStencilFail};ye.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail};ye.prototype.getStencilBackOperationDepthFail=function(){return this._stencilState.stencilBackOpDepthFail};ye.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass};ye.prototype.getStencilBackOperationPass=function(){return this._stencilState.stencilBackOpStencilDepthPass};ye.prototype.setStencilOperationFail=function(n){this._stencilState.stencilOpStencilFail=n};ye.prototype.setStencilBackOperationFail=function(n){this._stencilState.stencilBackOpStencilFail=n};ye.prototype.setStencilOperationDepthFail=function(n){this._stencilState.stencilOpDepthFail=n};ye.prototype.setStencilBackOperationDepthFail=function(n){this._stencilState.stencilBackOpDepthFail=n};ye.prototype.setStencilOperationPass=function(n){this._stencilState.stencilOpStencilDepthPass=n};ye.prototype.setStencilBackOperationPass=function(n){this._stencilState.stencilBackOpStencilDepthPass=n};ye.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()};ye.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)}});var MH=y(()=>{Yr();ye.prototype.getRenderPassNames=function(){return this._renderPassNames};ye.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]};ye.prototype.createRenderPassId=function(n){let e=++ye._RenderPassIdCounter;return this._renderPassNames[e]=n!=null?n:"NONAME",e};ye.prototype.releaseRenderPassId=function(n){this._renderPassNames[n]=void 0;for(let e=0;e<this.scenes.length;++e){let t=this.scenes[e];for(let i=0;i<t.meshes.length;++i){let r=t.meshes[i];if(r._releaseRenderPassId(n),r.subMeshes)for(let s=0;s<r.subMeshes.length;++s)r.subMeshes[s]._removeDrawWrapper(n)}}}});var yH=y(()=>{Yr();ye.prototype._loadFileAsync=async function(n,e,t){return await new Promise((i,r)=>{this._loadFile(n,s=>{i(s)},void 0,e,t,(s,a)=>{r(a)})})}});var IH=y(()=>{wD();Yr();ye.GetCompatibleTextureLoader=rb});function rhe(n){!n||!n.setAttribute||(n.setAttribute("touch-action","none"),n.style.touchAction="none",n.style.webkitTapHighlightColor="transparent")}function CH(n,e,t){n._onCanvasFocus=()=>{n.onCanvasFocusObservable.notifyObservers(n)},n._onCanvasBlur=()=>{n.onCanvasBlurObservable.notifyObservers(n)},n._onCanvasContextMenu=r=>{n.disableContextMenu&&r.preventDefault()},e.addEventListener("focus",n._onCanvasFocus),e.addEventListener("blur",n._onCanvasBlur),e.addEventListener("contextmenu",n._onCanvasContextMenu),n._onBlur=()=>{n.disablePerformanceMonitorInBackground&&n.performanceMonitor.disable(),n._windowIsBackground=!0},n._onFocus=()=>{n.disablePerformanceMonitorInBackground&&n.performanceMonitor.enable(),n._windowIsBackground=!1},n._onCanvasPointerOut=r=>{document.elementFromPoint(r.clientX,r.clientY)!==e&&n.onCanvasPointerOutObservable.notifyObservers(r)};let i=n.getHostWindow();i&&typeof i.addEventListener=="function"&&(i.addEventListener("blur",n._onBlur),i.addEventListener("focus",n._onFocus)),e.addEventListener("pointerout",n._onCanvasPointerOut),t.doNotHandleTouchAction||rhe(e),!ye.audioEngine&&t.audioEngine&&ye.AudioEngineFactory&&(ye.audioEngine=ye.AudioEngineFactory(n.getRenderingCanvas(),n.getAudioContext(),n.getAudioDestination())),jf()&&(n._onFullscreenChange=()=>{n.isFullscreen=!!document.fullscreenElement,n.isFullscreen&&n._pointerLockRequested&&e&&kD(e)},document.addEventListener("fullscreenchange",n._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",n._onFullscreenChange,!1),n._onPointerLockChange=()=>{n.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",n._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",n._onPointerLockChange,!1)),n.enableOfflineSupport=ye.OfflineProviderFactory!==void 0,n._deterministicLockstep=!!t.deterministicLockstep,n._lockstepMaxSteps=t.lockstepMaxSteps||0,n._timeStep=t.timeStep||1/60}function PH(n,e){Oe.Instances.length===1&&ye.audioEngine&&(ye.audioEngine.dispose(),ye.audioEngine=null);let t=n.getHostWindow();t&&typeof t.removeEventListener=="function"&&(t.removeEventListener("blur",n._onBlur),t.removeEventListener("focus",n._onFocus)),e&&(e.removeEventListener("focus",n._onCanvasFocus),e.removeEventListener("blur",n._onCanvasBlur),e.removeEventListener("pointerout",n._onCanvasPointerOut),e.removeEventListener("contextmenu",n._onCanvasContextMenu)),jf()&&(document.removeEventListener("fullscreenchange",n._onFullscreenChange),document.removeEventListener("mozfullscreenchange",n._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",n._onFullscreenChange),document.removeEventListener("msfullscreenchange",n._onFullscreenChange),document.removeEventListener("pointerlockchange",n._onPointerLockChange),document.removeEventListener("mspointerlockchange",n._onPointerLockChange),document.removeEventListener("mozpointerlockchange",n._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",n._onPointerLockChange))}function LH(n){let e=document.createElement("span");e.textContent="Hg",e.style.font=n;let t=document.createElement("div");t.style.display="inline-block",t.style.width="1px",t.style.height="0px",t.style.verticalAlign="bottom";let i=document.createElement("div");i.style.whiteSpace="nowrap",i.appendChild(e),i.appendChild(t),document.body.appendChild(i);let r,s;try{s=t.getBoundingClientRect().top-e.getBoundingClientRect().top,t.style.verticalAlign="baseline",r=t.getBoundingClientRect().top-e.getBoundingClientRect().top}finally{document.body.removeChild(i)}return{ascent:r,height:s,descent:s-r}}async function DH(n,e,t){return await new Promise((i,r)=>{let s=new Image;s.onload=()=>{s.decode().then(()=>{n.createImageBitmap(s,t).then(a=>{i(a)})})},s.onerror=()=>{r(`Error loading image ${s.src}`)},s.src=e})}function OH(n,e,t,i){let s=n.createCanvas(t,i).getContext("2d");if(!s)throw new Error("Unable to get 2d context for resizeImageBitmap");return s.drawImage(e,0,0),s.getImageData(0,0,t,i).data}function NH(n){let e=n.requestFullscreen||n.webkitRequestFullscreen;e&&e.call(n)}function wH(){let n=document;document.exitFullscreen?document.exitFullscreen():n.webkitCancelFullScreen&&n.webkitCancelFullScreen()}function kD(n){if(n.requestPointerLock){let e=n.requestPointerLock();e instanceof Promise?e.then(()=>{n.focus()}).catch(()=>{}):n.focus()}}function FH(){document.exitPointerLock&&document.exitPointerLock()}var BH=y(()=>{qa();Yr();Yi()});var ze,zD=y(()=>{ea();Yi();Is();NG();lR();wt();rL();wG();VG();GG();kG();zG();XG();YG();KG();SH();TH();AH();xH();RH();bH();MH();oL();yH();IH();Yr();BH();eD();Ll();ze=class n extends Pt{static get NpmPackage(){return ye.NpmPackage}static get Version(){return ye.Version}static get Instances(){return Oe.Instances}static get LastCreatedEngine(){return Oe.LastCreatedEngine}static get LastCreatedScene(){return Oe.LastCreatedScene}static DefaultLoadingScreenFactory(e){return ye.DefaultLoadingScreenFactory(e)}get _supportsHardwareTextureRescaling(){return!!n._RescalePostProcessFactory}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}get performanceMonitor(){return this._performanceMonitor}constructor(e,t,i,r=!1){super(e,t,i,r),this.customAnimationFrameRequester=null,this._performanceMonitor=new fR,this._drawCalls=new Vl,e&&(this._features.supportRenderPasses=!0)}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),CH(this,e,this._creationOptions)}resizeImageBitmap(e,t,i){return OH(this,e,t,i)}async _createImageBitmapFromSource(e,t){return await DH(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&NH(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&wH()}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}setDirectViewport(e,t,i,r){let s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),s}scissorClear(e,t,i,r,s){this.enableScissor(e,t,i,r),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,r){let s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,r)}disableScissor(){let e=this._gl;e.disable(e.SCISSOR_TEST)}getVertexShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(let e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(let e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return LH(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(this._frameHandler!==0){this._frameHandler=0;let{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(e){this._processFrame(e),this._activeRenderLoops.length>0&&this._frameHandler===0&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&kD(this._renderingCanvas)}exitPointerlock(){FH()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){let t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,r,s,a=null){s=s||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);let o=super.createShaderProgram(e,t,i,r,s,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,r,s=null){let a=r.createProgram();if(e.program=a,!a)throw new Error("Unable to create program");if(r.attachShader(a,t),r.attachShader(a,i),this.webGLVersion>1&&s){let o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(a,s),e.transformFeedback=o}return r.linkProgram(a),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),a}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e);for(let t of this.scenes){for(let i of t.postProcesses)i._outputTexture===e&&(i._outputTexture=null);for(let i of t.cameras)for(let r of i._postProcesses)r&&r._outputTexture===e&&(r._outputTexture=null)}}_rescaleTexture(e,t,i,r,s){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);let a=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});if(!this._rescalePostProcess&&n._RescalePostProcessFactory&&(this._rescalePostProcess=n._RescalePostProcessFactory(this)),this._rescalePostProcess){this._rescalePostProcess.externalTextureSamplerBinding=!0;let o=()=>{this._rescalePostProcess.onApply=function(f){f._bindTexture("textureSampler",e)};let c=i;c||(c=this.scenes[this.scenes.length-1]),c.postProcessManager.directRender([this._rescalePostProcess],a,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,r,0,0,t.width,t.height,0),this.unBindFramebuffer(a),a.dispose(),s&&s()},l=this._rescalePostProcess.getEffect();l?l.executeWhenCompiled(o):this._rescalePostProcess.onEffectCreatedObservable.addOnce(c=>{c.executeWhenCompiled(o)})}}wrapWebGLTexture(e,t=!1,i=3,r=0,s=0){let a=new ip(e,this._gl),o=new Xi(this,0,!0);return o._hardwareTexture=a,o.baseWidth=r,o.baseHeight=s,o.width=r,o.height=s,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,r=0){let s=this._gl,a=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),l=this._getRGBABufferInternalSizedFormat(e.type,o),c=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(c,e,!0),this._unpackFlipY(e.invertY);let f=s.TEXTURE_2D;e.isCube&&(f=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(f,r,l,o,a,t),this._bindTextureDirectly(c,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){te.Error("WebGL 1 does not support texture comparison.");return}let i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),t===0?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),t===0?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){let t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");let i=new Dl(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}async _clientWaitAsync(e,t=0,i=10){let r=this._gl;return await new Promise((s,a)=>{Pl(()=>{let o=r.clientWaitSync(e,t,0);if(o==r.WAIT_FAILED)throw new Error("clientWaitSync failed");return o!=r.TIMEOUT_EXPIRED},s,a,i)})}_readPixelsAsync(e,t,i,r,s,a,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");let l=this._gl,c=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,c),l.bufferData(l.PIXEL_PACK_BUFFER,o.byteLength,l.STREAM_READ),l.readPixels(e,t,i,r,s,a,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null);let f=l.fenceSync(l.SYNC_GPU_COMMANDS_COMPLETE,0);return f?(l.flush(),this._clientWaitAsync(f,0,10).then(()=>(l.deleteSync(f),l.bindBuffer(l.PIXEL_PACK_BUFFER,c),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,o),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(c),o))):null}dispose(){this.hideLoadingUI(),this._rescalePostProcess&&this._rescalePostProcess.dispose(),PH(this,this._renderingCanvas),super.dispose()}};ze.ALPHA_DISABLE=0;ze.ALPHA_ADD=1;ze.ALPHA_COMBINE=2;ze.ALPHA_SUBTRACT=3;ze.ALPHA_MULTIPLY=4;ze.ALPHA_MAXIMIZED=5;ze.ALPHA_ONEONE=6;ze.ALPHA_PREMULTIPLIED=7;ze.ALPHA_PREMULTIPLIED_PORTERDUFF=8;ze.ALPHA_INTERPOLATE=9;ze.ALPHA_SCREENMODE=10;ze.DELAYLOADSTATE_NONE=0;ze.DELAYLOADSTATE_LOADED=1;ze.DELAYLOADSTATE_LOADING=2;ze.DELAYLOADSTATE_NOTLOADED=4;ze.NEVER=512;ze.ALWAYS=519;ze.LESS=513;ze.EQUAL=514;ze.LEQUAL=515;ze.GREATER=516;ze.GEQUAL=518;ze.NOTEQUAL=517;ze.KEEP=7680;ze.REPLACE=7681;ze.INCR=7682;ze.DECR=7683;ze.INVERT=5386;ze.INCR_WRAP=34055;ze.DECR_WRAP=34056;ze.TEXTURE_CLAMP_ADDRESSMODE=0;ze.TEXTURE_WRAP_ADDRESSMODE=1;ze.TEXTURE_MIRROR_ADDRESSMODE=2;ze.TEXTUREFORMAT_ALPHA=0;ze.TEXTUREFORMAT_LUMINANCE=1;ze.TEXTUREFORMAT_LUMINANCE_ALPHA=2;ze.TEXTUREFORMAT_RGB=4;ze.TEXTUREFORMAT_RGBA=5;ze.TEXTUREFORMAT_RED=6;ze.TEXTUREFORMAT_R=6;ze.TEXTUREFORMAT_R16_UNORM=33322;ze.TEXTUREFORMAT_RG16_UNORM=33324;ze.TEXTUREFORMAT_RGB16_UNORM=32852;ze.TEXTUREFORMAT_RGBA16_UNORM=32859;ze.TEXTUREFORMAT_R16_SNORM=36760;ze.TEXTUREFORMAT_RG16_SNORM=36761;ze.TEXTUREFORMAT_RGB16_SNORM=36762;ze.TEXTUREFORMAT_RGBA16_SNORM=36763;ze.TEXTUREFORMAT_RG=7;ze.TEXTUREFORMAT_RED_INTEGER=8;ze.TEXTUREFORMAT_R_INTEGER=8;ze.TEXTUREFORMAT_RG_INTEGER=9;ze.TEXTUREFORMAT_RGB_INTEGER=10;ze.TEXTUREFORMAT_RGBA_INTEGER=11;ze.TEXTURETYPE_UNSIGNED_BYTE=0;ze.TEXTURETYPE_UNSIGNED_INT=0;ze.TEXTURETYPE_FLOAT=1;ze.TEXTURETYPE_HALF_FLOAT=2;ze.TEXTURETYPE_BYTE=3;ze.TEXTURETYPE_SHORT=4;ze.TEXTURETYPE_UNSIGNED_SHORT=5;ze.TEXTURETYPE_INT=6;ze.TEXTURETYPE_UNSIGNED_INTEGER=7;ze.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;ze.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;ze.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;ze.TEXTURETYPE_UNSIGNED_INT_24_8=12;ze.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;ze.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;ze.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;ze.TEXTURE_NEAREST_SAMPLINGMODE=1;ze.TEXTURE_BILINEAR_SAMPLINGMODE=2;ze.TEXTURE_TRILINEAR_SAMPLINGMODE=3;ze.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;ze.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;ze.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;ze.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;ze.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;ze.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;ze.TEXTURE_NEAREST_LINEAR=7;ze.TEXTURE_NEAREST_NEAREST=1;ze.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;ze.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;ze.TEXTURE_LINEAR_LINEAR=2;ze.TEXTURE_LINEAR_NEAREST=12;ze.TEXTURE_EXPLICIT_MODE=0;ze.TEXTURE_SPHERICAL_MODE=1;ze.TEXTURE_PLANAR_MODE=2;ze.TEXTURE_CUBIC_MODE=3;ze.TEXTURE_PROJECTION_MODE=4;ze.TEXTURE_SKYBOX_MODE=5;ze.TEXTURE_INVCUBIC_MODE=6;ze.TEXTURE_EQUIRECTANGULAR_MODE=7;ze.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;ze.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;ze.SCALEMODE_FLOOR=1;ze.SCALEMODE_NEAREST=2;ze.SCALEMODE_CEILING=3});var WD,bi,Na=y(()=>{jt();He();Yt();Si();Yi();Mn();Or();WD=class{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new re,this._onClonedObservable=new re,this._inheritVisibility=!1,this._isVisible=!0}},bi=class n{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){let s=this._NodeConstructors[e];return s?s(t,i,r):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return this._nodeDataStorage._doNotSerialize?!0:this._parentNode?this._parentNode.doNotSerialize:!1}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;let t=this._parentNode;if(this._parentNode&&this._parentNode._children!==void 0&&this._parentNode._children!==null){let i=this._parentNode._children.indexOf(this);i!==-1&&this._parentNode._children.splice(i,1),!e&&!this._nodeDataStorage._isDisposed&&this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&((this._parentNode._children===void 0||this._parentNode._children===null)&&(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}get inheritVisibility(){return this._nodeDataStorage._inheritVisibility}set inheritVisibility(e){this._nodeDataStorage._inheritVisibility=e}get isVisible(){return this.inheritVisibility&&this._parentNode&&!this._parentNode.isVisible?!1:this._nodeDataStorage._isVisible}set isVisible(e){this._nodeDataStorage._isVisible=e}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){this._nodeDataStorage._sceneRootNodesIndex===-1&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(this._nodeDataStorage._sceneRootNodesIndex!==-1){let e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,i=!0){this._isDirty=!1,this._nodeDataStorage=new WD,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new re,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=Q.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new re,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||Oe.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return this._behaviors.indexOf(e)!==-1?this:(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{this._behaviors.includes(e)&&e.attach(this)}):e.attach(this),this._behaviors.push(e),this)}removeBehavior(e){let t=this._behaviors.indexOf(e);return t===-1?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)}get behaviors(){return this._behaviors}getBehaviorByName(e){for(let t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return this._parentNode?this._parentNode._isDirty||this._parentUpdateId!==this._parentNode._childUpdateId?!1:this._parentNode.isSynchronized():!0}isSynchronized(){return this._parentNode&&!this.isSynchronizedWithParent()?!1:this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return e===!1?this._nodeDataStorage._isEnabled:this._nodeDataStorage._isEnabled?this._nodeDataStorage._isParentEnabled:!1}_syncParentEnabledState(){if(this._nodeDataStorage._isParentEnabled=this._parentNode?this._parentNode.isEnabled():!0,this._children)for(let e of this._children)e._syncParentEnabledState()}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return this.parent?this.parent===e?!0:this.parent.isDescendantOf(e):!1}_getDescendants(e,t=!1,i){if(this._children)for(let r=0;r<this._children.length;r++){let s=this._children[r];(!i||i(s))&&e.push(s),t||s._getDescendants(e,!1,i)}}getDescendants(e,t){let i=[];return this._getDescendants(i,e,t),i}getChildMeshes(e,t){let i=[];return this._getDescendants(i,e,r=>(!t||t(r))&&r.cullingStrategy!==void 0),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;t<this.animations.length;t++){let i=this.animations[t];if(i.name===e)return i}return null}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=n._AnimationRangeFactory(e,t,i);for(let r=0,s=this.animations.length;r<s;r++)this.animations[r]&&this.animations[r].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,r=this.animations.length;i<r;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}clone(e,t,i){let r=at.Clone(()=>new n(e,this.getScene()),this);if(t&&(r.parent=t),!i){let s=this.getDescendants(!0);for(let a=0;a<s.length;a++){let o=s[a];o.clone(e+"."+o.name,r)}}return r}getAnimationRanges(){let e=[],t;for(t in this._ranges)e.push(this._ranges[t]);return e}beginAnimation(e,t,i,r){let s=this.getAnimationRange(e);return s?this._scene.beginAnimation(this,s.from,s.to,t,i,r):null}serializeAnimationRanges(){let e=[];for(let t in this._ranges){let i=this._ranges[t];if(!i)continue;let r={};r.name=t,r.from=i.from,r.to=i.to,e.push(r)}return e}computeWorldMatrix(e){return this._worldMatrix||(this._worldMatrix=Q.Identity()),this._worldMatrix}dispose(e,t=!1){if(this._nodeDataStorage._isDisposed=!0,!e){let i=this.getDescendants(!0);for(let r of i)r.dispose(e,t)}this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onEnabledStateChangedObservable.clear(),this.onClonedObservable.clear();for(let i of this._behaviors)i.detach();this._behaviors.length=0,this.metadata=null}static ParseAnimationRanges(e,t,i){if(t.ranges)for(let r=0;r<t.ranges.length;r++){let s=t.ranges[r];e.createAnimationRange(s.name,s.from,s.to)}}getHierarchyBoundingVectors(e=!0,t=null){this.getScene().incrementRenderId(),this.computeWorldMatrix(!0);let i,r,s=this;if(s.getBoundingInfo&&s.subMeshes){let a=s.getBoundingInfo();i=a.boundingBox.minimumWorld.clone(),r=a.boundingBox.maximumWorld.clone()}else i=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(e){let a=this.getDescendants(!1);for(let o of a){let l=o;if(l.computeWorldMatrix(!0),t&&!t(l)||!l.getBoundingInfo||l.getTotalVertices()===0)continue;let f=l.getBoundingInfo().boundingBox,d=f.minimumWorld,u=f.maximumWorld;b.CheckExtends(d,i,r),b.CheckExtends(u,i,r)}}return{min:i,max:r}}};bi._AnimationRangeFactory=(n,e,t)=>{throw $e("AnimationRange")};bi._NodeConstructors={};P([F()],bi.prototype,"name",void 0);P([F()],bi.prototype,"id",void 0);P([F()],bi.prototype,"uniqueId",void 0);P([F()],bi.prototype,"state",void 0);P([F()],bi.prototype,"metadata",void 0)});function HD(n,e,t){try{let i=n.next();i.done?e(i):i.value?i.value.then(()=>{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function UH(n=25){let e;return(t,i,r)=>{let s=performance.now();e===void 0||s-e>n?(e=s,setTimeout(()=>{HD(t,i,r)},0)):HD(t,i,r)}}function VH(n,e,t,i,r){let s=()=>{let a,o=l=>{l.done?t(l.value):a===void 0?a=!0:s()};do a=void 0,!r||!r.aborted?e(n,o,i):i(new Error("Aborted")),a===void 0&&(a=!1);while(a)};s()}function Kv(n,e){let t;return VH(n,HD,i=>t=i,i=>{throw i},e),t}async function GH(n,e,t){return await new Promise((i,r)=>{VH(n,e,i,r,t)})}function kH(n,e){return(...t)=>Kv(n(...t),e)}var XD=y(()=>{});var Et,zl=y(()=>{jt();Yt();Wo();Gi();Si();He();Na();wt();ir();Mn();up();pR();Or();Et=class n extends bi{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var i,r,s,a;let e,t;if(this.mode===n.PERSPECTIVE_CAMERA)this.fovMode===n.FOVMODE_VERTICAL_FIXED?(t=this.minZ*2*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=this.minZ*2*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{let o=this.getEngine().getRenderWidth()/2,l=this.getEngine().getRenderHeight()/2;e=((i=this.orthoRight)!=null?i:o)-((r=this.orthoLeft)!=null?r:-o),t=((s=this.orthoTop)!=null?s:l)-((a=this.orthoBottom)!=null?a:-l)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(let t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(let t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(let t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(let t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}setFocalLength(e,t=36){this.fov=2*Math.atan(t/(2*e))}set mode(e){this._mode=e;for(let t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,r=!0){super(e,i,!1),this._position=b.Zero(),this._upVector=b.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=n.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Go(0,0,1,1),this.layerMask=268435455,this.fovMode=n.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=n.RIG_MODE_NONE,this.ignoreCameraMaxZ=!1,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new re,this.onProjectionMatrixChangedObservable=new re,this.onAfterCheckInputsObservable=new re,this.onRestoreStateObservable=new re,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new Q,this._postProcesses=new Array,this._activeMeshes=new Qi(256),this._globalPosition=b.Zero(),this._computedViewMatrix=Q.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=Q.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=je.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.layerMask=this.getScene().defaultCameraLayerMask,this.getScene().addCamera(this),r&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}hasStateStored(){return!!this._stateStored}_restoreStateValues(){return this._stateStored?(this.fov=this._storedFov,!0):!1}restoreState(){return this._restoreStateValues()?(this.onRestoreStateObservable.notifyObservers(this),!0):!1}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}applyVerticalCorrection(){let e=this.absoluteRotation.toEulerAngles();this.projectionPlaneTilt=this._scene.useRightHandedSystem?-e.x:e.x}get globalPosition(){return this._globalPosition}getActiveMeshes(){return this._activeMeshes}isActiveMesh(e){return this._activeMeshes.indexOf(e)!==-1}isReady(e=!1){if(e){for(let t of this._postProcesses)if(t&&!t.isReady())return!1}return super.isReady(e)}_initCache(){super._initCache(),this._cache.position=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.obliqueAngle=void 0,this._cache.obliqueLength=void 0,this._cache.obliqueOffset=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0}_updateCache(e){e||super._updateCache(),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)}_isSynchronized(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()}_isSynchronizedViewMatrix(){return super._isSynchronized()?this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent():!1}_isSynchronizedProjectionMatrix(){let e=this.ignoreCameraMaxZ?0:this.maxZ,t=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===e;if(!t)return!1;let i=this.getEngine();return this.mode===n.PERSPECTIVE_CAMERA?t=this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===i.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:(t=this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===i.getRenderWidth()&&this._cache.renderHeight===i.getRenderHeight(),this.oblique&&(t=t&&this._cache.obliqueAngle===this.oblique.angle&&this._cache.obliqueLength===this.oblique.length&&this._cache.obliqueOffset===this.oblique.offset)),t}attachControl(e,t){}detachControl(e){}update(){this._hasMoved=!1,this._checkInputs(),this.cameraRigMode!==n.RIG_MODE_NONE&&this._updateRigCameras(),this.getViewMatrix(),this.getProjectionMatrix()}_checkInputs(){this.onAfterCheckInputsObservable.notifyObservers(this)}get rigCameras(){return this._rigCameras}get rigPostProcess(){return this._rigPostProcess}_getFirstPostProcess(){for(let e=0;e<this._postProcesses.length;e++)if(this._postProcesses[e]!==null)return this._postProcesses[e];return null}_cascadePostProcessesToRigCams(){let e=this._getFirstPostProcess();e&&e.markTextureDirty();for(let t=0,i=this._rigCameras.length;t<i;t++){let r=this._rigCameras[t],s=r._rigPostProcess;s?(s.getEffectName()==="pass"&&(r.isIntermediate=this._postProcesses.length===0),r._postProcesses=this._postProcesses.slice(0).concat(s),s.markTextureDirty()):r._postProcesses=this._postProcesses.slice(0)}}attachPostProcess(e,t=null){return!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(te.Error("You're trying to reuse a post process not defined as reusable."),0):(t==null||t<0?this._postProcesses.push(e):this._postProcesses[t]===null?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){let t=this._postProcesses.indexOf(e);t!==-1&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)}_getViewMatrix(){return Q.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._worldMatrix.getTranslationToRef(this._globalPosition),this._computedViewMatrix)}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,e!==void 0&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){var a,o,l,c,f,d,u,h,m,g,p,_,v,E,S,T,A,R,M;if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;let t=this.ignoreCameraMaxZ?0:this.maxZ;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=t,this._refreshFrustumPlanes=!0;let i=this.getEngine(),r=this.getScene(),s=i.useReverseDepthBuffer;if(this.mode===n.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=i.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let I;r.useRightHandedSystem?I=Q.PerspectiveFovRHToRef:I=Q.PerspectiveFovLHToRef,I(this.fov,i.getAspectRatio(this),s?t:this.minZ,s?this.minZ:t,this._projectionMatrix,this.fovMode===n.FOVMODE_VERTICAL_FIXED,i.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{let I=i.getRenderWidth()/2,C=i.getRenderHeight()/2;r.useRightHandedSystem?this.oblique?Q.ObliqueOffCenterRHToRef((a=this.orthoLeft)!=null?a:-I,(o=this.orthoRight)!=null?o:I,(l=this.orthoBottom)!=null?l:-C,(c=this.orthoTop)!=null?c:C,s?t:this.minZ,s?this.minZ:t,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,i.isNDCHalfZRange):Q.OrthoOffCenterRHToRef((f=this.orthoLeft)!=null?f:-I,(d=this.orthoRight)!=null?d:I,(u=this.orthoBottom)!=null?u:-C,(h=this.orthoTop)!=null?h:C,s?t:this.minZ,s?this.minZ:t,this._projectionMatrix,i.isNDCHalfZRange):this.oblique?Q.ObliqueOffCenterLHToRef((m=this.orthoLeft)!=null?m:-I,(g=this.orthoRight)!=null?g:I,(p=this.orthoBottom)!=null?p:-C,(_=this.orthoTop)!=null?_:C,s?t:this.minZ,s?this.minZ:t,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,i.isNDCHalfZRange):Q.OrthoOffCenterLHToRef((v=this.orthoLeft)!=null?v:-I,(E=this.orthoRight)!=null?E:I,(S=this.orthoBottom)!=null?S:-C,(T=this.orthoTop)!=null?T:C,s?t:this.minZ,s?this.minZ:t,this._projectionMatrix,i.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=(A=this.oblique)==null?void 0:A.angle,this._cache.obliqueLength=(R=this.oblique)==null?void 0:R.length,this._cache.obliqueOffset=(M=this.oblique)==null?void 0:M.offset,this._cache.renderWidth=i.getRenderWidth(),this._cache.renderHeight=i.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){let t=this,i=this;return(t.radius||(i.target?b.Distance(this.position,i.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?qf.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=qf.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let i=!1;for(let r of this.rigCameras)r._updateFrustumPlanes(),i=i||e.isInFrustum(r._frustumPlanes);return i}else return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw $e("Ray")}getForwardRayToRef(e,t=100,i,r){throw $e("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){let r=this._rigCameras.pop();r&&r.dispose()}if(this._parentContainer){let r=this._parentContainer.cameras.indexOf(this);r>-1&&this._parentContainer.cameras.splice(r,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==n.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let r=this._postProcesses.length;for(;--r>=0;){let s=this._postProcesses[r];s&&s.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){let i=this._rigCameras.pop();i&&i.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=pe.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==n.RIG_MODE_NONE){let i=this.createRigCamera(this.name+"_L",0);i&&(i._isLeftCamera=!0);let r=this.createRigCamera(this.name+"_R",1);r&&(r._isRightCamera=!0),i&&r&&(this._rigCameras.push(i),this._rigCameras.push(r))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return Q.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.ignoreCameraMaxZ?0:this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=pe.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.ignoreCameraMaxZ?0:this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===n.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)}_setupInputs(){}serialize(){let e=at.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),at.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}clone(e,t=null){let i=at.Clone(n.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return i.name=e,i.parent=t,this.onClonedObservable.notifyObservers(i),i}getDirection(e){let t=b.Zero();return this.getDirectionToRef(e,t),t}get absoluteRotation(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation}getDirectionToRef(e,t){b.TransformNormalToRef(e,this.getWorldMatrix(),t)}static GetConstructorFromName(e,t,i,r=0,s=!0){let a=bi.Construct(e,t,i,{interaxial_distance:r,isStereoscopicSideBySide:s});return a||(()=>n._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){let i=e.type,r=n.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),s=at.Parse(r,e,t);if(e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s.inputs&&(s.inputs.parse(e),s._setupInputs()),e.upVector&&(s.upVector=b.FromArray(e.upVector)),s.setPosition&&(s.position.copyFromFloats(0,0,0),s.setPosition(b.FromArray(e.position))),e.target&&s.setTarget&&s.setTarget(b.FromArray(e.target)),e.cameraRigMode){let a=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};s.setCameraRigMode(e.cameraRigMode,a)}if(e.animations){for(let a=0;a<e.animations.length;a++){let o=e.animations[a],l=Vn("BABYLON.Animation");l&&s.animations.push(l.Parse(o))}bi.ParseAnimationRanges(s,e,t)}return e.autoAnimate&&t.beginAnimation(s,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.isEnabled!==void 0&&s.setEnabled(e.isEnabled),s}_calculateHandednessMultiplier(){let e=this.getScene().useRightHandedSystem?-1:1;return this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(e*=-1),e}};Et._CreateDefaultParsedCamera=(n,e)=>{throw $e("UniversalCamera")};Et.PERSPECTIVE_CAMERA=0;Et.ORTHOGRAPHIC_CAMERA=1;Et.FOVMODE_VERTICAL_FIXED=0;Et.FOVMODE_HORIZONTAL_FIXED=1;Et.RIG_MODE_NONE=0;Et.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;Et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;Et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;Et.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;Et.RIG_MODE_STEREOSCOPIC_INTERLACED=14;Et.RIG_MODE_VR=20;Et.RIG_MODE_CUSTOM=22;Et.ForceAttachControlToAlwaysPreventDefault=!1;P([nn("position")],Et.prototype,"_position",void 0);P([nn("upVector")],Et.prototype,"_upVector",void 0);P([F()],Et.prototype,"orthoLeft",null);P([F()],Et.prototype,"orthoRight",null);P([F()],Et.prototype,"orthoBottom",null);P([F()],Et.prototype,"orthoTop",null);P([F()],Et.prototype,"fov",void 0);P([F()],Et.prototype,"projectionPlaneTilt",void 0);P([F()],Et.prototype,"minZ",void 0);P([F()],Et.prototype,"maxZ",void 0);P([F()],Et.prototype,"inertia",void 0);P([F()],Et.prototype,"mode",null);P([F()],Et.prototype,"layerMask",void 0);P([F()],Et.prototype,"fovMode",void 0);P([F()],Et.prototype,"cameraRigMode",void 0);P([F()],Et.prototype,"interaxialDistance",void 0);P([F()],Et.prototype,"isStereoscopicSideBySide",void 0);P([F()],Et.prototype,"ignoreCameraMaxZ",void 0)});var eh,YD=y(()=>{eh=class{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0,this._internalSubMeshId=0}}});var ld,KD=y(()=>{Ol();He();es();ld=class n{constructor(e,t,i){this.vectors=yn(8,b.Zero),this.center=b.Zero(),this.centerWorld=b.Zero(),this.extendSize=b.Zero(),this.extendSizeWorld=b.Zero(),this.directions=yn(3,b.Zero),this.vectorsWorld=yn(8,b.Zero),this.minimumWorld=b.Zero(),this.maximumWorld=b.Zero(),this.minimum=b.Zero(),this.maximum=b.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){let r=e.x,s=e.y,a=e.z,o=t.x,l=t.y,c=t.z,f=this.vectors;this.minimum.copyFromFloats(r,s,a),this.maximum.copyFromFloats(o,l,c),f[0].copyFromFloats(r,s,a),f[1].copyFromFloats(o,l,c),f[2].copyFromFloats(o,s,a),f[3].copyFromFloats(r,l,a),f[4].copyFromFloats(r,s,c),f[5].copyFromFloats(o,l,a),f[6].copyFromFloats(r,l,c),f[7].copyFromFloats(o,s,c),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||Q.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){let t=n._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);let s=r*e,a=i.scaleInPlace(s*.5),o=this.center.subtractToRef(a,t[1]),l=this.center.addToRef(a,t[2]);return this.reConstruct(o,l,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){let t=this.minimumWorld,i=this.maximumWorld,r=this.directions,s=this.vectorsWorld,a=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let o=0;o<8;++o)s[o].copyFrom(a[o]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let o=0;o<8;++o){let l=s[o];b.TransformCoordinatesToRef(a[o],e,l),t.minimizeInPlace(l),i.maximizeInPlace(l)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}b.FromArrayToRef(e.m,0,r[0]),b.FromArrayToRef(e.m,4,r[1]),b.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return n.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return n.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){let t=this.minimumWorld,i=this.maximumWorld,r=t.x,s=t.y,a=t.z,o=i.x,l=i.y,c=i.z,f=e.x,d=e.y,u=e.z,h=-Vt;return!(o-f<h||h>f-r||l-d<h||h>d-s||c-u<h||h>u-a)}intersectsSphere(e){return n.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){let i=this.minimumWorld,r=this.maximumWorld,s=i.x,a=i.y,o=i.z,l=r.x,c=r.y,f=r.z,d=e.x,u=e.y,h=e.z,m=t.x,g=t.y,p=t.z;return!(l<d||s>m||c<u||a>g||f<h||o>p)}dispose(){var e,t;(e=this._drawWrapperFront)==null||e.dispose(),(t=this._drawWrapperBack)==null||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,r){let s=n._TmpVector3[0];return b.ClampToRef(i,e,t,s),b.DistanceSquared(i,s)<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){let r=t[i];for(let s=0;s<8;++s)if(r.dotCoordinate(e[s])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0,s=t[i];for(let a=0;a<8;++a)if(s.dotCoordinate(e[a])>=0){r=!1;break}if(r)return!1}return!0}};ld._TmpVector3=yn(3,b.Zero)});var yp,zH=y(()=>{Ol();He();yp=class n{constructor(e,t,i){this.center=b.Zero(),this.centerWorld=b.Zero(),this.minimum=b.Zero(),this.maximum=b.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);let r=b.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=r*.5,this._update(i||Q.IdentityReadOnly)}scale(e){let t=this.radius*e,i=n._TmpVector3,r=i[0].setAll(t),s=this.center.subtractToRef(r,i[1]),a=this.center.addToRef(r,i[2]);return this.reConstruct(s,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{b.TransformCoordinatesToRef(this.center,e,this.centerWorld);let t=n._TmpVector3[0];b.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){let t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){let t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){let t=b.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)}static Intersects(e,t){let i=b.DistanceSquared(e.centerWorld,t.centerWorld),r=e.radiusWorld+t.radiusWorld;return!(r*r<i)}static CreateFromCenterAndRadius(e,t,i){this._TmpVector3[0].copyFrom(e),this._TmpVector3[1].copyFromFloats(0,0,t),this._TmpVector3[2].copyFrom(e),this._TmpVector3[0].addInPlace(this._TmpVector3[1]),this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);let r=new n(this._TmpVector3[0],this._TmpVector3[2]);return i?r._worldMatrix=i:r._worldMatrix=Q.Identity(),r}};yp._TmpVector3=yn(3,b.Zero)});var jD,ZD,WH,Ds,In,Ip=y(()=>{Ol();He();KD();zH();jD={min:0,max:0},ZD={min:0,max:0},WH=(n,e,t)=>{let i=b.Dot(e.centerWorld,n),r=Math.abs(b.Dot(e.directions[0],n))*e.extendSize.x,s=Math.abs(b.Dot(e.directions[1],n))*e.extendSize.y,a=Math.abs(b.Dot(e.directions[2],n))*e.extendSize.z,o=r+s+a;t.min=i-o,t.max=i+o},Ds=(n,e,t)=>(WH(n,e,jD),WH(n,t,ZD),!(jD.min>ZD.max||ZD.min>jD.max)),In=class n{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new ld(e,t,i),this.boundingSphere=new yp(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){let i=n._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=n._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){let t=b.Minimize(this.minimum,e),i=b.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){let t=ee.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);let i=ee.Vector3[0];return b.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),b.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return(t===2||t===3)&&this.boundingSphere.isCenterInFrustum(e)?!0:this.boundingSphere.isInFrustum(e)?t===1||t===3?!0:this.boundingBox.isInFrustum(e):!1}get diagonalLength(){let e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,n._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!(!this.boundingSphere.centerWorld||!this.boundingSphere.intersectsPoint(e)||!this.boundingBox.intersectsPoint(e))}intersects(e,t){if(!yp.Intersects(this.boundingSphere,e.boundingSphere)||!ld.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;let i=this.boundingBox,r=e.boundingBox;return!(!Ds(i.directions[0],i,r)||!Ds(i.directions[1],i,r)||!Ds(i.directions[2],i,r)||!Ds(r.directions[0],i,r)||!Ds(r.directions[1],i,r)||!Ds(r.directions[2],i,r)||!Ds(b.Cross(i.directions[0],r.directions[0]),i,r)||!Ds(b.Cross(i.directions[0],r.directions[1]),i,r)||!Ds(b.Cross(i.directions[0],r.directions[2]),i,r)||!Ds(b.Cross(i.directions[1],r.directions[0]),i,r)||!Ds(b.Cross(i.directions[1],r.directions[1]),i,r)||!Ds(b.Cross(i.directions[1],r.directions[2]),i,r)||!Ds(b.Cross(i.directions[2],r.directions[0]),i,r)||!Ds(b.Cross(i.directions[2],r.directions[1]),i,r)||!Ds(b.Cross(i.directions[2],r.directions[2]),i,r))}};In._TmpVector3=yn(2,b.Zero)});function HH(n,e,t,i,r=null){let s=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return Cp.extractMinAndMaxIndexed(n,e,t,i,s,a),r&&(s.x-=s.x*r.x+r.y,s.y-=s.y*r.x+r.y,s.z-=s.z*r.x+r.y,a.x+=a.x*r.x+r.y,a.y+=a.y*r.x+r.y,a.z+=a.z*r.x+r.y),{minimum:s,maximum:a}}function sb(n,e,t,i=null,r){let s=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return r||(r=3),Cp.extractMinAndMax(n,e,t,r,s,a),i&&(s.x-=s.x*i.x+i.y,s.y-=s.y*i.x+i.y,s.z-=s.z*i.x+i.y,a.x+=a.x*i.x+i.y,a.y+=a.y*i.x+i.y,a.z+=a.z*i.x+i.y),{minimum:s,maximum:a}}var Cp,ab=y(()=>{jt();He();Yt();Cp=class{static extractMinAndMaxIndexed(e,t,i,r,s,a){for(let o=i;o<i+r;o++){let l=t[o]*3,c=e[l],f=e[l+1],d=e[l+2];s.minimizeInPlaceFromFloats(c,f,d),a.maximizeInPlaceFromFloats(c,f,d)}}static extractMinAndMax(e,t,i,r,s,a){for(let o=t,l=t*r;o<t+i;o++,l+=r){let c=e[l],f=e[l+1],d=e[l+2];s.minimizeInPlaceFromFloats(c,f,d),a.maximizeInPlaceFromFloats(c,f,d)}}};P([ia.filter((...n)=>!Array.isArray(n[0])&&!Array.isArray(n[1]))],Cp,"extractMinAndMaxIndexed",null);P([ia.filter((...n)=>!Array.isArray(n[0]))],Cp,"extractMinAndMax",null)});var sa,jv=y(()=>{qi();YD();Ip();ab();Yu();sa=class n{get materialDefines(){var t;let e=this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:(t=this._getDrawWrapper())==null?void 0:t.defines;return typeof e=="string"?null:e}set materialDefines(e){var i;let t=(i=this._mainDrawWrapperOverride)!=null?i:this._getDrawWrapper(void 0,!0);t.defines=e}_getDrawWrapper(e,t=!1){e=e!=null?e:this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Ps(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0,i=!1){var r;t&&((r=this._drawWrappers[e])==null||r.dispose(i)),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:(t=(e=this._getDrawWrapper())==null?void 0:e.effect)!=null?t:null}get _drawWrapper(){var e;return(e=this._mainDrawWrapperOverride)!=null?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,r=!0){let s=this._drawWrapper;s.setEffect(e,t,r),i!==void 0&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e,t=!1){if(this._drawWrappers)if(e!==void 0){this._removeDrawWrapper(e,!0,t);return}else for(let i of this._drawWrappers)i==null||i.dispose(t);this._drawWrappers=[]}static AddToMesh(e,t,i,r,s,a,o,l=!0){return new n(e,t,i,r,s,a,o,l)}constructor(e,t,i,r,s,a,o,l=!0,c=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=s,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=a,this._renderingMesh=o||a,c&&a.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=a.subMeshes.length-1,l&&(this.refreshBoundingInfo(),a.computeWorldMatrix(!0))}get IsGlobal(){return this.verticesStart===0&&this.verticesCount===this._mesh.getTotalVertices()&&this.indexStart===0&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){let e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){var i;let t=(i=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))!=null?i:this._renderingMesh.material;if(t){if(this._isMultiMaterial(t)){let r=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==r&&(this._currentMaterial=r,this.resetDrawCache()),r}}else return e&&this._mesh.getScene()._hasDefaultMaterial?this._mesh.getScene().defaultMaterial:null;return t}_isMultiMaterial(e){return e.getSubMaterial!==void 0}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(D.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;let t=this._renderingMesh.getIndices(),i;if(this.indexStart===0&&this.indexCount===t.length){let r=this._renderingMesh.getBoundingInfo();i={minimum:r.minimum.clone(),maximum:r.maximum.clone()}}else i=HH(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new In(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){let t=this.getBoundingInfo();return t?t.isInFrustum(e,this._mesh.cullingStrategy):!1}isCompletelyInFrustum(e){let t=this.getBoundingInfo();return t?t.isCompletelyInFrustum(e):!1}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){let i=Math.floor(this.indexCount/3)*6,s=this.verticesStart+this.verticesCount>65535?new Uint32Array(i):new Uint16Array(i),a=0;if(e.length===0)for(let o=this.indexStart;o<this.indexStart+this.indexCount;o+=3)s[a++]=o,s[a++]=o+1,s[a++]=o+1,s[a++]=o+2,s[a++]=o+2,s[a++]=o;else for(let o=this.indexStart;o<this.indexStart+this.indexCount;o+=3)s[a++]=e[o],s[a++]=e[o+1],s[a++]=e[o+1],s[a++]=e[o+2],s[a++]=e[o+2],s[a++]=e[o];this._linesIndexBuffer=t.createIndexBuffer(s),this._linesIndexCount=s.length}return this._linesIndexBuffer}canIntersects(e){let t=this.getBoundingInfo();return t?e.intersectsBox(t.boundingBox):!1}intersects(e,t,i,r,s){let a=this.getMaterial();if(!a)return null;let o=3,l=!1;switch(a.fillMode){case 3:case 5:case 6:case 8:return null;case 7:o=1,l=!0;break;default:break}return a.fillMode===4?i.length?this._intersectLines(e,t,i,this._mesh.intersectionThreshold,r):this._intersectUnIndexedLines(e,t,i,this._mesh.intersectionThreshold,r):!i.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(e,t,i,r,s):this._intersectTriangles(e,t,i,o,l,r,s)}_intersectLines(e,t,i,r,s){let a=null;for(let o=this.indexStart;o<this.indexStart+this.indexCount;o+=2){let l=t[i[o]],c=t[i[o+1]],f=e.intersectionSegment(l,c,r);if(!(f<0)&&(s||!a||f<a.distance)&&(a=new eh(null,null,f),a.faceId=o/2,s))break}return a}_intersectUnIndexedLines(e,t,i,r,s){let a=null;for(let o=this.verticesStart;o<this.verticesStart+this.verticesCount;o+=2){let l=t[o],c=t[o+1],f=e.intersectionSegment(l,c,r);if(!(f<0)&&(s||!a||f<a.distance)&&(a=new eh(null,null,f),a.faceId=o/2,s))break}return a}_intersectTriangles(e,t,i,r,s,a,o){let l=null,c=-1;for(let f=this.indexStart;f<this.indexStart+this.indexCount-(3-r);f+=r){c++;let d=i[f],u=i[f+1],h=i[f+2];if(s&&h===4294967295){f+=2;continue}let m=t[d],g=t[u],p=t[h];if(!m||!g||!p||o&&!o(m,g,p,e,d,u,h))continue;let _=e.intersectsTriangle(m,g,p);if(_){if(_.distance<0)continue;if((a||!l||_.distance<l.distance)&&(l=_,l.faceId=c,a))break}}return l}_intersectUnIndexedTriangles(e,t,i,r,s){let a=null;for(let o=this.verticesStart;o<this.verticesStart+this.verticesCount;o+=3){let l=t[o],c=t[o+1],f=t[o+2];if(s&&!s(l,c,f,e,-1,-1,-1))continue;let d=e.intersectsTriangle(l,c,f);if(d){if(d.distance<0)continue;if((r||!a||d.distance<a.distance)&&(a=d,a.faceId=o/3,r))break}}return a}_rebuild(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)}clone(e,t){let i=new n(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,t,!1);if(!this.IsGlobal){let r=this.getBoundingInfo();if(!r)return i;i._boundingInfo=new In(r.minimum,r.maximum)}return i}dispose(e=!1){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);let t=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(t,1),this.resetDrawCache(void 0,e)}getClassName(){return"SubMesh"}static CreateFromIndices(e,t,i,r,s,a=!0){let o=Number.MAX_VALUE,l=-Number.MAX_VALUE,f=(s||r).getIndices();for(let d=t;d<t+i;d++){let u=f[d];u<o&&(o=u),u>l&&(l=u)}return new n(e,o,l-o+1,t,i,r,s,a)}}});var Zv,Ie,vr=y(()=>{jt();He();qi();Mn();$t();wt();Yt();XD();Tv();jv();Zv=class{},Ie=class n{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=kH(this._applyToCoroutine.bind(this)),this.uniqueId=n._UniqueIdGenerator,n._UniqueIdGenerator++}set(e,t){switch(e.length||te.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case D.PositionKind:this.positions=e;break;case D.NormalKind:this.normals=e;break;case D.TangentKind:this.tangents=e;break;case D.UVKind:this.uvs=e;break;case D.UV2Kind:this.uvs2=e;break;case D.UV3Kind:this.uvs3=e;break;case D.UV4Kind:this.uvs4=e;break;case D.UV5Kind:this.uvs5=e;break;case D.UV6Kind:this.uvs6=e;break;case D.ColorKind:this.colors=e;break;case D.MatricesIndicesKind:this.matricesIndices=e;break;case D.MatricesWeightsKind:this.matricesWeights=e;break;case D.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case D.MatricesWeightsExtraKind:this.matricesWeightsExtra=e;break}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(D.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(D.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(D.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(D.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(D.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(D.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(D.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(D.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(D.UV6Kind,this.uvs6,t),i&&(yield)),this.colors){let r=this.positions&&this.colors.length===this.positions.length?3:4;e.setVerticesData(D.ColorKind,this.colors,t,r),this.hasVertexAlpha&&e.hasVertexAlpha!==void 0&&(e.hasVertexAlpha=!0),i&&(yield)}if(this.matricesIndices&&(e.setVerticesData(D.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(D.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(D.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(D.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){let r=e;r.subMeshes=[];for(let s of this.materialInfos)new sa(s.materialIndex,s.verticesStart,s.verticesCount,s.indexStart,s.indexCount,r)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(D.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(D.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(D.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(D.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(D.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(D.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(D.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(D.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(D.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(D.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(D.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(D.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(D.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(D.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){let s=ee.Vector3[0],a=ee.Vector3[1];for(let o=i;o<i+r;o+=3)b.FromArrayToRef(e,o,s),b.TransformCoordinatesToRef(s,t,a),e[o]=a.x,e[o+1]=a.y,e[o+2]=a.z}static _TransformVector3Normals(e,t,i=0,r=e.length){let s=ee.Vector3[0],a=ee.Vector3[1];for(let o=i;o<i+r;o+=3)b.FromArrayToRef(e,o,s),b.TransformNormalToRef(s,t,a),e[o]=a.x,e[o+1]=a.y,e[o+2]=a.z}static _TransformVector4Normals(e,t,i=0,r=e.length){let s=ee.Vector4[0],a=ee.Vector4[1];for(let o=i;o<i+r;o+=4)Vi.FromArrayToRef(e,o,s),Vi.TransformNormalToRef(s,t,a),e[o]=a.x,e[o+1]=a.y,e[o+2]=a.z,e[o+3]=a.w}static _FlipFaces(e,t=0,i=e.length){for(let r=t;r<t+i;r+=3){let s=e[r+1];e[r+1]=e[r+2],e[r+2]=s}}transform(e){let t=e.determinant()<0;return this.positions&&n._TransformVector3Coordinates(this.positions,e),this.normals&&n._TransformVector3Normals(this.normals,e),this.tangents&&n._TransformVector4Normals(this.tangents,e),t&&this.indices&&n._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];let e=[];for(let t of this.materialInfos){let i=new n;if(this.positions&&(i.positions=this.positions.slice(t.verticesStart*3,(t.verticesCount+t.verticesStart)*3)),this.normals&&(i.normals=this.normals.slice(t.verticesStart*3,(t.verticesCount+t.verticesStart)*3)),this.tangents&&(i.tangents=this.tangents.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.colors&&(i.colors=this.colors.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.uvs&&(i.uvs=this.uvs.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs2&&(i.uvs2=this.uvs2.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs3&&(i.uvs3=this.uvs3.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs4&&(i.uvs4=this.uvs4.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs5&&(i.uvs5=this.uvs5.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs6&&(i.uvs6=this.uvs6.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.matricesIndices&&(i.matricesIndices=this.matricesIndices.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.matricesWeights&&(i.matricesWeights=this.matricesWeights.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.indices){i.indices=[];for(let s=t.indexStart;s<t.indexStart+t.indexCount;s++)i.indices.push(this.indices[s]-t.verticesStart)}let r=new Zv;r.indexStart=0,r.indexCount=i.indices?i.indices.length:0,r.materialIndex=t.materialIndex,r.verticesStart=0,r.verticesCount=(i.positions?i.positions.length:0)/3,i.materialInfos=[r],e.push(i)}return e}merge(e,t=!1,i=!1,r=!1,s=!1){let a=Array.isArray(e)?e.map(o=>({vertexData:o})):[{vertexData:e}];return Kv(this._mergeCoroutine(void 0,a,t,!1,i,r,s))}*_mergeCoroutine(e,t,i=!1,r,s,a=!1,o=!1){var h,m,g,p;this._validate();let l=t.map(_=>_.vertexData),c=this;if(o)for(let _ of l)_&&(_._validate(),!this.normals&&_.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&_.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&_.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&_.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&_.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&_.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&_.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&_.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&_.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&_.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&_.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&_.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&_.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(let _ of l)if(_){if(o)this.normals&&!_.normals&&(_.normals=new Float32Array(_.positions.length)),this.tangents&&!_.tangents&&(_.tangents=new Float32Array(_.positions.length/3*4)),this.uvs&&!_.uvs&&(_.uvs=new Float32Array(_.positions.length/3*2)),this.uvs2&&!_.uvs2&&(_.uvs2=new Float32Array(_.positions.length/3*2)),this.uvs3&&!_.uvs3&&(_.uvs3=new Float32Array(_.positions.length/3*2)),this.uvs4&&!_.uvs4&&(_.uvs4=new Float32Array(_.positions.length/3*2)),this.uvs5&&!_.uvs5&&(_.uvs5=new Float32Array(_.positions.length/3*2)),this.uvs6&&!_.uvs6&&(_.uvs6=new Float32Array(_.positions.length/3*2)),this.colors&&!_.colors&&(_.colors=new Float32Array(_.positions.length/3*4),_.colors.fill(1)),this.matricesIndices&&!_.matricesIndices&&(_.matricesIndices=new Float32Array(_.positions.length/3*4)),this.matricesWeights&&!_.matricesWeights&&(_.matricesWeights=new Float32Array(_.positions.length/3*4)),this.matricesIndicesExtra&&!_.matricesIndicesExtra&&(_.matricesIndicesExtra=new Float32Array(_.positions.length/3*4)),this.matricesWeightsExtra&&!_.matricesWeightsExtra&&(_.matricesWeightsExtra=new Float32Array(_.positions.length/3*4));else if(_._validate(),!this.normals!=!_.normals||!this.tangents!=!_.tangents||!this.uvs!=!_.uvs||!this.uvs2!=!_.uvs2||!this.uvs3!=!_.uvs3||!this.uvs4!=!_.uvs4||!this.uvs5!=!_.uvs5||!this.uvs6!=!_.uvs6||!this.colors!=!_.colors||!this.matricesIndices!=!_.matricesIndices||!this.matricesWeights!=!_.matricesWeights||!this.matricesIndicesExtra!=!_.matricesIndicesExtra||!this.matricesWeightsExtra!=!_.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(a){let _,v=0,E=0,S=[],T=null,A=[];for(let M of this.splitBasedOnMaterialID())A.push({vertexData:M,transform:e});for(let M of t)if(M.vertexData)for(let I of M.vertexData.splitBasedOnMaterialID())A.push({vertexData:I,transform:M.transform});A.sort((M,I)=>{let C=M.vertexData.materialInfos?M.vertexData.materialInfos[0].materialIndex:0,L=I.vertexData.materialInfos?I.vertexData.materialInfos[0].materialIndex:0;return C>L?1:C===L?0:-1});for(let M of A){let I=M.vertexData;if(I.materialInfos?_=I.materialInfos[0].materialIndex:_=0,T&&T.materialIndex===_)T.indexCount+=I.indices.length,T.verticesCount+=I.positions.length/3;else{let C=new Zv;C.materialIndex=_,C.indexStart=v,C.indexCount=I.indices.length,C.verticesStart=E,C.verticesCount=I.positions.length/3,S.push(C),T=C}v+=I.indices.length,E+=I.positions.length/3}let R=A.splice(0,1)[0];c=R.vertexData,e=R.transform,l=A.map(M=>M.vertexData),t=A,this.materialInfos=S}let f=l.reduce((_,v)=>{var E,S;return _+((S=(E=v.indices)==null?void 0:E.length)!=null?S:0)},(m=(h=c.indices)==null?void 0:h.length)!=null?m:0),u=s||l.some(_=>_.indices===c.indices)?(g=c.indices)==null?void 0:g.slice():c.indices;if(f>0){let _=(p=u==null?void 0:u.length)!=null?p:0;if(u||(u=new Array(f)),u.length!==f){if(Array.isArray(u))u.length=f;else{let E=i||u instanceof Uint32Array?new Uint32Array(f):new Uint16Array(f);E.set(u),u=E}e&&e.determinant()<0&&n._FlipFaces(u,0,_)}let v=c.positions?c.positions.length/3:0;for(let{vertexData:E,transform:S}of t)if(E.indices){for(let T=0;T<E.indices.length;T++)u[_+T]=E.indices[T]+v;S&&S.determinant()<0&&n._FlipFaces(u,_,E.indices.length),v+=E.positions.length/3,_+=E.indices.length,r&&(yield)}}return this.indices=u,this.positions=n._MergeElement(D.PositionKind,c.positions,e,t.map(_=>[_.vertexData.positions,_.transform])),r&&(yield),c.normals&&(this.normals=n._MergeElement(D.NormalKind,c.normals,e,t.map(_=>[_.vertexData.normals,_.transform])),r&&(yield)),c.tangents&&(this.tangents=n._MergeElement(D.TangentKind,c.tangents,e,t.map(_=>[_.vertexData.tangents,_.transform])),r&&(yield)),c.uvs&&(this.uvs=n._MergeElement(D.UVKind,c.uvs,e,t.map(_=>[_.vertexData.uvs,_.transform])),r&&(yield)),c.uvs2&&(this.uvs2=n._MergeElement(D.UV2Kind,c.uvs2,e,t.map(_=>[_.vertexData.uvs2,_.transform])),r&&(yield)),c.uvs3&&(this.uvs3=n._MergeElement(D.UV3Kind,c.uvs3,e,t.map(_=>[_.vertexData.uvs3,_.transform])),r&&(yield)),c.uvs4&&(this.uvs4=n._MergeElement(D.UV4Kind,c.uvs4,e,t.map(_=>[_.vertexData.uvs4,_.transform])),r&&(yield)),c.uvs5&&(this.uvs5=n._MergeElement(D.UV5Kind,c.uvs5,e,t.map(_=>[_.vertexData.uvs5,_.transform])),r&&(yield)),c.uvs6&&(this.uvs6=n._MergeElement(D.UV6Kind,c.uvs6,e,t.map(_=>[_.vertexData.uvs6,_.transform])),r&&(yield)),c.colors&&(this.colors=n._MergeElement(D.ColorKind,c.colors,e,t.map(_=>[_.vertexData.colors,_.transform])),(c.hasVertexAlpha!==void 0||t.some(_=>_.vertexData.hasVertexAlpha!==void 0))&&(this.hasVertexAlpha=c.hasVertexAlpha||t.some(_=>_.vertexData.hasVertexAlpha)),r&&(yield)),c.matricesIndices&&(this.matricesIndices=n._MergeElement(D.MatricesIndicesKind,c.matricesIndices,e,t.map(_=>[_.vertexData.matricesIndices,_.transform])),r&&(yield)),c.matricesWeights&&(this.matricesWeights=n._MergeElement(D.MatricesWeightsKind,c.matricesWeights,e,t.map(_=>[_.vertexData.matricesWeights,_.transform])),r&&(yield)),c.matricesIndicesExtra&&(this.matricesIndicesExtra=n._MergeElement(D.MatricesIndicesExtraKind,c.matricesIndicesExtra,e,t.map(_=>[_.vertexData.matricesIndicesExtra,_.transform])),r&&(yield)),c.matricesWeightsExtra&&(this.matricesWeightsExtra=n._MergeElement(D.MatricesWeightsExtraKind,c.matricesWeightsExtra,e,t.map(_=>[_.vertexData.matricesWeightsExtra,_.transform]))),this}static _MergeElement(e,t,i,r){let s=r.filter(l=>l[0]!==null&&l[0]!==void 0);if(!t&&s.length==0)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));let a=s.reduce((l,c)=>l+c[0].length,t.length),o=e===D.PositionKind?n._TransformVector3Coordinates:e===D.NormalKind?n._TransformVector3Normals:e===D.TangentKind?n._TransformVector4Normals:()=>{};if(t instanceof Float32Array){let l=new Float32Array(a);l.set(t),i&&o(l,i,0,t.length);let c=t.length;for(let[f,d]of s)l.set(f,c),d&&o(l,d,c,f.length),c+=f.length;return l}else{let l=new Array(a);for(let f=0;f<t.length;f++)l[f]=t[f];i&&o(l,i,0,t.length);let c=t.length;for(let[f,d]of s){for(let u=0;u<f.length;u++)l[c+u]=f[u];d&&o(l,d,c,f.length),c+=f.length}return l}}_validate(){if(!this.positions)throw new ra("Positions are required",$a.MeshInvalidPositionsError);let e=(r,s)=>{let a=D.DeduceStride(r);if(s.length%a!==0)throw new Error("The "+r+"s array count must be a multiple of "+a);return s.length/a},t=e(D.PositionKind,this.positions),i=(r,s)=>{let a=e(r,s);if(a!==t)throw new Error("The "+r+"s element count ("+a+") does not match the positions count ("+t+")")};this.normals&&i(D.NormalKind,this.normals),this.tangents&&i(D.TangentKind,this.tangents),this.uvs&&i(D.UVKind,this.uvs),this.uvs2&&i(D.UV2Kind,this.uvs2),this.uvs3&&i(D.UV3Kind,this.uvs3),this.uvs4&&i(D.UV4Kind,this.uvs4),this.uvs5&&i(D.UV5Kind,this.uvs5),this.uvs6&&i(D.UV6Kind,this.uvs6),this.colors&&i(D.ColorKind,this.colors),this.matricesIndices&&i(D.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(D.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(D.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(D.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){let e=this.serialize();return n.Parse(e)}serialize(){let e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndicesExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtraExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=this.indices?Array.from(this.indices):[],this.materialInfos){e.materialInfos=[];for(let t of this.materialInfos){let i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return n._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return n._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){let r=new n;if(e.isVerticesDataPresent(D.PositionKind)&&(r.positions=e.getVerticesData(D.PositionKind,t,i)),e.isVerticesDataPresent(D.NormalKind)&&(r.normals=e.getVerticesData(D.NormalKind,t,i)),e.isVerticesDataPresent(D.TangentKind)&&(r.tangents=e.getVerticesData(D.TangentKind,t,i)),e.isVerticesDataPresent(D.UVKind)&&(r.uvs=e.getVerticesData(D.UVKind,t,i)),e.isVerticesDataPresent(D.UV2Kind)&&(r.uvs2=e.getVerticesData(D.UV2Kind,t,i)),e.isVerticesDataPresent(D.UV3Kind)&&(r.uvs3=e.getVerticesData(D.UV3Kind,t,i)),e.isVerticesDataPresent(D.UV4Kind)&&(r.uvs4=e.getVerticesData(D.UV4Kind,t,i)),e.isVerticesDataPresent(D.UV5Kind)&&(r.uvs5=e.getVerticesData(D.UV5Kind,t,i)),e.isVerticesDataPresent(D.UV6Kind)&&(r.uvs6=e.getVerticesData(D.UV6Kind,t,i)),e.isVerticesDataPresent(D.ColorKind)){let s=e.geometry||e,a=s.getVertexBuffer(D.ColorKind),o=s.getVerticesData(D.ColorKind,t,i);if(a.getSize()===3){let l=new Float32Array(o.length*4/3);for(let c=0,f=0;c<o.length;c+=3,f+=4)l[f]=o[c],l[f+1]=o[c+1],l[f+2]=o[c+2],l[f+3]=1;r.colors=l}else if(a.getSize()===4)r.colors=o;else throw new Error(`Unexpected number of color components: ${a.getSize()}`)}return e.isVerticesDataPresent(D.MatricesIndicesKind)&&(r.matricesIndices=e.getVerticesData(D.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(D.MatricesWeightsKind)&&(r.matricesWeights=e.getVerticesData(D.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(D.MatricesIndicesExtraKind)&&(r.matricesIndicesExtra=e.getVerticesData(D.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(D.MatricesWeightsExtraKind)&&(r.matricesWeightsExtra=e.getVerticesData(D.MatricesWeightsExtraKind,t,i)),r.indices=e.getIndices(t,i),r}static CreateRibbon(e){throw $e("ribbonBuilder")}static CreateBox(e){throw $e("boxBuilder")}static CreateTiledBox(e){throw $e("tiledBoxBuilder")}static CreateTiledPlane(e){throw $e("tiledPlaneBuilder")}static CreateSphere(e){throw $e("sphereBuilder")}static CreateCylinder(e){throw $e("cylinderBuilder")}static CreateTorus(e){throw $e("torusBuilder")}static CreateLineSystem(e){throw $e("linesBuilder")}static CreateDashedLines(e){throw $e("linesBuilder")}static CreateGround(e){throw $e("groundBuilder")}static CreateTiledGround(e){throw $e("groundBuilder")}static CreateGroundFromHeightMap(e){throw $e("groundBuilder")}static CreatePlane(e){throw $e("planeBuilder")}static CreateDisc(e){throw $e("discBuilder")}static CreatePolygon(e,t,i,r,s,a,o){throw $e("polygonBuilder")}static CreateIcoSphere(e){throw $e("icoSphereBuilder")}static CreatePolyhedron(e){throw $e("polyhedronBuilder")}static CreateCapsule(e={orientation:b.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw $e("capsuleBuilder")}static CreateTorusKnot(e){throw $e("torusKnotBuilder")}static ComputeNormals(e,t,i,r){let s,a,o,l,c,f,d,u,h,m,g,p,_,v,E,S,T,A,R,M,I=!1,C=!1,L=!1,w=!1,G=1,O=0,N=null;r&&(I=!!r.facetNormals,C=!!r.facetPositions,L=!!r.facetPartitioning,G=r.useRightHandedSystem===!0?-1:1,O=r.ratio||0,w=!!r.depthSort,N=r.distanceTo,w&&N===void 0&&(N=b.Zero()));let B=0,V=0,q=0,K=0;for(L&&r&&r.bbSize&&(B=r.subDiv.X*O/r.bbSize.x,V=r.subDiv.Y*O/r.bbSize.y,q=r.subDiv.Z*O/r.bbSize.z,K=r.subDiv.max*r.subDiv.max,r.facetPartitioning.length=0),s=0;s<e.length;s++)i[s]=0;let J=t.length/3|0;for(s=0;s<J;s++){if(p=t[s*3]*3,_=p+1,v=p+2,E=t[s*3+1]*3,S=E+1,T=E+2,A=t[s*3+2]*3,R=A+1,M=A+2,a=e[p]-e[E],o=e[_]-e[S],l=e[v]-e[T],c=e[A]-e[E],f=e[R]-e[S],d=e[M]-e[T],u=G*(o*d-l*f),h=G*(l*c-a*d),m=G*(a*f-o*c),g=Math.sqrt(u*u+h*h+m*m),g=g===0?1:g,u/=g,h/=g,m/=g,I&&r&&(r.facetNormals[s].x=u,r.facetNormals[s].y=h,r.facetNormals[s].z=m),C&&r&&(r.facetPositions[s].x=(e[p]+e[E]+e[A])/3,r.facetPositions[s].y=(e[_]+e[S]+e[R])/3,r.facetPositions[s].z=(e[v]+e[T]+e[M])/3),L&&r){let Y=Math.floor((r.facetPositions[s].x-r.bInfo.minimum.x*O)*B),j=Math.floor((r.facetPositions[s].y-r.bInfo.minimum.y*O)*V),ue=Math.floor((r.facetPositions[s].z-r.bInfo.minimum.z*O)*q),Ee=Math.floor((e[p]-r.bInfo.minimum.x*O)*B),Ue=Math.floor((e[_]-r.bInfo.minimum.y*O)*V),se=Math.floor((e[v]-r.bInfo.minimum.z*O)*q),ve=Math.floor((e[E]-r.bInfo.minimum.x*O)*B),ne=Math.floor((e[S]-r.bInfo.minimum.y*O)*V),me=Math.floor((e[T]-r.bInfo.minimum.z*O)*q),Le=Math.floor((e[A]-r.bInfo.minimum.x*O)*B),de=Math.floor((e[R]-r.bInfo.minimum.y*O)*V),be=Math.floor((e[M]-r.bInfo.minimum.z*O)*q),we=Ee+r.subDiv.max*Ue+K*se,dt=ve+r.subDiv.max*ne+K*me,Ve=Le+r.subDiv.max*de+K*be,Ze=Y+r.subDiv.max*j+K*ue;r.facetPartitioning[Ze]=r.facetPartitioning[Ze]?r.facetPartitioning[Ze]:[],r.facetPartitioning[we]=r.facetPartitioning[we]?r.facetPartitioning[we]:[],r.facetPartitioning[dt]=r.facetPartitioning[dt]?r.facetPartitioning[dt]:[],r.facetPartitioning[Ve]=r.facetPartitioning[Ve]?r.facetPartitioning[Ve]:[],r.facetPartitioning[we].push(s),dt!=we&&r.facetPartitioning[dt].push(s),Ve==dt||Ve==we||r.facetPartitioning[Ve].push(s),Ze==we||Ze==dt||Ze==Ve||r.facetPartitioning[Ze].push(s)}if(w&&r&&r.facetPositions){let Y=r.depthSortedFacets[s];Y.ind=s*3,Y.sqDistance=b.DistanceSquared(r.facetPositions[s],N)}i[p]+=u,i[_]+=h,i[v]+=m,i[E]+=u,i[S]+=h,i[T]+=m,i[A]+=u,i[R]+=h,i[M]+=m}for(s=0;s<i.length/3;s++)u=i[s*3],h=i[s*3+1],m=i[s*3+2],g=Math.sqrt(u*u+h*h+m*m),g=g===0?1:g,u/=g,h/=g,m/=g,i[s*3]=u,i[s*3+1]=h,i[s*3+2]=m}static _ComputeSides(e,t,i,r,s,a,o){let l=i.length,c=r.length,f,d;switch(e=e||n.DEFAULTSIDE,e){case n.FRONTSIDE:break;case n.BACKSIDE:for(f=0;f<l;f+=3){let u=i[f];i[f]=i[f+2],i[f+2]=u}for(d=0;d<c;d++)r[d]=-r[d];break;case n.DOUBLESIDE:{let u=t.length,h=u/3;for(let p=0;p<u;p++)t[u+p]=t[p];for(f=0;f<l;f+=3)i[f+l]=i[f+2]+h,i[f+1+l]=i[f+1]+h,i[f+2+l]=i[f]+h;for(d=0;d<c;d++)r[c+d]=-r[d];let m=s.length,g;for(g=0;g<m;g++)s[g+m]=s[g];for(a=a||new Vi(0,0,1,1),o=o||new Vi(0,0,1,1),g=0,f=0;f<m/2;f++)s[g]=a.x+(a.z-a.x)*s[g],s[g+1]=a.y+(a.w-a.y)*s[g+1],s[g+m]=o.x+(o.z-o.x)*s[g+m],s[g+m+1]=o.y+(o.w-o.y)*s[g+m+1],g+=2;break}}}static Parse(e){let t=new n,i=e.positions;i&&t.set(i,D.PositionKind);let r=e.normals;r&&t.set(r,D.NormalKind);let s=e.tangents;s&&t.set(s,D.TangentKind);let a=e.uvs;a&&t.set(a,D.UVKind);let o=e.uvs2;o&&t.set(o,D.UV2Kind);let l=e.uvs3;l&&t.set(l,D.UV3Kind);let c=e.uvs4;c&&t.set(c,D.UV4Kind);let f=e.uvs5;f&&t.set(f,D.UV5Kind);let d=e.uvs6;d&&t.set(d,D.UV6Kind);let u=e.colors;u&&(t.set(ht.CheckColors4(u,i.length/3),D.ColorKind),e.hasVertexAlpha!==void 0&&(t.hasVertexAlpha=e.hasVertexAlpha));let h=e.matricesIndices;h&&t.set(h,D.MatricesIndicesKind);let m=e.matricesWeights;m&&t.set(m,D.MatricesWeightsKind);let g=e.indices;g&&(t.indices=g);let p=e.materialInfos;if(p){t.materialInfos=[];for(let _ of p){let v=new Zv;v.indexCount=_.indexCount,v.indexStart=_.indexStart,v.verticesCount=_.verticesCount,v.verticesStart=_.verticesStart,v.materialIndex=_.materialIndex,t.materialInfos.push(v)}}return t}static ImportVertexData(e,t){let i=n.Parse(e);t.setAllVerticesData(i,e.updatable)}};Ie.FRONTSIDE=0;Ie.BACKSIDE=1;Ie.DOUBLESIDE=2;Ie.DEFAULTSIDE=0;Ie._UniqueIdGenerator=0;P([ia.filter((...n)=>!Array.isArray(n[0]))],Ie,"_TransformVector3Coordinates",null);P([ia.filter((...n)=>!Array.isArray(n[0]))],Ie,"_TransformVector3Normals",null);P([ia.filter((...n)=>!Array.isArray(n[0]))],Ie,"_TransformVector4Normals",null);P([ia.filter((...n)=>!Array.isArray(n[0]))],Ie,"_FlipFaces",null)});var an,ob=y(()=>{an=class n{static get ForceFullSceneLoadingForIncremental(){return n._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){n._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return n._ShowLoadingScreen}static set ShowLoadingScreen(e){n._ShowLoadingScreen=e}static get loggingLevel(){return n._LoggingLevel}static set loggingLevel(e){n._LoggingLevel=e}static get CleanBoneMatrixWeights(){return n._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){n._CleanBoneMatrixWeights=e}};an._ForceFullSceneLoadingForIncremental=!1;an._ShowLoadingScreen=!0;an._CleanBoneMatrixWeights=!1;an._LoggingLevel=0});var Cn,lb=y(()=>{He();$t();vr();qi();jv();ob();Ip();Gi();td();ab();Yi();vn();_p();Cn=class n{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){let t=new n(n.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,s=null,a=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._extend={minimum:new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),maximum:new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||Oe.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,a!==null&&(this._totalVertices=a),i?this.setAllVerticesData(i,r):a===null&&(this._totalVertices=0),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return this.delayLoadState===1||this.delayLoadState===0}get doNotSerialize(){for(let e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0}_rebuild(){this._vertexArrayObjects&&(this._vertexArrayObjects={}),this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer"));let e=new Set;for(let t in this._vertexBuffers)e.add(this._vertexBuffers[t].getWrapperBuffer());e.forEach(t=>{t._rebuild()})}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,r){i&&Array.isArray(t)&&(t=new Float32Array(t));let s=new D(this._engine,t,e,{updatable:i,postponeInternalCreation:this._meshes.length===0,stride:r,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(s)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){let r=e.getKind();this._vertexBuffers[r]&&i&&this._vertexBuffers[r].dispose(),e._buffer&&e._ownsBuffer&&e._buffer._increaseReferences(),this._vertexBuffers[r]=e;let s=this._meshes,a=s.length;if(r===D.PositionKind){this._totalVertices=t!=null?t:e._maxVerticesCount,this._updateExtend(this.useBoundingInfoFromGeometry&&this._boundingInfo?null:e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();let o=this._extend&&this._extend.minimum||new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),l=this._extend&&this._extend.maximum||new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let c=0;c<a;c++){let f=s[c];f.buildBoundingInfo(o,l),f._createGlobalSubMesh(f.isUnIndexed),f.computeWorldMatrix(!0),f.synchronizeInstances()}}this._notifyUpdate(r)}updateVerticesDataDirectly(e,t,i,r=!1){let s=this.getVertexBuffer(e);s&&(s.updateDirectly(t,i,r),this._notifyUpdate(e))}updateVerticesData(e,t,i=!1){let r=this.getVertexBuffer(e);r&&(r.update(t),e===D.PositionKind&&this._updateBoundingInfo(i,t),this._notifyUpdate(e))}_updateBoundingInfo(e,t){if(e&&this._updateExtend(t),this._resetPointsArrayCache(),e){let i=this._meshes;for(let r of i){r.hasBoundingInfo?r.getBoundingInfo().reConstruct(this._extend.minimum,this._extend.maximum):r.buildBoundingInfo(this._extend.minimum,this._extend.maximum);let s=r.subMeshes;for(let a of s)a.refreshBoundingInfo()}}}_bind(e,t,i,r){if(!e)return;t===void 0&&(t=this._indexBuffer);let s=this.getVertexBuffers();if(!s)return;if(t!=this._indexBuffer||!this._vertexArrayObjects&&!r){this._engine.bindBuffers(s,t,e,i);return}let a=r||this._vertexArrayObjects,o=this._engine;a[e.key]||(a[e.key]=o.recordVertexArrayObject(s,t,e,i)),o.bindVertexArrayObject(a[e.key],t)}getTotalVertices(){return this.isReady()?this._totalVertices:0}getVerticesData(e,t,i){let r=this.getVertexBuffer(e);return r?r.getFloatData(this._totalVertices,i||t&&this._meshes.length!==1):null}copyVerticesData(e,t){let i=this.getVertexBuffer(e);if(!i)return;t[e]||(t[e]=new Float32Array(this._totalVertices*i.getSize()));let r=i.getData();r&&gk(r,i.getSize(),i.type,i.byteOffset,i.byteStride,i.normalized,this._totalVertices,t[e])}isVertexBufferUpdatable(e){let t=this._vertexBuffers[e];return t?t.isUpdatable():!1}getVertexBuffer(e){return this.isReady()?this._vertexBuffers[e]:null}getVertexBuffers(){return this.isReady()?this._vertexBuffers:null}isVerticesDataPresent(e){return this._vertexBuffers?this._vertexBuffers[e]!==void 0:this._delayInfo?this._delayInfo.indexOf(e)!==-1:!1}getVerticesDataKinds(){let e=[],t;if(!this._vertexBuffers&&this._delayInfo)for(t in this._delayInfo)e.push(t);else for(t in this._vertexBuffers)e.push(t);return e}updateIndices(e,t,i=!1){if(this._indexBuffer)if(!this._indexBufferIsUpdatable)this.setIndices(e,null,!0);else{let r=e.length!==this._indices.length;if(i||(this._indices=e.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,e,t),r)for(let s of this._meshes)s._createGlobalSubMesh(!0)}}setIndexBuffer(e,t,i,r=null){this._indices=[],this._indexBufferIsUpdatable=!1,this._indexBuffer=e,this._totalVertices=t,this._totalIndices=i,r===null?e.is32Bits=t>65535:e.is32Bits=r;for(let s of this._meshes)s._createGlobalSubMesh(!0),s.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1,r=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),t!=null&&(this._totalVertices=t);for(let s of this._meshes)s._createGlobalSubMesh(!r),s.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?this._totalIndices!==void 0?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;let i=this._indices;return!t&&(!e||this._meshes.length===1)?i:i.slice()}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){!e||!this._vertexArrayObjects||this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){let i=this._meshes,r=i.indexOf(e);r!==-1&&(i.splice(r,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,i.length===0&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;let t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();let i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&(e=this.getVerticesData(D.PositionKind),!e))return;this._extend=sb(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){for(let t in this._vertexBuffers){let i=this._vertexBuffers[t];i._buffer.getBuffer()||i.create(),t===D.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo())}!this._indexBuffer&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(let t of this._meshes)t._markSubMeshesAsAttributesDirty()}load(e,t){if(this.delayLoadState!==2){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);let r=this._meshes,s=r.length;for(let a=0;a<s;a++)this._applyToMesh(r[a]);t&&t()},void 0,!0))}toLeftHanded(){let e=this.getIndices(!1);if(e!=null&&e.length>0){for(let r=0;r<e.length;r+=3){let s=e[r+0];e[r+0]=e[r+2],e[r+2]=s}this.setIndices(e)}let t=this.getVerticesData(D.PositionKind,!1);if(t!=null&&t.length>0){for(let r=0;r<t.length;r+=3)t[r+2]=-t[r+2];this.setVerticesData(D.PositionKind,t,!1)}let i=this.getVerticesData(D.NormalKind,!1);if(i!=null&&i.length>0){for(let r=0;r<i.length;r+=3)i[r+2]=-i[r+2];this.setVerticesData(D.NormalKind,i,!1)}}_resetPointsArrayCache(){this._positions=null}_generatePointsArray(){if(this._positions)return!0;let e=this.getVerticesData(D.PositionKind);if(!e||e.length===0)return!1;for(let t=this._positionsCache.length*3,i=this._positionsCache.length;t<e.length;t+=3,++i)this._positionsCache[i]=b.FromArray(e,t);for(let t=0,i=0;t<e.length;t+=3,++i)this._positionsCache[i].set(e[0+t],e[1+t],e[2+t]);return this._positionsCache.length=e.length/3,this._positions=this._positionsCache,!0}isDisposed(){return this._isDisposed}_disposeVertexArrayObjects(){if(this._vertexArrayObjects){for(let i in this._vertexArrayObjects)this._engine.releaseVertexArrayObject(this._vertexArrayObjects[i]);this._vertexArrayObjects={};let e=this._meshes,t=e.length;for(let i=0;i<t;i++)e[i]._invalidateInstanceVertexArrayObject()}}dispose(){let e=this._meshes,t=e.length,i;for(i=0;i<t;i++)this.releaseForMesh(e[i]);this._meshes.length=0,this._disposeVertexArrayObjects();for(let r in this._vertexBuffers)this._vertexBuffers[r].dispose();if(this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=0,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._parentContainer){let r=this._parentContainer.geometries.indexOf(this);r>-1&&this._parentContainer.geometries.splice(r,1),this._parentContainer=null}this._isDisposed=!0}copy(e){let t=new n(e,this._scene),i=this.getIndices(void 0,!0);i&&t.setIndices(i);let r=!1,s;for(s in this._vertexBuffers){let a=this.getVertexBuffer(s),o=a.getData();if(!o)continue;let l=a.isUpdatable(),c=a.getSize(),{type:f,byteOffset:d,byteStride:u,normalized:h}=a;r=r||l;let m=this._totalVertices;if(a.getIsInstanced()){let _;o instanceof Array?_=o.length*4:_=o.byteLength,m=_/u}let g=pk(o,c,f,d,u,m,!0),p=new D(this._engine,g,s,{updatable:l,useBytes:!1,stride:c,size:c,offset:0,type:f,normalized:h,takeBufferOwnership:!0,instanced:a.getIsInstanced()});t.setVerticesBuffer(p,m)}t._updatable=r,t.delayLoadState=this.delayLoadState,t.delayLoadingFile=this.delayLoadingFile,t._delayLoadingFunction=this._delayLoadingFunction;for(s in this._delayInfo)t._delayInfo=t._delayInfo||[],t._delayInfo.push(s);return t._boundingInfo=new In(this._extend.minimum,this._extend.maximum),t}serialize(){let e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,ni&&ni.HasTags(this)&&(e.tags=ni.GetTags(this)),e}_toNumberArray(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)}clearCachedData(){this._totalIndices=this._indices.length,this._indices=[],this._resetPointsArrayCache();for(let e in this._vertexBuffers)Object.prototype.hasOwnProperty.call(this._vertexBuffers,e)&&(this._vertexBuffers[e]._buffer._data=null)}serializeVerticeData(){let e=this.serialize();return this.isVerticesDataPresent(D.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(D.PositionKind)),this.isVertexBufferUpdatable(D.PositionKind)&&(e.positionsUpdatable=!0)),this.isVerticesDataPresent(D.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(D.NormalKind)),this.isVertexBufferUpdatable(D.NormalKind)&&(e.normalsUpdatable=!0)),this.isVerticesDataPresent(D.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(D.TangentKind)),this.isVertexBufferUpdatable(D.TangentKind)&&(e.tangentsUpdatable=!0)),this.isVerticesDataPresent(D.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(D.UVKind)),this.isVertexBufferUpdatable(D.UVKind)&&(e.uvsUpdatable=!0)),this.isVerticesDataPresent(D.UV2Kind)&&(e.uvs2=this._toNumberArray(this.getVerticesData(D.UV2Kind)),this.isVertexBufferUpdatable(D.UV2Kind)&&(e.uvs2Updatable=!0)),this.isVerticesDataPresent(D.UV3Kind)&&(e.uvs3=this._toNumberArray(this.getVerticesData(D.UV3Kind)),this.isVertexBufferUpdatable(D.UV3Kind)&&(e.uvs3Updatable=!0)),this.isVerticesDataPresent(D.UV4Kind)&&(e.uvs4=this._toNumberArray(this.getVerticesData(D.UV4Kind)),this.isVertexBufferUpdatable(D.UV4Kind)&&(e.uvs4Updatable=!0)),this.isVerticesDataPresent(D.UV5Kind)&&(e.uvs5=this._toNumberArray(this.getVerticesData(D.UV5Kind)),this.isVertexBufferUpdatable(D.UV5Kind)&&(e.uvs5Updatable=!0)),this.isVerticesDataPresent(D.UV6Kind)&&(e.uvs6=this._toNumberArray(this.getVerticesData(D.UV6Kind)),this.isVertexBufferUpdatable(D.UV6Kind)&&(e.uvs6Updatable=!0)),this.isVerticesDataPresent(D.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(D.ColorKind)),this.isVertexBufferUpdatable(D.ColorKind)&&(e.colorsUpdatable=!0)),this.isVerticesDataPresent(D.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(D.MatricesIndicesKind)),e.matricesIndicesExpanded=!0,this.isVertexBufferUpdatable(D.MatricesIndicesKind)&&(e.matricesIndicesUpdatable=!0)),this.isVerticesDataPresent(D.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(D.MatricesWeightsKind)),this.isVertexBufferUpdatable(D.MatricesWeightsKind)&&(e.matricesWeightsUpdatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e}static ExtractFromMesh(e,t){let i=e._geometry;return i?i.copy(t):null}static RandomId(){return pe.RandomId()}static _GetGeometryByLoadedUniqueId(e,t){for(let i=0;i<t.geometries.length;i++)if(t.geometries[i]._loadedUniqueId===e)return t.geometries[i];return null}static _ImportGeometry(e,t){let i=t.getScene(),r=e.geometryUniqueId,s=e.geometryId;if(r||s){let a=r?this._GetGeometryByLoadedUniqueId(r,i):i.getGeometryById(s);a&&a.applyToMesh(t)}else if(e instanceof ArrayBuffer){let a=t._binaryInfo;if(a.positionsAttrDesc&&a.positionsAttrDesc.count>0){let o=new Float32Array(e,a.positionsAttrDesc.offset,a.positionsAttrDesc.count);t.setVerticesData(D.PositionKind,o,!1)}if(a.normalsAttrDesc&&a.normalsAttrDesc.count>0){let o=new Float32Array(e,a.normalsAttrDesc.offset,a.normalsAttrDesc.count);t.setVerticesData(D.NormalKind,o,!1)}if(a.tangetsAttrDesc&&a.tangetsAttrDesc.count>0){let o=new Float32Array(e,a.tangetsAttrDesc.offset,a.tangetsAttrDesc.count);t.setVerticesData(D.TangentKind,o,!1)}if(a.uvsAttrDesc&&a.uvsAttrDesc.count>0){let o=new Float32Array(e,a.uvsAttrDesc.offset,a.uvsAttrDesc.count);if(Ot)for(let l=1;l<o.length;l+=2)o[l]=1-o[l];t.setVerticesData(D.UVKind,o,!1)}if(a.uvs2AttrDesc&&a.uvs2AttrDesc.count>0){let o=new Float32Array(e,a.uvs2AttrDesc.offset,a.uvs2AttrDesc.count);if(Ot)for(let l=1;l<o.length;l+=2)o[l]=1-o[l];t.setVerticesData(D.UV2Kind,o,!1)}if(a.uvs3AttrDesc&&a.uvs3AttrDesc.count>0){let o=new Float32Array(e,a.uvs3AttrDesc.offset,a.uvs3AttrDesc.count);if(Ot)for(let l=1;l<o.length;l+=2)o[l]=1-o[l];t.setVerticesData(D.UV3Kind,o,!1)}if(a.uvs4AttrDesc&&a.uvs4AttrDesc.count>0){let o=new Float32Array(e,a.uvs4AttrDesc.offset,a.uvs4AttrDesc.count);if(Ot)for(let l=1;l<o.length;l+=2)o[l]=1-o[l];t.setVerticesData(D.UV4Kind,o,!1)}if(a.uvs5AttrDesc&&a.uvs5AttrDesc.count>0){let o=new Float32Array(e,a.uvs5AttrDesc.offset,a.uvs5AttrDesc.count);if(Ot)for(let l=1;l<o.length;l+=2)o[l]=1-o[l];t.setVerticesData(D.UV5Kind,o,!1)}if(a.uvs6AttrDesc&&a.uvs6AttrDesc.count>0){let o=new Float32Array(e,a.uvs6AttrDesc.offset,a.uvs6AttrDesc.count);if(Ot)for(let l=1;l<o.length;l+=2)o[l]=1-o[l];t.setVerticesData(D.UV6Kind,o,!1)}if(a.colorsAttrDesc&&a.colorsAttrDesc.count>0){let o=new Float32Array(e,a.colorsAttrDesc.offset,a.colorsAttrDesc.count);t.setVerticesData(D.ColorKind,o,!1,a.colorsAttrDesc.stride)}if(a.matricesIndicesAttrDesc&&a.matricesIndicesAttrDesc.count>0){let o=new Int32Array(e,a.matricesIndicesAttrDesc.offset,a.matricesIndicesAttrDesc.count),l=[];for(let c=0;c<o.length;c++){let f=o[c];l.push(f&255),l.push((f&65280)>>8),l.push((f&16711680)>>16),l.push(f>>24&255)}t.setVerticesData(D.MatricesIndicesKind,l,!1)}if(a.matricesIndicesExtraAttrDesc&&a.matricesIndicesExtraAttrDesc.count>0){let o=new Int32Array(e,a.matricesIndicesExtraAttrDesc.offset,a.matricesIndicesExtraAttrDesc.count),l=[];for(let c=0;c<o.length;c++){let f=o[c];l.push(f&255),l.push((f&65280)>>8),l.push((f&16711680)>>16),l.push(f>>24&255)}t.setVerticesData(D.MatricesIndicesExtraKind,l,!1)}if(a.matricesWeightsAttrDesc&&a.matricesWeightsAttrDesc.count>0){let o=new Float32Array(e,a.matricesWeightsAttrDesc.offset,a.matricesWeightsAttrDesc.count);t.setVerticesData(D.MatricesWeightsKind,o,!1)}if(a.indicesAttrDesc&&a.indicesAttrDesc.count>0){let o=new Int32Array(e,a.indicesAttrDesc.offset,a.indicesAttrDesc.count);t.setIndices(o,null)}if(a.subMeshesAttrDesc&&a.subMeshesAttrDesc.count>0){let o=new Int32Array(e,a.subMeshesAttrDesc.offset,a.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let l=0;l<a.subMeshesAttrDesc.count;l++){let c=o[l*5+0],f=o[l*5+1],d=o[l*5+2],u=o[l*5+3],h=o[l*5+4];sa.AddToMesh(c,f,d,u,h,t)}}}else if(e.positions&&e.normals&&e.indices){if(t.setVerticesData(D.PositionKind,e.positions,e.positions._updatable||e.positionsUpdatable),t.setVerticesData(D.NormalKind,e.normals,e.normals._updatable||e.normalsUpdatable),e.tangents&&t.setVerticesData(D.TangentKind,e.tangents,e.tangents._updatable||e.tangentsUpdatable),e.uvs&&t.setVerticesData(D.UVKind,e.uvs,e.uvs._updatable||e.uvsUpdatable),e.uvs2&&t.setVerticesData(D.UV2Kind,e.uvs2,e.uvs2._updatable||e.uvs2Updatable),e.uvs3&&t.setVerticesData(D.UV3Kind,e.uvs3,e.uvs3._updatable||e.uvs3Updatable),e.uvs4&&t.setVerticesData(D.UV4Kind,e.uvs4,e.uvs4._updatable||e.uvs4Updatable),e.uvs5&&t.setVerticesData(D.UV5Kind,e.uvs5,e.uvs5._updatable||e.uvs5Updatable),e.uvs6&&t.setVerticesData(D.UV6Kind,e.uvs6,e.uvs6._updatable||e.uvs6Updatable),e.colors&&t.setVerticesData(D.ColorKind,ht.CheckColors4(e.colors,e.positions.length/3),e.colors._updatable),e.matricesIndices)if(!e.matricesIndices._isExpanded&&!e.matricesIndicesExpanded){let a=[];for(let o=0;o<e.matricesIndices.length;o++){let l=e.matricesIndices[o];a.push(l&255),a.push((l&65280)>>8),a.push((l&16711680)>>16),a.push(l>>24&255)}t.setVerticesData(D.MatricesIndicesKind,a,e.matricesIndices._updatable||e.matricesIndicesUpdatable)}else delete e.matricesIndices._isExpanded,delete e.matricesIndicesExpanded,t.setVerticesData(D.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable||e.matricesIndicesUpdatable);if(e.matricesIndicesExtra)if(e.matricesIndicesExtraExpanded||e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,delete e.matricesIndicesExtraExpanded,t.setVerticesData(D.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable||e.matricesIndicesExtraUpdatable);else{let a=[];for(let o=0;o<e.matricesIndicesExtra.length;o++){let l=e.matricesIndicesExtra[o];a.push(l&255),a.push((l&65280)>>8),a.push((l&16711680)>>16),a.push(l>>24&255)}t.setVerticesData(D.MatricesIndicesExtraKind,a,e.matricesIndicesExtra._updatable||e.matricesIndicesExtraUpdatable)}e.matricesWeights&&(n._CleanMatricesWeights(e,t),t.setVerticesData(D.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(D.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let a=0;a<e.subMeshes.length;a++){let o=e.subMeshes[a];sa.AddToMesh(o.materialIndex,o.verticesStart,o.verticesCount,o.indexStart,o.indexCount,t)}}t._shouldGenerateFlatShading&&(t.convertToFlatShadedMesh(),t._shouldGenerateFlatShading=!1),t.computeWorldMatrix(!0),i.onMeshImportedObservable.notifyObservers(t)}static _CleanMatricesWeights(e,t){if(!an.CleanBoneMatrixWeights)return;let r;if(e.skeletonId>-1){let d=t.getScene().getLastSkeletonById(e.skeletonId);if(!d)return;r=d.bones.length}else return;let s=t.getVerticesData(D.MatricesIndicesKind),a=t.getVerticesData(D.MatricesIndicesExtraKind),o=e.matricesWeights,l=e.matricesWeightsExtra,c=e.numBoneInfluencer,f=o.length;for(let d=0;d<f;d+=4){let u=0,h=-1;for(let m=0;m<4;m++){let g=o[d+m];u+=g,g<.001&&h<0&&(h=m)}if(l)for(let m=0;m<4;m++){let g=l[d+m];u+=g,g<.001&&h<0&&(h=m+4)}if((h<0||h>c-1)&&(h=c-1),u>.001){let m=1/u;for(let g=0;g<4;g++)o[d+g]*=m;if(l)for(let g=0;g<4;g++)l[d+g]*=m}else h>=4?(l[d+h-4]=1-u,a[d+h-4]=r):(o[d+h]=1-u,s[d+h]=r)}t.setVerticesData(D.MatricesIndicesKind,s),e.matricesWeightsExtra&&t.setVerticesData(D.MatricesIndicesExtraKind,a)}static Parse(e,t,i){let r=new n(e.id,t,void 0,e.updatable);return r._loadedUniqueId=e.uniqueId,ni&&ni.AddTagsTo(r,e.tags),e.delayLoadingFile?(r.delayLoadState=4,r.delayLoadingFile=i+e.delayLoadingFile,r._boundingInfo=new In(b.FromArray(e.boundingBoxMinimum),b.FromArray(e.boundingBoxMaximum)),r._delayInfo=[],e.hasUVs&&r._delayInfo.push(D.UVKind),e.hasUVs2&&r._delayInfo.push(D.UV2Kind),e.hasUVs3&&r._delayInfo.push(D.UV3Kind),e.hasUVs4&&r._delayInfo.push(D.UV4Kind),e.hasUVs5&&r._delayInfo.push(D.UV5Kind),e.hasUVs6&&r._delayInfo.push(D.UV6Kind),e.hasColors&&r._delayInfo.push(D.ColorKind),e.hasMatricesIndices&&r._delayInfo.push(D.MatricesIndicesKind),e.hasMatricesWeights&&r._delayInfo.push(D.MatricesWeightsKind),r._delayLoadingFunction=Ie.ImportVertexData):Ie.ImportVertexData(e,r),t.pushGeometry(r,!0),r}}});var ii,cd=y(()=>{jt();Yt();Or();Si();He();Na();ir();ii=class n extends bi{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&n.BILLBOARDMODE_USE_POSITION)!==0)}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t,!1),this._forward=new b(0,0,1),this._up=new b(0,1,0),this._right=new b(1,0,0),this._position=b.Zero(),this._rotation=b.Zero(),this._rotationQuaternion=null,this._scaling=b.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=n.BILLBOARDMODE_NONE,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=Q.Zero(),this._usePivotMatrix=!1,this._absolutePosition=b.Zero(),this._absoluteScaling=b.Zero(),this._absoluteRotationQuaternion=je.Identity(),this._pivotMatrix=Q.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new re,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._markAsDirtyInternal()}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._markAsDirtyInternal()}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._markAsDirtyInternal()}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._markAsDirtyInternal()}_markAsDirtyInternal(){this._isDirty||(this._isDirty=!0,this.customMarkAsDirty&&this.customMarkAsDirty())}get forward(){return b.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return b.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return b.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=Q.Identity()),this._poseMatrix}_isSynchronized(){let e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==n.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();let e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=Q.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);r&&i&&i(this,r);for(let s of this.getChildTransformNodes(!0))s.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||je.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,r;if(e.x===void 0){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){let s=ee.Matrix[0];this.parent.getWorldMatrix().invertToRef(s),b.TransformCoordinatesFromFloatsToRef(t,i,r,s,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=b.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();let e=ee.Matrix[0];return this._localMatrix.invertToRef(e),b.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=b.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,s=0){let a=n._LookAtVectorCache,o=s===0?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,a),this.setDirection(a,t,i,r),s===1&&this.parent)if(this.rotationQuaternion){let l=ee.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);let c=ee.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),l.multiplyToRef(c,l),this.rotationQuaternion.fromRotationMatrix(l)}else{let l=ee.Quaternion[0];je.FromEulerVectorToRef(this.rotation,l);let c=ee.Matrix[0];l.toRotationMatrix(c);let f=ee.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(f),f.invert(),c.multiplyToRef(f,c),l.fromRotationMatrix(c),l.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){let t=b.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return b.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){let s=-Math.atan2(e.z,e.x)+Math.PI/2,a=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,a);return this.rotationQuaternion?je.RotationYawPitchRollToRef(s+t,o+i,r,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=s+t,this.rotation.z=r),this}setPivotPoint(e,t=0){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);let i=this.getWorldMatrix();if(t==1){let r=ee.Matrix[0];i.invertToRef(r),e=b.TransformCoordinates(e,r)}return this.setPivotMatrix(Q.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){let e=b.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){let e=b.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),b.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(let t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;let r=ee.Quaternion[0],s=ee.Vector3[0],a=ee.Vector3[1],o=ee.Matrix[1];Q.IdentityToRef(o);let l=ee.Matrix[0];this.computeWorldMatrix(!0);let c=this.rotationQuaternion;return c||(c=n._TmpRotation,je.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,c)),Q.ComposeToRef(this.scaling,c,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(o),l.multiplyToRef(o,l)),l.decompose(a,r,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(a),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(Q.Identity()),this}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.parent!==this?this:(e.setParent(null,t),this)}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling===e?!1:(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0));let r;if(!i||i===0)r=je.RotationAxisToRef(e,t,n._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);else{if(this.parent){let s=this.parent.getWorldMatrix(),a=ee.Matrix[0];s.invertToRef(a),e=b.TransformNormal(e,a),s.determinant()<0&&(t*=-1)}r=je.RotationAxisToRef(e,t,n._RotationAxisCache),r.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=je.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));let r=ee.Vector3[0],s=ee.Vector3[1],a=ee.Vector3[2],o=ee.Quaternion[0],l=ee.Matrix[0],c=ee.Matrix[1],f=ee.Matrix[2],d=ee.Matrix[3];return e.subtractToRef(this.position,r),Q.TranslationToRef(r.x,r.y,r.z,l),Q.TranslationToRef(-r.x,-r.y,-r.z,c),Q.RotationAxisToRef(t,i,f),c.multiplyToRef(f,d),d.multiplyToRef(l,d),d.decompose(s,o,a),this.position.addInPlace(a),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){let r=e.scale(t);if(!i||i===0){let s=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(s)}else this.setAbsolutePosition(this.getAbsolutePosition().add(r));return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=ee.Quaternion[1],je.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));let s=ee.Quaternion[0];return je.RotationYawPitchRollToRef(t,e,i,s),r.multiplyInPlace(s),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==n.BILLBOARDMODE_NONE}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;let i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();let r=this._cache;r.pivotMatrixUpdated=!1,r.billboardMode=this.billboardMode,r.infiniteDistance=this.infiniteDistance,r.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;let s=this._getEffectiveParent(),a=n._TmpScaling,o=this._position;if(this._infiniteDistance&&!this.parent&&t){let f=t.getWorldMatrix().m;o=n._TmpTranslation,o.copyFromFloats(this._position.x+f[12],this._position.y+f[13],this._position.z+f[14])}a.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);let l;if(this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,l=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(je.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(l=n._TmpRotation,je.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),this._usePivotMatrix){let c=ee.Matrix[1];Q.ScalingToRef(a.x,a.y,a.z,c);let f=ee.Matrix[0];l.toRotationMatrix(f),this._pivotMatrix.multiplyToRef(c,ee.Matrix[4]),ee.Matrix[4].multiplyToRef(f,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else Q.ComposeToRef(a,l,o,this._localMatrix);if(s&&s.getWorldMatrix){if(e&&s.computeWorldMatrix(e),this.billboardMode){if(this._transformToBoneReferal){let u=this.parent;u.getSkeleton().prepare(),u.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),ee.Matrix[7])}else ee.Matrix[7].copyFrom(s.getWorldMatrix());let c=ee.Vector3[5],f=ee.Vector3[6],d=ee.Quaternion[0];ee.Matrix[7].decompose(f,d,c),Q.ScalingToRef(f.x,f.y,f.z,ee.Matrix[7]),ee.Matrix[7].setTranslation(c),n.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(d,c),this._localMatrix.setTranslation(c)),this._localMatrix.multiplyToRef(ee.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){let c=this.parent;c.getSkeleton().prepare(),this._localMatrix.multiplyToRef(c.getFinalMatrix(),ee.Matrix[6]),ee.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(s.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(t&&this.billboardMode)if(r.useBillboardPosition){let c=ee.Vector3[0];this._worldMatrix.getTranslationToRef(c);let f=t.globalPosition;this._worldMatrix.invertToRef(ee.Matrix[1]);let d=ee.Vector3[1];b.TransformCoordinatesToRef(f,ee.Matrix[1],d),d.normalize();let u=-Math.atan2(d.z,d.x)+Math.PI/2,h=Math.sqrt(d.x*d.x+d.z*d.z),m=-Math.atan2(d.y,h);if(je.RotationYawPitchRollToRef(u,m,0,ee.Quaternion[0]),(this.billboardMode&n.BILLBOARDMODE_ALL)!==n.BILLBOARDMODE_ALL){let g=ee.Vector3[1];ee.Quaternion[0].toEulerAnglesToRef(g),(this.billboardMode&n.BILLBOARDMODE_X)!==n.BILLBOARDMODE_X&&(g.x=0),(this.billboardMode&n.BILLBOARDMODE_Y)!==n.BILLBOARDMODE_Y&&(g.y=0),(this.billboardMode&n.BILLBOARDMODE_Z)!==n.BILLBOARDMODE_Z&&(g.z=0),Q.RotationYawPitchRollToRef(g.y,g.x,g.z,ee.Matrix[0])}else Q.FromQuaternionToRef(ee.Quaternion[0],ee.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ee.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ee.Vector3[0])}else{let c=ee.Vector3[0];this._worldMatrix.getTranslationToRef(c),ee.Matrix[1].copyFrom(t.getViewMatrix());let f=this.getScene().useRightHandedSystem;if(f&&ee.Matrix[1].multiplyToRef(n._TmpRHRestore,ee.Matrix[1]),ee.Matrix[1].setTranslationFromFloats(0,0,0),ee.Matrix[1].invertToRef(ee.Matrix[0]),(this.billboardMode&n.BILLBOARDMODE_ALL)!==n.BILLBOARDMODE_ALL){ee.Matrix[0].decompose(void 0,ee.Quaternion[0],void 0);let d=ee.Vector3[1];ee.Quaternion[0].toEulerAnglesToRef(d),(this.billboardMode&n.BILLBOARDMODE_X)!==n.BILLBOARDMODE_X&&(d.x=0),(this.billboardMode&n.BILLBOARDMODE_Y)!==n.BILLBOARDMODE_Y&&(d.y=0),(this.billboardMode&n.BILLBOARDMODE_Z)!==n.BILLBOARDMODE_Z&&(d.z=0),f&&(d.y+=Math.PI),Q.RotationYawPitchRollToRef(d.y,d.x,d.z,ee.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ee.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ee.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):s&&s._nonUniformScaling?this._updateNonUniformScalingState(s._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=Q.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){let t=this.getChildren();for(let i=0;i<t.length;++i){let r=t[i];if(r){r.computeWorldMatrix();let s=ee.Matrix[0];r._localMatrix.multiplyToRef(this._localMatrix,s);let a=ee.Quaternion[0];s.decompose(r.scaling,a,r.position),r.rotationQuaternion?r.rotationQuaternion.copyFrom(a):a.toEulerAnglesToRef(r.rotation)}}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=je.Identity()),this._worldMatrix=Q.Identity()}_afterComputeWorldMatrix(){}registerAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this}unregisterAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this}getPositionInCameraSpace(e=null){return e||(e=this.getScene().activeCamera),b.TransformCoordinates(this.getAbsolutePosition(),e.getViewMatrix())}getDistanceToCamera(e=null){return e||(e=this.getScene().activeCamera),this.getAbsolutePosition().subtract(e.globalPosition).length()}clone(e,t,i){let r=at.Clone(()=>new n(e,this.getScene()),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){let s=this.getDescendants(!0);for(let a=0;a<s.length;a++){let o=s[a];o.clone&&o.clone(e+"."+o.name,r)}}return r}serialize(e){let t=at.Serialize(this,e);return t.type=this.getClassName(),t.uniqueId=this.uniqueId,this.parent&&this.parent._serializeAsParent(t),t.localMatrix=this.getPivotMatrix().asArray(),t.isEnabled=this.isEnabled(),this._isWorldMatrixFrozen&&(t.freezeWorldMatrix=!0),at.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t}static Parse(e,t,i){let r=at.Parse(()=>new n(e.name,t),e,t,i);if(e.localMatrix?r.setPreTransformMatrix(Q.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(Q.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),e.freezeWorldMatrix&&(r._waitingFreezeWorldMatrix=e.freezeWorldMatrix),e.animations){for(let s=0;s<e.animations.length;s++){let a=e.animations[s],o=Vn("BABYLON.Animation");o&&r.animations.push(o.Parse(a))}bi.ParseAnimationRanges(r,e,t)}return e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),r}getChildTransformNodes(e,t){let i=[];return this._getDescendants(i,e,r=>(!t||t(r))&&r instanceof n),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){let i=this._parentContainer.transformNodes.indexOf(this);i>-1&&this._parentContainer.transformNodes.splice(i,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){let i=this.getChildTransformNodes(!0);for(let r of i)r.parent=null,r.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));let a=this.getHierarchyBoundingVectors(e,i),o=a.max.subtract(a.min),l=Math.max(o.x,o.y,o.z);if(l===0)return this;let c=1/l;return this.scaling.scaleInPlace(c),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&r&&this.rotation.copyFrom(r)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}};ii.BILLBOARDMODE_NONE=0;ii.BILLBOARDMODE_X=1;ii.BILLBOARDMODE_Y=2;ii.BILLBOARDMODE_Z=4;ii.BILLBOARDMODE_ALL=7;ii.BILLBOARDMODE_USE_POSITION=128;ii.BillboardUseParentOrientation=!1;ii._TmpRotation=je.Zero();ii._TmpScaling=b.Zero();ii._TmpTranslation=b.Zero();ii._TmpRHRestore=Q.Scaling(1,1,-1);ii._LookAtVectorCache=new b(0,0,0);ii._RotationAxisCache=new je;P([nn("position")],ii.prototype,"_position",void 0);P([nn("rotation")],ii.prototype,"_rotation",void 0);P([ck("rotationQuaternion")],ii.prototype,"_rotationQuaternion",void 0);P([nn("scaling")],ii.prototype,"_scaling",void 0);P([F("billboardMode")],ii.prototype,"_billboardMode",void 0);P([F()],ii.prototype,"scalingDeterminant",void 0);P([F("infiniteDistance")],ii.prototype,"_infiniteDistance",void 0);P([F()],ii.prototype,"ignoreNonUniformScaling",void 0);P([F()],ii.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0)});var cb,XH=y(()=>{He();cb=class{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new b(0,0,0),this._diffPositionForCollisions=new b(0,0,0),this._collisionResponse=!0}}});function YH(n){return Math.floor(n/8)}function KH(n){return 1<<n%8}var fb,jH=y(()=>{fb=class{constructor(e){this.size=e,this._byteArray=new Uint8Array(Math.ceil(this.size/8))}get(e){if(e>=this.size)throw new RangeError("Bit index out of range");let t=YH(e),i=KH(e);return(this._byteArray[t]&i)!==0}set(e,t){if(e>=this.size)throw new RangeError("Bit index out of range");let i=YH(e),r=KH(e);t?this._byteArray[i]|=r:this._byteArray[i]&=~r}}});var ZH={};Be(ZH,{OptimizeIndices:()=>nhe});function nhe(n){let e=[],t=n.length/3;for(let l=0;l<t;l++)e.push([n[l*3],n[l*3+1],n[l*3+2]]);let i=new Map;for(let l=0;l<e.length;l++){let c=e[l];for(let f of c){let d=i.get(f);d||i.set(f,d=[]),d.push(l)}}let r=new fb(t),s=[],a=l=>{let c=[l];for(;c.length>0;){let f=c.pop();if(!r.get(f)){r.set(f,!0),s.push(e[f]);for(let d of e[f]){let u=i.get(d);if(!u)return;for(let h of u)r.get(h)||c.push(h)}}}};for(let l=0;l<t;l++)r.get(l)||a(l);let o=0;for(let l of s)n[o++]=l[0],n[o++]=l[1],n[o++]=l[2]}var qH=y(()=>{jH()});function she(n,e,t){let i;switch(e){case D.PositionKind:i=r=>r.getPositions();break;case D.NormalKind:i=r=>r.getNormals();break;case D.TangentKind:i=r=>r.getTangents();break;case D.UVKind:i=r=>r.getUVs();break;case D.UV2Kind:i=r=>r.getUV2s();break;case D.ColorKind:i=r=>r.getColors();break;default:return}for(let r=0;r<n.length;r++){let s=n[r];for(let a=0;a<t.numTargets;a++){let o=t.getTarget(a),l=o.influence;if(l!==0){let c=i(o);c&&(s+=(c[r]-n[r])*l)}}n[r]=s}}function ahe(n,e,t,i,r,s,a){let o=ee.Vector3[0],l=ee.Matrix[0],c=ee.Matrix[1],f=e===D.NormalKind?b.TransformNormalFromFloatsToRef:b.TransformCoordinatesFromFloatsToRef;for(let d=0,u=0;d<n.length;d+=3,u+=4){l.reset();let h,m;for(h=0;h<4;h++)m=r[u+h],m>0&&(Q.FromFloat32ArrayToRefScaled(t,Math.floor(i[u+h]*16),m,c),l.addToSelf(c));if(s&&a)for(h=0;h<4;h++)m=a[u+h],m>0&&(Q.FromFloat32ArrayToRefScaled(t,Math.floor(s[u+h]*16),m,c),l.addToSelf(c));f(n[d],n[d+1],n[d+2],l,o),o.toArray(n,d)}}var qD,QD,Ir,Pp=y(()=>{jt();Si();He();qi();vr();cd();Ov();Ip();rd();XH();Mn();ab();$t();es();sp();ir();Yt();Yr();qD=class{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=b.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}},QD=class{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new qD,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=new Map,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new cb,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1,this._wasActiveLastFrame=!1}},Ir=class n extends ii{static get BILLBOARDMODE_NONE(){return ii.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return ii.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return ii.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return ii.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return ii.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return ii.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return super._updateNonUniformScalingState(e)?(this._markSubMeshesAsMiscDirty(),!0):!1}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;let t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(t===1&&e!==1||t!==1&&e===1)&&this._markSubMeshesAsDirty(i=>{i.markAsMiscDirty(),i.markAsPrePassDirty()})}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._setMaterial(e)}_setMaterial(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(void 0,e==null),this._unBindEffect()))}getMaterialForRenderPass(e){var t;return(t=this._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:t[e]}setMaterialForRenderPass(e,t){var r;this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]);let i=this._internalAbstractMeshDataInfo._materialForRenderPass[e];(r=i==null?void 0:i.meshMap)!=null&&r[this.uniqueId]&&(i.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t,t&&t.meshMap&&(t.meshMap[this.uniqueId]=this)}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}set skeleton(e){let t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new QD,this._waitingMaterialId=null,this._waitingMorphTargetManagerId=null,this._waitingSkeletonId=null,this._waitingSkeletonUniqueId=null,this.cullingStrategy=n.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new re,this.onCollisionPositionChangeObservable=new re,this.onMaterialChangedObservable=new re,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isPickable=n.DefaultIsPickable,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=he.Red(),this.outlineWidth=.02,this.overlayColor=he.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new b(.5,1,.5),this.ellipsoidOffset=new b(0,0,0),this.edgesWidth=1,this.edgesColor=new ht(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new re,this._onCollisionPositionChange=(i,r,s=null)=>{r.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>ye.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),s&&this.onCollideObservable.notifyObservers(s),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},t=this.getScene(),this.layerMask=t.defaultRenderableLayerMask,t.addMesh(this),this._resyncLightSources(),this._uniformBuffer=new xr(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case 2:this.doNotSyncBoundingInfo=!0;case 1:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1;break}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){let t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+(this.getClassName()==="InstancedMesh"?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);let i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==ii.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive))if(e){if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}else return this.actionManager;return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_releaseRenderPassId(e){}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery!==null&&(this._occlusionQuery=null),!!this.subMeshes){for(let t of this.subMeshes)t._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(let e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){let t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e),r=!1;if(i===-1){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(let e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){let i=this._lightSources.indexOf(e);i!==-1&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(let t of this.subMeshes)for(let i=0;i<t._drawWrappers.length;++i){let r=t._drawWrappers[i];!r||!r.defines||!r.defines.markAllAsDirty||e(r.defines)}}_markSubMeshesAsLightDirty(e=!1){this._markSubMeshesAsDirty(t=>t.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,super.markAsDirty(e),this._isDirty=!0,this}resetDrawCache(e,t=!1){if(this.subMeshes)for(let i of this.subMeshes)i.resetDrawCache(e,t)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,r){return this}updateVerticesData(e,t,i,r){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){var e;return(e=this.rawBoundingInfo)!=null?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return this._boundingInfo!==null}buildBoundingInfo(e,t,i){return this._boundingInfo=new In(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(D.MatricesIndicesKind)&&this.isVerticesDataPresent(D.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===ii.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){let r=new Q;(this.rotationQuaternion?this.rotationQuaternion:je.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(r);let a=b.Zero(),o=this.definedFacingForward?-1:1;return b.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,r,a),a}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){let r=this.definedFacingForward?1:-1;return new b(e*r,t,i*r)}_refreshBoundingInfo(e,t){if(e){let i=sb(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new In(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i<this.subMeshes.length;i++)this.subMeshes[i].refreshBoundingInfo(e);this._updateBoundingInfo()}_refreshBoundingInfoDirect(e){if(this._boundingInfo?this._boundingInfo.reConstruct(e.minimum,e.maximum):this._boundingInfo=new In(e.minimum,e.maximum),this.subMeshes)for(let t=0;t<this.subMeshes.length;t++)this.subMeshes[t].refreshBoundingInfo(null);this._updateBoundingInfo()}static _ApplySkeleton(e,t,i,r,s,a,o){ahe(e,t,i,r,s,a,o)}_getData(e,t,i=D.PositionKind){let r=e.cache,s=a=>{if(r){let o=r._vertexData||(r._vertexData={});return o[a]||this.copyVerticesData(a,o),o[a]}return this.getVerticesData(a)};if(t||(t=s(i)),!t)return null;if(r?(r._outputData?r._outputData.set(t):r._outputData=new Float32Array(t),t=r._outputData):(e.applyMorph&&this.morphTargetManager||e.applySkeleton&&this.skeleton)&&(t=t.slice()),e.applyMorph&&this.morphTargetManager&&she(t,i,this.morphTargetManager),e.applySkeleton&&this.skeleton){let a=s(D.MatricesIndicesKind),o=s(D.MatricesWeightsKind);if(o&&a){let l=this.numBoneInfluencers>4,c=l?s(D.MatricesIndicesExtraKind):null,f=l?s(D.MatricesWeightsExtraKind):null,d=this.skeleton.getTransformMatrices(this);n._ApplySkeleton(t,i,d,a,o,c,f)}}if(e.updatePositionsArray!==!1&&i===D.PositionKind){let a=this._internalAbstractMeshDataInfo._positions||[],o=a.length;if(a.length=t.length/3,o<a.length)for(let l=o;l<a.length;l++)a[l]=new b;for(let l=0,c=0;l<a.length;l++,c+=3)a[l].copyFromFloats(t[c],t[c+1],t[c+2]);this._internalAbstractMeshDataInfo._positions=a}return t}getNormalsData(e=!1,t=!1){return this._getData({applySkeleton:e,applyMorph:t,updatePositionsArray:!1},null,D.NormalKind)}getPositionData(e=!1,t=!1,i=null){return this._getData({applySkeleton:e,applyMorph:t,updatePositionsArray:!1},i,D.PositionKind)}_updateBoundingInfo(){return this._boundingInfo?this._boundingInfo.update(this.worldMatrixFromCache):this._boundingInfo=new In(b.Zero(),b.Zero(),this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}_updateSubMeshesBoundingInfo(e){if(!this.subMeshes)return this;let t=this.subMeshes.length;for(let i=0;i<t;i++){let r=this.subMeshes[i];(t>1||!r.IsGlobal)&&r.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){let r=this.getBoundingInfo(),s=e.getBoundingInfo();if(r.intersects(s,t))return!0;if(i){for(let a of this.getChildMeshes())if(a.intersectsMesh(e,t,!0))return!0}return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e,t=!0){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);let r=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=r.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,r.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId,t),this}_collideForSubMesh(e,t,i){var r;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];let s=e.verticesStart,a=e.verticesStart+e.verticesCount;for(let o=s;o<a;o++)e._lastColliderWorldVertices.push(b.TransformCoordinates(this._positions[o],t))}return i._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this,this._shouldConvertRHS(),((r=e.getMaterial())==null?void 0:r.fillMode)===7),this}_processCollisionsForSubMeshes(e,t){let i=this._scene.getCollidingSubMeshCandidates(this,e),r=i.length;for(let s=0;s<r;s++){let a=i.data[s];r>1&&!a._checkCollision(e)||this._collideForSubMesh(a,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;let t=ee.Matrix[0],i=ee.Matrix[1];return Q.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,r=!1,s,a=!1){let o=new Ls,l=this.getClassName(),c=l==="InstancedLinesMesh"||l==="LinesMesh"||l==="GreasedLineMesh"?this.intersectionThreshold:0,f=this.getBoundingInfo();if(!this.subMeshes||!a&&(!e.intersectsSphere(f.boundingSphere,c)||!e.intersectsBox(f.boundingBox,c)))return o;if(r)return o.hit=!a,o.pickedMesh=a?null:this,o.distance=a?0:b.Distance(e.origin,f.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let d=null,u=this._scene.getIntersectingSubMeshCandidates(this,e),h=u.length,m=!1;for(let g=0;g<h;g++){let _=u.data[g].getMaterial();if(_&&(_.fillMode==7||_.fillMode==0||_.fillMode==1||_.fillMode==2||_.fillMode==4)){m=!0;break}}if(!m)return o.hit=!0,o.pickedMesh=this,o.distance=b.Distance(e.origin,f.boundingSphere.center),o.subMeshId=-1,o;for(let g=0;g<h;g++){let p=u.data[g];if(h>1&&!a&&!p.canIntersects(e))continue;let _=p.intersects(e,this._positions,this.getIndices(),t,i);if(_&&(t||!d||_.distance<d.distance)&&(d=_,d.subMeshId=p._id,d._internalSubMeshId=g,t))break}if(d){let g=s!=null?s:this.getWorldMatrix(),p=ee.Vector3[0],_=ee.Vector3[1];b.TransformCoordinatesToRef(e.origin,g,p),e.direction.scaleToRef(d.distance,_);let E=b.TransformNormal(_,g).addInPlace(p);return o.hit=!0,o.distance=b.Distance(p,E),o.pickedPoint=E,o.pickedMesh=this,o.bu=d.bu||0,o.bv=d.bv||0,o.subMeshFaceId=d.faceId,o.faceId=d.faceId+u.data[d._internalSubMeshId].indexStart/(this.getClassName().indexOf("LinesMesh")!==-1?2:3),o.subMeshId=d.subMeshId,o}return o}clone(e,t,i){return null}releaseSubMeshes(e=!1){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose(e);else this.subMeshes=[];return this}dispose(e,t=!1){let i,r=this.getScene();for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),r.freeActiveMeshes(),r.freeRenderingGroups(),r.renderingManager.maintainStateBetweenFrames&&r.renderingManager.restoreDispachedFlags(),this.actionManager!==void 0&&this.actionManager!==null&&(this.actionManager.disposeWhenUnowned&&!this._scene.meshes.some(o=>o!==this&&o.actionManager===this.actionManager)&&this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i<this._intersectionsInProgress.length;i++){let o=this._intersectionsInProgress[i],l=o._intersectionsInProgress.indexOf(this);o._intersectionsInProgress.splice(l,1)}this._intersectionsInProgress.length=0;let s=r.lights;for(let o of s){let l=o.includedOnlyMeshes.indexOf(this);l!==-1&&o.includedOnlyMeshes.splice(l,1),l=o.excludedMeshes.indexOf(this),l!==-1&&o.excludedMeshes.splice(l,1);let c=o.getShadowGenerators();if(c){let f=c.values();for(let d=f.next();d.done!==!0;d=f.next()){let h=d.value.getShadowMap();h&&h.renderList&&(l=h.renderList.indexOf(this),l!==-1&&h.renderList.splice(l,1))}}}(this.getClassName()!=="InstancedMesh"||this.getClassName()!=="InstancedLinesMesh")&&this.releaseSubMeshes(!0);let a=r.getEngine();if(this._occlusionQuery!==null&&(this.isOcclusionQueryInProgress=!1,a.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),a.wipeCaches(),r.removeMesh(this),this._parentContainer){let o=this._parentContainer.meshes.indexOf(this);o>-1&&this._parentContainer.meshes.splice(o,1),this._parentContainer=null}if(t&&this.material&&(this.material.getClassName()==="MultiMaterial"?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i<r.particleSystems.length;i++)r.particleSystems[i].emitter===this&&(r.particleSystems[i].dispose(),i--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this._uniformBuffer.dispose(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),super.dispose(e,t)}_initFacetData(){let e=this._internalAbstractMeshDataInfo._facetData;e.facetNormals||(e.facetNormals=[]),e.facetPositions||(e.facetPositions=[]),e.facetPartitioning||(e.facetPartitioning=new Array),e.facetNb=this.getIndices().length/3|0,e.partitioningSubdivisions=e.partitioningSubdivisions?e.partitioningSubdivisions:10,e.partitioningBBoxRatio=e.partitioningBBoxRatio?e.partitioningBBoxRatio:1.01;for(let t=0;t<e.facetNb;t++)e.facetNormals[t]=b.Zero(),e.facetPositions[t]=b.Zero();return e.facetDataEnabled=!0,this}updateFacetData(){var o;let e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();let t=this.getVerticesData(D.PositionKind),i=this.getIndices(),r=(o=this.getVerticesData(D.NormalKind))==null?void 0:o.slice(),s=this.getBoundingInfo();if(e.facetDepthSort&&!e.facetDepthSortEnabled){if(e.facetDepthSortEnabled=!0,i instanceof Uint16Array)e.depthSortedIndices=new Uint16Array(i);else if(i instanceof Uint32Array)e.depthSortedIndices=new Uint32Array(i);else{let l=!1;for(let c=0;c<i.length;c++)if(i[c]>65535){l=!0;break}l?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(l,c){return c.sqDistance-l.sqDistance},!e.facetDepthSortFrom){let l=this.getScene().activeCamera;e.facetDepthSortFrom=l?l.position:b.Zero()}e.depthSortedFacets=[];for(let l=0;l<e.facetNb;l++){let c={ind:l*3,sqDistance:0};e.depthSortedFacets.push(c)}e.invertedMatrix=Q.Identity(),e.facetDepthSortOrigin=b.Zero()}e.bbSize.x=s.maximum.x-s.minimum.x>Vt?s.maximum.x-s.minimum.x:Vt,e.bbSize.y=s.maximum.y-s.minimum.y>Vt?s.maximum.y-s.minimum.y:Vt,e.bbSize.z=s.maximum.z-s.minimum.z>Vt?s.maximum.z-s.minimum.z:Vt;let a=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(a=a>e.bbSize.z?a:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/a),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/a),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/a),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=s,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),b.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&Ie.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);let l=e.depthSortedIndices.length/3|0;for(let c=0;c<l;c++){let f=e.depthSortedFacets[c].ind;e.depthSortedIndices[c*3]=i[f],e.depthSortedIndices[c*3+1]=i[f+1],e.depthSortedIndices[c*3+2]=i[f+2]}this.updateIndices(e.depthSortedIndices,void 0,!0)}return this}getFacetLocalNormals(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetNormals||this.updateFacetData(),e.facetNormals}getFacetLocalPositions(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetPositions||this.updateFacetData(),e.facetPositions}getFacetLocalPartitioning(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetPartitioning||this.updateFacetData(),e.facetPartitioning}getFacetPosition(e){let t=b.Zero();return this.getFacetPositionToRef(e,t),t}getFacetPositionToRef(e,t){let i=this.getFacetLocalPositions()[e],r=this.getWorldMatrix();return b.TransformCoordinatesToRef(i,r,t),this}getFacetNormal(e){let t=b.Zero();return this.getFacetNormalToRef(e,t),t}getFacetNormalToRef(e,t){let i=this.getFacetLocalNormals()[e];return b.TransformNormalToRef(i,this.getWorldMatrix(),t),this}getFacetsAtLocalCoordinates(e,t,i){let r=this.getBoundingInfo(),s=this._internalAbstractMeshDataInfo._facetData,a=Math.floor((e-r.minimum.x*s.partitioningBBoxRatio)*s.subDiv.X*s.partitioningBBoxRatio/s.bbSize.x),o=Math.floor((t-r.minimum.y*s.partitioningBBoxRatio)*s.subDiv.Y*s.partitioningBBoxRatio/s.bbSize.y),l=Math.floor((i-r.minimum.z*s.partitioningBBoxRatio)*s.subDiv.Z*s.partitioningBBoxRatio/s.bbSize.z);return a<0||a>s.subDiv.max||o<0||o>s.subDiv.max||l<0||l>s.subDiv.max?null:s.facetPartitioning[a+s.subDiv.max*o+s.subDiv.max*s.subDiv.max*l]}getClosestFacetAtCoordinates(e,t,i,r,s=!1,a=!0){let o=this.getWorldMatrix(),l=ee.Matrix[5];o.invertToRef(l);let c=ee.Vector3[8];b.TransformCoordinatesFromFloatsToRef(e,t,i,l,c);let f=this.getClosestFacetAtLocalCoordinates(c.x,c.y,c.z,r,s,a);return r&&b.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,o,r),f}getClosestFacetAtLocalCoordinates(e,t,i,r,s=!1,a=!0){let o=null,l,c,f,d,u,h,m,g,p=this.getFacetLocalPositions(),_=this.getFacetLocalNormals(),v=this.getFacetsAtLocalCoordinates(e,t,i);if(!v)return null;let E=Number.MAX_VALUE,S,T,A,R;for(let M=0;M<v.length;M++)T=v[M],A=_[T],R=p[T],d=(e-R.x)*A.x+(t-R.y)*A.y+(i-R.z)*A.z,(!s||s&&a&&d>=0||s&&!a&&d<=0)&&(d=A.x*R.x+A.y*R.y+A.z*R.z,u=-(A.x*e+A.y*t+A.z*i-d)/(A.x*A.x+A.y*A.y+A.z*A.z),h=e+A.x*u,m=t+A.y*u,g=i+A.z*u,l=h-e,c=m-t,f=g-i,S=l*l+c*c+f*f,S<E&&(E=S,o=T,r&&(r.x=h,r.y=m,r.z=g)));return o}getFacetDataParameters(){return this._internalAbstractMeshDataInfo._facetData.facetParameters}disableFacetData(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=[],e.facetNormals=[],e.facetPartitioning=new Array,e.facetParameters={},e.depthSortedIndices=new Uint32Array(0)),this}updateIndices(e,t,i=!1){return this}createNormals(e){let t=this.getVerticesData(D.PositionKind),i=this.getIndices(),r;return this.isVerticesDataPresent(D.NormalKind)?r=this.getVerticesData(D.NormalKind):r=[],Ie.ComputeNormals(t,i,r,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(D.NormalKind,r,e),this}async optimizeIndicesAsync(){let e=this.getIndices();if(!e)return this;let{OptimizeIndices:t}=await Promise.resolve().then(()=>(qH(),ZH));return t(e),this.setIndices(e,this.getTotalVertices()),this}alignWithNormal(e,t){t||(t=ta.Y);let i=ee.Vector3[0],r=ee.Vector3[1];return b.CrossToRef(t,e,r),b.CrossToRef(e,r,i),this.rotationQuaternion?je.RotationQuaternionFromAxisToRef(i,e,r,this.rotationQuaternion):b.RotationFromAxisToRef(i,e,r,this.rotation),this}_checkOcclusionQuery(e=!1){return!1}disableEdgesRendering(){throw $e("EdgesRenderer")}enableEdgesRendering(e,t,i){throw $e("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter(e=>e.emitter===this)}};Ir.OCCLUSION_TYPE_NONE=0;Ir.OCCLUSION_TYPE_OPTIMISTIC=1;Ir.OCCLUSION_TYPE_STRICT=2;Ir.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;Ir.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;Ir.CULLINGSTRATEGY_STANDARD=0;Ir.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;Ir.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;Ir.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;Ir.DefaultIsPickable=!0;P([ia.filter((...n)=>!Array.isArray(n[0])&&!Array.isArray(n[3])&&!Array.isArray(n[4])&&!Array.isArray(n[5])&&!Array.isArray(n[6]))],Ir,"_ApplySkeleton",null);zt("BABYLON.AbstractMesh",Ir)});var rs,QH=y(()=>{jt();Or();Yt();rs=class{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.funcRef=1,this.funcMask=255,this.func=519,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681,this.backFunc=519,this.backOpStencilFail=7680,this.backOpDepthFail=7680,this.backOpStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get backFunc(){return this._backFunc}set backFunc(e){this._backFunc=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get backOpStencilFail(){return this._backOpStencilFail}set backOpStencilFail(e){this._backOpStencilFail=e}get backOpDepthFail(){return this._backOpDepthFail}set backOpDepthFail(e){this._backOpDepthFail=e}get backOpStencilDepthPass(){return this._backOpStencilDepthPass}set backOpStencilDepthPass(e){this._backOpStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){at.Clone(()=>e,this)}serialize(){return at.Serialize(this)}parse(e,t,i){at.Parse(()=>this,e,t,i)}};P([F()],rs.prototype,"func",null);P([F()],rs.prototype,"backFunc",null);P([F()],rs.prototype,"funcRef",null);P([F()],rs.prototype,"funcMask",null);P([F()],rs.prototype,"opStencilFail",null);P([F()],rs.prototype,"opDepthFail",null);P([F()],rs.prototype,"opStencilDepthPass",null);P([F()],rs.prototype,"backOpStencilFail",null);P([F()],rs.prototype,"backOpDepthFail",null);P([F()],rs.prototype,"backOpStencilDepthPass",null);P([F()],rs.prototype,"mask",null);P([F()],rs.prototype,"enabled",null)});function ns(n){n.indexOf("vClipPlane")===-1&&n.push("vClipPlane"),n.indexOf("vClipPlane2")===-1&&n.push("vClipPlane2"),n.indexOf("vClipPlane3")===-1&&n.push("vClipPlane3"),n.indexOf("vClipPlane4")===-1&&n.push("vClipPlane4"),n.indexOf("vClipPlane5")===-1&&n.push("vClipPlane5"),n.indexOf("vClipPlane6")===-1&&n.push("vClipPlane6")}function Wl(n,e,t){var c,f,d,u,h,m;let i=!!((c=n.clipPlane)!=null?c:e.clipPlane),r=!!((f=n.clipPlane2)!=null?f:e.clipPlane2),s=!!((d=n.clipPlane3)!=null?d:e.clipPlane3),a=!!((u=n.clipPlane4)!=null?u:e.clipPlane4),o=!!((h=n.clipPlane5)!=null?h:e.clipPlane5),l=!!((m=n.clipPlane6)!=null?m:e.clipPlane6);i&&t.push("#define CLIPPLANE"),r&&t.push("#define CLIPPLANE2"),s&&t.push("#define CLIPPLANE3"),a&&t.push("#define CLIPPLANE4"),o&&t.push("#define CLIPPLANE5"),l&&t.push("#define CLIPPLANE6")}function $H(n,e,t){var f,d,u,h,m,g;let i=!1,r=!!((f=n.clipPlane)!=null?f:e.clipPlane),s=!!((d=n.clipPlane2)!=null?d:e.clipPlane2),a=!!((u=n.clipPlane3)!=null?u:e.clipPlane3),o=!!((h=n.clipPlane4)!=null?h:e.clipPlane4),l=!!((m=n.clipPlane5)!=null?m:e.clipPlane5),c=!!((g=n.clipPlane6)!=null?g:e.clipPlane6);return t.CLIPPLANE!==r&&(t.CLIPPLANE=r,i=!0),t.CLIPPLANE2!==s&&(t.CLIPPLANE2=s,i=!0),t.CLIPPLANE3!==a&&(t.CLIPPLANE3=a,i=!0),t.CLIPPLANE4!==o&&(t.CLIPPLANE4=o,i=!0),t.CLIPPLANE5!==l&&(t.CLIPPLANE5=l,i=!0),t.CLIPPLANE6!==c&&(t.CLIPPLANE6=c,i=!0),i}function ss(n,e,t){var r,s,a,o,l,c;let i=(r=e.clipPlane)!=null?r:t.clipPlane;Lp(n,"vClipPlane",i),i=(s=e.clipPlane2)!=null?s:t.clipPlane2,Lp(n,"vClipPlane2",i),i=(a=e.clipPlane3)!=null?a:t.clipPlane3,Lp(n,"vClipPlane3",i),i=(o=e.clipPlane4)!=null?o:t.clipPlane4,Lp(n,"vClipPlane4",i),i=(l=e.clipPlane5)!=null?l:t.clipPlane5,Lp(n,"vClipPlane5",i),i=(c=e.clipPlane6)!=null?c:t.clipPlane6,Lp(n,"vClipPlane6",i)}function Lp(n,e,t){var i;if(t){let r=((i=no.getScene())==null?void 0:i.floatingOriginOffset)||b.ZeroReadOnly;n.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d+b.Dot(t.normal,r))}}var Hl=y(()=>{Fv();He()});var fe,co=y(()=>{Yr();fe=class{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get BaseWeightTextureEnabled(){return this._BaseWeightTextureEnabled}static set BaseWeightTextureEnabled(e){this._BaseWeightTextureEnabled!==e&&(this._BaseWeightTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get BaseDiffuseRoughnessTextureEnabled(){return this._BaseDiffuseRoughnessTextureEnabled}static set BaseDiffuseRoughnessTextureEnabled(e){this._BaseDiffuseRoughnessTextureEnabled!==e&&(this._BaseDiffuseRoughnessTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,ye.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._TranslucencyIntensityTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get TranslucencyColorTextureEnabled(){return this._TranslucencyColorTextureEnabled}static set TranslucencyColorTextureEnabled(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,ye.MarkAllMaterialsAsDirty(1))}};fe._DiffuseTextureEnabled=!0;fe._BaseWeightTextureEnabled=!0;fe._BaseDiffuseRoughnessTextureEnabled=!0;fe._DetailTextureEnabled=!0;fe._DecalMapEnabled=!0;fe._AmbientTextureEnabled=!0;fe._OpacityTextureEnabled=!0;fe._ReflectionTextureEnabled=!0;fe._EmissiveTextureEnabled=!0;fe._SpecularTextureEnabled=!0;fe._BumpTextureEnabled=!0;fe._LightmapTextureEnabled=!0;fe._RefractionTextureEnabled=!0;fe._ColorGradingTextureEnabled=!0;fe._FresnelEnabled=!0;fe._ClearCoatTextureEnabled=!0;fe._ClearCoatBumpTextureEnabled=!0;fe._ClearCoatTintTextureEnabled=!0;fe._SheenTextureEnabled=!0;fe._AnisotropicTextureEnabled=!0;fe._ThicknessTextureEnabled=!0;fe._RefractionIntensityTextureEnabled=!0;fe._TranslucencyIntensityTextureEnabled=!0;fe._TranslucencyColorTextureEnabled=!0;fe._IridescenceTextureEnabled=!0});function fd(n,e,t){if(!n||n.LOGARITHMICDEPTH||n.indexOf&&n.indexOf("LOGARITHMICDEPTH")>=0){let i=t.activeCamera;i.mode===1&&te.Error("Logarithmic depth is not compatible with orthographic cameras!",20),e.setFloat("logarithmicDepthConstant",2/(Math.log(i.maxZ+1)/Math.LN2))}}var JH=y(()=>{wt()});function dd(n,e,t,i=!1){t&&n.fogEnabled&&(!e||e.applyFog)&&n.fogMode!==0&&(t.setFloat4("vFogInfos",n.fogMode,n.fogStart,n.fogEnd,n.fogDensity),i?(n.fogColor.toLinearSpaceToRef(e4,n.getEngine().useExactSrgbConversions),t.setColor3("vFogColor",e4)):t.setColor3("vFogColor",n.fogColor))}function Xl(n,e,t,i,r,s,a,o,l,c){let f=n.numMaxInfluencers||n.numInfluencers;return f<=0?0:(e.push("#define MORPHTARGETS"),n.hasPositions&&e.push("#define MORPHTARGETTEXTURE_HASPOSITIONS"),n.hasNormals&&e.push("#define MORPHTARGETTEXTURE_HASNORMALS"),n.hasTangents&&e.push("#define MORPHTARGETTEXTURE_HASTANGENTS"),n.hasUVs&&e.push("#define MORPHTARGETTEXTURE_HASUVS"),n.hasUV2s&&e.push("#define MORPHTARGETTEXTURE_HASUV2S"),n.hasColors&&e.push("#define MORPHTARGETTEXTURE_HASCOLORS"),n.supportsPositions&&r&&e.push("#define MORPHTARGETS_POSITION"),n.supportsNormals&&s&&e.push("#define MORPHTARGETS_NORMAL"),n.supportsTangents&&a&&e.push("#define MORPHTARGETS_TANGENT"),n.supportsUVs&&o&&e.push("#define MORPHTARGETS_UV"),n.supportsUV2s&&l&&e.push("#define MORPHTARGETS_UV2"),n.supportsColors&&c&&e.push("#define MORPHTARGETS_COLOR"),e.push("#define NUM_MORPH_INFLUENCERS "+f),n.isUsingTextureForTargets&&e.push("#define MORPHTARGETS_TEXTURE"),th.NUM_MORPH_INFLUENCERS=f,th.NORMAL=s,th.TANGENT=a,th.UV=o,th.UV2=l,th.COLOR=c,ih(t,i,th,r),f)}function ih(n,e,t,i=!0){let r=t.NUM_MORPH_INFLUENCERS;if(r>0&&Oe.LastCreatedEngine){let s=Oe.LastCreatedEngine.getCaps().maxVertexAttribs,a=e.morphTargetManager;if(a!=null&&a.isUsingTextureForTargets)return;let o=a&&a.supportsPositions&&i,l=a&&a.supportsNormals&&t.NORMAL,c=a&&a.supportsTangents&&t.TANGENT,f=a&&a.supportsUVs&&t.UV1,d=a&&a.supportsUV2s&&t.UV2,u=a&&a.supportsColors&&t.VERTEXCOLOR;for(let h=0;h<r;h++)o&&n.push("position"+h),l&&n.push("normal"+h),c&&n.push("tangent"+h),f&&n.push("uv_"+h),d&&n.push("uv2_"+h),u&&n.push("color"+h),n.length>s&&te.Error("Cannot add more vertex attributes for mesh "+e.name)}}function Qo(n,e=!1){n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"),e&&(n.push("previousWorld0"),n.push("previousWorld1"),n.push("previousWorld2"),n.push("previousWorld3"))}function as(n,e){let t=n.morphTargetManager;!n||!t||e.setFloatArray("morphTargetInfluences",t.influences)}function ud(n,e){e.bindToEffect(n,"Scene")}function Dp(n,e,t,i,r=null,s=!1,a=!1,o=!1,l=!1,c=!1,f=!1,d=0){if(n.texturesEnabled&&r&&fe.ReflectionTextureEnabled){if(t.updateMatrix("reflectionMatrix",r.getReflectionTextureMatrix()),t.updateFloat2("vReflectionInfos",r.level*n.iblIntensity,d),o&&r.boundingBoxSize){let u=r;t.updateVector3("vReflectionPosition",u.boundingBoxPosition),t.updateVector3("vReflectionSize",u.boundingBoxSize)}if(s){let u=r.getSize().width;t.updateFloat2("vReflectionFilteringInfo",u,Math.log2(u))}if(c&&!e.USEIRRADIANCEMAP){let u=r.sphericalPolynomial;if(e.USESPHERICALFROMREFLECTIONMAP&&u)if(e.SPHERICAL_HARMONICS){let h=u.preScaledHarmonics;t.updateVector3("vSphericalL00",h.l00),t.updateVector3("vSphericalL1_1",h.l1_1),t.updateVector3("vSphericalL10",h.l10),t.updateVector3("vSphericalL11",h.l11),t.updateVector3("vSphericalL2_2",h.l2_2),t.updateVector3("vSphericalL2_1",h.l2_1),t.updateVector3("vSphericalL20",h.l20),t.updateVector3("vSphericalL21",h.l21),t.updateVector3("vSphericalL22",h.l22)}else t.updateFloat3("vSphericalX",u.x.x,u.x.y,u.x.z),t.updateFloat3("vSphericalY",u.y.x,u.y.y,u.y.z),t.updateFloat3("vSphericalZ",u.z.x,u.z.y,u.z.z),t.updateFloat3("vSphericalXX_ZZ",u.xx.x-u.zz.x,u.xx.y-u.zz.y,u.xx.z-u.zz.z),t.updateFloat3("vSphericalYY_ZZ",u.yy.x-u.zz.x,u.yy.y-u.zz.y,u.yy.z-u.zz.z),t.updateFloat3("vSphericalZZ",u.zz.x,u.zz.y,u.zz.z),t.updateFloat3("vSphericalXY",u.xy.x,u.xy.y,u.xy.z),t.updateFloat3("vSphericalYZ",u.yz.x,u.yz.y,u.yz.z),t.updateFloat3("vSphericalZX",u.zx.x,u.zx.y,u.zx.z)}else l&&e.USEIRRADIANCEMAP&&e.USE_IRRADIANCE_DOMINANT_DIRECTION&&r.irradianceTexture&&t.updateVector3("vReflectionDominantDirection",r.irradianceTexture._dominantDirection);a&&t.updateFloat3("vReflectionMicrosurfaceInfos",r.getSize().width,r.lodGenerationScale,r.lodGenerationOffset)}f&&t.updateColor3("vReflectionColor",i)}function db(n,e,t,i=null,r=!1){if(i&&fe.ReflectionTextureEnabled){e.LODBASEDMICROSFURACE?t.setTexture("reflectionSampler",i):(t.setTexture("reflectionSampler",i._lodTextureMid||i),t.setTexture("reflectionSamplerLow",i._lodTextureLow||i),t.setTexture("reflectionSamplerHigh",i._lodTextureHigh||i)),e.USEIRRADIANCEMAP&&t.setTexture("irradianceSampler",i.irradianceTexture);let s=n.iblCdfGenerator;r&&s&&t.setTexture("icdfSampler",s.getIcdfTexture())}}function fi(n,e,t){e._needUVs=!0,e[t]=!0,n.optimizeUVAllocation&&n.getTextureMatrix().isIdentityAs3x2()?(e[t+"DIRECTUV"]=n.coordinatesIndex+1,e["MAINUV"+(n.coordinatesIndex+1)]=!0):e[t+"DIRECTUV"]=0}function di(n,e,t){let i=n.getTextureMatrix();e.updateMatrix(t+"Matrix",i)}function Op(n,e,t){t.BAKED_VERTEX_ANIMATION_TEXTURE&&t.INSTANCES&&n.push("bakedVertexAnimationSettingsInstanced")}function ohe(n,e){return e.set(n),e}function aa(n,e,t){if(!(!e||!n)&&(n.computeBonesUsingShaders&&e._bonesComputationForcedToCPU&&(n.computeBonesUsingShaders=!1),n.useBones&&n.computeBonesUsingShaders&&n.skeleton)){let i=n.skeleton;if(i.isUsingTextureForMatrices&&e.getUniformIndex("boneTextureInfo")>-1){let r=i.getTransformMatrixTexture(n);e.setTexture("boneSampler",r),e.setFloat2("boneTextureInfo",i._textureWidth,i._textureHeight)}else{let r=i.getTransformMatrices(n);r&&(e.setMatrices("mBones",r),t&&n.getScene().prePassRenderer&&n.getScene().prePassRenderer.getIndex(2)&&(t.previousBones[n.uniqueId]||(t.previousBones[n.uniqueId]=r.slice()),e.setMatrices("mPreviousBones",t.previousBones[n.uniqueId]),ohe(r,t.previousBones[n.uniqueId])))}}}function lhe(n,e,t,i,r,s=!0){n._bindLight(e,t,i,r,s)}function Np(n,e,t,i,r=4){let s=Math.min(e.lightSources.length,r);for(let a=0;a<s;a++){let o=e.lightSources[a];lhe(o,a,n,t,typeof i=="boolean"?i:i.SPECULARTERM,e.receiveShadows)}}function wp(n,e,t,i){t.NUM_BONE_INFLUENCERS>0&&(i.addCPUSkinningFallback(0,e),n.push("matricesIndices"),n.push("matricesWeights"),t.NUM_BONE_INFLUENCERS>4&&(n.push("matricesIndicesExtra"),n.push("matricesWeightsExtra")))}function Fp(n,e){(e.INSTANCES||e.THIN_INSTANCES)&&Qo(n,!!e.PREPASS_VELOCITY),e.INSTANCESCOLOR&&n.push("instanceColor")}function Bp(n,e,t=4,i=0){let r=0;for(let s=0;s<t&&n["LIGHT"+s];s++)s>0&&(r=i+s,e.addFallback(r,"LIGHT"+s)),n.SHADOWS||(n["SHADOW"+s]&&e.addFallback(i,"SHADOW"+s),n["SHADOWPCF"+s]&&e.addFallback(i,"SHADOWPCF"+s),n["SHADOWPCSS"+s]&&e.addFallback(i,"SHADOWPCSS"+s),n["SHADOWPOISSON"+s]&&e.addFallback(i,"SHADOWPOISSON"+s),n["SHADOWESM"+s]&&e.addFallback(i,"SHADOWESM"+s),n["SHADOWCLOSEESM"+s]&&e.addFallback(i,"SHADOWCLOSEESM"+s));return r}function che(n,e){return e.fogEnabled&&n.applyFog&&e.fogMode!==0}function Up(n,e,t,i,r,s,a,o=!1,l=!1,c,f){var d;if(a._areMiscDirty){a.LOGARITHMICDEPTH=t,a.POINTSIZE=i,a.FOG=r&&che(n,e),a.NONUNIFORMSCALING=n.nonUniformScaling,a.ALPHATEST=s,a.DECAL_AFTER_DETAIL=o,a.USE_VERTEX_PULLING=l,a.RIGHT_HANDED=e.useRightHandedSystem;let u=(d=c==null?void 0:c.geometry)==null?void 0:d.getIndexBuffer(),h=c?c.isUnIndexed:!1;a.VERTEX_PULLING_USE_INDEX_BUFFER=!!u&&!h,a.VERTEX_PULLING_INDEX_BUFFER_32BITS=u&&!h?u.is32Bits:!1,a.VERTEXOUTPUT_INVARIANT=!!f}}function Vp(n,e,t,i=!1){if(!n.lightsEnabled||i)return!0;let r=e.lightSources,s=Math.min(r.length,t);for(let a=0;a<s;a++)if(!r[a].areLightTexturesReady())return!1;return!0}function Gp(n,e,t,i,r=4,s=!1){if(!t._areLightsDirty)return t._needNormals;let a=0,o={needNormals:t._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(n.lightsEnabled&&!s){for(let f of e.lightSources)if(fhe(n,e,f,a,t,i,o),a++,a===r)break}t.SPECULARTERM=o.specularEnabled,t.SHADOWS=o.shadowEnabled;let l=Math.max(r,t.MAXLIGHTCOUNT||0);for(let f=a;f<l;f++)t["LIGHT"+f]!==void 0&&(t["LIGHT"+f]=!1,t["HEMILIGHT"+f]=!1,t["POINTLIGHT"+f]=!1,t["DIRLIGHT"+f]=!1,t["SPOTLIGHT"+f]=!1,t["AREALIGHT"+f]=!1,t["CLUSTLIGHT"+f]=!1,t["SHADOW"+f]=!1,t["SHADOWCSM"+f]=!1,t["SHADOWCSMDEBUG"+f]=!1,t["SHADOWCSMNUM_CASCADES"+f]=!1,t["SHADOWCSMUSESHADOWMAXZ"+f]=!1,t["SHADOWCSMNOBLEND"+f]=!1,t["SHADOWCSM_RIGHTHANDED"+f]=!1,t["SHADOWPCF"+f]=!1,t["SHADOWPCSS"+f]=!1,t["SHADOWPOISSON"+f]=!1,t["SHADOWESM"+f]=!1,t["SHADOWCLOSEESM"+f]=!1,t["SHADOWCUBE"+f]=!1,t["SHADOWLOWQUALITY"+f]=!1,t["SHADOWMEDIUMQUALITY"+f]=!1);t.LIGHTCOUNT=a,t.MAXLIGHTCOUNT=r;let c=n.getEngine().getCaps();return t.SHADOWFLOAT===void 0&&(o.needRebuild=!0),t.SHADOWFLOAT=o.shadowEnabled&&(c.textureFloatRender&&c.textureFloatLinearFiltering||c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering),t.LIGHTMAPEXCLUDED=o.lightmapMode,o.needRebuild&&t.rebuild(),o.needNormals}function hd(n,e,t,i=!1,r=8,s=!1){if(e&&fe.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;t._needNormals=!0,t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,t.USEIRRADIANCEMAP=!1,t.LODBASEDMICROSFURACE=n.getEngine().getCaps().textureLOD;let a=n.getEngine();switch(i&&r>0?(t.NUM_SAMPLES=""+r,a._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0,n.iblCdfGenerator&&(t.IBL_CDF_FILTERING=!0)):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===_e.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&n.useRightHandedSystem?!e.invertZ:e.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.coordinatesMode){case _e.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case _e.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case _e.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case _e.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case _e.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case _e.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case _e.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case _e.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case _e.CUBIC_MODE:case _e.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize;break}e.coordinatesMode!==_e.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USESPHERICALINVERTEX=!1,e.irradianceTexture._dominantDirection?t.USE_IRRADIANCE_DOMINANT_DIRECTION=!0:t.USE_IRRADIANCE_DOMINANT_DIRECTION=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,t.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,t.USESPHERICALINVERTEX=s))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;return!0}function fhe(n,e,t,i,r,s,a){var o;switch(a.needNormals=!0,r["LIGHT"+i]===void 0&&(a.needRebuild=!0),r["LIGHT"+i]=!0,r["SPOTLIGHT"+i]=!1,r["HEMILIGHT"+i]=!1,r["POINTLIGHT"+i]=!1,r["DIRLIGHT"+i]=!1,r["AREALIGHT"+i]=!1,r["CLUSTLIGHT"+i]=!1,t.prepareLightSpecificDefines(r,i),r["LIGHT_FALLOFF_PHYSICAL"+i]=!1,r["LIGHT_FALLOFF_GLTF"+i]=!1,r["LIGHT_FALLOFF_STANDARD"+i]=!1,t.falloffType){case ti.FALLOFF_GLTF:r["LIGHT_FALLOFF_GLTF"+i]=!0;break;case ti.FALLOFF_PHYSICAL:r["LIGHT_FALLOFF_PHYSICAL"+i]=!0;break;case ti.FALLOFF_STANDARD:r["LIGHT_FALLOFF_STANDARD"+i]=!0;break}if(s&&!t.specular.equalsFloats(0,0,0)&&(a.specularEnabled=!0),r["SHADOW"+i]=!1,r["SHADOWCSM"+i]=!1,r["SHADOWCSMDEBUG"+i]=!1,r["SHADOWCSMNUM_CASCADES"+i]=!1,r["SHADOWCSMUSESHADOWMAXZ"+i]=!1,r["SHADOWCSMNOBLEND"+i]=!1,r["SHADOWCSM_RIGHTHANDED"+i]=!1,r["SHADOWPCF"+i]=!1,r["SHADOWPCSS"+i]=!1,r["SHADOWPOISSON"+i]=!1,r["SHADOWESM"+i]=!1,r["SHADOWCLOSEESM"+i]=!1,r["SHADOWCUBE"+i]=!1,r["SHADOWLOWQUALITY"+i]=!1,r["SHADOWMEDIUMQUALITY"+i]=!1,e&&e.receiveShadows&&n.shadowsEnabled&&t.shadowEnabled){let l=(o=t.getShadowGenerator(n.activeCamera))!=null?o:t.getShadowGenerator();if(l){let c=l.getShadowMap();c&&c.renderList&&c.renderList.length>0&&(a.shadowEnabled=!0,l.prepareDefines(r,i))}}t.lightmapMode!=ti.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+i]=!0,r["LIGHTMAPNOSPECULAR"+i]=t.lightmapMode==ti.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+i]=!1,r["LIGHTMAPNOSPECULAR"+i]=!1)}function kp(n,e,t,i,r,s=null,a=!1){let o=mhe(n,i);s!==!1&&(o=$H(t,n,i)),i.DEPTHPREPASS!==!e.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==r&&(i.INSTANCES=r,o=!0),i.THIN_INSTANCES!==a&&(i.THIN_INSTANCES=a,o=!0),o&&i.markAsUnprocessed()}function dhe(n,e){if(n.useBones&&n.computeBonesUsingShaders&&n.skeleton){e.NUM_BONE_INFLUENCERS=n.numBoneInfluencers;let t=e.BONETEXTURE!==void 0;if(n.skeleton.isUsingTextureForMatrices&&t)e.BONETEXTURE=!0;else{e.BonesPerMesh=n.skeleton.bones.length+1,e.BONETEXTURE=t?!1:void 0;let i=n.getScene().prePassRenderer;if(i&&i.enabled){let r=i.excludedSkinnedMesh.indexOf(n)===-1;e.BONES_VELOCITY_ENABLED=r}}}else e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE!==void 0&&(e.BONETEXTURE=!1)}function uhe(n,e){let t=n.morphTargetManager;t?(e.MORPHTARGETS_UV=t.supportsUVs&&e.UV1,e.MORPHTARGETS_UV2=t.supportsUV2s&&e.UV2,e.MORPHTARGETS_TANGENT=t.supportsTangents&&e.TANGENT,e.MORPHTARGETS_NORMAL=t.supportsNormals&&e.NORMAL,e.MORPHTARGETS_POSITION=t.supportsPositions,e.MORPHTARGETS_COLOR=t.supportsColors,e.MORPHTARGETTEXTURE_HASUVS=t.hasUVs,e.MORPHTARGETTEXTURE_HASUV2S=t.hasUV2s,e.MORPHTARGETTEXTURE_HASTANGENTS=t.hasTangents,e.MORPHTARGETTEXTURE_HASNORMALS=t.hasNormals,e.MORPHTARGETTEXTURE_HASPOSITIONS=t.hasPositions,e.MORPHTARGETTEXTURE_HASCOLORS=t.hasColors,e.NUM_MORPH_INFLUENCERS=t.numMaxInfluencers||t.numInfluencers,e.MORPHTARGETS=e.NUM_MORPH_INFLUENCERS>0,e.MORPHTARGETS_TEXTURE=t.isUsingTextureForTargets):(e.MORPHTARGETS_UV=!1,e.MORPHTARGETS_UV2=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS_POSITION=!1,e.MORPHTARGETS_COLOR=!1,e.MORPHTARGETTEXTURE_HASUVS=!1,e.MORPHTARGETTEXTURE_HASUV2S=!1,e.MORPHTARGETTEXTURE_HASTANGENTS=!1,e.MORPHTARGETTEXTURE_HASNORMALS=!1,e.MORPHTARGETTEXTURE_HASPOSITIONS=!1,e.MORPHTARGETTEXTURE_HAS_COLORS=!1,e.MORPHTARGETS=!1,e.NUM_MORPH_INFLUENCERS=0)}function hhe(n,e){let t=n.bakedVertexAnimationManager;e.BAKED_VERTEX_ANIMATION_TEXTURE=!!(t&&t.isEnabled)}function zp(n,e,t,i,r=!1,s=!0,a=!0){if(!e._areAttributesDirty&&e._needNormals===e._normals&&e._needUVs===e._uvs)return!1;e._normals=e._needNormals,e._uvs=e._needUVs,e.NORMAL=e._needNormals&&n.isVerticesDataPresent("normal"),e._needNormals&&n.isVerticesDataPresent("tangent")&&(e.TANGENT=!0);for(let o=1;o<=6;++o)e["UV"+o]=e._needUVs?n.isVerticesDataPresent(`uv${o===1?"":o}`):!1;if(t){let o=n.useVertexColors&&n.isVerticesDataPresent("color");e.VERTEXCOLOR=o,e.VERTEXALPHA=n.hasVertexAlpha&&o&&s}return n.isVerticesDataPresent("instanceColor")&&(n.hasInstances||n.hasThinInstances)&&(e.INSTANCESCOLOR=!0),i&&dhe(n,e),r&&uhe(n,e),a&&hhe(n,e),!0}function Wp(n,e){if(n.activeCamera){let t=e.MULTIVIEW;e.MULTIVIEW=n.activeCamera.outputRenderTarget!==null&&n.activeCamera.outputRenderTarget.getViewCount()>1,e.MULTIVIEW!=t&&e.markAsUnprocessed()}}function Hp(n,e,t){let i=e.ORDER_INDEPENDENT_TRANSPARENCY,r=e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;e.ORDER_INDEPENDENT_TRANSPARENCY=n.useOrderIndependentTransparency&&t,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!n.getEngine().getCaps().textureFloatLinearFiltering,(i!==e.ORDER_INDEPENDENT_TRANSPARENCY||r!==e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&e.markAsUnprocessed()}function Xp(n,e,t){let i=e.PREPASS;if(!e._arePrePassDirty)return;let r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:9,define:"PREPASS_LOCAL_POSITION",index:"PREPASS_LOCAL_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:11,define:"PREPASS_VELOCITY_LINEAR",index:"PREPASS_VELOCITY_LINEAR_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE_LEGACY",index:"PREPASS_IRRADIANCE_LEGACY_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:10,define:"PREPASS_SCREENSPACE_DEPTH",index:"PREPASS_SCREENSPACE_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"},{type:8,define:"PREPASS_WORLD_NORMAL",index:"PREPASS_WORLD_NORMAL_INDEX"},{type:14,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"}];if(n.prePassRenderer&&n.prePassRenderer.enabled&&t){e.PREPASS=!0,e.SCENE_MRT_COUNT=n.prePassRenderer.mrtCount,e.PREPASS_NORMAL_WORLDSPACE=n.prePassRenderer.generateNormalsInWorldSpace,e.PREPASS_COLOR=!0,e.PREPASS_COLOR_INDEX=0;for(let s=0;s<r.length;s++){let a=n.prePassRenderer.getIndex(r[s].type);a!==-1?(e[r[s].define]=!0,e[r[s].index]=a):e[r[s].define]=!1}}else{e.PREPASS=!1;for(let s=0;s<r.length;s++)e[r[s].define]=!1}e.PREPASS!=i&&(e.markAsUnprocessed(),e.markAsImageProcessingDirty())}function mhe(n,e){let t=!1;if(n.activeCamera){let i=e.CAMERA_ORTHOGRAPHIC?1:0,r=e.CAMERA_PERSPECTIVE?1:0,s=n.activeCamera.mode===1?1:0,a=n.activeCamera.mode===0?1:0;(i^s||r^a)&&(e.CAMERA_ORTHOGRAPHIC=s===1,e.CAMERA_PERSPECTIVE=a===1,t=!0)}return t}function phe(n,e,t,i,r=null,s=!1,a=!1,o=!1,l=!1,c=!1){r&&r.push("Light"+n),!s&&(e.push("vLightData"+n,"vLightDiffuse"+n,"vLightSpecular"+n,"vLightDirection"+n,"vLightWidth"+n,"vLightHeight"+n,"vLightFalloff"+n,"vLightGround"+n,"vSliceData"+n,"vSliceRanges"+n,"lightMatrix"+n,"shadowsInfo"+n,"depthValues"+n),t.push("shadowTexture"+n),t.push("depthTexture"+n),e.push("viewFrustumZ"+n,"cascadeBlendFactor"+n,"lightSizeUVCorrection"+n,"depthCorrection"+n,"penumbraDarkness"+n,"frustumLengths"+n),i&&(t.push("projectionLightTexture"+n),e.push("textureProjectionMatrix"+n)),a&&t.push("iesLightTexture"+n),l&&t.push("rectAreaLightEmissionTexture"+n),o&&(t.push("lightDataTexture"+n),c||t.push("tileMaskTexture"+n)))}function md(n,e,t){let i=["vReflectionMicrosurfaceInfos","vReflectionDominantDirection","reflectionMatrix","vReflectionInfos","vReflectionPosition","vReflectionSize","vReflectionColor","vReflectionFilteringInfo"];t&&i.push("vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22"),n.push(...i);let r=["reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","icdfSampler"];e.push(...r)}function Yp(n,e,t,i=4){var o;let r,s,a=null;if(n.uniformsNames){let l=n;r=l.uniformsNames,s=l.uniformBuffersNames,e=l.samplers,t=l.defines,i=l.maxSimultaneousLights||0,a=(o=l.shaderLanguage)!=null?o:null}else r=n,e||(e=[]);for(let l=0;l<i&&t["LIGHT"+l];l++)phe(l,r,e,t["PROJECTEDLIGHTTEXTURE"+l],s,!1,t["IESLIGHTTEXTURE"+l],t["CLUSTLIGHT"+l],t["RECTAREALIGHTEMISSIONTEXTURE"+l],a===1);t.NUM_MORPH_INFLUENCERS&&(r.push("morphTargetInfluences"),r.push("morphTargetCount")),t.BAKED_VERTEX_ANIMATION_TEXTURE&&(r.push("bakedVertexAnimationSettings"),r.push("bakedVertexAnimationTextureSizeInverted"),r.push("bakedVertexAnimationTime"),e.push("bakedVertexAnimationTexture"))}function Kp(n,e=!1,t=!1,i=!1,r=!1,s=!1){n.addUniform("vReflectionInfos",2),n.addUniform("reflectionMatrix",16),e&&n.addUniform("vReflectionMicrosurfaceInfos",3),t&&(n.addUniform("vReflectionPosition",3),n.addUniform("vReflectionSize",3)),i&&(n.addUniform("vReflectionFilteringInfo",2),n.addUniform("vReflectionDominantDirection",3)),s&&n.addUniform("vReflectionColor",3),r&&(n.addUniform("vSphericalL00",3),n.addUniform("vSphericalL1_1",3),n.addUniform("vSphericalL10",3),n.addUniform("vSphericalL11",3),n.addUniform("vSphericalL2_2",3),n.addUniform("vSphericalL2_1",3),n.addUniform("vSphericalL20",3),n.addUniform("vSphericalL21",3),n.addUniform("vSphericalL22",3),n.addUniform("vSphericalX",3),n.addUniform("vSphericalY",3),n.addUniform("vSphericalZ",3),n.addUniform("vSphericalXX_ZZ",3),n.addUniform("vSphericalYY_ZZ",3),n.addUniform("vSphericalZZ",3),n.addUniform("vSphericalXY",3),n.addUniform("vSphericalYZ",3),n.addUniform("vSphericalZX",3))}var e4,th,os=y(()=>{wt();Yi();yv();Hl();co();Kr();JH();e4={r:0,g:0,b:0},th={NUM_MORPH_INFLUENCERS:0,NORMAL:!1,TANGENT:!1,UV:!1,UV2:!1,COLOR:!1}});var Ae,ls=y(()=>{jt();Yt();Gi();Si();Yi();jv();rd();wt();Gu();Yu();QH();os();Or();eL();Ae=class n{get useVertexPulling(){return this._useVertexPulling}set useVertexPulling(e){this._useVertexPulling!==e&&(this._useVertexPulling=e,this.markAsDirty(n.MiscDirtyFlag))}get _supportGlowLayer(){return!1}set _glowModeEnabled(e){}get shaderLanguage(){return this._shaderLanguage}get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;let t=this._alpha;this._alpha=e,(t===1||e===1)&&this.markAsDirty(n.MiscDirtyFlag+n.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(n.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(n.TextureDirtyFlag))}get cullBackFaces(){return this._cullBackFaces}get blockDirtyMechanism(){return this._blockDirtyMechanism}set blockDirtyMechanism(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())}atomicMaterialsUpdate(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}}get hasRenderTargetTextures(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new re),this._onBindObservable}set onBind(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)}get onUnBindObservable(){return this._onUnBindObservable||(this._onUnBindObservable=new re),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new re),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode[0]!==e&&(this._alphaMode[0]=e,this.markAsDirty(n.TextureDirtyFlag))}get alphaMode(){return this._alphaMode[0]}get alphaModes(){return this._alphaMode}setAlphaMode(e,t=0){this._alphaMode[t]!==e&&(this._alphaMode[t]=e,this.markAsDirty(n.TextureDirtyFlag))}set needDepthPrePass(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))}get needDepthPrePass(){return this._needDepthPrePass}get isPrePassCapable(){return!1}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAsDirty(n.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case n.WireFrameFillMode:case n.LineListDrawMode:case n.LineLoopDrawMode:case n.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?n.WireFrameFillMode:n.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case n.PointFillMode:case n.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?n.PointFillMode:n.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(n.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){let t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&te.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._markAllSubMeshesAsMiscDirty()}get isVertexOutputInvariant(){return this._isVertexOutputInvariant}set isVertexOutputInvariant(e){this._isVertexOutputInvariant!==e&&(this._isVertexOutputInvariant=e,this._markAllSubMeshesAsMiscDirty())}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i,r=!1){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this._shaderLanguage=0,this._forceGLSL=!1,this._useVertexPulling=!1,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.sideOrientation=null,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new re,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=[2],this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new rs,this._isVertexOutputInvariant=n.ForceVertexOutputInvariant,this._useUBO=!1,this._fillMode=n.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._uniformBufferLayoutBuilt=!1,this._eventInfo={},this._callbackPluginEventGeneric=()=>{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._transparencyMode=null,this.name=e;let s=t||Oe.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._forceGLSL=r,this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[127]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||pe.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Ps(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new xr(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,this._createUniformBuffer(),i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),n.OnEventObservable.notifyObservers(this,1))}_createUniformBuffer(){var t;let e=this.getScene().getEngine();(t=this._uniformBuffer)==null||t.dispose(),e.isWebGPU&&!this._forceGLSL?(this._uniformBuffer=new xr(e,void 0,void 0,this.name,!0),this._shaderLanguage=1):this._uniformBuffer=new xr(this._scene.getEngine(),void 0,void 0,this.name),this._uniformBufferLayoutBuilt=!1}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){let r=t.materialDefines;return r?(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh):!1}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}_getEffectiveOrientation(e){return this.sideOrientation!==null?this.sideOrientation:e.sideOrientation}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _hasTransparencyMode(){return this._transparencyMode!=null}get _transparencyModeIsBlend(){return this._transparencyMode===n.MATERIAL_ALPHABLEND||this._transparencyMode===n.MATERIAL_ALPHATESTANDBLEND}get _transparencyModeIsTest(){return this._transparencyMode===n.MATERIAL_ALPHATEST||this._transparencyMode===n.MATERIAL_ALPHATESTANDBLEND}get _disableAlphaBlending(){return this._transparencyMode===n.MATERIAL_OPAQUE||this._transparencyMode===n.MATERIAL_ALPHATEST}needAlphaBlending(){return this._hasTransparencyMode?this._transparencyModeIsBlend:this._disableAlphaBlending?!1:this.alpha<1}needAlphaBlendingForMesh(e){return this._hasTransparencyMode?this._transparencyModeIsBlend:e.visibility<1?!0:this._disableAlphaBlending?!1:e.hasVertexAlpha||this.needAlphaBlending()}needAlphaTesting(){return this._hasTransparencyMode?this._transparencyModeIsTest:!1}needAlphaTestingForMesh(e){return this._hasTransparencyMode?this._transparencyModeIsTest:!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){let t=this.getScene().meshes;for(let i of t)if(i.subMeshes){for(let r of i.subMeshes)if(r.getMaterial()===this)for(let s of r._drawWrappers)s&&this._materialContext===s.materialContext&&(s._wasPreviouslyReady=!1,s._wasPreviouslyUsingInstances=null,s._forceRebindOnNextCall=e)}e&&this.markAsDirty(n.AllDirtyFlag)}_preBind(e,t=null){let i=this._scene.getEngine(),s=(t==null?this.sideOrientation:t)===n.ClockWiseSideOrientation,a=e||this._getDrawWrapper();return sR(a)&&a.materialContext&&(a.materialContext.useVertexPulling=this.useVertexPulling),i.enableEffect(a),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){let e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(8,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){let r=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()),e.setMatrix("inverseProjection",this.getScene().getInverseProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,ud(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){let r=this._scene.getEngine();this._cachedDepthWriteState=r.getDepthWrite(),r.setDepthWrite(!1)}if(this.disableColorWrite){let r=this._scene.getEngine();this._cachedColorWriteState=r.getColorWrite(),r.setColorWrite(!1)}if(this.depthFunction!==0){let r=this._scene.getEngine();this._cachedDepthFunctionState=r.getDepthFunction()||0,r.setDepthFunction(this.depthFunction)}}unbind(){this._scene.getSceneUniformBuffer().unbindEffect(),this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),this.depthFunction!==0&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(256,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(512,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(1024,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){let i={};if(this._serializePlugins(i),n._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(let r of this.pluginManager._plugins){let s=e.pluginManager.getPlugin(r.name);s&&r.copyTo(s)}}getBindedMeshes(){if(this.meshMap){let e=[];for(let t in this.meshMap){let i=this.meshMap[t];i&&e.push(i)}return e}else return this._scene.meshes.filter(t=>t.material===this)}forceCompilation(e,t,i,r){let s={clipPlane:!1,useInstances:!1,...i},a=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;let l=()=>{if(!this._scene||!this._scene.getEngine())return;let c=a.clipPlane;if(s.clipPlane&&(a.clipPlane=new Da(0,0,0,1)),this._storeEffectOnSubMeshes){let f=!0,d=null;if(e.subMeshes){let u=new sa(0,0,0,0,0,e,void 0,!1,!1);u.materialDefines&&(u.materialDefines._renderId=-1),this.isReadyForSubMesh(e,u,s.useInstances)||(u.effect&&u.effect.getCompilationError()&&u.effect.allFallbacksProcessed()?d=u.effect.getCompilationError():(f=!1,setTimeout(l,16)))}f&&(this.allowShaderHotSwapping=o,d&&r&&r(d),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(l,16);s.clipPlane&&(a.clipPlane=c)};l()}async forceCompilationAsync(e,t){return await new Promise((i,r)=>{this.forceCompilation(e,()=>{i()},t,s=>{r(s)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(n._DirtyCallbackArray.length=0,e&n.ImageProcessingDirtyFlag&&n._DirtyCallbackArray.push(n._ImageProcessingDirtyCallBack),e&n.TextureDirtyFlag&&n._DirtyCallbackArray.push(n._TextureDirtyCallBack),e&n.LightDirtyFlag&&n._DirtyCallbackArray.push(n._LightsDirtyCallBack),e&n.FresnelDirtyFlag&&n._DirtyCallbackArray.push(n._FresnelDirtyCallBack),e&n.AttributesDirtyFlag&&n._DirtyCallbackArray.push(n._AttributeDirtyCallBack),e&n.MiscDirtyFlag&&n._DirtyCallbackArray.push(n._MiscDirtyCallBack),e&n.PrePassDirtyFlag&&n._DirtyCallbackArray.push(n._PrePassDirtyCallBack),n._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(n._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){let e=this.getScene().meshes;for(let t of e)if(t.subMeshes)for(let i of t.subMeshes)i.getMaterial()===this&&i.resetDrawCache()}_markAllSubMeshesAsDirty(e){let t=this.getScene();if(t.blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let i=t.meshes;for(let r of i)if(r.subMeshes){for(let s of r.subMeshes)if((s.getMaterial()||(t._hasDefaultMaterial?t.defaultMaterial:null))===this)for(let o of s._drawWrappers)!o||!o.defines||!o.defines.markAllAsDirty||this._materialContext===o.materialContext&&e(o.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(n._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(n._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(n._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(n._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(n._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(n._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(n._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(n._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(n._PrePassDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(n._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==0){this.checkReadyOnlyOnce=!0;let e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){let r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(2,this._eventInfo),this._parentContainer){let s=this._parentContainer.materials.indexOf(this);s>-1&&this._parentContainer.materials.splice(s,1),this._parentContainer=null}if(i!==!0)if(this.meshMap)for(let s in this.meshMap){let a=this.meshMap[s];this._disposeMeshResources(a)}else{let s=r.meshes;for(let a of s)this._disposeMeshResources(a)}this._uniformBuffer.dispose(),this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}_disposeMeshResources(e){var r;if(!e)return;let t=e.geometry,i=e._internalAbstractMeshDataInfo._materialForRenderPass;if(this._storeEffectOnSubMeshes){if(e.subMeshes&&i)for(let s of e.subMeshes){let a=s._drawWrappers;for(let o=0;o<a.length;o++){let l=(r=a[o])==null?void 0:r.effect;if(!l)continue;i[o]===this&&(t==null||t._releaseVertexArrayObject(l),s._removeDrawWrapper(o,!0,!0))}}}else t==null||t._releaseVertexArrayObject(this._drawWrapper.effect);e.material===this&&!e.sourceMesh&&(e.material=null)}serialize(){let e=at.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(let t of this.pluginManager._plugins)t.doNotSerialize||(e.plugins[t.getClassName()]=t.serialize())}static ParseAlphaMode(e,t){e._alphaMode!==void 0?t._alphaMode=Array.isArray(e._alphaMode)?e._alphaMode:[e._alphaMode]:e.alphaMode!==void 0?t._alphaMode=Array.isArray(e.alphaMode)?e.alphaMode:[e.alphaMode]:t._alphaMode=[2]}static Parse(e,t,i){if(!e.customType)e.customType="BABYLON.StandardMaterial";else if(e.customType==="BABYLON.PBRMaterial"&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return te.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;let s=pe.Instantiate(e.customType).Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,n.ParseAlphaMode(e,s),s}static _ParsePlugins(e,t,i,r){var s;if(e.plugins)for(let a in e.plugins){let o=e.plugins[a],l=(s=t.pluginManager)==null?void 0:s.getPlugin(o.name);if(!l){let c=pe.Instantiate("BABYLON."+a);c&&(l=new c(t))}l==null||l.parse(o,i,r)}}};Ae.TriangleFillMode=0;Ae.WireFrameFillMode=1;Ae.PointFillMode=2;Ae.PointListDrawMode=3;Ae.LineListDrawMode=4;Ae.LineLoopDrawMode=5;Ae.LineStripDrawMode=6;Ae.TriangleStripDrawMode=7;Ae.TriangleFanDrawMode=8;Ae.ClockWiseSideOrientation=0;Ae.CounterClockWiseSideOrientation=1;Ae.ImageProcessingDirtyFlag=64;Ae.TextureDirtyFlag=1;Ae.LightDirtyFlag=2;Ae.FresnelDirtyFlag=4;Ae.AttributesDirtyFlag=8;Ae.MiscDirtyFlag=16;Ae.PrePassDirtyFlag=32;Ae.AllDirtyFlag=127;Ae.MATERIAL_OPAQUE=0;Ae.MATERIAL_ALPHATEST=1;Ae.MATERIAL_ALPHABLEND=2;Ae.MATERIAL_ALPHATESTANDBLEND=3;Ae.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0;Ae.MATERIAL_NORMALBLENDMETHOD_RNM=1;Ae.LIGHTFALLOFF_PHYSICAL=0;Ae.LIGHTFALLOFF_GLTF=1;Ae.LIGHTFALLOFF_STANDARD=2;Ae.OnEventObservable=new re;Ae.ForceVertexOutputInvariant=!1;Ae._AllDirtyCallBack=n=>n.markAllAsDirty();Ae._ImageProcessingDirtyCallBack=n=>n.markAsImageProcessingDirty();Ae._TextureDirtyCallBack=n=>n.markAsTexturesDirty();Ae._FresnelDirtyCallBack=n=>n.markAsFresnelDirty();Ae._MiscDirtyCallBack=n=>n.markAsMiscDirty();Ae._PrePassDirtyCallBack=n=>n.markAsPrePassDirty();Ae._LightsDirtyCallBack=n=>n.markAsLightDirty();Ae._AttributeDirtyCallBack=n=>n.markAsAttributesDirty();Ae._FresnelAndMiscDirtyCallBack=n=>{Ae._FresnelDirtyCallBack(n),Ae._MiscDirtyCallBack(n)};Ae._TextureAndMiscDirtyCallBack=n=>{Ae._TextureDirtyCallBack(n),Ae._MiscDirtyCallBack(n)};Ae._DirtyCallbackArray=[];Ae._RunDirtyCallBacks=n=>{for(let e of Ae._DirtyCallbackArray)e(n)};P([F()],Ae.prototype,"id",void 0);P([F()],Ae.prototype,"uniqueId",void 0);P([F()],Ae.prototype,"name",void 0);P([F()],Ae.prototype,"metadata",void 0);P([F()],Ae.prototype,"checkReadyOnEveryCall",void 0);P([F()],Ae.prototype,"checkReadyOnlyOnce",void 0);P([F()],Ae.prototype,"state",void 0);P([F("alpha")],Ae.prototype,"_alpha",void 0);P([F("backFaceCulling")],Ae.prototype,"_backFaceCulling",void 0);P([F("cullBackFaces")],Ae.prototype,"_cullBackFaces",void 0);P([F()],Ae.prototype,"sideOrientation",void 0);P([F()],Ae.prototype,"_alphaMode",void 0);P([F()],Ae.prototype,"_needDepthPrePass",void 0);P([F()],Ae.prototype,"disableDepthWrite",void 0);P([F()],Ae.prototype,"disableColorWrite",void 0);P([F()],Ae.prototype,"forceDepthWrite",void 0);P([F()],Ae.prototype,"depthFunction",void 0);P([F()],Ae.prototype,"separateCullingPass",void 0);P([F("fogEnabled")],Ae.prototype,"_fogEnabled",void 0);P([F()],Ae.prototype,"pointSize",void 0);P([F()],Ae.prototype,"zOffset",void 0);P([F()],Ae.prototype,"zOffsetUnits",void 0);P([F()],Ae.prototype,"pointsCloud",null);P([F()],Ae.prototype,"fillMode",null);P([F()],Ae.prototype,"useLogarithmicDepth",null);P([F()],Ae.prototype,"_isVertexOutputInvariant",void 0);P([F()],Ae.prototype,"transparencyMode",null)});var jp,t4=y(()=>{ls();td();ir();jp=class n extends Ae{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){let t=e.push;e.push=(...r)=>{let s=t.apply(e,r);return this._markAllSubMeshesAsTexturesDirty(),s};let i=e.splice;e.splice=(r,s)=>{let a=i.call(e,r,s!=null?s:e.length);return this._markAllSubMeshesAsTexturesDirty(),a}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map(e=>e?e.getActiveTextures():[]))}hasTexture(e){var t;if(super.hasTexture(e))return!0;for(let i=0;i<this.subMaterials.length;i++)if((t=this.subMaterials[i])!=null&&t.hasTexture(e))return!0;return!1}getClassName(){return"MultiMaterial"}isReadyForSubMesh(e,t,i){for(let r=0;r<this.subMaterials.length;r++){let s=this.subMaterials[r];if(s){if(s._storeEffectOnSubMeshes){if(!s.isReadyForSubMesh(e,t,i))return!1;continue}if(!s.isReady(e))return!1}}return!0}clone(e,t){let i=new n(e,this.getScene());for(let r=0;r<this.subMaterials.length;r++){let s,a=this.subMaterials[r];t&&a?s=a.clone(e+"-"+a.name):s=this.subMaterials[r],i.subMaterials.push(s)}return i}serialize(){let e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,ni&&(e.tags=ni.GetTags(this)),e.materialsUniqueIds=[],e.materials=[];for(let t=0;t<this.subMaterials.length;t++){let i=this.subMaterials[t];i?(e.materialsUniqueIds.push(i.uniqueId),e.materials.push(i.id)):(e.materialsUniqueIds.push(null),e.materials.push(null))}return e}dispose(e,t,i){let r=this.getScene();if(!r)return;if(i)for(let a=0;a<this.subMaterials.length;a++){let o=this.subMaterials[a];o&&o.dispose(e,t)}let s=r.multiMaterials.indexOf(this);s>=0&&r.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){let i=new n(e.name,t);if(i.id=e.id,i._loadedUniqueId=e.uniqueId,ni&&ni.AddTagsTo(i,e.tags),e.materialsUniqueIds)i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds;else for(let r of e.materials)i.subMaterials.push(t.getLastMaterialById(r));return i}};zt("BABYLON.MultiMaterial",jp)});var ub,i4=y(()=>{ub=class{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}});var Zp,hb,$D,mb,JD,eO,Yl,$,ki=y(()=>{Si();Gi();bv();td();XD();zl();He();$t();Na();qi();vr();lb();Pp();jv();ls();t4();ob();Or();wt();ir();Mn();Sp();i4();Zp=class{},hb=class{constructor(){this.batchCache=new mb(this),this.batchCacheReplacementModeInFrozenMode=new mb(this),this.instancesBufferSize=512*4}},$D=class{constructor(){this.renderPasses={}}},mb=class{constructor(e){this.parent=e,this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}},JD=class{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}},eO=class{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}},Yl={source:null,parent:null,doNotCloneChildren:!1,clonePhysicsImpostor:!0,cloneThinInstances:!1},$=class n extends Ir{static _GetDefaultSideOrientation(e){return e||n.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(D.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(D.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new re),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new re),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new re),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new re),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new re),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get sideOrientation(){return this._internalMeshDataInfo._sideOrientation}set sideOrientation(e){this._internalMeshDataInfo._sideOrientation=e,this._internalAbstractMeshDataInfo._sideOrientationHint=this._scene.useRightHandedSystem&&e===1||!this._scene.useRightHandedSystem&&e===0}get _effectiveSideOrientation(){return this._internalMeshDataInfo._effectiveSideOrientation}get overrideMaterialSideOrientation(){return this.sideOrientation}set overrideMaterialSideOrientation(e){this.sideOrientation=e,this.material&&(this.material.sideOrientation=null)}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){e&&(this.material&&this.material.sideOrientation===null||this._internalAbstractMeshDataInfo._sideOrientationHint)&&(e.sideOrientation=null),this._setMaterial(e)}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){let e=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._instanceDataStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];return e?e.instancesData:void 0}get previousWorldMatrixInstancedBuffer(){let e=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._instanceDataStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];return e?e.instancesPreviousData:void 0}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}_copySource(e,t,i=!0,r=!1){var a,o;let s=this.getScene();if(e._geometry&&e._geometry.applyToMesh(this),Ul.DeepCopy(e,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=e,s.useClonedMeshMap&&(e._internalMeshDataInfo.meshMap||(e._internalMeshDataInfo.meshMap={}),e._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=e._originalBuilderSideOrientation,this._creationDataStorage=e._creationDataStorage,e._ranges){let l=e._ranges;for(let c in l)Object.prototype.hasOwnProperty.call(l,c)&&l[c]&&this.createAnimationRange(c,l[c].from,l[c].to)}if(e.metadata&&e.metadata.clone?this.metadata=e.metadata.clone():this.metadata=e.metadata,this._internalMetadata=e._internalMetadata,ni&&ni.HasTags(e)&&ni.AddTagsTo(this,ni.GetTags(e,!0)),this.setEnabled(e.isEnabled(!1)),this.parent=e.parent,this.setPivotMatrix(e.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=this.name+"."+e.id,this.material=e.material,!t){let l=e.getDescendants(!0);for(let c=0;c<l.length;c++){let f=l[c];f._isMesh?(Yl.parent=this,Yl.doNotCloneChildren=t,Yl.clonePhysicsImpostor=i,Yl.cloneThinInstances=r,f.clone(this.name+"."+f.name,Yl)):f.clone&&f.clone(this.name+"."+f.name,this)}}if(e.morphTargetManager&&(this.morphTargetManager=e.morphTargetManager),s.getPhysicsEngine){let l=s.getPhysicsEngine();if(i&&l)if(l.getPluginVersion()===1){let c=l.getImpostorForPhysicsObject(e);c&&(this.physicsImpostor=c.clone(this))}else l.getPluginVersion()===2&&e.physicsBody&&e.physicsBody.clone(this)}for(let l=0;l<s.particleSystems.length;l++){let c=s.particleSystems[l];c.emitter===e&&c.clone(c.name,this)}if(this.skeleton=e.skeleton,r&&(e._thinInstanceDataStorage.matrixData?(this.thinInstanceSetBuffer("matrix",new Float32Array(e._thinInstanceDataStorage.matrixData),16,!e._thinInstanceDataStorage.matrixBuffer.isUpdatable()),this._thinInstanceDataStorage.matrixBufferSize=e._thinInstanceDataStorage.matrixBufferSize,this._thinInstanceDataStorage.instancesCount=e._thinInstanceDataStorage.instancesCount):this._thinInstanceDataStorage.matrixBufferSize=e._thinInstanceDataStorage.matrixBufferSize,e._userThinInstanceBuffersStorage)){let l=e._userThinInstanceBuffersStorage;for(let c in l.data)this.thinInstanceSetBuffer(c,new Float32Array(l.data[c]),l.strides[c],!((o=(a=l.vertexBuffers)==null?void 0:a[c])!=null&&o.isUpdatable())),this._userThinInstanceBuffersStorage.sizes[c]=l.sizes[c]}this.refreshBoundingInfo(!0,!0),this.computeWorldMatrix(!0)}constructor(e,t=null,i=null,r=null,s,a=!0){var c,f,d,u,h;super(e,t),this._internalMeshDataInfo=new eO,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._thinInstanceDataStorage=new JD,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=n.DEFAULTSIDE,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._instanceDataStorage=new $D,this._instanceDataStorage.engine=t.getEngine(),this._instanceDataStorage.useMonoDataStorageRenderPass=!this._instanceDataStorage.engine.isWebGPU,this._instanceDataStorage.useMonoDataStorageRenderPass&&(this._instanceDataStorage.dataStorageRenderPass=new hb),this._scene.useRightHandedSystem?this.sideOrientation=0:this.sideOrientation=1,this._onBeforeDraw=(m,g,p)=>{m&&p&&(this._uniformBuffer?this.transferToEffect(g):p.bindOnlyWorldMatrix(g))};let o,l=!1;if(i&&i._addToSceneRootNodes===void 0){let m=i;o=(c=m.parent)!=null?c:null,r=(f=m.source)!=null?f:null,s=(d=m.doNotCloneChildren)!=null?d:!1,a=(u=m.clonePhysicsImpostor)!=null?u:!0,l=(h=m.cloneThinInstances)!=null?h:!1}else o=i;r&&this._copySource(r,s,a,l),o!==null&&(this.parent=o),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=m=>{m.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add(()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))}))},this.onMeshReadyObservable=new re(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){let r=this.getTotalVertices()===0||t&&t.doNotInstantiate&&(t.doNotInstantiate===!0||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));r.parent=e||this.parent,r.position=this.position.clone(),r.scaling=this.scaling.clone(),this.rotationQuaternion?r.rotationQuaternion=this.rotationQuaternion.clone():r.rotation=this.rotation.clone(),i&&i(this,r);for(let s of this.getChildTransformNodes(!0))s.getClassName()==="InstancedMesh"&&r.getClassName()==="Mesh"&&s.sourceMesh===this?s.instantiateHierarchy(r,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:r},i):s.instantiateHierarchy(r,t,i);return r}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);if(e)if(this._geometry){let i=this.getIndices(),r=this.getVerticesData(D.PositionKind);r&&i&&(t+=", flat shading: "+(r.length/3===i.length?"YES":"NO"))}else t+=", flat shading: UNKNOWN";return t}_unBindEffect(){super._unBindEffect();for(let e of this.instances)e._unBindEffect()}get hasLODLevels(){return this._internalMeshDataInfo._LODLevels.length>0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){let e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,i)=>t.distanceOrScreenCoverage<i.distanceOrScreenCoverage?e:t.distanceOrScreenCoverage>i.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return te.Warn("You cannot use a mesh as LOD level twice"),this;let i=new ub(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){let t=this._internalMeshDataInfo;for(let i=0;i<t._LODLevels.length;i++){let r=t._LODLevels[i];if(r.distanceOrScreenCoverage===e)return r.mesh}return null}removeLODLevel(e){let t=this._internalMeshDataInfo;for(let i=0;i<t._LODLevels.length;i++)t._LODLevels[i].mesh===e&&(t._LODLevels.splice(i,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this}getLOD(e,t){let i=this._internalMeshDataInfo;if(!i._LODLevels||i._LODLevels.length===0)return this;let r=t||this.getBoundingInfo().boundingSphere,s=e.mode===Et.ORTHOGRAPHIC_CAMERA?e.minZ:r.centerWorld.subtract(e.globalPosition).length(),a=s,o=1;if(i._useLODScreenCoverage){let l=e.screenArea,c=r.radiusWorld*e.minZ/s;c=c*c*Math.PI,a=c/l,o=-1}if(o*i._LODLevels[i._LODLevels.length-1].distanceOrScreenCoverage>o*a)return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this;for(let l=0;l<i._LODLevels.length;l++){let c=i._LODLevels[l];if(o*c.distanceOrScreenCoverage<o*a){if(c.mesh){if(c.mesh.delayLoadState===4)return c.mesh._checkDelayState(),this;if(c.mesh.delayLoadState===2)return this;c.mesh._preActivate(),c.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)}return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,c.mesh),c.mesh}}return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this}get geometry(){return this._geometry}getTotalVertices(){return this._geometry===null||this._geometry===void 0?0:this._geometry.getTotalVertices()}getVerticesData(e,t,i,r){var a,o;if(!this._geometry)return null;let s=r||(o=(a=this._userInstancedBuffersStorage)==null?void 0:a.vertexBuffers[e])==null?void 0:o.getFloatData(this.instances.length+1,i||t&&this._geometry.meshes.length!==1);return s||(s=this._geometry.getVerticesData(e,t,i)),s}copyVerticesData(e,t){this._geometry&&this._geometry.copyVerticesData(e,t)}getVertexBuffer(e,t){var i,r;return this._geometry?(r=t||(i=this._userInstancedBuffersStorage)==null?void 0:i.vertexBuffers[e])!=null?r:this._geometry.getVertexBuffer(e):null}isVerticesDataPresent(e,t){var i;return this._geometry?!t&&((i=this._userInstancedBuffersStorage)==null?void 0:i.vertexBuffers[e])!==void 0||this._geometry.isVerticesDataPresent(e):this._delayInfo?this._delayInfo.indexOf(e)!==-1:!1}isVertexBufferUpdatable(e,t){var i;if(!this._geometry)return this._delayInfo?this._delayInfo.indexOf(e)!==-1:!1;if(!t){let r=(i=this._userInstancedBuffersStorage)==null?void 0:i.vertexBuffers[e];if(r)return r.isUpdatable()}return this._geometry.isVertexBufferUpdatable(e)}getVerticesDataKinds(e){if(!this._geometry){let i=[];if(this._delayInfo)for(let r of this._delayInfo)i.push(r);return i}let t=this._geometry.getVerticesDataKinds();if(!e&&this._userInstancedBuffersStorage)for(let i in this._userInstancedBuffersStorage.vertexBuffers)t.indexOf(i)===-1&&t.push(i);return t}getTotalIndices(){return this._geometry?this._geometry.getTotalIndices():0}getIndices(e,t){return this._geometry?this._geometry.getIndices(e,t):[]}get isBlocked(){return this._masterMesh!==null&&this._masterMesh!==void 0}isReady(e=!1,t=!1){var l,c,f,d,u,h,m;if(this.delayLoadState===2||!super.isReady(e))return!1;if(!this.subMeshes||this.subMeshes.length===0||!e)return!0;let i=this.getEngine(),r=this.getScene(),s=t||i.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();let a=this.material||r.defaultMaterial;if(a){if(a._storeEffectOnSubMeshes)for(let g of this.subMeshes){let p=g.getMaterial();if(p){if(p._storeEffectOnSubMeshes){if(!p.isReadyForSubMesh(this,g,s))return!1}else if(!p.isReady(this,s))return!1}}else if(!a.isReady(this,s))return!1}let o=i.currentRenderPassId;for(let g of this.lightSources){let p=g.getShadowGenerators();if(!p)continue;let _=p.values();for(let v=_.next();v.done!==!0;v=_.next()){let E=v.value;if(E&&(!((l=E.getShadowMap())!=null&&l.renderList)||(c=E.getShadowMap())!=null&&c.renderList&&((d=(f=E.getShadowMap())==null?void 0:f.renderList)==null?void 0:d.indexOf(this))!==-1)){let T=(u=E.getShadowMap().renderPassIds)!=null?u:[i.currentRenderPassId];for(let A=0;A<T.length;++A){i.currentRenderPassId=T[A];for(let R of this.subMeshes)if(!E.isReady(R,s,(m=(h=R.getMaterial())==null?void 0:h.needAlphaBlendingForMesh(this))!=null?m:!1))return i.currentRenderPassId=o,!1}i.currentRenderPassId=o}}}for(let g of this._internalMeshDataInfo._LODLevels)if(g.mesh&&!g.mesh.isReady(s))return!1;return!0}get areNormalsFrozen(){return this._internalMeshDataInfo._areNormalsFrozen}freezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this}unfreezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this}set overridenInstanceCount(e){this._instanceDataStorage.overridenInstanceCount=e}_getInstanceDataStorage(){if(this._instanceDataStorage.useMonoDataStorageRenderPass)return this._instanceDataStorage.dataStorageRenderPass;let e=this._instanceDataStorage.engine.currentRenderPassId,t=this._instanceDataStorage.renderPasses[e];return t||(t=new hb,this._instanceDataStorage.renderPasses[e]=t),t}_preActivate(){let e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t?this:(e._preActivateId=t,this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass.visibleInstances=null:this._getInstanceDataStorage().visibleInstances=null,this)}_preActivateForIntermediateRendering(e){let t=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._getInstanceDataStorage();return t.visibleInstances&&(t.visibleInstances.intermediateDefaultRenderId=e),this}_registerInstanceForRenderId(e,t){let i=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._getInstanceDataStorage();return i.visibleInstances||(i.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId,intermediateDefaultRenderId:-1}),i.visibleInstances[t]||(i.previousRenderId!==void 0&&(!this._instanceDataStorage.useMonoDataStorageRenderPass||this._instanceDataStorage.isFrozen)&&delete i.visibleInstances[i.previousRenderId],i.previousRenderId=t,i.visibleInstances[t]=new Array),i.visibleInstances[t].push(e),this}_afterComputeWorldMatrix(){super._afterComputeWorldMatrix(),this.hasThinInstances&&(this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1))}_postActivate(){this.edgesShareWithInstances&&this.edgesRenderer&&this.edgesRenderer.isEnabled&&this._renderingGroup&&(this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),this.edgesRenderer.customInstances.push(this.getWorldMatrix()))}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i;typeof e=="object"?i=e:i={applySkeleton:e,applyMorph:t};let r=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getData(i,null,D.PositionKind),r),this}_createGlobalSubMesh(e){let t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){let i=this.getIndices();if(!i)return null;let r=i.length,s=!1;if(e)s=!0;else for(let a of this.subMeshes){if(a.indexStart+a.indexCount>r){s=!0;break}if(a.verticesStart+a.verticesCount>t){s=!0;break}}if(!s)return this.subMeshes[0]}return this.releaseSubMeshes(),new sa(0,0,t,0,this.getTotalIndices()||(this.isUnIndexed?t:0),this)}subdivide(e){if(e<1)return;let t=this.getTotalIndices(),i=t/e|0,r=0;for(;i%3!==0;)i++;this.releaseSubMeshes();for(let s=0;s<e&&!(r>=t);s++)sa.CreateFromIndices(0,r,r+i>=t?t-r:i,this,void 0,!1),r+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,r){if(this._geometry)this._geometry.setVerticesData(e,t,i,r);else{let s=new Ie;s.set(t,e);let a=this.getScene();new Cn(Cn.RandomId(),a,s,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){let i=this.getVertexBuffer(e);!i||i.isUpdatable()===t||this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0,i=null){return this._geometry||(this._geometry=Cn.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,i,t),this}updateVerticesData(e,t,i,r){return this._geometry?(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){let i=this.getVerticesData(D.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(D.PositionKind,i,!1,!1),t){let r=this.getIndices(),s=this.getVerticesData(D.NormalKind);if(!s)return this;Ie.ComputeNormals(i,r,s),this.updateVerticesData(D.NormalKind,s,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(this._geometry.meshes.length===1)return this;let e=this._geometry,t=this._geometry.copy(Cn.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i,r=null){let s=this._geometry;s||(s=new Cn(Cn.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i,r)}setIndices(e,t=null,i=!1,r=!1){if(this._geometry)this._geometry.setIndices(e,t,i,r);else{let s=new Ie;s.indices=e;let a=this.getScene();new Cn(Cn.RandomId(),a,s,i,this,t)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,r=!0){if(!this._geometry)return this;let s=this.getScene().getEngine(),a;if(this._unIndexed)this._getRenderingFillMode(i)===Ae.WireFrameFillMode?a=e._getLinesIndexBuffer(this.getIndices(),s):a=null;else switch(this._getRenderingFillMode(i)){case Ae.PointFillMode:a=null;break;case Ae.WireFrameFillMode:a=e._getLinesIndexBuffer(this.getIndices(),s);break;default:case Ae.TriangleFillMode:a=this._geometry.getIndexBuffer();break}return this._bindDirect(t,a,r)}_bindDirect(e,t,i=!0){if(!this._geometry)return this;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(e),!i||!this._userInstancedBuffersStorage||this.hasThinInstances)this._geometry._bind(e,t);else{if(!this._instanceDataStorage.useMonoDataStorageRenderPass&&this._userInstancedBuffersStorage.renderPasses&&this._userInstancedBuffersStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId]){let r=this._userInstancedBuffersStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];for(let s in r)this._userInstancedBuffersStorage.vertexBuffers[s]=r[s]}this._geometry._bind(e,t,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);let s=this.getScene().getEngine(),a=s._currentMaterialContext,o=a&&a.useVertexPulling;return this._unIndexed&&t!==Ae.WireFrameFillMode||t==Ae.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Ae.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):o?s.drawArraysType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){let i=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._getInstanceDataStorage();if(this._instanceDataStorage.isFrozen){if(t)return i.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,i.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,i.batchCacheReplacementModeInFrozenMode;if(i.previousBatch)return i.previousBatch}let r=this.getScene(),s=r._isInIntermediateRendering(),a=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,o=i.batchCache;if(o.mustReturn=!1,o.renderSelf[e]=t||!a&&this.isEnabled()&&this.isVisible,o.visibleInstances[e]=null,i.visibleInstances&&!t){let l=i.visibleInstances,c=r.getRenderId(),f=s?l.intermediateDefaultRenderId:l.defaultRenderId;o.visibleInstances[e]=l[c],!o.visibleInstances[e]&&f&&(o.visibleInstances[e]=l[f])}return o.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&o.visibleInstances[e]!==null&&o.visibleInstances[e]!==void 0,i.previousBatch=o,o}_updateInstancedBuffers(e,t,i,r,s,a){var v;let o=t.visibleInstances[e._id],l=o?o.length:0,c=t.parent,f=this._instanceDataStorage,d=c.instancesBuffer,u=c.instancesPreviousBuffer,h=0,m=0,g=t.renderSelf[e._id],p=this._scene.floatingOriginOffset,_=!d||i!==c.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!c.instancesPreviousBuffer;if(!this._instanceDataStorage.manualUpdate&&(!f.isFrozen||_)){let E=this.getWorldMatrix();if(g){this._scene.needsPreviousWorldMatrices&&(f.masterMeshPreviousWorldMatrix?(f.masterMeshPreviousWorldMatrix.copyToArray(c.instancesPreviousData,h),f.masterMeshPreviousWorldMatrix.copyFrom(E)):(f.masterMeshPreviousWorldMatrix=E.clone(),f.masterMeshPreviousWorldMatrix.copyToArray(c.instancesPreviousData,h))),E.copyToArray(c.instancesData,h);let S=E.asArray();c.instancesData[h+12]=S[12]-p.x,c.instancesData[h+13]=S[13]-p.y,c.instancesData[h+14]=S[14]-p.z,h+=16,m++}if(o){if(n.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&((v=e.getMaterial())!=null&&v.needAlphaBlendingForMesh(e.getRenderingMesh()))){let S=this._scene.activeCamera.globalPosition;for(let T=0;T<o.length;T++){let A=o[T];A._distanceToCamera=b.Distance(A.getBoundingInfo().boundingSphere.centerWorld,S)}o.sort((T,A)=>T._distanceToCamera>A._distanceToCamera?-1:T._distanceToCamera<A._distanceToCamera?1:0)}for(let S=0;S<o.length;S++){let T=o[S],A=T.getWorldMatrix();A.copyToArray(c.instancesData,h),this._scene.needsPreviousWorldMatrices&&(T._previousWorldMatrix?(T._previousWorldMatrix.copyToArray(c.instancesPreviousData,h),T._previousWorldMatrix.copyFrom(A)):(T._previousWorldMatrix=A.clone(),T._previousWorldMatrix.copyToArray(c.instancesPreviousData,h)));let R=A.asArray();c.instancesData[h+12]=R[12]-p.x,c.instancesData[h+13]=R[13]-p.y,c.instancesData[h+14]=R[14]-p.z,h+=16,m++}}}else m=(g?1:0)+l;if(_){d&&d.dispose(),u&&u.dispose(),d=new ko(r,c.instancesData,!0,16,!1,!0),c.instancesBuffer=d,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0});let E;if(this._instanceDataStorage.useMonoDataStorageRenderPass)E=this._userInstancedBuffersStorage.vertexBuffers;else{this._userInstancedBuffersStorage.renderPasses||(this._userInstancedBuffersStorage.renderPasses={});let S=this._instanceDataStorage.engine.currentRenderPassId;E=this._userInstancedBuffersStorage.renderPasses[S],E||(this._userInstancedBuffersStorage.renderPasses[S]=E={})}E.world0=d.createVertexBuffer("world0",0,4),E.world1=d.createVertexBuffer("world1",4,4),E.world2=d.createVertexBuffer("world2",8,4),E.world3=d.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(u=new ko(r,c.instancesPreviousData,!0,16,!1,!0),c.instancesPreviousBuffer=u,E.previousWorld0=u.createVertexBuffer("previousWorld0",0,4),E.previousWorld1=u.createVertexBuffer("previousWorld1",4,4),E.previousWorld2=u.createVertexBuffer("previousWorld2",8,4),E.previousWorld3=u.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()}else(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&(d.updateDirectly(c.instancesData,0,m),this._scene.needsPreviousWorldMatrices&&(!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.previousManualUpdate)&&u.updateDirectly(c.instancesPreviousData,0,m));this._processInstancedBuffers(o,g),a&&s!==void 0&&(this.getScene()._activeIndices.addCount(e.indexCount*m,!1),r._currentDrawContext&&(r._currentDrawContext.useInstancing=!0),this._bind(e,a,s),this._draw(e,s,m)),this._scene.needsPreviousWorldMatrices&&!_&&this._instanceDataStorage.manualUpdate&&(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&!this._instanceDataStorage.previousManualUpdate&&u.updateDirectly(c.instancesData,0,m)}_renderWithInstances(e,t,i,r,s){let a=i.visibleInstances[e._id],o=a?a.length:0,l=i.parent,c=l.instancesBufferSize,d=(o+1)*16*4;for(;l.instancesBufferSize<d;)l.instancesBufferSize*=2;return(!l.instancesData||c!=l.instancesBufferSize)&&(l.instancesData=new Float32Array(l.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!l.instancesPreviousData||c!=l.instancesBufferSize)&&(l.instancesPreviousData=new Float32Array(l.instancesBufferSize/4)),this._updateInstancedBuffers(e,i,c,s,t,r),s.unbindInstanceAttributes(),this}_renderWithThinInstances(e,t,i,r){var a,o;let s=(o=(a=this._thinInstanceDataStorage)==null?void 0:a.instancesCount)!=null?o:0;this.getScene()._activeIndices.addCount(e.indexCount*s,!1),r._currentDrawContext&&(r._currentDrawContext.useInstancing=!0),this._bind(e,i,t),this._draw(e,t,s),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,s):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),r.unbindInstanceAttributes()}_processInstancedBuffers(e,t){}_processRendering(e,t,i,r,s,a,o,l){let c=this.getScene(),f=c.getEngine();if(r=this._getRenderingFillMode(r),a&&t.getRenderingMesh().hasThinInstances)return this._renderWithThinInstances(t,r,i,f),this;if(a)this._renderWithInstances(t,r,s,i,f);else{f._currentDrawContext&&(f._currentDrawContext.useInstancing=!1);let d=0;s.renderSelf[t._id]&&(o&&o(!1,e.getWorldMatrix(),l),d++,this._draw(t,r,this._instanceDataStorage.overridenInstanceCount));let u=s.visibleInstances[t._id];if(u){let h=u.length;d+=h;for(let m=0;m<h;m++){let p=u[m].getWorldMatrix();o&&o(!0,p,l),this._draw(t,r)}}c._activeIndices.addCount(t.indexCount*d,!1)}return this}_disposeInstanceDataStorageRenderPass(e,t=!1){e!=null&&e.instancesBuffer&&(t&&e.instancesBuffer.dispose(),e.instancesBuffer=null),e!=null&&e.instancesPreviousBuffer&&(t&&e.instancesPreviousBuffer.dispose(),e.instancesPreviousBuffer=null)}_rebuild(e=!1){for(let t in this._instanceDataStorage.renderPasses){let i=this._instanceDataStorage.renderPasses[t];this._disposeInstanceDataStorageRenderPass(i,e)}if(this._disposeInstanceDataStorageRenderPass(this._instanceDataStorage.dataStorageRenderPass,e),this._userInstancedBuffersStorage){for(let t in this._userInstancedBuffersStorage.vertexBuffers){let i=this._userInstancedBuffersStorage.vertexBuffers[t];i&&(e&&i.dispose(),this._userInstancedBuffersStorage.vertexBuffers[t]=null)}this._userInstancedBuffersStorage.vertexArrayObjects&&(this._userInstancedBuffersStorage.vertexArrayObjects={})}this._internalMeshDataInfo._effectiveMaterial=null,super._rebuild(e)}_releaseRenderPassId(e){var i,r;let t=this._instanceDataStorage.renderPasses[e];if(t&&(this._disposeInstanceDataStorageRenderPass(t,!0),delete this._instanceDataStorage.renderPasses[e]),(i=this._userInstancedBuffersStorage)!=null&&i.renderPasses){let s=this._userInstancedBuffersStorage.renderPasses[e];if(s)for(let a in s)(r=s[a])==null||r.dispose();delete this._userInstancedBuffersStorage.renderPasses[e]}}_freeze(){if(this.subMeshes){for(let e=0;e<this.subMeshes.length;e++)this._getInstancesRenderList(e);this._internalMeshDataInfo._effectiveMaterial=null,this._instanceDataStorage.isFrozen=!0}}_unFreeze(){this._instanceDataStorage.isFrozen=!1;for(let e in this._instanceDataStorage.renderPasses){let t=this._instanceDataStorage.renderPasses[e];t.previousBatch=null}this._instanceDataStorage.dataStorageRenderPass&&(this._instanceDataStorage.dataStorageRenderPass.previousBatch=null)}renderWithRenderPassId(e,t,i,r,s=!0){let a=this._scene.getEngine(),o=a.currentRenderPassId;if(e!==void 0&&(a.currentRenderPassId=e),r)(!s||s&&r.isInFrustum(this._scene._frustumPlanes))&&this.render(r,!!t,i);else for(let l=0;l<this.subMeshes.length;l++){let c=this.subMeshes[l];(!s||s&&c.isInFrustum(this._scene._frustumPlanes))&&this.render(c,!!t,i)}return e!==void 0&&(a.currentRenderPassId=o),this}directRender(){if(!this.subMeshes)return this;for(let e of this.subMeshes)this.render(e,!1);return this}render(e,t,i){var M,I,C,L;let r=this.getScene(),s=r.getEngine();this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1;let a=(I=(M=r.activeCameras)==null?void 0:M.length)!=null?I:0,o=a>1&&r.activeCamera===r.activeCameras[0]||a<=1,l=this._occlusionDataStorage&&this._occlusionDataStorage.occlusionForRenderPassId!==-1&&this._occlusionDataStorage.occlusionForRenderPassId!==s.currentRenderPassId;if(o&&this._checkOcclusionQuery(l)&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;let c=this._getInstancesRenderList(e._id,!!i);if(c.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let f=0,d=null;this.ignoreCameraMaxZ&&r.activeCamera&&!r._isInIntermediateRendering()&&(f=r.activeCamera.maxZ,d=r.activeCamera,r.activeCamera.maxZ=0,r.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);let u=e.getRenderingMesh(),h=c.hardwareInstancedRendering[e._id]||u.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,m=this._instanceDataStorage,g=e.getMaterial();if(!g)return d&&(d.maxZ=f,r.updateTransformMatrix(!0)),this;if(!m.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==g){if(g._storeEffectOnSubMeshes){if(!g.isReadyForSubMesh(this,e,h))return d&&(d.maxZ=f,r.updateTransformMatrix(!0)),this}else if(!g.isReady(this,h))return d&&(d.maxZ=f,r.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=g}else if(g._storeEffectOnSubMeshes&&!((C=e._drawWrapper)!=null&&C._wasPreviouslyReady)||!g._storeEffectOnSubMeshes&&!g._getDrawWrapper()._wasPreviouslyReady)return d&&(d.maxZ=f,r.updateTransformMatrix(!0)),this;if(t){let w=this._internalMeshDataInfo._effectiveMaterial;if(w.alphaModes.length===1)s.setAlphaMode(w.alphaMode);else for(let G=0;G<w.alphaModes.length;G++){let O=w.alphaModes[G];s.setAlphaMode(O!==void 0?O:2,!1,G)}}let p;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?p=e._drawWrapper:p=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();let _=(L=p==null?void 0:p.effect)!=null?L:null;for(let w of r._beforeRenderingMeshStage)w.action(this,e,c,_);if(!p||!_)return d&&(d.maxZ=f,r.updateTransformMatrix(!0)),this;let v=i||this,E;if(!m.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||this._internalMeshDataInfo._effectiveMaterial.sideOrientation!==null||this._internalMeshDataInfo._effectiveMaterial._twoSidedLighting)){let w=v._getWorldMatrixDeterminant();E=this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this),w<0&&(E=E===Ae.ClockWiseSideOrientation?Ae.CounterClockWiseSideOrientation:Ae.ClockWiseSideOrientation),this._internalMeshDataInfo._effectiveSideOrientation=E}let S=this._internalMeshDataInfo._effectiveMaterial._preBind(p,this._internalMeshDataInfo._effectiveSideOrientation);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&s.setDepthWrite(!0);let T=this._internalMeshDataInfo._effectiveMaterial,A=T.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),h||this._bind(e,_,A,!1);let R=v.getWorldMatrix();T._storeEffectOnSubMeshes?T.bindForSubMesh(R,this,e):T.bind(R,this),!T.backFaceCulling&&T.separateCullingPass&&(s.setState(!0,T.zOffset,!1,!S,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._processRendering(this,e,_,A,c,h,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),s.setState(!0,T.zOffset,!1,S,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,_,A,c,h,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(let w of r._afterRenderingMeshStage)w.action(this,e,c,_);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),d&&(d.maxZ=f,r.updateTransformMatrix(!0)),r.performancePriority===2&&!m.isFrozen&&this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(D.MatricesWeightsKind)&&(this.isVerticesDataPresent(D.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){let e=this.getVerticesData(D.MatricesWeightsKind),t=e.length;for(let i=0;i<t;i+=4){let r=e[i]+e[i+1]+e[i+2]+e[i+3];if(r===0)e[i]=1;else{let s=1/r;e[i]*=s,e[i+1]*=s,e[i+2]*=s,e[i+3]*=s}}this.setVerticesData(D.MatricesWeightsKind,e)}_normalizeSkinWeightsAndExtra(){let e=this.getVerticesData(D.MatricesWeightsExtraKind),t=this.getVerticesData(D.MatricesWeightsKind),i=t.length;for(let r=0;r<i;r+=4){let s=t[r]+t[r+1]+t[r+2]+t[r+3];if(s+=e[r]+e[r+1]+e[r+2]+e[r+3],s===0)t[r]=1;else{let a=1/s;t[r]*=a,t[r+1]*=a,t[r+2]*=a,t[r+3]*=a,e[r]*=a,e[r+1]*=a,e[r+2]*=a,e[r+3]*=a}}this.setVerticesData(D.MatricesWeightsKind,t),this.setVerticesData(D.MatricesWeightsKind,e)}validateSkinning(){let e=this.getVerticesData(D.MatricesWeightsExtraKind),t=this.getVerticesData(D.MatricesWeightsKind);if(t===null||this.skeleton==null)return{skinned:!1,valid:!0,report:"not skinned"};let i=t.length,r=0,s=0,a=0,o=0,l=e===null?4:8,c=[];for(let p=0;p<=l;p++)c[p]=0;let f=.001;for(let p=0;p<i;p+=4){let _=t[p],v=_,E=v===0?0:1;for(let S=1;S<l;S++){let T=S<4?t[p+S]:e[p+S-4];T>_&&r++,T!==0&&E++,v+=T,_=T}if(c[E]++,E>a&&(a=E),v===0)s++;else{let S=1/v,T=0;for(let A=0;A<l;A++)A<4?T+=Math.abs(t[p+A]-t[p+A]*S):T+=Math.abs(e[p+A-4]-e[p+A-4]*S);T>f&&o++}}let d=this.skeleton.bones.length,u=this.getVerticesData(D.MatricesIndicesKind),h=this.getVerticesData(D.MatricesIndicesExtraKind),m=0;for(let p=0;p<i;p+=4)for(let _=0;_<l;_++){let v=_<4?u[p+_]:h[p+_-4];(v>=d||v<0)&&m++}let g="Number of Weights = "+i/4+`
Maximum influences = `+a+`
Missing Weights = `+s+`
Not Sorted = `+r+`
Not Normalized = `+o+`
WeightCounts = [`+c+`]
Number of bones = `+d+`
Bad Bone Indices = `+m;return{skinned:!0,valid:s===0&&o===0&&m===0,report:g}}_checkDelayState(){let e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===4&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);let t=this.delayLoadingFile.indexOf(".babylonbinarymeshdata")!==-1;return pe.LoadFile(this.delayLoadingFile,i=>{i instanceof ArrayBuffer?this._delayLoadingFunction(i,this):this._delayLoadingFunction(JSON.parse(i),this);for(let r of this.instances)r.refreshBoundingInfo(),r._syncSubMeshes();this.delayLoadState=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return this.delayLoadState===2||!super.isInFrustum(e)?!1:(this._checkDelayState(),!0)}setMaterialById(e){let t=this.getScene().materials,i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;let r=this.getScene().multiMaterials;for(i=r.length-1;i>-1;i--)if(r[i].id===e)return this.material=r[i],this;return this}getAnimatables(){let e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(D.PositionKind))return this;let t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(D.PositionKind),r=b.Zero(),s;for(s=0;s<i.length;s+=3)b.TransformCoordinatesFromFloatsToRef(i[s],i[s+1],i[s+2],e,r).toArray(i,s);if(this.setVerticesData(D.PositionKind,i,this.getVertexBuffer(D.PositionKind).isUpdatable()),this.isVerticesDataPresent(D.NormalKind)){for(i=this.getVerticesData(D.NormalKind),s=0;s<i.length;s+=3)b.TransformNormalFromFloatsToRef(i[s],i[s+1],i[s+2],e,r).normalize().toArray(i,s);this.setVerticesData(D.NormalKind,i,this.getVertexBuffer(D.NormalKind).isUpdatable())}if(this.isVerticesDataPresent(D.TangentKind)){for(i=this.getVerticesData(D.TangentKind),s=0;s<i.length;s+=4)b.TransformNormalFromFloatsToRef(i[s],i[s+1],i[s+2],e,r).normalize().toArray(i,s);this.setVerticesData(D.TangentKind,i,this.getVertexBuffer(D.TangentKind).isUpdatable())}return e.determinant()<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=t,this}bakeCurrentTransformIntoVertices(e=!0,t=!1){return t&&this.makeGeometryUnique(),this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions||this._geometry&&this._geometry._positions||null}_resetPointsArrayCache(){return this._geometry&&this._geometry._resetPointsArrayCache(),this}_generatePointsArray(){return this._geometry?this._geometry._generatePointsArray():!1}clone(e="",t=null,i,r=!0){if(t&&t._addToSceneRootNodes===void 0){let s=t;return Yl.source=this,Yl.doNotCloneChildren=s.doNotCloneChildren,Yl.clonePhysicsImpostor=s.clonePhysicsImpostor,Yl.cloneThinInstances=s.cloneThinInstances,new n(e,this.getScene(),Yl)}return new n(e,this.getScene(),t,this,i,r)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);let i=this._internalMeshDataInfo;if(i._onBeforeDrawObservable&&i._onBeforeDrawObservable.clear(),i._onBeforeBindObservable&&i._onBeforeBindObservable.clear(),i._onBeforeRenderObservable&&i._onBeforeRenderObservable.clear(),i._onAfterRenderObservable&&i._onAfterRenderObservable.clear(),i._onBetweenPassObservable&&i._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(i.meshMap)for(let r in i.meshMap){let s=i.meshMap[r];s&&(s._internalMeshDataInfo._source=null,i.meshMap[r]=void 0)}i._source&&i._source._internalMeshDataInfo.meshMap&&(i._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else{let r=this.getScene().meshes;for(let s of r){let a=s;a._internalMeshDataInfo&&a._internalMeshDataInfo._source&&a._internalMeshDataInfo._source===this&&(a._internalMeshDataInfo._source=null)}}i._source=null,this._disposeInstanceSpecificData(),this._disposeThinInstanceSpecificData(),this._internalMeshDataInfo._checkReadinessObserver&&this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),super.dispose(e,t)}_disposeInstanceSpecificData(){}_disposeThinInstanceSpecificData(){}_invalidateInstanceVertexArrayObject(){}applyDisplacementMap(e,t,i,r,s,a,o=!1,l){let c=this.getScene(),f=d=>{let u=d.width,h=d.height,g=this.getEngine().createCanvas(u,h).getContext("2d");g.drawImage(d,0,0);let p=g.getImageData(0,0,u,h).data;this.applyDisplacementMapFromBuffer(p,u,h,t,i,s,a,o),r&&r(this)};return pe.LoadImage(e,f,l||(()=>{}),c.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,r,s,a,o,l=!1){if(!this.isVerticesDataPresent(D.PositionKind)||!this.isVerticesDataPresent(D.NormalKind)||!this.isVerticesDataPresent(D.UVKind))return te.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;let c=this.getVerticesData(D.PositionKind,!0,!0),f=this.getVerticesData(D.NormalKind),d=this.getVerticesData(D.UVKind),u=b.Zero(),h=b.Zero(),m=Fe.Zero();a=a||Fe.Zero(),o=o||new Fe(1,1);for(let g=0;g<c.length;g+=3){b.FromArrayToRef(c,g,u),b.FromArrayToRef(f,g,h),Fe.FromArrayToRef(d,g/3*2,m);let p=Math.abs(m.x*o.x+a.x%1)*(t-1)%t|0,_=Math.abs(m.y*o.y+a.y%1)*(i-1)%i|0,v=(p+_*t)*4,E=e[v]/255,S=e[v+1]/255,T=e[v+2]/255,A=E*.3+S*.59+T*.11;h.normalize(),h.scaleInPlace(r+(s-r)*A),u=u.add(h),u.toArray(c,g)}return Ie.ComputeNormals(c,this.getIndices(),f),l?(this.setVerticesData(D.PositionKind,c),this.setVerticesData(D.NormalKind,f),this.setVerticesData(D.UVKind,d)):(this.updateVerticesData(D.PositionKind,c),this.updateVerticesData(D.NormalKind,f)),this}_getFlattenedNormals(e,t){let i=new Float32Array(e.length*3),r=0,s=this.sideOrientation===(this._scene.useRightHandedSystem?1:0);for(let a=0;a<e.length;a+=3){let o=b.FromArray(t,e[a]*3),l=b.FromArray(t,e[a+1]*3),c=b.FromArray(t,e[a+2]*3),f=o.subtract(l),d=c.subtract(l),u=b.Normalize(b.Cross(f,d));s&&u.scaleInPlace(-1);for(let h=0;h<3;h++)i[r++]=u.x,i[r++]=u.y,i[r++]=u.z}return i}_convertToUnIndexedMesh(e=!1){let t=this.getVerticesDataKinds().filter(l=>{var c;return!((c=this.getVertexBuffer(l))!=null&&c.getIsInstanced())}),i=this.getIndices(!1,!0),r={},s=(l,c)=>{let f=new Float32Array(i.length*c),d=0;for(let u=0;u<i.length;u++)for(let h=0;h<c;h++)f[d++]=l[i[u]*c+h];return f},a=this.getBoundingInfo(),o=this.geometry?this.subMeshes.slice(0):[];for(let l of t)r[l]=this.getVerticesData(l);for(let l of t){let c=this.getVertexBuffer(l),f=c.getSize();if(e&&l===D.NormalKind){let d=this._getFlattenedNormals(i,r[D.PositionKind]);this.setVerticesData(D.NormalKind,d,c.isUpdatable(),f)}else this.setVerticesData(l,s(r[l],f),c.isUpdatable(),f)}if(this.morphTargetManager){for(let l=0;l<this.morphTargetManager.numTargets;l++){let c=this.morphTargetManager.getTarget(l),f=c.getPositions();c.setPositions(s(f,3));let d=c.getNormals();d&&c.setNormals(e?this._getFlattenedNormals(i,f):s(d,3));let u=c.getTangents();u&&c.setTangents(s(u,3));let h=c.getUVs();h&&c.setUVs(s(h,2));let m=c.getColors();m&&c.setColors(s(m,4))}this.morphTargetManager.synchronize()}for(let l=0;l<i.length;l++)i[l]=l;this.setIndices(i),this._unIndexed=!0,this.releaseSubMeshes();for(let l of o){let c=l.getBoundingInfo();sa.AddToMesh(l.materialIndex,l.indexStart,l.indexCount,l.indexStart,l.indexCount,this).setBoundingInfo(c)}return this.setBoundingInfo(a),this.synchronizeInstances(),this}convertToFlatShadedMesh(){return this._convertToUnIndexedMesh(!0)}convertToUnIndexedMesh(){return this._convertToUnIndexedMesh()}flipFaces(e=!1){let t=Ie.ExtractFromMesh(this),i;if(e&&this.isVerticesDataPresent(D.NormalKind)&&t.normals){for(i=0;i<t.normals.length;i++)t.normals[i]*=-1;this.setVerticesData(D.NormalKind,t.normals,this.isVertexBufferUpdatable(D.NormalKind))}if(t.indices){let r;for(i=0;i<t.indices.length;i+=3)r=t.indices[i+1],t.indices[i+1]=t.indices[i+2],t.indices[i+2]=r;this.setIndices(t.indices,null,this.isVertexBufferUpdatable(D.PositionKind),!0)}return this}increaseVertices(e=1){let t=Ie.ExtractFromMesh(this),i=t.indices&&!Array.isArray(t.indices)&&Array.from?Array.from(t.indices):t.indices,r=t.positions&&!Array.isArray(t.positions)&&Array.from?Array.from(t.positions):t.positions,s=t.uvs&&!Array.isArray(t.uvs)&&Array.from?Array.from(t.uvs):t.uvs,a=t.normals&&!Array.isArray(t.normals)&&Array.from?Array.from(t.normals):t.normals;if(!i||!r)te.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions");else{t.indices=i,t.positions=r,s&&(t.uvs=s),a&&(t.normals=a);let o=e+1,l=[];for(let T=0;T<o+1;T++)l[T]=[];let c,f,d=new b(0,0,0),u=new b(0,0,0),h=new Fe(0,0),m=[],g=[],p=[],_,v=r.length,E;s&&(E=s.length);let S;a&&(S=a.length);for(let T=0;T<i.length;T+=3){g[0]=i[T],g[1]=i[T+1],g[2]=i[T+2];for(let A=0;A<3;A++)if(c=g[A],f=g[(A+1)%3],p[c]===void 0&&p[f]===void 0?(p[c]=[],p[f]=[]):(p[c]===void 0&&(p[c]=[]),p[f]===void 0&&(p[f]=[])),p[c][f]===void 0&&p[f][c]===void 0){p[c][f]=[],d.x=(r[3*f]-r[3*c])/o,d.y=(r[3*f+1]-r[3*c+1])/o,d.z=(r[3*f+2]-r[3*c+2])/o,a&&(u.x=(a[3*f]-a[3*c])/o,u.y=(a[3*f+1]-a[3*c+1])/o,u.z=(a[3*f+2]-a[3*c+2])/o),s&&(h.x=(s[2*f]-s[2*c])/o,h.y=(s[2*f+1]-s[2*c+1])/o),p[c][f].push(c);for(let R=1;R<o;R++)p[c][f].push(r.length/3),r[v++]=r[3*c]+R*d.x,r[v++]=r[3*c+1]+R*d.y,r[v++]=r[3*c+2]+R*d.z,a&&(a[S++]=a[3*c]+R*u.x,a[S++]=a[3*c+1]+R*u.y,a[S++]=a[3*c+2]+R*u.z),s&&(s[E++]=s[2*c]+R*h.x,s[E++]=s[2*c+1]+R*h.y);p[c][f].push(f),p[f][c]=[],_=p[c][f].length;for(let R=0;R<_;R++)p[f][c][R]=p[c][f][_-1-R]}l[0][0]=i[T],l[1][0]=p[i[T]][i[T+1]][1],l[1][1]=p[i[T]][i[T+2]][1];for(let A=2;A<o;A++){l[A][0]=p[i[T]][i[T+1]][A],l[A][A]=p[i[T]][i[T+2]][A],d.x=(r[3*l[A][A]]-r[3*l[A][0]])/A,d.y=(r[3*l[A][A]+1]-r[3*l[A][0]+1])/A,d.z=(r[3*l[A][A]+2]-r[3*l[A][0]+2])/A,a&&(u.x=(a[3*l[A][A]]-a[3*l[A][0]])/A,u.y=(a[3*l[A][A]+1]-a[3*l[A][0]+1])/A,u.z=(a[3*l[A][A]+2]-a[3*l[A][0]+2])/A),s&&(h.x=(s[2*l[A][A]]-s[2*l[A][0]])/A,h.y=(s[2*l[A][A]+1]-s[2*l[A][0]+1])/A);for(let R=1;R<A;R++)l[A][R]=r.length/3,r[v++]=r[3*l[A][0]]+R*d.x,r[v++]=r[3*l[A][0]+1]+R*d.y,r[v++]=r[3*l[A][0]+2]+R*d.z,a&&(a[S++]=a[3*l[A][0]]+R*u.x,a[S++]=a[3*l[A][0]+1]+R*u.y,a[S++]=a[3*l[A][0]+2]+R*u.z),s&&(s[E++]=s[2*l[A][0]]+R*h.x,s[E++]=s[2*l[A][0]+1]+R*h.y)}l[o]=p[i[T+1]][i[T+2]],m.push(l[0][0],l[1][0],l[1][1]);for(let A=1;A<o;A++){let R;for(R=0;R<A;R++)m.push(l[A][R],l[A+1][R],l[A+1][R+1]),m.push(l[A][R],l[A+1][R+1],l[A][R+1]);m.push(l[A][R],l[A+1][R],l[A+1][R+1])}}t.indices=m,t.applyToMesh(this,this.isVertexBufferUpdatable(D.PositionKind))}}forceSharedVertices(){let e=Ie.ExtractFromMesh(this),t=e.uvs,i=e.indices,r=e.positions,s=e.colors,a=e.matricesIndices,o=e.matricesWeights,l=e.matricesIndicesExtra,c=e.matricesWeightsExtra;if(i===void 0||r===void 0||i===null||r===null)te.Warn("VertexData contains empty entries");else{let f=[],d=[],u=[],h=[],m=[],g=[],p=[],_=[],v,E=0,S={},T,A;for(let M=0;M<i.length;M+=3){A=[i[M],i[M+1],i[M+2]],v=[];for(let I=0;I<3;I++){v[I]="";for(let C=0;C<3;C++)Math.abs(r[3*A[I]+C])<1e-8&&(r[3*A[I]+C]=0),v[I]+=r[3*A[I]+C]+"|"}if(!(v[0]==v[1]||v[0]==v[2]||v[1]==v[2]))for(let I=0;I<3;I++){if(T=S[v[I]],T===void 0){S[v[I]]=E,T=E++;for(let C=0;C<3;C++)f.push(r[3*A[I]+C]);if(s!=null)for(let C=0;C<4;C++)h.push(s[4*A[I]+C]);if(t!=null)for(let C=0;C<2;C++)u.push(t[2*A[I]+C]);if(a!=null)for(let C=0;C<4;C++)m.push(a[4*A[I]+C]);if(o!=null)for(let C=0;C<4;C++)g.push(o[4*A[I]+C]);if(l!=null)for(let C=0;C<4;C++)p.push(l[4*A[I]+C]);if(c!=null)for(let C=0;C<4;C++)_.push(c[4*A[I]+C])}d.push(T)}}let R=[];Ie.ComputeNormals(f,d,R),e.positions=f,e.indices=d,e.normals=R,t!=null&&(e.uvs=u),s!=null&&(e.colors=h),a!=null&&(e.matricesIndices=m),o!=null&&(e.matricesWeights=g),l!=null&&(e.matricesIndicesExtra=p),o!=null&&(e.matricesWeightsExtra=_),e.applyToMesh(this,this.isVertexBufferUpdatable(D.PositionKind))}}static _instancedMeshFactory(e,t){throw $e("InstancedMesh")}static _PhysicsImpostorParser(e,t,i){throw $e("PhysicsImpostor")}createInstance(e){let t=n._instancedMeshFactory(e,this);return t.parent=this.parent,t}synchronizeInstances(){for(let e=0;e<this.instances.length;e++)this.instances[e]._syncSubMeshes();return this}optimizeIndices(e){let t=this.getIndices(),i=this.getVerticesData(D.PositionKind);if(!i||!t)return this;let r=[];for(let a=0;a<i.length;a=a+3)r.push(b.FromArray(i,a));let s=[];return CR.SyncAsyncForLoop(r.length,40,a=>{let o=r.length-1-a,l=r[o];for(let c=0;c<o;++c){let f=r[c];if(l.equals(f)){s[o]=c;break}}},()=>{for(let o=0;o<t.length;++o)t[o]=s[t[o]]||t[o];let a=this.subMeshes.slice(0);this.setIndices(t),this.subMeshes=a,e&&e(this)}),this}serialize(e={}){var i,r;e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,e.type=this.getClassName(),ni&&ni.HasTags(this)&&(e.tags=ni.GetTags(this)),e.position=this.position.asArray(),this.rotationQuaternion?e.rotationQuaternion=this.rotationQuaternion.asArray():this.rotation&&(e.rotation=this.rotation.asArray()),e.scaling=this.scaling.asArray(),this._postMultiplyPivotMatrix?e.pivotMatrix=this.getPivotMatrix().asArray():e.localMatrix=this.getPivotMatrix().asArray(),e.isEnabled=this.isEnabled(!1),e.isVisible=this.isVisible,e.infiniteDistance=this.infiniteDistance,e.pickable=this.isPickable,e.receiveShadows=this.receiveShadows,e.billboardMode=this.billboardMode,e.visibility=this.visibility,e.alwaysSelectAsActiveMesh=this.alwaysSelectAsActiveMesh,e.checkCollisions=this.checkCollisions,e.ellipsoid=this.ellipsoid.asArray(),e.ellipsoidOffset=this.ellipsoidOffset.asArray(),e.doNotSyncBoundingInfo=this.doNotSyncBoundingInfo,e.isBlocker=this.isBlocker,e.sideOrientation=this.sideOrientation,this._isWorldMatrixFrozen&&(e.freezeWorldMatrix=!0),this.parent&&this.parent._serializeAsParent(e),e.isUnIndexed=this.isUnIndexed;let t=this._geometry;if(t&&this.subMeshes){e.geometryUniqueId=t.uniqueId,e.geometryId=t.id,e.subMeshes=[];for(let s=0;s<this.subMeshes.length;s++){let a=this.subMeshes[s];e.subMeshes.push({materialIndex:a.materialIndex,verticesStart:a.verticesStart,verticesCount:a.verticesCount,indexStart:a.indexStart,indexCount:a.indexCount})}}if(this.material?this.material.doNotSerialize||(e.materialUniqueId=this.material.uniqueId,e.materialId=this.material.id):(this.material=null,e.materialUniqueId=this._scene.defaultMaterial.uniqueId,e.materialId=this._scene.defaultMaterial.id),this.morphTargetManager&&(e.morphTargetManagerId=this.morphTargetManager.uniqueId),this.skeleton&&(e.skeletonId=this.skeleton.id,e.skeletonUniqueId=this.skeleton.uniqueId,e.numBoneInfluencers=this.numBoneInfluencers),this.getScene()._getComponent(tt.NAME_PHYSICSENGINE)){let s=(i=this.getPhysicsImpostor)==null?void 0:i.call(this);s&&(e.physicsMass=s.getParam("mass"),e.physicsFriction=s.getParam("friction"),e.physicsRestitution=s.getParam("mass"),e.physicsImpostor=s.type)}this.metadata&&(e.metadata=this.metadata),e.instances=[];for(let s=0;s<this.instances.length;s++){let a=this.instances[s];if(a.doNotSerialize)continue;let o={name:a.name,id:a.id,isEnabled:a.isEnabled(!1),isVisible:a.isVisible,isPickable:a.isPickable,checkCollisions:a.checkCollisions,position:a.position.asArray(),scaling:a.scaling.asArray()};if(a.parent&&a.parent._serializeAsParent(o),a.rotationQuaternion?o.rotationQuaternion=a.rotationQuaternion.asArray():a.rotation&&(o.rotation=a.rotation.asArray()),this.getScene()._getComponent(tt.NAME_PHYSICSENGINE)){let l=(r=a.getPhysicsImpostor)==null?void 0:r.call(a);l&&(o.physicsMass=l.getParam("mass"),o.physicsFriction=l.getParam("friction"),o.physicsRestitution=l.getParam("mass"),o.physicsImpostor=l.type)}a.metadata&&(o.metadata=a.metadata),a.actionManager&&(o.actions=a.actionManager.serialize(a.name)),e.instances.push(o),at.AppendSerializedAnimations(a,o),o.ranges=a.serializeAnimationRanges()}if(this._thinInstanceDataStorage.instancesCount&&this._thinInstanceDataStorage.matrixData&&(e.thinInstances={instancesCount:this._thinInstanceDataStorage.instancesCount,matrixData:Array.from(this._thinInstanceDataStorage.matrixData),matrixBufferSize:this._thinInstanceDataStorage.matrixBufferSize,enablePicking:this.thinInstanceEnablePicking},this._userThinInstanceBuffersStorage)){let s={data:{},sizes:{},strides:{}};for(let a in this._userThinInstanceBuffersStorage.data)s.data[a]=Array.from(this._userThinInstanceBuffersStorage.data[a]),s.sizes[a]=this._userThinInstanceBuffersStorage.sizes[a],s.strides[a]=this._userThinInstanceBuffersStorage.strides[a];e.thinInstances.userThinInstance=s}return at.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.layerMask=this.layerMask,e.alphaIndex=this.alphaIndex,e.hasVertexAlpha=this.hasVertexAlpha,e.overlayAlpha=this.overlayAlpha,e.overlayColor=this.overlayColor.asArray(),e.renderOverlay=this.renderOverlay,e.applyFog=this.applyFog,this.actionManager&&(e.actions=this.actionManager.serialize(this.name)),e}_syncGeometryWithMorphTargetManager(){if(!this.geometry)return;this._markSubMeshesAsAttributesDirty();let e=this._internalAbstractMeshDataInfo._morphTargetManager;if(e&&e.vertexCount){if(e.vertexCount!==this.getTotalVertices()){te.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),this.morphTargetManager=null;return}if(e.isUsingTextureForTargets)return;for(let t=0;t<e.numInfluencers;t++){let i=e.getActiveTarget(t),r=i.getPositions();if(!r){te.Error("Invalid morph target. Target must have positions.");return}this.geometry.setVerticesData(D.PositionKind+t,r,!1,3);let s=i.getNormals();s&&this.geometry.setVerticesData(D.NormalKind+t,s,!1,3);let a=i.getTangents();a&&this.geometry.setVerticesData(D.TangentKind+t,a,!1,3);let o=i.getUVs();o&&this.geometry.setVerticesData(D.UVKind+"_"+t,o,!1,2);let l=i.getUV2s();l&&this.geometry.setVerticesData(D.UV2Kind+"_"+t,l,!1,2);let c=i.getColors();c&&this.geometry.setVerticesData(D.ColorKind+t,c,!1,4)}}else{let t=0;for(;this.geometry.isVerticesDataPresent(D.PositionKind+t);)this.geometry.removeVerticesData(D.PositionKind+t),this.geometry.isVerticesDataPresent(D.NormalKind+t)&&this.geometry.removeVerticesData(D.NormalKind+t),this.geometry.isVerticesDataPresent(D.TangentKind+t)&&this.geometry.removeVerticesData(D.TangentKind+t),this.geometry.isVerticesDataPresent(D.UVKind+t)&&this.geometry.removeVerticesData(D.UVKind+"_"+t),this.geometry.isVerticesDataPresent(D.UV2Kind+t)&&this.geometry.removeVerticesData(D.UV2Kind+"_"+t),this.geometry.isVerticesDataPresent(D.ColorKind+t)&&this.geometry.removeVerticesData(D.ColorKind+t),t++}}static Parse(e,t,i){let r,s=!1;if(e.type&&e.type==="LinesMesh"?r=n._LinesMeshParser(e,t):e.type&&e.type==="GroundMesh"?r=n._GroundMeshParser(e,t):e.type&&e.type==="GoldbergMesh"?r=n._GoldbergMeshParser(e,t):e.type&&e.type==="GreasedLineMesh"?r=n._GreasedLineMeshParser(e,t):e.type&&e.type==="TrailMesh"?r=n._TrailMeshParser(e,t):e.type&&e.type==="GaussianSplattingMesh"?(e._isCompound?r=n._GaussianSplattingCompoundMeshParser(e,t):r=n._GaussianSplattingMeshParser(e,t),s=!0):e.type&&e.type==="GaussianSplattingPartProxyMesh"?(r=n._GaussianSplattingPartProxyMeshParser(e,t),s=!0):r=new n(e.name,t),r.id=e.id,r._waitingParsedUniqueId=e.uniqueId,ni&&ni.AddTagsTo(r,e.tags),r.position=b.FromArray(e.position),e.metadata!==void 0&&(r.metadata=e.metadata),e.rotationQuaternion?r.rotationQuaternion=je.FromArray(e.rotationQuaternion):e.rotation&&(r.rotation=b.FromArray(e.rotation)),r.scaling=b.FromArray(e.scaling),e.localMatrix?r.setPreTransformMatrix(Q.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(Q.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r.isVisible=e.isVisible,r.infiniteDistance=e.infiniteDistance,r.alwaysSelectAsActiveMesh=!!e.alwaysSelectAsActiveMesh,r.showBoundingBox=e.showBoundingBox,r.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,e.applyFog!==void 0&&(r.applyFog=e.applyFog),e.pickable!==void 0&&(r.isPickable=e.pickable),e.alphaIndex!==void 0&&(r.alphaIndex=e.alphaIndex),r.receiveShadows=e.receiveShadows,e.billboardMode!==void 0&&(r.billboardMode=e.billboardMode),e.visibility!==void 0&&(r.visibility=e.visibility),r.checkCollisions=e.checkCollisions,r.doNotSyncBoundingInfo=!!e.doNotSyncBoundingInfo,e.ellipsoid&&(r.ellipsoid=b.FromArray(e.ellipsoid)),e.ellipsoidOffset&&(r.ellipsoidOffset=b.FromArray(e.ellipsoidOffset)),e.overrideMaterialSideOrientation!=null&&(r.sideOrientation=e.overrideMaterialSideOrientation),e.sideOrientation!==void 0&&(r.sideOrientation=e.sideOrientation),e.isBlocker!==void 0&&(r.isBlocker=e.isBlocker),r._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(r._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),e.actions!==void 0&&(r._waitingData.actions=e.actions),e.overlayAlpha!==void 0&&(r.overlayAlpha=e.overlayAlpha),e.overlayColor!==void 0&&(r.overlayColor=he.FromArray(e.overlayColor)),e.renderOverlay!==void 0&&(r.renderOverlay=e.renderOverlay),r.isUnIndexed=!!e.isUnIndexed,r.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(r.delayLoadState=4,r.delayLoadingFile=i+e.delayLoadingFile,r.buildBoundingInfo(b.FromArray(e.boundingBoxMinimum),b.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(r._binaryInfo=e._binaryInfo),r._delayInfo=[],e.hasUVs&&r._delayInfo.push(D.UVKind),e.hasUVs2&&r._delayInfo.push(D.UV2Kind),e.hasUVs3&&r._delayInfo.push(D.UV3Kind),e.hasUVs4&&r._delayInfo.push(D.UV4Kind),e.hasUVs5&&r._delayInfo.push(D.UV5Kind),e.hasUVs6&&r._delayInfo.push(D.UV6Kind),e.hasColors&&r._delayInfo.push(D.ColorKind),e.hasMatricesIndices&&r._delayInfo.push(D.MatricesIndicesKind),e.hasMatricesWeights&&r._delayInfo.push(D.MatricesWeightsKind),r._delayLoadingFunction=Cn._ImportGeometry,an.ForceFullSceneLoadingForIncremental&&r._checkDelayState()):s||Cn._ImportGeometry(e,r),e.materialUniqueId?r._waitingMaterialId=e.materialUniqueId:e.materialId&&(r._waitingMaterialId=e.materialId),e.morphTargetManagerId>-1&&(r._waitingMorphTargetManagerId=e.morphTargetManagerId),e.skeletonId!==void 0&&e.skeletonId!==null&&(r.skeleton=t.getLastSkeletonById(e.skeletonId),r._waitingSkeletonId=e.skeletonId,e.numBoneInfluencers&&(r.numBoneInfluencers=e.numBoneInfluencers)),e.skeletonUniqueId!==void 0&&e.skeletonUniqueId!==null&&(r._waitingSkeletonUniqueId=e.skeletonUniqueId),e.animations){for(let a=0;a<e.animations.length;a++){let o=e.animations[a],l=Vn("BABYLON.Animation");l&&r.animations.push(l.Parse(o))}bi.ParseAnimationRanges(r,e,t)}if(e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?r.layerMask=Math.abs(parseInt(e.layerMask)):r.layerMask=268435455,e.physicsImpostor&&(r.physicsImpostor=n._PhysicsImpostorParser(t,r,e)),e.lodMeshIds&&(r._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(let a=0;a<e.instances.length;a++){let o=e.instances[a],l=r.createInstance(o.name);if(o.id&&(l.id=o.id),ni&&(o.tags?ni.AddTagsTo(l,o.tags):ni.AddTagsTo(l,e.tags)),l.position=b.FromArray(o.position),o.metadata!==void 0&&(l.metadata=o.metadata),o.parentId!==void 0&&(l._waitingParentId=o.parentId),o.parentInstanceIndex!==void 0&&(l._waitingParentInstanceIndex=o.parentInstanceIndex),o.isEnabled!==void 0&&o.isEnabled!==null&&l.setEnabled(o.isEnabled),o.isVisible!==void 0&&o.isVisible!==null&&(l.isVisible=o.isVisible),o.isPickable!==void 0&&o.isPickable!==null&&(l.isPickable=o.isPickable),o.rotationQuaternion?l.rotationQuaternion=je.FromArray(o.rotationQuaternion):o.rotation&&(l.rotation=b.FromArray(o.rotation)),l.scaling=b.FromArray(o.scaling),o.checkCollisions!=null&&o.checkCollisions!=null&&(l.checkCollisions=o.checkCollisions),o.pickable!=null&&o.pickable!=null&&(l.isPickable=o.pickable),o.showBoundingBox!=null&&o.showBoundingBox!=null&&(l.showBoundingBox=o.showBoundingBox),o.showSubMeshesBoundingBox!=null&&o.showSubMeshesBoundingBox!=null&&(l.showSubMeshesBoundingBox=o.showSubMeshesBoundingBox),o.alphaIndex!=null&&o.showSubMeshesBoundingBox!=null&&(l.alphaIndex=o.alphaIndex),o.physicsImpostor&&(l.physicsImpostor=n._PhysicsImpostorParser(t,l,o)),o.actions!==void 0&&(l._waitingData.actions=o.actions),o.animations){for(let c=0;c<o.animations.length;c++){let f=o.animations[c],d=Vn("BABYLON.Animation");d&&l.animations.push(d.Parse(f))}bi.ParseAnimationRanges(l,o,t),o.autoAnimate&&t.beginAnimation(l,o.autoAnimateFrom,o.autoAnimateTo,o.autoAnimateLoop,o.autoAnimateSpeed||1)}}if(e.thinInstances){let a=e.thinInstances;if(r.thinInstanceEnablePicking=!!a.enablePicking,a.matrixData?(r.thinInstanceSetBuffer("matrix",new Float32Array(a.matrixData),16,!1),r._thinInstanceDataStorage.matrixBufferSize=a.matrixBufferSize,r._thinInstanceDataStorage.instancesCount=a.instancesCount):r._thinInstanceDataStorage.matrixBufferSize=a.matrixBufferSize,e.thinInstances.userThinInstance){let o=e.thinInstances.userThinInstance;for(let l in o.data)r.thinInstanceSetBuffer(l,new Float32Array(o.data[l]),o.strides[l],!1),r._userThinInstanceBuffersStorage.sizes[l]=o.sizes[l]}}return r}setPositionsForCPUSkinning(){let e=this._internalMeshDataInfo;if(!e._sourcePositions){let t=this.getVerticesData(D.PositionKind);if(!t)return e._sourcePositions;e._sourcePositions=new Float32Array(t),this.isVertexBufferUpdatable(D.PositionKind)||this.setVerticesData(D.PositionKind,t,!0)}return e._sourcePositions}setNormalsForCPUSkinning(){let e=this._internalMeshDataInfo;if(!e._sourceNormals){let t=this.getVerticesData(D.NormalKind);if(!t)return e._sourceNormals;e._sourceNormals=new Float32Array(t),this.isVertexBufferUpdatable(D.NormalKind)||this.setVerticesData(D.NormalKind,t,!0)}return e._sourceNormals}applySkeleton(e){if(!this.geometry)return this;if(this.geometry._softwareSkinningFrameId==this.getScene().getFrameId())return this;if(this.geometry._softwareSkinningFrameId=this.getScene().getFrameId(),!this.isVerticesDataPresent(D.PositionKind))return this;if(!this.isVerticesDataPresent(D.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(D.MatricesWeightsKind))return this;let t=this.isVerticesDataPresent(D.NormalKind),i=this._internalMeshDataInfo;if(!i._sourcePositions){let _=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=_}t&&!i._sourceNormals&&this.setNormalsForCPUSkinning();let r=this.getVerticesData(D.PositionKind);if(!r)return this;r instanceof Float32Array||(r=new Float32Array(r));let s=this.getVerticesData(D.NormalKind);if(t){if(!s)return this;s instanceof Float32Array||(s=new Float32Array(s))}let a=this.getVerticesData(D.MatricesIndicesKind),o=this.getVerticesData(D.MatricesWeightsKind);if(!o||!a)return this;let l=this.numBoneInfluencers>4,c=l?this.getVerticesData(D.MatricesIndicesExtraKind):null,f=l?this.getVerticesData(D.MatricesWeightsExtraKind):null,d=e.getTransformMatrices(this),u=b.Zero(),h=new Q,m=new Q,g=0,p;for(let _=0;_<r.length;_+=3,g+=4){let v;for(p=0;p<4;p++)v=o[g+p],v>0&&(Q.FromFloat32ArrayToRefScaled(d,Math.floor(a[g+p]*16),v,m),h.addToSelf(m));if(l)for(p=0;p<4;p++)v=f[g+p],v>0&&(Q.FromFloat32ArrayToRefScaled(d,Math.floor(c[g+p]*16),v,m),h.addToSelf(m));b.TransformCoordinatesFromFloatsToRef(i._sourcePositions[_],i._sourcePositions[_+1],i._sourcePositions[_+2],h,u),u.toArray(r,_),t&&(b.TransformNormalFromFloatsToRef(i._sourceNormals[_],i._sourceNormals[_+1],i._sourceNormals[_+2],h,u),u.toArray(s,_)),h.reset()}return this.updateVerticesData(D.PositionKind,r),t&&this.updateVerticesData(D.NormalKind,s),this}static MinMax(e){let t=null,i=null;for(let r of e){let a=r.getBoundingInfo().boundingBox;!t||!i?(t=a.minimumWorld.clone(),i=a.maximumWorld.clone()):(t.minimizeInPlace(a.minimumWorld),i.maximizeInPlace(a.maximumWorld))}return!t||!i?{min:b.Zero(),max:b.Zero()}:{min:t,max:i}}static Center(e){let t=e instanceof Array?n.MinMax(e):e;return b.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,r,s,a){return Kv(n._MergeMeshesCoroutine(e,t,i,r,s,a,!1))}static async MergeMeshesAsync(e,t=!0,i,r,s,a){return await GH(n._MergeMeshesCoroutine(e,t,i,r,s,a,!0),UH())}static*_MergeMeshesCoroutine(e,t=!0,i,r,s,a,o){if(e=e.filter(Boolean),e.length===0)return null;let l;if(!i){let R=0;for(l=0;l<e.length;l++)if(R+=e[l].getTotalVertices(),R>=65536)return te.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}let c=e[0];a&&(s=!1,e.sort((R,M)=>{var I,C,L,w;return((C=(I=R.material)==null?void 0:I.uniqueId)!=null?C:-1)-((w=(L=M.material)==null?void 0:L.uniqueId)!=null?w:-1)}));let f=new Array,d=new Array,u=new Array,h=e[0].sideOrientation;for(l=0;l<e.length;l++){let R=e[l];if(R.isAnInstance)return te.Warn("Cannot merge instance meshes."),null;if(h!==R.sideOrientation)return te.Warn("Cannot merge meshes with different sideOrientation values."),null;if(s||a){let M=u.reduce((I,C)=>Math.max(I,C.start+C.count),0);if(a)if(R.material){let I=R.material;if(I instanceof jp){for(let C=0;C<I.subMaterials.length;C++)f.indexOf(I.subMaterials[C])<0&&f.push(I.subMaterials[C]);for(let C=0;C<R.subMeshes.length;C++)d.push(f.indexOf(I.subMaterials[R.subMeshes[C].materialIndex])),u.push({start:M+R.subMeshes[C].indexStart,count:R.subMeshes[C].indexCount})}else{f.indexOf(I)<0&&f.push(I);for(let C=0;C<R.subMeshes.length;C++)d.push(f.indexOf(I)),u.push({start:M+R.subMeshes[C].indexStart,count:R.subMeshes[C].indexCount})}}else for(let I=0;I<R.subMeshes.length;I++)d.push(0),u.push({start:M+R.subMeshes[I].indexStart,count:R.subMeshes[I].indexCount});else u.push({start:M,count:R.getTotalIndices()})}}if(a&&u.length>1){let R=0;for(let M=1;M<u.length;M++){let I=u[R],C=u[M];d[M]===d[R]&&I.start+I.count===C.start?I.count+=C.count:(R++,u[R]=C,d[R]=d[M])}u.length=R+1,d.length=R+1}let m=R=>{let M=R.computeWorldMatrix(!0);return{vertexData:Ie.ExtractFromMesh(R,!1,!1),transform:M}},{vertexData:g,transform:p}=m(e[0]);o&&(yield);let _=new Array(e.length-1);for(let R=1;R<e.length;R++)_[R-1]=m(e[R]),o&&(yield);let v=g._mergeCoroutine(p,_,i,o,!t),E=v.next();for(;!E.done;)o&&(yield),E=v.next();let S=E.value;r||(r=new n(c.name+"_merged",c.getScene()));let T=S._applyToCoroutine(r,void 0,o),A=T.next();for(;!A.done;)o&&(yield),A=T.next();if(r.checkCollisions=c.checkCollisions,r.sideOrientation=c.sideOrientation,t)for(l=0;l<e.length;l++)e[l].dispose();if(s||a){for(r.releaseSubMeshes(),l=0;l<u.length;)sa.CreateFromIndices(0,u[l].start,u[l].count,r,void 0,!1),l++;for(let R of r.subMeshes)R.refreshBoundingInfo();r.computeWorldMatrix(!0)}if(a){let R=new jp(c.name+"_merged",c.getScene());R.subMaterials=f;for(let M=0;M<r.subMeshes.length;M++)r.subMeshes[M].materialIndex=d[M];r.material=R}else r.material=c.material;return r}addInstance(e){e._indexInSourceMeshInstanceArray=this.instances.length,this.instances.push(e)}removeInstance(e){let t=e._indexInSourceMeshInstanceArray;if(t!=-1){if(t!==this.instances.length-1){let i=this.instances[this.instances.length-1];this.instances[t]=i,i._indexInSourceMeshInstanceArray=t}e._indexInSourceMeshInstanceArray=-1,this.instances.pop()}}_shouldConvertRHS(){return this._scene.useRightHandedSystem&&this.sideOrientation===Ae.CounterClockWiseSideOrientation}_getRenderingFillMode(e){var i;let t=this.getScene();return t.forcePointsCloud?Ae.PointFillMode:t.forceWireframe?Ae.WireFrameFillMode:(i=this.overrideRenderingFillMode)!=null?i:e}setMaterialByID(e){return this.setMaterialById(e)}static CreateRibbon(e,t,i,r,s,a,o,l,c){throw new Error("Import MeshBuilder to populate this function")}static CreateDisc(e,t,i,r,s,a){throw new Error("Import MeshBuilder to populate this function")}static CreateBox(e,t,i,r,s){throw new Error("Import MeshBuilder to populate this function")}static CreateSphere(e,t,i,r,s,a){throw new Error("Import MeshBuilder to populate this function")}static CreateHemisphere(e,t,i,r){throw new Error("Import MeshBuilder to populate this function")}static CreateCylinder(e,t,i,r,s,a,o,l,c){throw new Error("Import MeshBuilder to populate this function")}static CreateTorus(e,t,i,r,s,a,o){throw new Error("Import MeshBuilder to populate this function")}static CreateTorusKnot(e,t,i,r,s,a,o,l,c,f){throw new Error("Import MeshBuilder to populate this function")}static CreateLines(e,t,i,r,s){throw new Error("Import MeshBuilder to populate this function")}static CreateDashedLines(e,t,i,r,s,a,o,l){throw new Error("Import MeshBuilder to populate this function")}static CreatePolygon(e,t,i,r,s,a,o){throw new Error("Import MeshBuilder to populate this function")}static ExtrudePolygon(e,t,i,r,s,a,o,l){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShape(e,t,i,r,s,a,o,l,c,f){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShapeCustom(e,t,i,r,s,a,o,l,c,f,d,u){throw new Error("Import MeshBuilder to populate this function")}static CreateLathe(e,t,i,r,s,a,o){throw new Error("Import MeshBuilder to populate this function")}static CreatePlane(e,t,i,r,s){throw new Error("Import MeshBuilder to populate this function")}static CreateGround(e,t,i,r,s,a){throw new Error("Import MeshBuilder to populate this function")}static CreateTiledGround(e,t,i,r,s,a,o,l,c){throw new Error("Import MeshBuilder to populate this function")}static CreateGroundFromHeightMap(e,t,i,r,s,a,o,l,c,f,d){throw new Error("Import MeshBuilder to populate this function")}static CreateTube(e,t,i,r,s,a,o,l,c,f){throw new Error("Import MeshBuilder to populate this function")}static CreatePolyhedron(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static CreateIcoSphere(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static CreateDecal(e,t,i,r,s,a){throw new Error("Import MeshBuilder to populate this function")}static CreateCapsule(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static ExtendToGoldberg(e){throw new Error("Import MeshBuilder to populate this function")}};$.FRONTSIDE=Ie.FRONTSIDE;$.BACKSIDE=Ie.BACKSIDE;$.DOUBLESIDE=Ie.DOUBLESIDE;$.DEFAULTSIDE=Ie.DEFAULTSIDE;$.NO_CAP=0;$.CAP_START=1;$.CAP_END=2;$.CAP_ALL=3;$.NO_FLIP=0;$.FLIP_TILE=1;$.ROTATE_TILE=2;$.FLIP_ROW=3;$.ROTATE_ROW=4;$.FLIP_N_ROTATE_TILE=5;$.FLIP_N_ROTATE_ROW=6;$.CENTER=0;$.LEFT=1;$.RIGHT=2;$.TOP=3;$.BOTTOM=4;$.INSTANCEDMESH_SORT_TRANSPARENT=!1;$._GroundMeshParser=(n,e)=>{throw $e("GroundMesh")};$._GoldbergMeshParser=(n,e)=>{throw $e("GoldbergMesh")};$._LinesMeshParser=(n,e)=>{throw $e("LinesMesh")};$._GreasedLineMeshParser=(n,e)=>{throw $e("GreasedLineMesh")};$._GreasedLineRibbonMeshParser=(n,e)=>{throw $e("GreasedLineRibbonMesh")};$._TrailMeshParser=(n,e)=>{throw $e("TrailMesh")};$._GaussianSplattingMeshParser=(n,e)=>{throw $e("GaussianSplattingMesh")};$._GaussianSplattingPartProxyMeshParser=(n,e)=>{throw $e("GaussianSplattingPartProxyMesh")};$._GaussianSplattingCompoundMeshParser=(n,e)=>{throw $e("GaussianSplattingCompoundMesh")};zt("BABYLON.Mesh",$)});var qp,tO=y(()=>{Xo();Ac();es();qp=class{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._attachedCamera=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}get attachedNode(){return this._attachedCamera}init(){}attach(e){this._attachedCamera=e;let t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===ot.POINTERDOWN){this._isPointerDown=!0;return}i.type===ot.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;let i=br.Now,r=0;this._lastFrameTime!=null&&(r=i-this._lastFrameTime),this._lastFrameTime=i,this._applyUserInteraction();let s=i-this._lastInteractionTime-this._idleRotationWaitTime,a=Math.max(Math.min(s/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*a,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(r/1e3))})}detach(){if(!this._attachedCamera)return;let e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null,this._lastFrameTime=null}resetLastInteractionTime(e){this._lastInteractionTime=e!=null?e:br.Now}_reachTargetAlpha(){return this._attachedCamera&&this.targetAlpha?Math.abs(this._attachedCamera.alpha-this.targetAlpha)<Vt:!1}_userIsZooming(){return this._attachedCamera?this._attachedCamera.inertialRadiusOffset!==0:!1}_shouldAnimationStopForInteraction(){if(!this._attachedCamera)return!1;let e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&this._attachedCamera.inertialRadiusOffset!==0&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()}_applyUserInteraction(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=br.Now)}_userIsMoving(){return this._attachedCamera?this._attachedCamera.inertialAlphaOffset!==0||this._attachedCamera.inertialBetaOffset!==0||this._attachedCamera.inertialRadiusOffset!==0||this._attachedCamera.inertialPanningX!==0||this._attachedCamera.inertialPanningY!==0||this._isPointerDown:!1}}});var $o,pb,gb,iO=y(()=>{zu();$o=class n{constructor(){this._easingMode=n.EASINGMODE_EASEIN}setEasingMode(e){let t=Math.min(Math.max(e,0),2);this._easingMode=t}getEasingMode(){return this._easingMode}easeInCore(e){throw new Error("You must implement this method")}ease(e){switch(this._easingMode){case n.EASINGMODE_EASEIN:return this.easeInCore(e);case n.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?(1-this.easeInCore((1-e)*2))*.5+.5:this.easeInCore(e*2)*.5}};$o.EASINGMODE_EASEIN=0;$o.EASINGMODE_EASEOUT=1;$o.EASINGMODE_EASEINOUT=2;pb=class extends $o{constructor(e=1){super(),this.amplitude=e}easeInCore(e){let t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}},gb=class extends $o{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}}});var pd,rO=y(()=>{pd=class n{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new n(this.name,this.from,this.to)}}});var nO,sO,aO,oO,lO,cO,Jo,gt,gd=y(()=>{He();$t();ts();ir();rO();Na();gR();Wu();Or();nO=Object.freeze(new je(0,0,0,0)),sO=Object.freeze(b.Zero()),aO=Object.freeze(Fe.Zero()),oO=Object.freeze(bc.Zero()),lO=Object.freeze(he.Black()),cO=Object.freeze(new ht(0,0,0,0)),Jo={key:0,repeatCount:0,loopMode:2},gt=class n{static _PrepareAnimation(e,t,i,r,s,a,o,l){let c;if(!isNaN(parseFloat(s))&&isFinite(s)?c=n.ANIMATIONTYPE_FLOAT:s instanceof je?c=n.ANIMATIONTYPE_QUATERNION:s instanceof b?c=n.ANIMATIONTYPE_VECTOR3:s instanceof Fe?c=n.ANIMATIONTYPE_VECTOR2:s instanceof he?c=n.ANIMATIONTYPE_COLOR3:s instanceof ht?c=n.ANIMATIONTYPE_COLOR4:s instanceof bc&&(c=n.ANIMATIONTYPE_SIZE),c==null)return null;let f=new n(e,t,i,c,o),d=[{frame:0,value:s},{frame:r,value:a}];return f.setKeys(d),l!==void 0&&f.setEasingFunction(l),f}static CreateAnimation(e,t,i,r){let s=new n(e+"Animation",e,i,t,n.ANIMATIONLOOPMODE_CONSTANT);return s.setEasingFunction(r),s}static CreateAndStartAnimation(e,t,i,r,s,a,o,l,c,f,d){let u=n._PrepareAnimation(e,i,r,s,a,o,l,c);return!u||(t.getScene&&(d=t.getScene()),!d)?null:d.beginDirectAnimation(t,[u],0,s,u.loopMode!==n.ANIMATIONLOOPMODE_CONSTANT,1,f)}static CreateAndStartHierarchyAnimation(e,t,i,r,s,a,o,l,c,f,d){let u=n._PrepareAnimation(e,r,s,a,o,l,c,f);return u?t.getScene().beginDirectHierarchyAnimation(t,i,[u],0,a,u.loopMode===1,1,d):null}static CreateMergeAndStartAnimation(e,t,i,r,s,a,o,l,c,f){let d=n._PrepareAnimation(e,i,r,s,a,o,l,c);return d?(t.animations.push(d),t.getScene().beginAnimation(t,0,s,d.loopMode===1,1,f)):null}static MakeAnimationAdditive(e,t,i,r=!1,s){var v,E;let a;typeof t=="object"?a=t:a={referenceFrame:t!=null?t:0,range:i,cloneOriginalAnimation:r,clonedAnimationName:s};let o=e;if(a.cloneOriginalAnimation&&(o=e.clone(),o.name=a.clonedAnimationName||o.name),!o._keys.length)return o;let l=a.referenceFrame&&a.referenceFrame>=0?a.referenceFrame:0,c=0,f=o._keys[0],d=o._keys.length-1,u=o._keys[d],h={referenceValue:f.value,referencePosition:ee.Vector3[0],referenceQuaternion:ee.Quaternion[0],referenceScaling:ee.Vector3[1],keyPosition:ee.Vector3[2],keyQuaternion:ee.Quaternion[1],keyScaling:ee.Vector3[3]},m=f.frame,g=u.frame;if(a.range){let S=o.getRange(a.range);S&&(m=S.from,g=S.to)}else m=(v=a.fromFrame)!=null?v:m,g=(E=a.toFrame)!=null?E:g;if(m!==f.frame&&(c=o.createKeyForFrame(m)),g!==u.frame&&(d=o.createKeyForFrame(g)),o._keys.length===1){let S=o._getKeyValue(o._keys[0]);h.referenceValue=S.clone?S.clone():S}else if(l<=f.frame){let S=o._getKeyValue(f.value);h.referenceValue=S.clone?S.clone():S}else if(l>=u.frame){let S=o._getKeyValue(u.value);h.referenceValue=S.clone?S.clone():S}else{Jo.key=0;let S=o._interpolate(l,Jo);h.referenceValue=S.clone?S.clone():S}o.dataType===n.ANIMATIONTYPE_QUATERNION?h.referenceValue.normalize().conjugateInPlace():o.dataType===n.ANIMATIONTYPE_MATRIX&&(h.referenceValue.decompose(h.referenceScaling,h.referenceQuaternion,h.referencePosition),h.referenceQuaternion.normalize().conjugateInPlace());let p=Number.MAX_VALUE,_=a.clipKeys?[]:null;for(let S=c;S<=d;S++){let T=o._keys[S];if((_||a.cloneOriginalAnimation)&&(T={frame:T.frame,value:T.value.clone?T.value.clone():T.value,inTangent:T.inTangent,outTangent:T.outTangent,interpolation:T.interpolation,lockedTangent:T.lockedTangent,easingFunction:T.easingFunction},_&&(p===Number.MAX_VALUE&&(p=T.frame),T.frame-=p,_.push(T))),!(S&&o.dataType!==n.ANIMATIONTYPE_FLOAT&&T.value===f.value))switch(o.dataType){case n.ANIMATIONTYPE_MATRIX:T.value.decompose(h.keyScaling,h.keyQuaternion,h.keyPosition),h.keyPosition.subtractInPlace(h.referencePosition),h.keyScaling.divideInPlace(h.referenceScaling),h.referenceQuaternion.multiplyToRef(h.keyQuaternion,h.keyQuaternion),Q.ComposeToRef(h.keyScaling,h.keyQuaternion,h.keyPosition,T.value);break;case n.ANIMATIONTYPE_QUATERNION:h.referenceValue.multiplyToRef(T.value,T.value);break;case n.ANIMATIONTYPE_VECTOR2:case n.ANIMATIONTYPE_VECTOR3:case n.ANIMATIONTYPE_COLOR3:case n.ANIMATIONTYPE_COLOR4:T.value.subtractToRef(h.referenceValue,T.value);break;case n.ANIMATIONTYPE_SIZE:T.value.width-=h.referenceValue.width,T.value.height-=h.referenceValue.height;break;default:T.value-=h.referenceValue}}return _&&o.setKeys(_,!0),o}static TransitionTo(e,t,i,r,s,a,o,l=null,c=!0,f){if(o<=0)return i[e]=t,l&&l(),null;let d=s*(o/1e3);return a.setKeys(f!=null?f:[{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:d,value:t}]),i.animations||(i.animations=[]),i.animations.push(a),r.beginAnimation(i,0,d,!1,1,l!=null?l:void 0,void 0,c)}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(let e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,s,a){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=s,this.enableBlending=a,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this._coreAnimation=null,this.targetPropertyPath=t.split("."),this.dataType=r,this.loopMode=s===void 0?n.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=n._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let i=!0;for(let r in this._ranges)i||(t+=", "),i=!1,t+=r;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort((t,i)=>t.frame-i.frame)}removeEvents(e){for(let t=0;t<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)}getEvents(){return this._events}createRange(e,t,i){this._ranges[e]||(this._ranges[e]=new pd(e,t,i))}deleteRange(e,t=!0){let i=this._ranges[e];if(i){if(t){let r=i.from,s=i.to;for(let a=this._keys.length-1;a>=0;a--)this._keys[a].frame>=r&&this._keys[a].frame<=s&&this._keys.splice(a,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t<i;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e}getEasingFunction(){return this._easingFunction}setEasingFunction(e){this._easingFunction=e}floatInterpolateFunction(e,t,i){return Uo(e,t,i)}floatInterpolateFunctionWithTangents(e,t,i,r,s){return qG(e,t,i,r,s)}quaternionInterpolateFunction(e,t,i){return je.Slerp(e,t,i)}quaternionInterpolateFunctionWithTangents(e,t,i,r,s){return je.Hermite(e,t,i,r,s).normalize()}vector3InterpolateFunction(e,t,i){return b.Lerp(e,t,i)}vector3InterpolateFunctionWithTangents(e,t,i,r,s){return b.Hermite(e,t,i,r,s)}vector2InterpolateFunction(e,t,i){return Fe.Lerp(e,t,i)}vector2InterpolateFunctionWithTangents(e,t,i,r,s){return Fe.Hermite(e,t,i,r,s)}sizeInterpolateFunction(e,t,i){return bc.Lerp(e,t,i)}color3InterpolateFunction(e,t,i){return he.Lerp(e,t,i)}color3InterpolateFunctionWithTangents(e,t,i,r,s){return he.Hermite(e,t,i,r,s)}color4InterpolateFunction(e,t,i){return ht.Lerp(e,t,i)}color4InterpolateFunctionWithTangents(e,t,i,r,s){return ht.Hermite(e,t,i,r,s)}_getKeyValue(e){return typeof e=="function"?e():e}evaluate(e){return Jo.key=0,this._interpolate(e,Jo)}_interpolate(e,t,i=!1){var m;if(t.loopMode===n.ANIMATIONLOOPMODE_CONSTANT&&t.repeatCount>0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;let r=this._keys,s;if(this._coreAnimation)s=this._coreAnimation._key;else{let g=r.length;for(s=t.key;s>=0&&e<r[s].frame;)--s;for(;s+1<=g-1&&e>=r[s+1].frame;)++s;if(t.key=s,s<0)return i?void 0:this._getKeyValue(r[0].value);if(s+1>g-1)return i?void 0:this._getKeyValue(r[g-1].value);this._key=s}let a=r[s],o=r[s+1];if(i&&(e===a.frame||e===o.frame))return;let l=this._getKeyValue(a.value),c=this._getKeyValue(o.value);if(a.interpolation===1)return o.frame>e?l:c;let f=a.outTangent!==void 0&&o.inTangent!==void 0,d=o.frame-a.frame,u=(e-a.frame)/d,h=a.easingFunction||this.getEasingFunction();switch(h&&(u=h.ease(u)),this.dataType){case n.ANIMATIONTYPE_FLOAT:{let g=f?this.floatInterpolateFunctionWithTangents(l,a.outTangent*d,c,o.inTangent*d,u):this.floatInterpolateFunction(l,c,u);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return g;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return((m=t.offsetValue)!=null?m:0)*t.repeatCount+g}break}case n.ANIMATIONTYPE_QUATERNION:{let g=f?this.quaternionInterpolateFunctionWithTangents(l,a.outTangent.scale(d),c,o.inTangent.scale(d),u):this.quaternionInterpolateFunction(l,c,u);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return g;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.addInPlace((t.offsetValue||nO).scale(t.repeatCount))}return g}case n.ANIMATIONTYPE_VECTOR3:{let g=f?this.vector3InterpolateFunctionWithTangents(l,a.outTangent.scale(d),c,o.inTangent.scale(d),u):this.vector3InterpolateFunction(l,c,u);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return g;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||sO).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_VECTOR2:{let g=f?this.vector2InterpolateFunctionWithTangents(l,a.outTangent.scale(d),c,o.inTangent.scale(d),u):this.vector2InterpolateFunction(l,c,u);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return g;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||aO).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,c,u);case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,c,u).add((t.offsetValue||oO).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_COLOR3:{let g=f?this.color3InterpolateFunctionWithTangents(l,a.outTangent.scale(d),c,o.inTangent.scale(d),u):this.color3InterpolateFunction(l,c,u);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return g;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||lO).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_COLOR4:{let g=f?this.color4InterpolateFunctionWithTangents(l,a.outTangent.scale(d),c,o.inTangent.scale(d),u):this.color4InterpolateFunction(l,c,u);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return g;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||cO).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return n.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,c,u,t.workValue):l;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}break}}return 0}matrixInterpolateFunction(e,t,i,r){return n.AllowMatrixDecomposeForInterpolation?r?(Q.DecomposeLerpToRef(e,t,i,r),r):Q.DecomposeLerp(e,t,i):r?(Q.LerpToRef(e,t,i,r),r):Q.Lerp(e,t,i)}clone(e=!1){let t=new n(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(t.enableBlending=this.enableBlending,t.blendingSpeed=this.blendingSpeed,this._keys&&t.setKeys(this._keys,!1,e),this._ranges){t._ranges={};for(let i in this._ranges){let r=this._ranges[i];r&&(t._ranges[i]=r.clone())}}return t}setKeys(e,t=!1,i=!1){if(t)this._keys=e;else if(this._keys=e.slice(0),i)for(let r=0;r<this._keys.length;r++){let s=this._keys[r];this._keys[r]={frame:s.frame,value:s.value.clone?s.value.clone():s.value,inTangent:s.inTangent&&s.inTangent.clone?s.inTangent.clone():s.inTangent,outTangent:s.outTangent&&s.outTangent.clone?s.outTangent.clone():s.outTangent,interpolation:s.interpolation,lockedTangent:s.lockedTangent,easingFunction:s.easingFunction}}}createKeyForFrame(e){Jo.key=0;let t=this._interpolate(e,Jo,!0);if(!t)return this._keys[Jo.key].frame===e?Jo.key:Jo.key+1;let i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(Jo.key+1,0,i),Jo.key+1}serialize(){let e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;let t=this.dataType;e.keys=[];let i=this.getKeys();for(let r=0;r<i.length;r++){let s=i[r],a={};switch(a.frame=s.frame,t){case n.ANIMATIONTYPE_FLOAT:a.values=[s.value],s.inTangent!==void 0&&a.values.push(s.inTangent),s.outTangent!==void 0&&(s.inTangent===void 0&&a.values.push(void 0),a.values.push(s.outTangent)),s.interpolation!==void 0&&(s.inTangent===void 0&&a.values.push(void 0),s.outTangent===void 0&&a.values.push(void 0),a.values.push(s.interpolation));break;case n.ANIMATIONTYPE_QUATERNION:case n.ANIMATIONTYPE_MATRIX:case n.ANIMATIONTYPE_VECTOR3:case n.ANIMATIONTYPE_COLOR3:case n.ANIMATIONTYPE_COLOR4:a.values=s.value.asArray(),s.inTangent!=null&&a.values.push(s.inTangent.asArray()),s.outTangent!=null&&(s.inTangent===void 0&&a.values.push(void 0),a.values.push(s.outTangent.asArray())),s.interpolation!==void 0&&(s.inTangent===void 0&&a.values.push(void 0),s.outTangent===void 0&&a.values.push(void 0),a.values.push(s.interpolation));break}e.keys.push(a)}e.ranges=[];for(let r in this._ranges){let s=this._ranges[r];if(!s)continue;let a={};a.name=r,a.from=s.from,a.to=s.to,e.ranges.push(a)}return e}static _UniversalLerp(e,t,i){let r=e.constructor;return r.Lerp?r.Lerp(e,t,i):r.Slerp?r.Slerp(e,t,i):e.toFixed?e*(1-i)+i*t:t}static Parse(e){let t=new n(e.name,e.property,e.framePerSecond,e.dataType,e.loopBehavior),i=e.dataType,r=[],s,a;for(e.enableBlending&&(t.enableBlending=e.enableBlending),e.blendingSpeed&&(t.blendingSpeed=e.blendingSpeed),a=0;a<e.keys.length;a++){let o=e.keys[a],l,c,f;switch(i){case n.ANIMATIONTYPE_FLOAT:s=o.values[0],o.values.length>=2&&(l=o.values[1]),o.values.length>=3&&(c=o.values[2]),o.values.length>=4&&(f=o.values[3]);break;case n.ANIMATIONTYPE_QUATERNION:if(s=je.FromArray(o.values),o.values.length>=8){let u=je.FromArray(o.values.slice(4,8));u.equals(je.Zero())||(l=u)}if(o.values.length>=12){let u=je.FromArray(o.values.slice(8,12));u.equals(je.Zero())||(c=u)}o.values.length>=13&&(f=o.values[12]);break;case n.ANIMATIONTYPE_MATRIX:s=Q.FromArray(o.values),o.values.length>=17&&(f=o.values[16]);break;case n.ANIMATIONTYPE_COLOR3:s=he.FromArray(o.values),o.values[3]&&(l=he.FromArray(o.values[3])),o.values[4]&&(c=he.FromArray(o.values[4])),o.values[5]&&(f=o.values[5]);break;case n.ANIMATIONTYPE_COLOR4:s=ht.FromArray(o.values),o.values[4]&&(l=ht.FromArray(o.values[4])),o.values[5]&&(c=ht.FromArray(o.values[5])),o.values[6]&&(f=ht.FromArray(o.values[6]));break;case n.ANIMATIONTYPE_VECTOR3:default:s=b.FromArray(o.values),o.values[3]&&(l=b.FromArray(o.values[3])),o.values[4]&&(c=b.FromArray(o.values[4])),o.values[5]&&(f=o.values[5]);break}let d={};d.frame=o.frame,d.value=s,l!=null&&(d.inTangent=l),c!=null&&(d.outTangent=c),f!=null&&(d.interpolation=f),r.push(d)}if(t.setKeys(r),e.ranges)for(a=0;a<e.ranges.length;a++)s=e.ranges[a],t.createRange(s.name,s.from,s.to);return t}static AppendSerializedAnimations(e,t){at.AppendSerializedAnimations(e,t)}static async ParseFromFileAsync(e,t){return await new Promise((i,r)=>{let s=new Ur;s.addEventListener("readystatechange",()=>{if(s.readyState==4)if(s.status==200){let a=JSON.parse(s.responseText);if(a.animations&&(a=a.animations),a.length){let o=[];for(let l of a)o.push(this.Parse(l));i(o)}else{let o=this.Parse(a);e&&(o.name=e),i(o)}}else r("Unable to load the animation")}),s.open("GET",t),s.send()})}static async ParseFromSnippetAsync(e){return await new Promise((t,i)=>{let r=new Ur;r.addEventListener("readystatechange",()=>{if(r.readyState==4)if(r.status==200){let s=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(s.animations){let a=JSON.parse(s.animations),o=[];for(let l of a.animations){let c=this.Parse(l);c.snippetId=e,o.push(c)}t(o)}else{let a=JSON.parse(s.animation),o=this.Parse(a);o.snippetId=e,t(o)}}else i("Unable to load the snippet "+e)}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}};gt._UniqueIdGenerator=0;gt.AllowMatricesInterpolation=!1;gt.AllowMatrixDecomposeForInterpolation=!0;gt.InheritOriginalValueFromActiveAnimations=!1;gt.SnippetUrl="https://snippet.babylonjs.com";gt.ANIMATIONTYPE_FLOAT=0;gt.ANIMATIONTYPE_VECTOR3=1;gt.ANIMATIONTYPE_QUATERNION=2;gt.ANIMATIONTYPE_MATRIX=3;gt.ANIMATIONTYPE_COLOR3=4;gt.ANIMATIONTYPE_COLOR4=7;gt.ANIMATIONTYPE_VECTOR2=5;gt.ANIMATIONTYPE_SIZE=6;gt.ANIMATIONLOOPMODE_RELATIVE=0;gt.ANIMATIONLOOPMODE_CYCLE=1;gt.ANIMATIONLOOPMODE_CONSTANT=2;gt.ANIMATIONLOOPMODE_YOYO=4;gt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5;gt.CreateFromSnippetAsync=gt.ParseFromSnippetAsync;zt("BABYLON.Animation",gt);bi._AnimationRangeFactory=(n,e,t)=>new pd(n,e,t)});var Qp,r4=y(()=>{iO();gd();Qp=class n{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._attachedCamera=null,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;let t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(i=>{if(i&&(i.computeWorldMatrix(!0),i.getBoundingInfo)){let r=i.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=r*.05,this.upperRadiusTransitionRange=r*.05}}):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}get attachedNode(){return this._attachedCamera}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))})}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return this._attachedCamera?this._attachedCamera.radius===e&&!this._radiusIsAnimating:!1}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(n.EasingFunction.setEasingMode(n.EasingMode),this._radiusBounceTransition=gt.CreateAnimation("radius",gt.ANIMATIONTYPE_FLOAT,60,n.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;let t=gt.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,()=>this._clearAnimationLocks());t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}};Qp.EasingFunction=new pb(.3);Qp.EasingMode=$o.EASINGMODE_EASEOUT});var _d,n4=y(()=>{iO();Si();Xo();Ac();He();gd();_d=class n{constructor(){this.onTargetFramingAnimationEndObservable=new re,this._mode=n.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._attachedCamera=null,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}get attachedNode(){return this._attachedCamera}init(){}attach(e){this._attachedCamera=e;let t=this._attachedCamera.getScene();n.EasingFunction.setEasingMode(n.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===ot.POINTERDOWN){this._isPointerDown=!0;return}i.type===ot.POINTERUP&&(this._isPointerDown=!1)}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(i=>{i&&i.getBoundingInfo&&this.zoomOnMesh(i,void 0,()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()})}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()})}detach(){if(!this._attachedCamera)return;let e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);let r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);let r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){let r=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let a=0;a<e.length;a++){let o=e[a].getHierarchyBoundingVectors(!0);b.CheckExtends(o.min,r,s),b.CheckExtends(o.max,r,s)}this.zoomOnBoundingInfo(r,s,t,i)}zoomOnBoundingInfo(e,t,i=!1,r=null){let s;if(!this._attachedCamera)return!1;let a=e.y,o=t.y,l=a+(o-a)*this._positionScale,c=t.subtract(e).scale(.5);if(!isFinite(l))return!1;if(i)s=new b(0,l,0);else{let u=e.add(c);s=new b(u.x,l,u.z)}this._vectorTransition||(this._vectorTransition=gt.CreateAnimation("target",gt.ANIMATIONTYPE_VECTOR3,60,n.EasingFunction)),this._betaIsAnimating=!0;let f=gt.TransitionTo("target",s,this._attachedCamera,this._attachedCamera.getScene(),60,this._vectorTransition,this._framingTime);f&&this._animatables.push(f);let d=0;if(this._mode===n.FitFrustumSidesMode){let u=this._calculateLowerRadiusFromModelBoundingSphere(e,t);this.autoCorrectCameraLimitsAndSensibility&&(this._attachedCamera.lowerRadiusLimit=c.length()+this._attachedCamera.minZ),d=u}else this._mode===n.IgnoreBoundsSizeMode&&(d=this._calculateLowerRadiusFromModelBoundingSphere(e,t),this.autoCorrectCameraLimitsAndSensibility&&this._attachedCamera.lowerRadiusLimit===null&&(this._attachedCamera.lowerRadiusLimit=this._attachedCamera.minZ));if(this.autoCorrectCameraLimitsAndSensibility){let u=t.subtract(e).length();this._attachedCamera.panningSensibility=5e3/u,this._attachedCamera.wheelPrecision=100/d}return this._radiusTransition||(this._radiusTransition=gt.CreateAnimation("radius",gt.ANIMATIONTYPE_FLOAT,60,n.EasingFunction)),f=gt.TransitionTo("radius",d,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusTransition,this._framingTime,()=>{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}),f&&this._animatables.push(f),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){let i=this._attachedCamera;if(!i)return 0;let r=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===n.IgnoreBoundsSizeMode&&(r=r<i.lowerRadiusLimit?i.lowerRadiusLimit:r),i.upperRadiusLimit&&(r=r>i.upperRadiusLimit?i.upperRadiusLimit:r),r}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;let e=br.Now-this._lastInteractionTime,t=Math.PI*.5-this._defaultElevation,i=Math.PI*.5;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=gt.CreateAnimation("beta",gt.ANIMATIONTYPE_FLOAT,60,n.EasingFunction));let r=gt.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});r&&this._animatables.push(r)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=br.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return this._attachedCamera?this._attachedCamera.inertialAlphaOffset!==0||this._attachedCamera.inertialBetaOffset!==0||this._attachedCamera.inertialRadiusOffset!==0||this._attachedCamera.inertialPanningX!==0||this._attachedCamera.inertialPanningY!==0||this._isPointerDown:!1}};_d.EasingFunction=new gb;_d.EasingMode=$o.EASINGMODE_EASEINOUT;_d.IgnoreBoundsSizeMode=0;_d.FitFrustumSidesMode=1});var _b,fO,oa,dO=y(()=>{jt();Yt();zl();He();es();sp();Na();bi.AddNodeConstructor("TargetCamera",(n,e)=>()=>new oa(n,b.Zero(),e));_b=Q.Zero(),fO=je.Identity(),oa=class n extends Et{constructor(e,t,i,r=!0){super(e,t,i,r),this.cameraDirection=new b(0,0,0),this.cameraRotation=new Fe(0,0),this.updateUpVectorFromRotation=!1,this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this._panningEpsilon=Vt,this._rotationEpsilon=Vt,this.lockedTarget=null,this._currentTarget=b.Zero(),this._initialFocalDistance=1,this._viewMatrix=Q.Zero(),this._cameraTransformMatrix=Q.Zero(),this._cameraRotationMatrix=Q.Zero(),this._transformedReferencePoint=b.Zero(),this._deferredPositionUpdate=new b,this._deferredRotationQuaternionUpdate=new je,this._deferredRotationUpdate=new b,this._deferredUpdated=!1,this._deferOnly=!1,this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0,this._referencePoint=b.Forward(this.getScene().useRightHandedSystem),this.rotation=new b(0,this.getScene().useRightHandedSystem?Math.PI:0,0)}getFrontPosition(e){this.getWorldMatrix();let t=ee.Vector3[0],i=ee.Vector3[1];return i.set(0,0,this._scene.useRightHandedSystem?-1:1),this.getDirectionToRef(i,t),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){let e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return super._restoreStateValues()?(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&this._storedRotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0):!1}_initCache(){super._initCache(),this._cache.lockedTarget=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new je(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();let t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;let e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){let e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(e.getFps()*100))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=Vt),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),this.getScene().useRightHandedSystem?Q.LookAtRHToRef(this.position,e,b.UpReadOnly,_b):Q.LookAtLHToRef(this.position,e,b.UpReadOnly,_b),_b.invert();let t=this.rotationQuaternion||fO;je.FromRotationMatrixToRef(_b,t),t.toEulerAnglesToRef(this.rotation),this.rotation.z=0}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent){this.parent.getWorldMatrix().invertToRef(ee.Matrix[0]),b.TransformNormalToRef(this.cameraDirection,ee.Matrix[0],ee.Vector3[0]),this._deferredPositionUpdate.addInPlace(ee.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){let e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,this.noRotationConstraint||(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(je.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)));let r=this.speed*this._panningEpsilon,s=this.speed*this._rotationEpsilon;t&&(Math.abs(this.cameraDirection.x)<r&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<r&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<r&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),i&&(Math.abs(this.cameraRotation.x)<s&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<s&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),super._checkInputs()}_updateCameraRotationMatrix(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):Q.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)}_rotateUpVectorWithCameraRotationMatrix(){return b.TransformNormalToRef(b.UpReadOnly,this._cameraRotationMatrix,this.upVector),this}_getViewMatrix(){return this.lockedTarget&&this.setTarget(this._getLockedTargetPosition()),this._updateCameraRotationMatrix(),this.rotationQuaternion&&this._cachedQuaternionRotationZ!=this.rotationQuaternion.z?(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedQuaternionRotationZ=this.rotationQuaternion.z):this._cachedRotationZ!==this.rotation.z&&(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedRotationZ=this.rotation.z),b.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?ta.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(je.FromEulerVectorToRef(this.rotation,fO),ta.Y.rotateByQuaternionToRef(fO,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix}_computeViewMatrix(e,t,i){if(this.getScene().useRightHandedSystem?Q.LookAtRHToRef(e,t,i,this._viewMatrix):Q.LookAtLHToRef(e,t,i,this._viewMatrix),this.parent){let r=this.parent.getWorldMatrix();this._viewMatrix.invert(),this._viewMatrix.multiplyToRef(r,this._viewMatrix),this._viewMatrix.invert(),this._markSyncedWithParent()}}createRigCamera(e,t){if(this.cameraRigMode!==Et.RIG_MODE_NONE){let i=new n(e,this.position.clone(),this.getScene());return i.isRigCamera=!0,i.rigParent=this,this.cameraRigMode===Et.RIG_MODE_VR&&(this.rotationQuaternion||(this.rotationQuaternion=new je),i._cameraRigParams={},i.rotationQuaternion=new je),i.mode=this.mode,i.orthoLeft=this.orthoLeft,i.orthoRight=this.orthoRight,i.orthoTop=this.orthoTop,i.orthoBottom=this.orthoBottom,i}return null}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case Et.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case Et.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Et.RIG_MODE_STEREOSCOPIC_INTERLACED:{let i=this.cameraRigMode===Et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,r=this.cameraRigMode===Et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*i,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*r,t);break}case Et.RIG_MODE_VR:e.rotationQuaternion&&t.rotationQuaternion&&this.rotationQuaternion?(e.rotationQuaternion.copyFrom(this.rotationQuaternion),t.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.rotation.copyFrom(this.rotation),t.rotation.copyFrom(this.rotation)),e.position.copyFrom(this.position),t.position.copyFrom(this.position);break}super._updateRigCameras()}_getRigCamPositionAndTarget(e,t){this.getTarget().subtractToRef(this.position,n._TargetFocalPoint),n._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);let r=n._TargetFocalPoint.addInPlace(this.position);Q.TranslationToRef(-r.x,-r.y,-r.z,n._TargetTransformMatrix),n._TargetTransformMatrix.multiplyToRef(Q.RotationAxis(t.upVector,e),n._RigCamTransformMatrix),Q.TranslationToRef(r.x,r.y,r.z,n._TargetTransformMatrix),n._RigCamTransformMatrix.multiplyToRef(n._TargetTransformMatrix,n._RigCamTransformMatrix),b.TransformCoordinatesToRef(this.position,n._RigCamTransformMatrix,t.position),t.setTarget(r)}getClassName(){return"TargetCamera"}};oa._RigCamTransformMatrix=new Q;oa._TargetTransformMatrix=new Q;oa._TargetFocalPoint=new b;P([F()],oa.prototype,"updateUpVectorFromRotation",void 0);P([nn()],oa.prototype,"rotation",void 0);P([F()],oa.prototype,"speed",void 0);P([SR("lockedTargetId")],oa.prototype,"lockedTarget",void 0)});var cs,$p,Kl=y(()=>{wt();Or();zl();cs={},$p=class{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){let t=e.getSimpleName();if(this.attached[t]){te.Warn("camera input of type "+t+" already exists on camera");return}this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault)}remove(e){for(let t in this.attached){let i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(let t in this.attached){let i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){let t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=Et.ForceAttachControlToAlwaysPreventDefault?!1:e,this.attachedToElement=!0,this.noPreventDefault=e;for(let t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(let t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(let e in this.attached){let t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){let t={};for(let i in this.attached){let r=this.attached[i],s=at.Serialize(r);t[r.getClassName()]=s}e.inputsmgr=t}parse(e){let t=e.inputsmgr;if(t){this.clear();for(let i in t){let r=cs[i];if(r){let s=t[i],a=at.Parse(()=>new r,s,null);this.add(a)}}}else for(let i in this.attached){let r=cs[this.attached[i].getClassName()];if(r){let s=at.Parse(()=>new r,e,null);this.remove(this.attached[i]),this.add(s)}}}}});var qv,s4=y(()=>{jt();Yt();Gi();Xo();qv=class{constructor(){this._currentMousePointerIdDown=-1,this.buttons=[0,1,2]}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement(),r=0,s=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=o=>{var d,u;let l=o.event,c=l.pointerType==="touch";if(o.type!==ot.POINTERMOVE&&this.buttons.indexOf(l.button)===-1)return;let f=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){let h=l.movementX,m=l.movementY;this.onTouch(null,h,m),this._pointA=null,this._pointB=null}else{if(o.type!==ot.POINTERDOWN&&o.type!==ot.POINTERDOUBLETAP&&c&&((d=this._pointA)==null?void 0:d.pointerId)!==l.pointerId&&((u=this._pointB)==null?void 0:u.pointerId)!==l.pointerId)return;if(o.type===ot.POINTERDOWN&&(this._currentMousePointerIdDown===-1||c)){try{f==null||f.setPointerCapture(l.pointerId)}catch(h){}if(this._pointA===null)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType,button:l.button};else if(this._pointB===null)this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType,button:l.button};else return;this._currentMousePointerIdDown===-1&&!c&&(this._currentMousePointerIdDown=l.pointerId),this.onButtonDown(l),e||(l.preventDefault(),i&&i.focus())}else if(o.type===ot.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(o.type===ot.POINTERUP&&(this._currentMousePointerIdDown===l.pointerId||c)){try{f==null||f.releasePointerCapture(l.pointerId)}catch(h){}c||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==l.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==l.pointerId?this._pointB=null:this._pointA=this._pointB=null,(r!==0||s)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,s,null),r=0,s=null),this._currentMousePointerIdDown=-1,this.onButtonUp(l),e||l.preventDefault()}else if(o.type===ot.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&this._pointB===null){let h=l.clientX-this._pointA.x,m=l.clientY-this._pointA.y;this._pointA.x=l.clientX,this._pointA.y=l.clientY,this.onTouch(this._pointA,h,m)}else if(this._pointA&&this._pointB){let h=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;h.x=l.clientX,h.y=l.clientY;let m=this._pointA.x-this._pointB.x,g=this._pointA.y-this._pointB.y,p=m*m+g*g,_={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:o.type};this.onMultiTouch(this._pointA,this._pointB,r,p,s,_),s=_,r=p}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ot.POINTERDOWN|ot.POINTERUP|ot.POINTERMOVE|ot.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,s=null,this.onLostFocus()},this._contextMenuBind=o=>this.onContextMenu(o),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);let a=this.camera.getScene().getEngine().getHostWindow();a&&pe.RegisterTopRootEvents(a,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){let e=this.camera.getScene().getEngine().getHostWindow();e&&pe.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){let e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentMousePointerIdDown=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,r,s,a){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}};P([F()],qv.prototype,"buttons",void 0)});var rh,a4=y(()=>{jt();Yt();s4();rh=class extends qv{constructor(){super(...arguments),this.pinchZoom=!0,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this._isPinching=!1,this._twoFingerActivityCount=0,this._shouldStartPinchZoom=!1}_computePinchZoom(e,t){}_computeMultiTouchPanning(e,t){}onMultiTouch(e,t,i,r,s,a){i===0&&s===null||r===0&&a===null||(this.multiTouchPanAndZoom?(this._computePinchZoom(i,r),this._computeMultiTouchPanning(s,a)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._shouldStartPinchZoom?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(s,a)):this.multiTouchPanning?this._computeMultiTouchPanning(s,a):this.pinchZoom&&this._computePinchZoom(i,r))}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._twoFingerActivityCount=0,this._isPinching=!1}};P([F()],rh.prototype,"pinchZoom",void 0);P([F()],rh.prototype,"multiTouchPanning",void 0);P([F()],rh.prototype,"multiTouchPanAndZoom",void 0)});var wa,o4=y(()=>{jt();Yt();Kl();a4();wa=class n extends rh{constructor(){super(...arguments),this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.useNaturalPinchZoom=!1,this.panningSensibility=1e3,this.pinchInwards=!0,this._isPanClick=!1}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(this.panningSensibility!==0&&e&&t){let i=t.x-e.x,r=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=r/this.panningSensibility}}_computePinchZoom(e,t){let i=this.camera.radius||n.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=(t-e)*.001*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){this.panningSensibility!==0&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,r,s,a){this._shouldStartPinchZoom=this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(r)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance,super.onMultiTouch(e,t,i,r,s,a)}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton,super.onButtonDown(e)}onButtonUp(e){super.onButtonUp(e)}onLostFocus(){this._isPanClick=!1,super.onLostFocus()}};wa.MinimumRadiusForPinch=.001;P([F()],wa.prototype,"buttons",void 0);P([F()],wa.prototype,"angularSensibilityX",void 0);P([F()],wa.prototype,"angularSensibilityY",void 0);P([F()],wa.prototype,"pinchPrecision",void 0);P([F()],wa.prototype,"pinchDeltaPercentage",void 0);P([F()],wa.prototype,"useNaturalPinchZoom",void 0);P([F()],wa.prototype,"panningSensibility",void 0);cs.ArcRotateCameraPointersInput=wa});var la,l4=y(()=>{jt();Yt();Kl();kR();Gi();la=class{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{let i=t.event;if(!i.metaKey){if(t.type===Yo.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1){let r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),i.preventDefault&&(e||i.preventDefault())}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){let e=this.camera;for(let t=0;t<this._keys.length;t++){let i=this._keys[t];this.keysLeft.indexOf(i)!==-1?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX-=1/this.panningSensibility:e.inertialAlphaOffset-=this.angularSpeed:this.keysUp.indexOf(i)!==-1?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY+=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset+=1/this.zoomingSensibility:e.inertialBetaOffset-=this.angularSpeed:this.keysRight.indexOf(i)!==-1?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX+=1/this.panningSensibility:e.inertialAlphaOffset+=this.angularSpeed:this.keysDown.indexOf(i)!==-1?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY-=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset-=1/this.zoomingSensibility:e.inertialBetaOffset+=this.angularSpeed:this.keysReset.indexOf(i)!==-1&&e.useInputToRestoreState&&e.restoreState()}}}getClassName(){return"ArcRotateCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}};P([F()],la.prototype,"keysUp",void 0);P([F()],la.prototype,"keysDown",void 0);P([F()],la.prototype,"keysLeft",void 0);P([F()],la.prototype,"keysRight",void 0);P([F()],la.prototype,"keysReset",void 0);P([F()],la.prototype,"panningSensibility",void 0);P([F()],la.prototype,"zoomingSensibility",void 0);P([F()],la.prototype,"useAltToZoom",void 0);P([F()],la.prototype,"angularSpeed",void 0);cs.ArcRotateCameraKeyboardMoveInput=la});var ghe,vd,c4=y(()=>{jt();Yt();Kl();Xo();Gu();He();es();zR();ts();Gi();ghe=40,vd=class{constructor(){this.wheelPrecision=3,this.zoomToMouseLocation=!1,this.wheelDeltaPercentage=0,this.customComputeDeltaFromMouseWheel=null,this._viewOffset=new b(0,0,0),this._globalOffset=new b(0,0,0),this._inertialPanning=b.Zero()}_computeDeltaFromMouseWheelLegacyEvent(e,t){let i,r=e*.01*this.wheelDeltaPercentage*t;return e>0?i=r/(1+this.wheelDeltaPercentage):i=r*(1+this.wheelDeltaPercentage),i}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==ot.POINTERWHEEL)return;let i=t.event,r,s=i.deltaMode===Ko.DOM_DELTA_LINE?ghe:1,a=-(i.deltaY*s);if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(a,this,i);else if(this.wheelDeltaPercentage){if(r=this._computeDeltaFromMouseWheelLegacyEvent(a,this.camera.radius),r>0){let o=this.camera.radius,l=this.camera.inertialRadiusOffset+r;for(let c=0;c<20&&!(o<=l||Math.abs(l*this.camera.inertia)<.001);c++)o-=l,l*=this.camera.inertia;o=Gt(o,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(a,o)}}else r=a/(this.wheelPrecision*40);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,ot.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;let e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){let e=this.camera,t=e.target.subtract(e.position);this._hitPlane=Da.FromPositionAndNormal(e.target,t)}_getPosition(){var s;let e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,Q.Identity(),e,!1);(e.targetScreenOffset.x!==0||e.targetScreenOffset.y!==0)&&(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=b.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let r=0;return this._hitPlane&&(r=(s=i.intersectsPlane(this._hitPlane))!=null?s:0),i.origin.addInPlace(i.direction.scaleInPlace(r))}_zoomToMouse(e){var l,c;let t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){let f=(l=t.lowerRadiusLimit)!=null?l:0;t.radius-(t.inertialRadiusOffset+e)/i<f&&(e=(t.radius-f)*i-t.inertialRadiusOffset)}if(t.upperRadiusLimit){let f=(c=t.upperRadiusLimit)!=null?c:0;t.radius-(t.inertialRadiusOffset+e)/i>f&&(e=(t.radius-f)*i-t.inertialRadiusOffset)}let s=e/i/t.radius,a=this._getPosition(),o=ee.Vector3[6];a.subtractToRef(t.target,o),o.scaleInPlace(s),o.scaleInPlace(i),this._inertialPanning.addInPlace(o),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)<Vt&&(e.x=0),Math.abs(e.y)<Vt&&(e.y=0),Math.abs(e.z)<Vt&&(e.z=0)}};P([F()],vd.prototype,"wheelPrecision",void 0);P([F()],vd.prototype,"zoomToMouseLocation",void 0);P([F()],vd.prototype,"wheelDeltaPercentage",void 0);cs.ArcRotateCameraMouseWheelInput=vd});var vb,f4=y(()=>{o4();l4();c4();Kl();vb=class extends $p{constructor(e){super(e)}addMouseWheel(){return this.add(new vd),this}addPointers(){return this.add(new wa),this}addKeyboard(){return this.add(new la),this}}});function _he(n){let e=Math.PI/2;return n.x===0&&n.z===0||(e=Math.acos(n.x/Math.sqrt(Math.pow(n.x,2)+Math.pow(n.z,2)))),n.z<0&&(e=2*Math.PI-e),e}function vhe(n,e){return Math.acos(n/e)}function fs(n,e){return isNaN(n)?e:n}var Mi,Eb=y(()=>{jt();Yt();Si();He();ts();Na();ki();tO();r4();n4();zl();dO();f4();es();Gi();ir();bi.AddNodeConstructor("ArcRotateCamera",(n,e)=>()=>new Mi(n,0,0,1,b.Zero(),e));Mi=class n extends oa{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new Q,this._upToYMatrix=new Q,this._upVector=b.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){Q.RotationAlignToRef(b.UpReadOnly,this._upVector,this._yToUpMatrix),Q.RotationAlignToRef(this._upVector,b.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){let e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){let t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){let e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){let t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){let e=this.inputs.attached.pointers;return e?e.useNaturalPinchZoom:!1}set useNaturalPinchZoom(e){let t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){let e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){let t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){let e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){let t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){let e=this.inputs.attached.mousewheel;return e?e.zoomToMouseLocation:!1}set zoomToMouseLocation(e){let t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){let e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){let t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get isInterpolating(){return this._isInterpolating}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return this._bouncingBehavior!=null}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Qp,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return this._framingBehavior!=null}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new _d,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return this._autoRotationBehavior!=null}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new qp,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,s,a,o=!0){super(e,b.Zero(),a,o),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.lowerTargetYLimit=-1/0,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=b.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=Fe.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this.restoreStateInterpolationFactor=0,this._currentInterpolationFactor=0,this._viewMatrix=new Q,this.panningAxis=new b(1,1,0),this._transformedDirection=new b,this.mapPanning=!1,this._isInterpolating=!1,this.onMeshTargetChangedObservable=new re,this.checkCollisions=!1,this.collisionRadius=new b(.5,.5,.5),this._previousPosition=b.Zero(),this._collisionVelocity=b.Zero(),this._newPosition=b.Zero(),this._computationVector=b.Zero(),this._goalAlpha=NaN,this._goalBeta=NaN,this._goalRadius=NaN,this._goalTarget=new b(NaN,NaN,NaN),this._goalTargetScreenOffset=new Fe(NaN,NaN),this._onCollisionPositionChange=(l,c,f=null)=>{f?(this.setPosition(c),this.onCollide&&this.onCollide(f)):this._previousPosition.copyFrom(this._position);let d=Math.cos(this.alpha),u=Math.sin(this.alpha),h=Math.cos(this.beta),m=Math.sin(this.beta);m===0&&(m=1e-4);let g=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*d*m,this.radius*h,this.radius*u*m),g.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let p=this.upVector;this.allowUpsideDown&&this.beta<0&&(p=p.clone(),p=p.negate()),this._computeViewMatrix(this._position,g,p),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=b.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new vb(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=Fe.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){let t=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?t.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(t)}let e=this._getLockedTargetPosition();return e||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return this.hasStateStored()&&this.restoreStateInterpolationFactor>Vt&&this.restoreStateInterpolationFactor<1?(this.interpolateTo(this._storedAlpha,this._storedBeta,this._storedRadius,this._storedTarget,this._storedTargetScreenOffset,this.restoreStateInterpolationFactor),!0):super._restoreStateValues()?(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0):!1}stopInterpolation(){this._goalAlpha=NaN,this._goalBeta=NaN,this._goalRadius=NaN,this._goalTarget.set(NaN,NaN,NaN),this._goalTargetScreenOffset.set(NaN,NaN)}interpolateTo(e=this.alpha,t=this.beta,i=this.radius,r=this.target,s=this.targetScreenOffset,a){var o,l,c,f,d,u,h;this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,a!=null?this._currentInterpolationFactor=a:this.restoreStateInterpolationFactor!==0?this._currentInterpolationFactor=this.restoreStateInterpolationFactor:this._currentInterpolationFactor=.1,this._goalAlpha=fs(e,this._goalAlpha),this._goalBeta=fs(t,this._goalBeta),this._goalRadius=fs(i,this._goalRadius),this._goalTarget.set(fs(r.x,this._goalTarget.x),fs(r.y,this._goalTarget.y),fs(r.z,this._goalTarget.z)),this._goalTargetScreenOffset.set(fs(s.x,this._goalTargetScreenOffset.x),fs(s.y,this._goalTargetScreenOffset.y)),this._goalAlpha=Gt(this._goalAlpha,(o=this.lowerAlphaLimit)!=null?o:-1/0,(l=this.upperAlphaLimit)!=null?l:1/0),this._goalBeta=Gt(this._goalBeta,(c=this.lowerBetaLimit)!=null?c:-1/0,(f=this.upperBetaLimit)!=null?f:1/0),this._goalRadius=Gt(this._goalRadius,(d=this.lowerRadiusLimit)!=null?d:-1/0,(u=this.upperRadiusLimit)!=null?u:1/0),this._goalTarget.y=Gt(this._goalTarget.y,(h=this.lowerTargetYLimit)!=null?h:-1/0,1/0),this._isInterpolating=!0}_isSynchronizedViewMatrix(){return super._isSynchronizedViewMatrix()?this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset):!1}attachControl(e,t,i=!0,r=2){let s=arguments;t=pe.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=r,typeof s[0]=="boolean"&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(this._collisionTriggered)return;this.inputs.checkInputs();let e=!1;if(this.inertialAlphaOffset!==0||this.inertialBetaOffset!==0||this.inertialRadiusOffset!==0){e=!0;let t=this.invertRotation?-1:1,i=this._calculateHandednessMultiplier(),r=this.inertialAlphaOffset*i;this.beta<0&&(r*=-1),this.alpha+=r*t,this.beta+=this.inertialBetaOffset*t,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)<this._rotationEpsilon&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<this._rotationEpsilon&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<this.speed*this._rotationEpsilon&&(this.inertialRadiusOffset=0)}if(this.inertialPanningX!==0||this.inertialPanningY!==0){e=!0;let t=ee.Vector3[0];if(t.copyFromFloats(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY),this._viewMatrix.invertToRef(this._cameraTransformMatrix),t.multiplyInPlace(this.panningAxis),b.TransformNormalToRef(t,this._cameraTransformMatrix,this._transformedDirection),this.mapPanning){let r=this.upVector,s=b.CrossToRef(this._transformedDirection,r,this._transformedDirection);b.CrossToRef(r,s,this._transformedDirection)}else this.panningAxis.y||(this._transformedDirection.y=0);if(!this._targetHost)if(this.panningDistanceLimit)this._transformedDirection.addInPlace(this._target),b.DistanceSquared(this._transformedDirection,this.panningOriginTarget)<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection);else{if(this.parent){let r=ee.Matrix[0];this.parent.getWorldMatrix().getRotationMatrixToRef(r),r.transposeToRef(r),b.TransformCoordinatesToRef(this._transformedDirection,r,this._transformedDirection)}this._target.addInPlace(this._transformedDirection)}this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia;let i=this.speed*this._panningEpsilon;Math.abs(this.inertialPanningX)<i&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<i&&(this.inertialPanningY=0)}if(e)this.stopInterpolation();else if(this._isInterpolating){let t=!1,i=this._scene.getEngine().getDeltaTime()/1e3,r=1-Math.pow(2,-i/this._currentInterpolationFactor),s=fs(this._goalRadius,this.radius);if(!isNaN(this._goalTarget.x)||!isNaN(this._goalTarget.y)||!isNaN(this._goalTarget.z)){let a=ee.Vector3[0].set(fs(this._goalTarget.x,this._target.x),fs(this._goalTarget.y,this._target.y),fs(this._goalTarget.z,this._target.z));b.LerpToRef(this.target,a,r,this._target),b.Distance(this.target,a)*10/s<Vt?(this._goalTarget.set(NaN,NaN,NaN),this.target.copyFrom(a),this.setTarget(this.target,!1,!0,!0)):t=!0}if(!isNaN(this._goalAlpha)||!isNaN(this._goalBeta)){let a=je.RotationAlphaBetaGammaToRef(fs(this._goalAlpha,this.alpha),fs(this._goalBeta,this.beta),0,ee.Quaternion[0]),o=je.RotationAlphaBetaGammaToRef(this.alpha,this.beta,0,ee.Quaternion[1]),l=je.SlerpToRef(o,a,r,ee.Quaternion[2]);l.normalize();let c=l.toAlphaBetaGammaToRef(ee.Vector3[0]);if(this.alpha=c.x,this.beta=c.y,l.isApprox(a,Vt/5)){this._goalAlpha=NaN,this._goalBeta=NaN;let f=a.toAlphaBetaGammaToRef(ee.Vector3[0]);this.alpha=f.x,this.beta=f.y}else t=!0}if(isNaN(this._goalRadius)||(this.radius+=(s-this.radius)*r,Math.abs(s/this.radius-1)<Vt?(this._goalRadius=NaN,this.radius=s):t=!0),!isNaN(this._goalTargetScreenOffset.x)||!isNaN(this._goalTargetScreenOffset.y)){let a=ee.Vector2[0].set(fs(this._goalTargetScreenOffset.x,this.targetScreenOffset.x),fs(this._goalTargetScreenOffset.y,this.targetScreenOffset.y));Fe.LerpToRef(this.targetScreenOffset,a,r,this.targetScreenOffset),Fe.Distance(this.targetScreenOffset,a)<Vt?(this._goalTargetScreenOffset.set(NaN,NaN),this.targetScreenOffset.copyFrom(a)):t=!0}this._isInterpolating=t}this._checkLimits(),super._checkInputs()}_checkLimits(){this.lowerBetaLimit===null||this.lowerBetaLimit===void 0?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),this.upperBetaLimit===null||this.upperBetaLimit===void 0?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit!==null&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),this.upperAlphaLimit!==null&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit!==null&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit,this.inertialRadiusOffset=0),this.upperRadiusLimit!==null&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0),this.target.y=Math.max(this.target.y,this.lowerTargetYLimit)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&b.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),this.radius===0&&(this.radius=1e-4);let e=this.alpha;this.alpha=_he(this._computationVector),this.beta=vhe(this._computationVector.y,this.radius);let t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=t*2*Math.PI,this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,r=!1){var s;if(r=(s=this.overrideCloneAlphaBetaRadius)!=null?s:r,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{let a=e,o=this._getTargetPosition();if(o&&!i&&o.equals(a))return;this._targetHost=null,this._target=a,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){let e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta),r=Math.sin(this.beta);r===0&&(r=1e-4),this.radius===0&&(this.radius=1e-4);let s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&b.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){let a=this.getScene().collisionCoordinator;this._collider||(this._collider=a.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,a.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let a=this.upVector;this.allowUpsideDown&&r<0&&(a=a.negate()),this._computeViewMatrix(this._position,s,a),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget.copyFrom(s),this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;let i=$.MinMax(e),r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);if(r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.mode===Et.ORTHOGRAPHIC_CAMERA){let s=this.getScene().getEngine().getAspectRatio(this),a=r*this.zoomOnFactor/2;this.orthoLeft=-a*s,this.orthoRight=a*s,this.orthoBottom=-a,this.orthoTop=a}this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(e.min===void 0){let s=e||this.getScene().meshes;i=$.MinMax(s),r=b.Distance(i.min,i.max)}else{let s=e;i=s,r=s.distance}this._target=$.Center(i),t||(this.maxZ=r*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case Et.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Et.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Et.RIG_MODE_STEREOSCOPIC_INTERLACED:case Et.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case Et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}let r=new n(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case Et.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Et.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Et.RIG_MODE_STEREOSCOPIC_INTERLACED:case Et.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case Et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle;break}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){let r=b.Distance(e,t),a=this.getScene().getEngine().getAspectRatio(this),o=Math.tan(this.fov/2),l=o*a,f=r*.5*i,d=f*Math.sqrt(1+1/(l*l)),u=f*Math.sqrt(1+1/(o*o));return Math.max(d,u)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}};P([F()],Mi.prototype,"alpha",void 0);P([F()],Mi.prototype,"beta",void 0);P([F()],Mi.prototype,"radius",void 0);P([F()],Mi.prototype,"overrideCloneAlphaBetaRadius",void 0);P([nn("target")],Mi.prototype,"_target",void 0);P([SR("targetHost")],Mi.prototype,"_targetHost",void 0);P([F()],Mi.prototype,"inertialAlphaOffset",void 0);P([F()],Mi.prototype,"inertialBetaOffset",void 0);P([F()],Mi.prototype,"inertialRadiusOffset",void 0);P([F()],Mi.prototype,"lowerAlphaLimit",void 0);P([F()],Mi.prototype,"upperAlphaLimit",void 0);P([F()],Mi.prototype,"lowerBetaLimit",void 0);P([F()],Mi.prototype,"upperBetaLimit",void 0);P([F()],Mi.prototype,"lowerRadiusLimit",void 0);P([F()],Mi.prototype,"upperRadiusLimit",void 0);P([F()],Mi.prototype,"lowerTargetYLimit",void 0);P([F()],Mi.prototype,"inertialPanningX",void 0);P([F()],Mi.prototype,"inertialPanningY",void 0);P([F()],Mi.prototype,"pinchToPanMaxDistance",void 0);P([F()],Mi.prototype,"panningDistanceLimit",void 0);P([nn()],Mi.prototype,"panningOriginTarget",void 0);P([F()],Mi.prototype,"panningInertia",void 0);P([F()],Mi.prototype,"zoomToMouseLocation",null);P([F()],Mi.prototype,"zoomOnFactor",void 0);P([mp()],Mi.prototype,"targetScreenOffset",void 0);P([F()],Mi.prototype,"allowUpsideDown",void 0);P([F()],Mi.prototype,"useInputToRestoreState",void 0);P([F()],Mi.prototype,"restoreStateInterpolationFactor",void 0);zt("BABYLON.ArcRotateCamera",Mi)});var Jt,Ed=y(()=>{jt();Yt();He();$t();Na();rd();ir();yv();Or();Jt=class n extends bi{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}getViewMatrix(e){return null}getProjectionMatrix(e,t){return null}constructor(e,t,i){super(e,t,!1),this.diffuse=new he(1,1,1),this.specular=new he(1,1,1),this.falloffType=n.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=n.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this.renderPriority=0,this._shadowEnabled=!0,this._excludeWithLayerMask=0,this._includeOnlyWithLayerMask=0,this._lightmapMode=0,this._shadowGenerators=null,this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,this._currentViewDepth=0,this._clusteredContainer=null,this._isLight=!0,i||this.getScene().addLight(this),this._uniformBuffer=new xr(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],i||this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,r,s=!0){var l;let a=e.toString(),o=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+a),this._renderId!==t.getRenderId()||this._lastUseSpecular!==r||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=r;let c=this.getScaledIntensity();this.transferToEffect(i,a),this.diffuse.scaleToRef(c,Gn.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",Gn.Color3[0],this.range,a),r&&(this.specular.scaleToRef(c,Gn.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",Gn.Color3[1],this.radius,a)),o=!0}if(this.transferTexturesToEffect(i,a),t.shadowsEnabled&&this.shadowEnabled&&s){let c=(l=this.getShadowGenerator(t.activeCamera))!=null?l:this.getShadowGenerator();c&&(c.bindShadowLight(a,i),o=!0)}o?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()}getClassName(){return"Light"}toString(e){let t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric","Clustered"][this.getTypeID()],this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}_syncParentEnabledState(){super._syncParentEnabledState(),this.isDisposed()||this._resyncMeshes()}setEnabled(e){super.setEnabled(e),this._resyncMeshes()}getShadowGenerator(e=null){var t;return this._shadowGenerators===null?null:(t=this._shadowGenerators.get(e))!=null?t:null}getShadowGenerators(){return this._shadowGenerators}getAbsolutePosition(){return b.Zero()}canAffectMesh(e){return e?!(this.includedOnlyMeshes&&this.includedOnlyMeshes.length>0&&this.includedOnlyMeshes.indexOf(e)===-1||this.excludedMeshes&&this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1||this.includeOnlyWithLayerMask!==0&&(this.includeOnlyWithLayerMask&e.layerMask)===0||this.excludeWithLayerMask!==0&&this.excludeWithLayerMask&e.layerMask):!0}dispose(e,t=!1){if(this._shadowGenerators){let i=this._shadowGenerators.values();for(let r=i.next();r.done!==!0;r=i.next())r.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){let i=this._parentContainer.lights.indexOf(this);i>-1&&this._parentContainer.lights.splice(i,1),this._parentContainer=null}for(let i of this.getScene().meshes)i._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){let i=n.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;let r=at.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){let e=at.Serialize(this);if(e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0){e.excludedMeshesIds=[];for(let t of this.excludedMeshes)e.excludedMeshesIds.push(t.id)}if(this.includedOnlyMeshes.length>0){e.includedOnlyMeshesIds=[];for(let t of this.includedOnlyMeshes)e.includedOnlyMeshesIds.push(t.id)}return at.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){let r=bi.Construct("Light_Type_"+e,t,i);return r||null}static Parse(e,t){let i=n.GetConstructorFromName(e.type,e.name,t);if(!i)return null;let r=at.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),e.falloffType!==void 0&&(r.falloffType=e.falloffType),e.lightmapMode!==void 0&&(r.lightmapMode=e.lightmapMode),e.animations){for(let s=0;s<e.animations.length;s++){let a=e.animations[s],o=Vn("BABYLON.Animation");o&&r.animations.push(o.Parse(a))}bi.ParseAnimationRanges(r,e,t)}return e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.isEnabled!==void 0&&r.setEnabled(e.isEnabled),r._onParsed(e,t),r}_onParsed(e,t){}_hookArrayForExcluded(e){let t=e.push;e.push=(...r)=>{let s=t.apply(e,r);if(this._clusteredContainer)return s;for(let a of r)a._resyncLightSource(this);return s};let i=e.splice;if(e.splice=(r,s)=>{let a=i.call(e,r,s!=null?s:e.length);if(this._clusteredContainer)return a;for(let o of a)o._resyncLightSource(this);return a},!this._clusteredContainer)for(let r of e)r._resyncLightSource(this)}_hookArrayForIncludedOnly(e){let t=e.push;e.push=(...r)=>{let s=t.apply(e,r);return this._resyncMeshes(),s};let i=e.splice;e.splice=(r,s)=>{let a=i.call(e,r,s!=null?s:e.length);return this._resyncMeshes(),a},this._resyncMeshes()}_resyncMeshes(){if(!this._clusteredContainer)for(let e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(let e of this.getScene().meshes)e.lightSources.indexOf(this)!==-1&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0,t=this.getTypeID(),i=this.intensityMode;switch(i===n.INTENSITYMODE_AUTOMATIC&&(t===n.LIGHTTYPEID_DIRECTIONALLIGHT?i=n.INTENSITYMODE_ILLUMINANCE:i=n.INTENSITYMODE_LUMINOUSINTENSITY),t){case n.LIGHTTYPEID_POINTLIGHT:case n.LIGHTTYPEID_SPOTLIGHT:switch(i){case n.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case n.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case n.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case n.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case n.INTENSITYMODE_ILLUMINANCE:e=1;break;case n.INTENSITYMODE_LUMINANCE:{let r=this.radius;r=Math.max(r,.001),e=2*Math.PI*(1-Math.cos(r));break}}break;case n.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){let e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}areLightTexturesReady(){return!0}_isReady(){return!0}};Jt.FALLOFF_DEFAULT=ti.FALLOFF_DEFAULT;Jt.FALLOFF_PHYSICAL=ti.FALLOFF_PHYSICAL;Jt.FALLOFF_GLTF=ti.FALLOFF_GLTF;Jt.FALLOFF_STANDARD=ti.FALLOFF_STANDARD;Jt.LIGHTMAP_DEFAULT=ti.LIGHTMAP_DEFAULT;Jt.LIGHTMAP_SPECULAR=ti.LIGHTMAP_SPECULAR;Jt.LIGHTMAP_SHADOWSONLY=ti.LIGHTMAP_SHADOWSONLY;Jt.INTENSITYMODE_AUTOMATIC=ti.INTENSITYMODE_AUTOMATIC;Jt.INTENSITYMODE_LUMINOUSPOWER=ti.INTENSITYMODE_LUMINOUSPOWER;Jt.INTENSITYMODE_LUMINOUSINTENSITY=ti.INTENSITYMODE_LUMINOUSINTENSITY;Jt.INTENSITYMODE_ILLUMINANCE=ti.INTENSITYMODE_ILLUMINANCE;Jt.INTENSITYMODE_LUMINANCE=ti.INTENSITYMODE_LUMINANCE;Jt.LIGHTTYPEID_POINTLIGHT=ti.LIGHTTYPEID_POINTLIGHT;Jt.LIGHTTYPEID_DIRECTIONALLIGHT=ti.LIGHTTYPEID_DIRECTIONALLIGHT;Jt.LIGHTTYPEID_SPOTLIGHT=ti.LIGHTTYPEID_SPOTLIGHT;Jt.LIGHTTYPEID_HEMISPHERICLIGHT=ti.LIGHTTYPEID_HEMISPHERICLIGHT;Jt.LIGHTTYPEID_RECT_AREALIGHT=ti.LIGHTTYPEID_RECT_AREALIGHT;P([yr()],Jt.prototype,"diffuse",void 0);P([yr()],Jt.prototype,"specular",void 0);P([F()],Jt.prototype,"falloffType",void 0);P([F()],Jt.prototype,"intensity",void 0);P([F()],Jt.prototype,"range",null);P([F()],Jt.prototype,"intensityMode",null);P([F()],Jt.prototype,"radius",null);P([F()],Jt.prototype,"_renderPriority",void 0);P([le("_reorderLightsInScene")],Jt.prototype,"renderPriority",void 0);P([F("shadowEnabled")],Jt.prototype,"_shadowEnabled",void 0);P([F("excludeWithLayerMask")],Jt.prototype,"_excludeWithLayerMask",void 0);P([F("includeOnlyWithLayerMask")],Jt.prototype,"_includeOnlyWithLayerMask",void 0);P([F("lightmapMode")],Jt.prototype,"_lightmapMode",void 0)});var Fa,Sb=y(()=>{jt();Yt();He();$t();Na();Ed();ir();bi.AddNodeConstructor("Light_Type_3",(n,e)=>()=>new Fa(n,b.Zero(),e));Fa=class extends Jt{constructor(e,t,i,r){super(e,i,r),this.groundColor=new he(0,0,0),this.direction=t||b.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=b.Normalize(e.subtract(b.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){let i=b.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){let i=b.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=Q.Identity()),this._worldMatrix}getTypeID(){return Jt.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}};P([yr()],Fa.prototype,"groundColor",void 0);P([nn()],Fa.prototype,"direction",void 0);zt("BABYLON.HemisphericLight",Fa)});var fo,Tb=y(()=>{jt();Yt();He();Ed();sp();fo=class extends Jt{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=Q.Identity(),this._projectionMatrix=Q.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return this.parent&&this.parent.getWorldMatrix?(this.transformedPosition||(this.transformedPosition=b.Zero()),b.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=b.Zero()),b.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0):!1}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=b.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();let e=b.Cross(this.direction,ta.Y),t=b.Cross(e,this.direction);return b.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=b.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=Q.Identity()),Q.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return this.shadowMinZ!==void 0?this.shadowMinZ:(e==null?void 0:e.minZ)||0}getDepthMaxZ(e){return this.shadowMaxZ!==void 0?this.shadowMaxZ:(e==null?void 0:e.maxZ)||1e4}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){let t=ee.Vector3[0],i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),b.NormalizeToRef(this.getShadowDirection(e),t),Math.abs(b.Dot(t,b.Up()))===1&&(t.z=1e-13);let r=ee.Vector3[1];return i.addToRef(t,r),Q.LookAtLHToRef(i,r,b.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e!=null?e:this._viewMatrix,t!=null?t:[]),this._projectionMatrix}};P([nn()],fo.prototype,"position",null);P([nn()],fo.prototype,"direction",null);P([F()],fo.prototype,"shadowMinZ",null);P([F()],fo.prototype,"shadowMaxZ",null)});var ca,d4=y(()=>{jt();Yt();He();Na();Ed();Tb();ir();bi.AddNodeConstructor("Light_Type_1",(n,e)=>()=>new ca(n,b.Zero(),e));ca=class extends fo{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i,r){super(e,i,r),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return Jt.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){let t=this.getScene().activeCamera;Q.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,this.shadowMinZ!==void 0?this.shadowMinZ:t?t.minZ:0,this.shadowMaxZ!==void 0?this.shadowMaxZ:t?t.maxZ:1e4,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){let f=b.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let d=Number.MAX_VALUE,u=-Number.MAX_VALUE;for(let h=0;h<i.length;h++){let m=i[h];if(!m)continue;let p=m.getBoundingInfo().boundingBox;for(let _=0;_<p.vectorsWorld.length;_++)b.TransformCoordinatesToRef(p.vectorsWorld[_],t,f),f.x<this._orthoLeft&&(this._orthoLeft=f.x),f.y<this._orthoBottom&&(this._orthoBottom=f.y),f.x>this._orthoRight&&(this._orthoRight=f.x),f.y>this._orthoTop&&(this._orthoTop=f.y),this.autoCalcShadowZBounds&&(f.z<d&&(d=f.z),f.z>u&&(u=f.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=d,this._shadowMaxZ=u)}let s=this._orthoRight-this._orthoLeft,a=this._orthoTop-this._orthoBottom,o=this.shadowMinZ!==void 0?this.shadowMinZ:(r==null?void 0:r.minZ)||0,l=this.shadowMaxZ!==void 0?this.shadowMaxZ:(r==null?void 0:r.maxZ)||1e4,c=this.getScene().getEngine().useReverseDepthBuffer;Q.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-a*this.shadowOrthoScale,this._orthoTop+a*this.shadowOrthoScale,c?l:o,c?o:l,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){let t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){let t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}};P([F()],ca.prototype,"shadowFrustumSize",null);P([F()],ca.prototype,"shadowOrthoScale",null);P([F()],ca.prototype,"autoUpdateExtends",void 0);P([F()],ca.prototype,"autoCalcShadowZBounds",void 0);P([F("orthoLeft")],ca.prototype,"_orthoLeft",void 0);P([F("orthoRight")],ca.prototype,"_orthoRight",void 0);P([F("orthoTop")],ca.prototype,"_orthoTop",void 0);P([F("orthoBottom")],ca.prototype,"_orthoBottom",void 0);zt("BABYLON.DirectionalLight",ca)});var Sd,u4=y(()=>{jt();Yt();He();Na();Ed();Tb();ir();bi.AddNodeConstructor("Light_Type_0",(n,e)=>()=>new Sd(n,b.Zero(),e));Sd=class extends fo{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){let t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){let i=this._shadowGenerators.values();for(let r=i.next();r.done!==!0;r=i.next())r.value.recreateShadowMap()}}constructor(e,t,i,r){super(e,i,r),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return Jt.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new b(1,0,0);case 1:return new b(-1,0,0);case 2:return new b(0,-1,0);case 3:return new b(0,1,0);case 4:return new b(0,0,1);case 5:return new b(0,0,-1)}return b.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera,s=this.getDepthMinZ(r),a=this.getDepthMaxZ(r),o=this.getScene().getEngine().useReverseDepthBuffer;Q.PerspectiveFovLHToRef(this.shadowAngle,1,o?a:s,o?s:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){let i=this._scene.floatingOriginOffset;return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x-i.x,this.transformedPosition.y-i.y,this.transformedPosition.z-i.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x-i.x,this.position.y-i.y,this.position.z-i.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){let i=this._scene.floatingOriginOffset;return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x-i.x,this.transformedPosition.y-i.y,this.transformedPosition.z-i.z):e.setFloat3(t,this.position.x-i.x,this.position.y-i.y,this.position.z-i.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}};P([F()],Sd.prototype,"shadowAngle",null);zt("BABYLON.PointLight",Sd)});var Zr,uO=y(()=>{jt();Yt();He();Na();Ed();Tb();Kr();ir();bi.AddNodeConstructor("Light_Type_2",(n,e)=>()=>new Zr(n,b.Zero(),b.Zero(),0,0,e));Zr=class n extends fo{get iesProfileTexture(){return this._iesProfileTexture}set iesProfileTexture(e){this._iesProfileTexture!==e&&(this._iesProfileTexture=e,this._iesProfileTexture&&n._IsTexture(this._iesProfileTexture)&&this._iesProfileTexture.onLoadObservable.addOnce(()=>{this._markMeshesAsLightDirty()}))}get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(e*.5),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(n._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):n._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce(()=>{this._markMeshesAsLightDirty()})))}static _IsProceduralTexture(e){return e.onGeneratedObservable!==void 0}static _IsTexture(e){return e.onLoadObservable!==void 0}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,r,s,a,o){super(e,a,o),this._innerAngle=0,this._iesProfileTexture=null,this._projectionTextureMatrix=Q.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=b.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=b.Zero(),this._projectionTextureViewLightMatrix=Q.Zero(),this._projectionTextureProjectionLightMatrix=Q.Zero(),this._projectionTextureScalingMatrix=Q.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=r,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return Jt.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;let s=this._shadowAngleScale*this._angle,a=this.shadowMinZ!==void 0?this.shadowMinZ:r.minZ,o=this.shadowMaxZ!==void 0?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;Q.PerspectiveFovLHToRef(s,1,l?o:a,l?a:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,l)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),Q.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;let e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=-i*t,s=1/Math.tan(this._angle/2);Q.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,r,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof _e){let e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;Q.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(this._innerAngle*.5)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightTexture"+t,this.projectionTexture)),this._iesProfileTexture&&this._iesProfileTexture.isReady()&&e.setTexture("iesLightTexture"+t,this._iesProfileTexture),this}transferToEffect(e,t){let i,r=this._scene.floatingOriginOffset;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x-r.x,this.transformedPosition.y-r.y,this.transformedPosition.z-r.z,this.exponent,t),i=b.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x-r.x,this.position.y-r.y,this.position.z-r.z,this.exponent,t),i=b.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return this.computeTransformedInformation()?i=b.Normalize(this.transformedDirection):i=b.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose(),this._iesProfileTexture&&(this._iesProfileTexture.dispose(),this._iesProfileTexture=null)}getDepthMinZ(e){var r;let t=this._scene.getEngine(),i=this.shadowMinZ!==void 0?this.shadowMinZ:(r=e==null?void 0:e.minZ)!=null?r:0;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){var r;let t=this._scene.getEngine(),i=this.shadowMaxZ!==void 0?this.shadowMaxZ:(r=e==null?void 0:e.maxZ)!=null?r:1e4;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}areLightTexturesReady(){return!(this._projectionTexture&&!this._projectionTexture.isReadyOrNotBlocking()||this._iesProfileTexture&&!this._iesProfileTexture.isReadyOrNotBlocking())}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!(this.projectionTexture&&this.projectionTexture.isReady()),e["IESLIGHTTEXTURE"+t]=!!(this._iesProfileTexture&&this._iesProfileTexture.isReady())}};P([F()],Zr.prototype,"angle",null);P([F()],Zr.prototype,"innerAngle",null);P([F()],Zr.prototype,"shadowAngleScale",null);P([F()],Zr.prototype,"exponent",void 0);P([F()],Zr.prototype,"projectionTextureLightNear",null);P([F()],Zr.prototype,"projectionTextureLightFar",null);P([F()],Zr.prototype,"projectionTextureUpDirection",null);P([Xt("projectedLightTexture")],Zr.prototype,"_projectionTexture",void 0);zt("BABYLON.SpotLight",Zr)});function h4(n){let e=n.pathArray,t=n.closeArray||!1,i=n.closePath||!1,r=n.invertUV||!1,s=Math.floor(e[0].length/2),a=n.offset||s;a=a>s?s:Math.floor(a);let o=n.sideOrientation===0?0:n.sideOrientation||Ie.DEFAULTSIDE,l=n.uvs,c=n.colors,f=[],d=[],u=[],h=[],m=[],g=[],p=[],_=[],v,E=[],S=[],T,A,R;if(e.length<2){let be=[],we=[];for(A=0;A<e[0].length-a;A++)be.push(e[0][A]),we.push(e[0][A+a]);e=[be,we]}let M=0,I=i?1:0,C=t?1:0,L,w;v=e[0].length;let G,O;for(T=0;T<e.length+C;T++){for(p[T]=0,m[T]=[0],L=T===e.length?e[0]:e[T],w=L.length,v=v<w?v:w,R=0;R<w;)f.push(L[R].x,L[R].y,L[R].z),R>0&&(G=L[R].subtract(L[R-1]).length(),O=G+p[T],m[T].push(O),p[T]=O),R++;i&&(R--,f.push(L[0].x,L[0].y,L[0].z),G=L[R].subtract(L[0]).length(),O=G+p[T],m[T].push(O),p[T]=O),E[T]=w+I,S[T]=M,M+=w+I}let N,B,V,q;for(A=0;A<v+I;A++)for(_[A]=0,g[A]=[0],T=0;T<e.length-1+C;T++)N=e[T],B=T===e.length-1?e[0]:e[T+1],A===v?(V=N[0],q=B[0]):(V=N[A],q=B[A]),G=q.subtract(V).length(),O=G+_[A],g[A].push(O),_[A]=O;let K,J;if(l)for(T=0;T<l.length;T++)h.push(l[T].x,Ot?1-l[T].y:l[T].y);else for(T=0;T<e.length+C;T++)for(A=0;A<v+I;A++)K=p[T]!=0?m[T][A]/p[T]:0,J=_[A]!=0?g[A][T]/_[A]:0,r?h.push(J,K):h.push(K,Ot?1-J:J);T=0;let Y=0,j=E[T]-1,ue=E[T+1]-1,Ee=j<ue?j:ue,Ue=S[1]-S[0],se=E.length-1;for(;Y<=Ee&&T<se;)d.push(Y,Y+Ue,Y+1),d.push(Y+Ue+1,Y+1,Y+Ue),Y+=1,Y===Ee&&(T++,Ue=S[T+1]-S[T],j=E[T]-1,ue=E[T+1]-1,Y=S[T],Ee=j<ue?j+Y:ue+Y);if(Ie.ComputeNormals(f,d,u),i){let be,we;for(T=0;T<e.length;T++){be=S[T]*3,T+1<e.length?we=(S[T+1]-1)*3:we=u.length-3,u[be]=(u[be]+u[we])*.5,u[be+1]=(u[be+1]+u[we+1])*.5,u[be+2]=(u[be+2]+u[we+2])*.5;let dt=Math.sqrt(u[be]*u[be]+u[be+1]*u[be+1]+u[be+2]*u[be+2]);u[be]/=dt,u[be+1]/=dt,u[be+2]/=dt,u[we]=u[be],u[we+1]=u[be+1],u[we+2]=u[be+2]}}if(t){let be=S[0]*3,we=S[e.length]*3;for(A=0;A<v+I;A++){u[be]=(u[be]+u[we])*.5,u[be+1]=(u[be+1]+u[we+1])*.5,u[be+2]=(u[be+2]+u[we+2])*.5;let dt=Math.sqrt(u[be]*u[be]+u[be+1]*u[be+1]+u[be+2]*u[be+2]);u[be]/=dt,u[be+1]/=dt,u[be+2]/=dt,u[we]=u[be],u[we+1]=u[be+1],u[we+2]=u[be+2],be+=3,we+=3}}Ie._ComputeSides(o,f,d,u,h,n.frontUVs,n.backUVs);let ve=null;if(c){ve=new Float32Array(c.length*4);for(let be=0;be<c.length;be++)ve[be*4]=c[be].r,ve[be*4+1]=c[be].g,ve[be*4+2]=c[be].b,ve[be*4+3]=c[be].a}let ne=new Ie,me=new Float32Array(f),Le=new Float32Array(u),de=new Float32Array(h);return ne.indices=d,ne.positions=me,ne.normals=Le,ne.uvs=de,ve&&ne.set(ve,D.ColorKind),i&&(ne._idx=S),ne}function el(n,e,t=null){let i=e.pathArray,r=e.closeArray,s=e.closePath,a=$._GetDefaultSideOrientation(e.sideOrientation),o=e.instance,l=e.updatable;if(o){let c=ee.Vector3[0].setAll(Number.MAX_VALUE),f=ee.Vector3[1].setAll(-Number.MAX_VALUE),d=h=>{let m=i[0].length,g=o,p=0,_=g._originalBuilderSideOrientation===$.DOUBLESIDE?2:1;for(let v=1;v<=_;++v)for(let E=0;E<i.length;++E){let S=i[E],T=S.length;m=m<T?m:T;for(let A=0;A<m;++A){let R=S[A];h[p]=R.x,h[p+1]=R.y,h[p+2]=R.z,c.minimizeInPlaceFromFloats(R.x,R.y,R.z),f.maximizeInPlaceFromFloats(R.x,R.y,R.z),p+=3}if(g._creationDataStorage&&g._creationDataStorage.closePath){let A=S[0];h[p]=A.x,h[p+1]=A.y,h[p+2]=A.z,p+=3}}},u=o.getVerticesData(D.PositionKind);if(d(u),o.hasBoundingInfo?o.getBoundingInfo().reConstruct(c,f,o._worldMatrix):o.buildBoundingInfo(c,f,o._worldMatrix),o.updateVerticesData(D.PositionKind,u,!1,!1),e.colors){let h=o.getVerticesData(D.ColorKind);for(let m=0,g=0;m<e.colors.length;m++,g+=4){let p=e.colors[m];h[g]=p.r,h[g+1]=p.g,h[g+2]=p.b,h[g+3]=p.a}o.updateVerticesData(D.ColorKind,h,!1,!1)}if(e.uvs){let h=o.getVerticesData(D.UVKind);for(let m=0;m<e.uvs.length;m++)h[m*2]=e.uvs[m].x,h[m*2+1]=Ot?1-e.uvs[m].y:e.uvs[m].y;o.updateVerticesData(D.UVKind,h,!1,!1)}if(!o.areNormalsFrozen||o.isFacetDataEnabled){let h=o.getIndices(),m=o.getVerticesData(D.NormalKind),g=o.isFacetDataEnabled?o.getFacetDataParameters():null;if(Ie.ComputeNormals(u,h,m,g),o._creationDataStorage&&o._creationDataStorage.closePath){let p,_;for(let v=0;v<i.length;v++)p=o._creationDataStorage.idx[v]*3,v+1<i.length?_=(o._creationDataStorage.idx[v+1]-1)*3:_=m.length-3,m[p]=(m[p]+m[_])*.5,m[p+1]=(m[p+1]+m[_+1])*.5,m[p+2]=(m[p+2]+m[_+2])*.5,m[_]=m[p],m[_+1]=m[p+1],m[_+2]=m[p+2]}o.areNormalsFrozen||o.updateVerticesData(D.NormalKind,m,!1,!1)}return o}else{let c=new $(n,t);c._originalBuilderSideOrientation=a,c._creationDataStorage=new Zp;let f=h4(e);return s&&(c._creationDataStorage.idx=f._idx),c._creationDataStorage.closePath=s,c._creationDataStorage.closeArray=r,f.applyToMesh(c,l),c}}var Qv=y(()=>{He();ki();qi();vr();vn();Ie.CreateRibbon=h4;$.CreateRibbon=(n,e,t=!1,i,r,s,a=!1,o,l)=>el(n,{pathArray:e,closeArray:t,closePath:i,offset:r,updatable:a,sideOrientation:o,instance:l},s)});function m4(n){let e=[],t=[],i=[],r=[],s=n.radius||.5,a=n.tessellation||64,o=n.arc&&(n.arc<=0||n.arc>1)?1:n.arc||1,l=n.sideOrientation===0?0:n.sideOrientation||Ie.DEFAULTSIDE;e.push(0,0,0),r.push(.5,.5);let c=Math.PI*2*o,f=o===1?c/a:c/(a-1),d=0;for(let m=0;m<a;m++){let g=Math.cos(d),p=Math.sin(d),_=(g+1)/2,v=(1-p)/2;e.push(s*g,s*p,0),r.push(_,Ot?1-v:v),d+=f}o===1&&(e.push(e[3],e[4],e[5]),r.push(r[2],Ot?1-r[3]:r[3]));let u=e.length/3;for(let m=1;m<u-1;m++)t.push(m+1,0,m);Ie.ComputeNormals(e,t,i),Ie._ComputeSides(l,e,t,i,r,n.frontUVs,n.backUVs);let h=new Ie;return h.indices=t,h.positions=e,h.normals=i,h.uvs=r,h}function hO(n,e={},t=null){let i=new $(n,t);return e.sideOrientation=$._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,m4(e).applyToMesh(i,e.updatable),i}var p4=y(()=>{ki();vr();vn();Ie.CreateDisc=m4;$.CreateDisc=(n,e,t,i=null,r,s)=>hO(n,{radius:e,tessellation:t,sideOrientation:s,updatable:r},i)});var Jp,g4=y(()=>{He();qi();ki();$._GroundMeshParser=(n,e)=>Jp.Parse(n,e);Jp=class n extends ${constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);let i=this;i.createOrUpdateSubmeshesOctree&&i.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){let i=this.getWorldMatrix(),r=ee.Matrix[5];i.invertToRef(r);let s=ee.Vector3[8];if(b.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e<this._minX||e>=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());let a=this._getFacetAt(e,t),o=-(a.x*e+a.z*t+a.w)/a.y;return b.TransformCoordinatesFromFloatsToRef(0,o,0,i,s),s.y}getNormalAtCoordinates(e,t){let i=new b(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){let r=this.getWorldMatrix(),s=ee.Matrix[5];r.invertToRef(s);let a=ee.Vector3[8];if(b.TransformCoordinatesFromFloatsToRef(e,0,t,s,a),e=a.x,t=a.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());let o=this._getFacetAt(e,t);return b.TransformNormalFromFloatsToRef(o.x,o.y,o.z,r,i),this}updateCoordinateHeights(){return(!this._heightQuads||this._heightQuads.length==0)&&this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){let i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[r*this._subdivisionsX+i],a;return t<s.slope.x*e+s.slope.y?a=s.facet1:a=s.facet2,a}_initHeightQuads(){let e=this._subdivisionsX,t=this._subdivisionsY;this._heightQuads=[];for(let i=0;i<t;i++)for(let r=0;r<e;r++){let s={slope:Fe.Zero(),facet1:new Vi(0,0,0,0),facet2:new Vi(0,0,0,0)};this._heightQuads[i*e+r]=s}return this}_computeHeightQuads(){let e=this.getVerticesData(D.PositionKind);if(!e)return this;let t=ee.Vector3[3],i=ee.Vector3[2],r=ee.Vector3[1],s=ee.Vector3[0],a=ee.Vector3[4],o=ee.Vector3[5],l=ee.Vector3[6],c=ee.Vector3[7],f=ee.Vector3[8],d,u,h,m,g,p,_,v=this._subdivisionsX,E=this._subdivisionsY;for(let S=0;S<E;S++)for(let T=0;T<v;T++){d=T*3,u=S*(v+1)*3,h=(S+1)*(v+1)*3,t.x=e[u+d],t.y=e[u+d+1],t.z=e[u+d+2],i.x=e[u+d+3],i.y=e[u+d+4],i.z=e[u+d+5],r.x=e[h+d],r.y=e[h+d+1],r.z=e[h+d+2],s.x=e[h+d+3],s.y=e[h+d+4],s.z=e[h+d+5],m=(s.z-t.z)/(s.x-t.x),g=t.z-m*t.x,i.subtractToRef(t,a),r.subtractToRef(t,o),s.subtractToRef(t,l),b.CrossToRef(l,o,c),b.CrossToRef(a,l,f),c.normalize(),f.normalize(),p=-(c.x*t.x+c.y*t.y+c.z*t.z),_=-(f.x*i.x+f.y*i.y+f.z*i.z);let A=this._heightQuads[S*v+T];A.slope.copyFromFloats(m,g),A.facet1.copyFromFloats(c.x,c.y,c.z,p),A.facet2.copyFromFloats(f.x,f.y,f.z,_)}return this}serialize(e){super.serialize(e),e.subdivisionsX=this._subdivisionsX,e.subdivisionsY=this._subdivisionsY,e.minX=this._minX,e.maxX=this._maxX,e.minZ=this._minZ,e.maxZ=this._maxZ,e.width=this._width,e.height=this._height}static Parse(e,t){let i=new n(e.name,t);return i._subdivisionsX=e.subdivisionsX||1,i._subdivisionsY=e.subdivisionsY||1,i._minX=e.minX,i._maxX=e.maxX,i._minZ=e.minZ,i._maxZ=e.maxZ,i._width=e.width,i._height=e.height,i}}});function mO(n){let e=[],t=[],i=[],r=[],s,a,o=n.width||n.size||1,l=n.height||n.size||1,c=(n.subdivisionsX||n.subdivisions||1)|0,f=(n.subdivisionsY||n.subdivisions||1)|0;for(s=0;s<=f;s++)for(a=0;a<=c;a++){let u=new b(a*o/c-o/2,0,(f-s)*l/f-l/2),h=new b(0,1,0);t.push(u.x,u.y,u.z),i.push(h.x,h.y,h.z),r.push(a/c,Ot?s/f:1-s/f)}for(s=0;s<f;s++)for(a=0;a<c;a++)e.push(a+1+(s+1)*(c+1)),e.push(a+1+s*(c+1)),e.push(a+s*(c+1)),e.push(a+(s+1)*(c+1)),e.push(a+1+(s+1)*(c+1)),e.push(a+s*(c+1));let d=new Ie;return d.indices=e,d.positions=t,d.normals=i,d.uvs=r,d}function _4(n){let e=n.xmin!==void 0&&n.xmin!==null?n.xmin:-1,t=n.zmin!==void 0&&n.zmin!==null?n.zmin:-1,i=n.xmax!==void 0&&n.xmax!==null?n.xmax:1,r=n.zmax!==void 0&&n.zmax!==null?n.zmax:1,s=n.subdivisions||{w:1,h:1},a=n.precision||{w:1,h:1},o=[],l=[],c=[],f=[],d,u,h,m;s.h=s.h<1?1:s.h,s.w=s.w<1?1:s.w,a.w=a.w<1?1:a.w,a.h=a.h<1?1:a.h;let g={w:(i-e)/s.w,h:(r-t)/s.h};function p(v,E,S,T){let A=l.length/3,R=a.w+1;for(d=0;d<a.h;d++)for(u=0;u<a.w;u++){let C=[A+u+d*R,A+(u+1)+d*R,A+(u+1)+(d+1)*R,A+u+(d+1)*R];o.push(C[1]),o.push(C[2]),o.push(C[3]),o.push(C[0]),o.push(C[1]),o.push(C[3])}let M=b.Zero(),I=new b(0,1,0);for(d=0;d<=a.h;d++)for(M.z=d*(T-E)/a.h+E,u=0;u<=a.w;u++)M.x=u*(S-v)/a.w+v,M.y=0,l.push(M.x,M.y,M.z),c.push(I.x,I.y,I.z),f.push(u/a.w,d/a.h)}for(h=0;h<s.h;h++)for(m=0;m<s.w;m++)p(e+m*g.w,t+h*g.h,e+(m+1)*g.w,t+(h+1)*g.h);let _=new Ie;return _.indices=o,_.positions=l,_.normals=c,_.uvs=f,_}function v4(n){let e=[],t=[],i=[],r=[],s,a,o=n.colorFilter||new he(.3,.59,.11),l=n.alphaFilter||0,c=!1;if(n.minHeight>n.maxHeight){c=!0;let d=n.maxHeight;n.maxHeight=n.minHeight,n.minHeight=d}for(s=0;s<=n.subdivisions;s++)for(a=0;a<=n.subdivisions;a++){let d=new b(a*n.width/n.subdivisions-n.width/2,0,(n.subdivisions-s)*n.height/n.subdivisions-n.height/2),u=(d.x+n.width/2)/n.width*(n.bufferWidth-1)|0,h=(1-(d.z+n.height/2)/n.height)*(n.bufferHeight-1)|0,m=(u+h*n.bufferWidth)*4,g=n.buffer[m]/255,p=n.buffer[m+1]/255,_=n.buffer[m+2]/255,v=n.buffer[m+3]/255;c&&(g=1-g,p=1-p,_=1-_);let E=g*o.r+p*o.g+_*o.b;v>=l?d.y=n.minHeight+(n.maxHeight-n.minHeight)*E:d.y=n.minHeight-Vt,n.heightBuffer&&(n.heightBuffer[s*(n.subdivisions+1)+a]=d.y),t.push(d.x,d.y,d.z),i.push(0,0,0),r.push(a/n.subdivisions,1-s/n.subdivisions)}for(s=0;s<n.subdivisions;s++)for(a=0;a<n.subdivisions;a++){let d=a+1+(s+1)*(n.subdivisions+1),u=a+1+s*(n.subdivisions+1),h=a+s*(n.subdivisions+1),m=a+(s+1)*(n.subdivisions+1),g=t[d*3+1]>=n.minHeight,p=t[u*3+1]>=n.minHeight,_=t[h*3+1]>=n.minHeight;g&&p&&_&&(e.push(d),e.push(u),e.push(h)),t[m*3+1]>=n.minHeight&&g&&_&&(e.push(m),e.push(d),e.push(h))}Ie.ComputeNormals(t,e,i);let f=new Ie;return f.indices=e,f.positions=t,f.normals=i,f.uvs=r,f}function pO(n,e={},t){let i=new Jp(n,t);return i._setReady(!1),i._subdivisionsX=e.subdivisionsX||e.subdivisions||1,i._subdivisionsY=e.subdivisionsY||e.subdivisions||1,i._width=e.width||1,i._height=e.height||1,i._maxX=i._width/2,i._maxZ=i._height/2,i._minX=-i._maxX,i._minZ=-i._maxZ,mO(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function gO(n,e,t=null){let i=new $(n,t);return _4(e).applyToMesh(i,e.updatable),i}function _O(n,e,t={},i=null){let r=t.width||10,s=t.height||10,a=t.subdivisions||1,o=t.minHeight||0,l=t.maxHeight||1,c=t.colorFilter||new he(.3,.59,.11),f=t.alphaFilter||0,d=t.updatable,u=t.onReady;i=i||Oe.LastCreatedScene;let h=new Jp(n,i);h._subdivisionsX=a,h._subdivisionsY=a,h._width=r,h._height=s,h._maxX=h._width/2,h._maxZ=h._height/2,h._minX=-h._maxX,h._minZ=-h._maxZ,h._setReady(!1);let m;t.passHeightBufferInCallback&&(m=new Float32Array((a+1)*(a+1)));let g=(p,_,v)=>{v4({width:r,height:s,subdivisions:a,minHeight:o,maxHeight:l,colorFilter:c,buffer:p,bufferWidth:_,bufferHeight:v,alphaFilter:f,heightBuffer:m}).applyToMesh(h,d),u&&u(h,m),h._setReady(!0)};if(typeof e=="string"){i.addPendingData(h);let p=v=>{let E=v.width,S=v.height;if(i.isDisposed){i.removePendingData(h);return}let T=i==null?void 0:i.getEngine().resizeImageBitmap(v,E,S);g(T,E,S),i.removePendingData(h)},_=(v,E)=>{i.removePendingData(h),t.onError&&t.onError(v,E)};pe.LoadImage(e,p,_,i.offlineProvider)}else g(e.data,e.width,e.height);return h}var vO=y(()=>{He();$t();ki();vr();g4();Gi();Yi();es();vn();Ie.CreateGround=mO;Ie.CreateTiledGround=_4;Ie.CreateGroundFromHeightMap=v4;$.CreateGround=(n,e,t,i,r,s)=>pO(n,{width:e,height:t,subdivisions:i,updatable:s},r);$.CreateTiledGround=(n,e,t,i,r,s,a,o,l)=>gO(n,{xmin:e,zmin:t,xmax:i,zmax:r,subdivisions:s,precision:a,updatable:l},o);$.CreateGroundFromHeightMap=(n,e,t,i,r,s,a,o,l,c,f)=>_O(n,e,{width:t,height:i,subdivisions:r,minHeight:s,maxHeight:a,updatable:l,onReady:c,alphaFilter:f},o)});function Ab(n){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23],i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],r=[],s=n.width||n.size||1,a=n.height||n.size||1,o=n.depth||n.size||1,l=n.wrap||!1,c=n.topBaseAt===void 0?1:n.topBaseAt,f=n.bottomBaseAt===void 0?0:n.bottomBaseAt;c=(c+4)%4,f=(f+4)%4;let d=[2,0,3,1],u=[2,0,1,3],h=d[c],m=u[f],g=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],g=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let R=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],M=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]],I=[17,18,19,16],C=[22,23,20,21];for(;h>0;)R.unshift(R.pop()),I.unshift(I.pop()),h--;for(;m>0;)M.unshift(M.pop()),C.unshift(C.pop()),m--;R=R.flat(),M=M.flat(),g=g.concat(R).concat(M),t.push(I[0],I[2],I[3],I[0],I[1],I[2]),t.push(C[0],C[2],C[3],C[0],C[1],C[2])}let p=[s/2,a/2,o/2],_=g.reduce((R,M,I)=>R.concat(M*p[I%3]),[]),v=n.sideOrientation===0?0:n.sideOrientation||Ie.DEFAULTSIDE,E=n.faceUV||new Array(6),S=n.faceColors,T=[];for(let R=0;R<6;R++)E[R]===void 0&&(E[R]=new Vi(0,0,1,1)),S&&S[R]===void 0&&(S[R]=new ht(1,1,1,1));for(let R=0;R<6;R++)if(r.push(E[R].z,Ot?1-E[R].w:E[R].w),r.push(E[R].x,Ot?1-E[R].w:E[R].w),r.push(E[R].x,Ot?1-E[R].y:E[R].y),r.push(E[R].z,Ot?1-E[R].y:E[R].y),S)for(let M=0;M<4;M++)T.push(S[R].r,S[R].g,S[R].b,S[R].a);Ie._ComputeSides(v,_,t,i,r,n.frontUVs,n.backUVs);let A=new Ie;if(A.indices=t,A.positions=_,A.normals=i,A.uvs=r,S){let R=v===Ie.DOUBLESIDE?T.concat(T):T;A.colors=R}return A}function EO(n,e={},t=null){let i=new $(n,t);return e.sideOrientation=$._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Ab(e).applyToMesh(i,e.updatable),i}var SO=y(()=>{He();$t();ki();vr();vn();vO();Ie.CreateBox=Ab;$.CreateBox=(n,e,t=null,i,r)=>EO(n,{size:e,sideOrientation:r,updatable:i},t)});function eg(n){let e=n.pattern||$.NO_FLIP,t=n.tileWidth||n.tileSize||1,i=n.tileHeight||n.tileSize||1,r=n.alignHorizontal||0,s=n.alignVertical||0,a=n.width||n.size||1,o=Math.floor(a/t),l=a-o*t,c=n.height||n.size||1,f=Math.floor(c/i),d=c-f*i,u=t*o/2,h=i*f/2,m=0,g=0,p=0,_=0,v=0,E=0;if(l>0||d>0){switch(p=-u,_=-h,v=u,E=h,r){case $.CENTER:l/=2,p-=l,v+=l;break;case $.LEFT:v+=l,m=-l/2;break;case $.RIGHT:p-=l,m=l/2;break}switch(s){case $.CENTER:d/=2,_-=d,E+=d;break;case $.BOTTOM:E+=d,g=-d/2;break;case $.TOP:_-=d,g=d/2;break}}let S=[],T=[],A=[];A[0]=[0,0,1,0,1,1,0,1],A[1]=[0,0,1,0,1,1,0,1],(e===$.ROTATE_TILE||e===$.ROTATE_ROW)&&(A[1]=[1,1,0,1,0,0,1,0]),(e===$.FLIP_TILE||e===$.FLIP_ROW)&&(A[1]=[1,0,0,0,0,1,1,1]),(e===$.FLIP_N_ROTATE_TILE||e===$.FLIP_N_ROTATE_ROW)&&(A[1]=[0,1,1,1,1,0,0,0]);let R=[],M=[],I=[],C=0;for(let O=0;O<f;O++)for(let N=0;N<o;N++)S.push(-u+N*t+m,-h+O*i+g,0),S.push(-u+(N+1)*t+m,-h+O*i+g,0),S.push(-u+(N+1)*t+m,-h+(O+1)*i+g,0),S.push(-u+N*t+m,-h+(O+1)*i+g,0),I.push(C,C+1,C+3,C+1,C+2,C+3),e===$.FLIP_TILE||e===$.ROTATE_TILE||e===$.FLIP_N_ROTATE_TILE?R=R.concat(A[(N%2+O%2)%2]):e===$.FLIP_ROW||e===$.ROTATE_ROW||e===$.FLIP_N_ROTATE_ROW?R=R.concat(A[O%2]):R=R.concat(A[0]),M.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1),C+=4;if(l>0||d>0){let O=d>0&&(s===$.CENTER||s===$.TOP),N=d>0&&(s===$.CENTER||s===$.BOTTOM),B=l>0&&(r===$.CENTER||r===$.RIGHT),V=l>0&&(r===$.CENTER||r===$.LEFT),q,K,J,Y,j;if(O&&B&&(S.push(p+m,_+g,0),S.push(-u+m,_+g,0),S.push(-u+m,_+d+g,0),S.push(p+m,_+d+g,0),I.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,K=1-l/t,J=1-d/i,Y=1,j=1,q=[K,J,Y,J,Y,j,K,j],e===$.ROTATE_ROW&&(q=[1-K,1-J,1-Y,1-J,1-Y,1-j,1-K,1-j]),e===$.FLIP_ROW&&(q=[1-K,J,1-Y,J,1-Y,j,1-K,j]),e===$.FLIP_N_ROTATE_ROW&&(q=[K,1-J,Y,1-J,Y,1-j,K,1-j]),R=R.concat(q),M.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),O&&V&&(S.push(u+m,_+g,0),S.push(v+m,_+g,0),S.push(v+m,_+d+g,0),S.push(u+m,_+d+g,0),I.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,K=0,J=1-d/i,Y=l/t,j=1,q=[K,J,Y,J,Y,j,K,j],(e===$.ROTATE_ROW||e===$.ROTATE_TILE&&o%2===0)&&(q=[1-K,1-J,1-Y,1-J,1-Y,1-j,1-K,1-j]),(e===$.FLIP_ROW||e===$.FLIP_TILE&&o%2===0)&&(q=[1-K,J,1-Y,J,1-Y,j,1-K,j]),(e===$.FLIP_N_ROTATE_ROW||e===$.FLIP_N_ROTATE_TILE&&o%2===0)&&(q=[K,1-J,Y,1-J,Y,1-j,K,1-j]),R=R.concat(q),M.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),N&&B&&(S.push(p+m,h+g,0),S.push(-u+m,h+g,0),S.push(-u+m,E+g,0),S.push(p+m,E+g,0),I.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,K=1-l/t,J=0,Y=1,j=d/i,q=[K,J,Y,J,Y,j,K,j],(e===$.ROTATE_ROW&&f%2===1||e===$.ROTATE_TILE&&f%1===0)&&(q=[1-K,1-J,1-Y,1-J,1-Y,1-j,1-K,1-j]),(e===$.FLIP_ROW&&f%2===1||e===$.FLIP_TILE&&f%2===0)&&(q=[1-K,J,1-Y,J,1-Y,j,1-K,j]),(e===$.FLIP_N_ROTATE_ROW&&f%2===1||e===$.FLIP_N_ROTATE_TILE&&f%2===0)&&(q=[K,1-J,Y,1-J,Y,1-j,K,1-j]),R=R.concat(q),M.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),N&&V&&(S.push(u+m,h+g,0),S.push(v+m,h+g,0),S.push(v+m,E+g,0),S.push(u+m,E+g,0),I.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,K=0,J=0,Y=l/t,j=d/i,q=[K,J,Y,J,Y,j,K,j],(e===$.ROTATE_ROW&&f%2===1||e===$.ROTATE_TILE&&(f+o)%2===1)&&(q=[1-K,1-J,1-Y,1-J,1-Y,1-j,1-K,1-j]),(e===$.FLIP_ROW&&f%2===1||e===$.FLIP_TILE&&(f+o)%2===1)&&(q=[1-K,J,1-Y,J,1-Y,j,1-K,j]),(e===$.FLIP_N_ROTATE_ROW&&f%2===1||e===$.FLIP_N_ROTATE_TILE&&(f+o)%2===1)&&(q=[K,1-J,Y,1-J,Y,1-j,K,1-j]),R=R.concat(q),M.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),O){let ue=[];K=0,J=1-d/i,Y=1,j=1,ue[0]=[K,J,Y,J,Y,j,K,j],ue[1]=[K,J,Y,J,Y,j,K,j],(e===$.ROTATE_TILE||e===$.ROTATE_ROW)&&(ue[1]=[1-K,1-J,1-Y,1-J,1-Y,1-j,1-K,1-j]),(e===$.FLIP_TILE||e===$.FLIP_ROW)&&(ue[1]=[1-K,J,1-Y,J,1-Y,j,1-K,j]),(e===$.FLIP_N_ROTATE_TILE||e===$.FLIP_N_ROTATE_ROW)&&(ue[1]=[K,1-J,Y,1-J,Y,1-j,K,1-j]);for(let Ee=0;Ee<o;Ee++)S.push(-u+Ee*t+m,_+g,0),S.push(-u+(Ee+1)*t+m,_+g,0),S.push(-u+(Ee+1)*t+m,_+d+g,0),S.push(-u+Ee*t+m,_+d+g,0),I.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,e===$.FLIP_TILE||e===$.ROTATE_TILE||e===$.FLIP_N_ROTATE_TILE?R=R.concat(ue[(Ee+1)%2]):e===$.FLIP_ROW||e===$.ROTATE_ROW||e===$.FLIP_N_ROTATE_ROW?R=R.concat(ue[1]):R=R.concat(ue[0]),M.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(N){let ue=[];K=0,J=0,Y=1,j=d/i,ue[0]=[K,J,Y,J,Y,j,K,j],ue[1]=[K,J,Y,J,Y,j,K,j],(e===$.ROTATE_TILE||e===$.ROTATE_ROW)&&(ue[1]=[1-K,1-J,1-Y,1-J,1-Y,1-j,1-K,1-j]),(e===$.FLIP_TILE||e===$.FLIP_ROW)&&(ue[1]=[1-K,J,1-Y,J,1-Y,j,1-K,j]),(e===$.FLIP_N_ROTATE_TILE||e===$.FLIP_N_ROTATE_ROW)&&(ue[1]=[K,1-J,Y,1-J,Y,1-j,K,1-j]);for(let Ee=0;Ee<o;Ee++)S.push(-u+Ee*t+m,E-d+g,0),S.push(-u+(Ee+1)*t+m,E-d+g,0),S.push(-u+(Ee+1)*t+m,E+g,0),S.push(-u+Ee*t+m,E+g,0),I.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,e===$.FLIP_TILE||e===$.ROTATE_TILE||e===$.FLIP_N_ROTATE_TILE?R=R.concat(ue[(Ee+f)%2]):e===$.FLIP_ROW||e===$.ROTATE_ROW||e===$.FLIP_N_ROTATE_ROW?R=R.concat(ue[f%2]):R=R.concat(ue[0]),M.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(B){let ue=[];K=1-l/t,J=0,Y=1,j=1,ue[0]=[K,J,Y,J,Y,j,K,j],ue[1]=[K,J,Y,J,Y,j,K,j],(e===$.ROTATE_TILE||e===$.ROTATE_ROW)&&(ue[1]=[1-K,1-J,1-Y,1-J,1-Y,1-j,1-K,1-j]),(e===$.FLIP_TILE||e===$.FLIP_ROW)&&(ue[1]=[1-K,J,1-Y,J,1-Y,j,1-K,j]),(e===$.FLIP_N_ROTATE_TILE||e===$.FLIP_N_ROTATE_ROW)&&(ue[1]=[K,1-J,Y,1-J,Y,1-j,K,1-j]);for(let Ee=0;Ee<f;Ee++)S.push(p+m,-h+Ee*i+g,0),S.push(p+l+m,-h+Ee*i+g,0),S.push(p+l+m,-h+(Ee+1)*i+g,0),S.push(p+m,-h+(Ee+1)*i+g,0),I.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,e===$.FLIP_TILE||e===$.ROTATE_TILE||e===$.FLIP_N_ROTATE_TILE?R=R.concat(ue[(Ee+1)%2]):e===$.FLIP_ROW||e===$.ROTATE_ROW||e===$.FLIP_N_ROTATE_ROW?R=R.concat(ue[Ee%2]):R=R.concat(ue[0]),M.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(V){let ue=[];K=0,J=0,Y=l/i,j=1,ue[0]=[K,J,Y,J,Y,j,K,j],ue[1]=[K,J,Y,J,Y,j,K,j],(e===$.ROTATE_TILE||e===$.ROTATE_ROW)&&(ue[1]=[1-K,1-J,1-Y,1-J,1-Y,1-j,1-K,1-j]),(e===$.FLIP_TILE||e===$.FLIP_ROW)&&(ue[1]=[1-K,J,1-Y,J,1-Y,j,1-K,j]),(e===$.FLIP_N_ROTATE_TILE||e===$.FLIP_N_ROTATE_ROW)&&(ue[1]=[K,1-J,Y,1-J,Y,1-j,K,1-j]);for(let Ee=0;Ee<f;Ee++)S.push(v-l+m,-h+Ee*i+g,0),S.push(v+m,-h+Ee*i+g,0),S.push(v+m,-h+(Ee+1)*i+g,0),S.push(v-l+m,-h+(Ee+1)*i+g,0),I.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,e===$.FLIP_TILE||e===$.ROTATE_TILE||e===$.FLIP_N_ROTATE_TILE?R=R.concat(ue[(Ee+o)%2]):e===$.FLIP_ROW||e===$.ROTATE_ROW||e===$.FLIP_N_ROTATE_ROW?R=R.concat(ue[Ee%2]):R=R.concat(ue[0]),M.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}}let L=n.sideOrientation===0?0:n.sideOrientation||Ie.DEFAULTSIDE;Ie._ComputeSides(L,S,I,T,R,n.frontUVs,n.backUVs);let w=new Ie;w.indices=I,w.positions=S,w.normals=T,w.uvs=R;let G=L===Ie.DOUBLESIDE?M.concat(M):M;return w.colors=G,w}function E4(n,e,t=null){let i=new $(n,t);return e.sideOrientation=$._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,eg(e).applyToMesh(i,e.updatable),i}var TO=y(()=>{ki();vr();Ie.CreateTiledPlane=eg});function S4(n){let t=n.faceUV||new Array(6),i=n.faceColors,r=n.pattern||$.NO_FLIP,s=n.width||n.size||1,a=n.height||n.size||1,o=n.depth||n.size||1,l=n.tileWidth||n.tileSize||1,c=n.tileHeight||n.tileSize||1,f=n.alignHorizontal||0,d=n.alignVertical||0,u=n.sideOrientation===0?0:n.sideOrientation||Ie.DEFAULTSIDE;for(let O=0;O<6;O++)t[O]===void 0&&(t[O]=new Vi(0,0,1,1)),i&&i[O]===void 0&&(i[O]=new ht(1,1,1,1));let h=s/2,m=a/2,g=o/2,p=[];for(let O=0;O<2;O++)p[O]=eg({pattern:r,tileWidth:l,tileHeight:c,width:s,height:a,alignVertical:d,alignHorizontal:f,sideOrientation:u});for(let O=2;O<4;O++)p[O]=eg({pattern:r,tileWidth:l,tileHeight:c,width:o,height:a,alignVertical:d,alignHorizontal:f,sideOrientation:u});let _=d;d===$.BOTTOM?_=$.TOP:d===$.TOP&&(_=$.BOTTOM);for(let O=4;O<6;O++)p[O]=eg({pattern:r,tileWidth:l,tileHeight:c,width:s,height:o,alignVertical:_,alignHorizontal:f,sideOrientation:u});let v=[],E=[],S=[],T=[],A=[],R=[],M=[],I=[],C,L=0;for(let O=0;O<6;O++){let N=p[O].positions.length;R[O]=[],M[O]=[];for(let B=0;B<N/3;B++)R[O].push(new b(p[O].positions[3*B],p[O].positions[3*B+1],p[O].positions[3*B+2])),M[O].push(new b(p[O].normals[3*B],p[O].normals[3*B+1],p[O].normals[3*B+2]));C=p[O].uvs.length,I[O]=[];for(let B=0;B<C;B+=2)I[O][B]=t[O].x+(t[O].z-t[O].x)*p[O].uvs[B],I[O][B+1]=t[O].y+(t[O].w-t[O].y)*p[O].uvs[B+1],Ot&&(I[O][B+1]=1-I[O][B+1]);if(S=S.concat(I[O]),T=T.concat(p[O].indices.map(B=>B+L)),L+=R[O].length,i){let B=i[O];for(let V=0;V<R[O].length;V++)A.push(B.r,B.g,B.b,B.a)}}let w=[{m:Q.RotationY(Math.PI),t:new b(0,0,g),op:xb},{m:Q.Identity(),t:new b(0,0,g),op:AO},{m:Q.RotationY(-Math.PI/2),t:new b(h,0,0),op:xb},{m:Q.RotationY(Math.PI/2),t:new b(h,0,0),op:AO},{m:Q.RotationX(Math.PI/2),t:new b(0,m,0),op:xb},{m:Q.RotationX(-Math.PI/2),t:new b(0,m,0),op:AO}];for(let O=0;O<6;O++){let{m:N,t:B,op:V}=w[O];for(let q of R[O]){let K=b.TransformCoordinates(q,N),J=V===xb?K.add(B):K.subtract(B);v.push(J.x,J.y,J.z)}for(let q of M[O]){let K=b.TransformNormal(q,N);E.push(K.x,K.y,K.z)}}let G=new Ie;if(G.indices=T,G.positions=v,G.normals=E,G.uvs=S,i){let O=u===Ie.DOUBLESIDE?A.concat(A):A;G.colors=O}return G}function T4(n,e,t=null){let i=new $(n,t);return e.sideOrientation=$._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,S4(e).applyToMesh(i,e.updatable),i}var xb,AO,A4=y(()=>{He();$t();ki();vr();TO();vn();xb=1,AO=-1;Ie.CreateTiledBox=S4});function x4(n){let e=(n.segments||32)|0,t=n.diameterX||n.diameter||1,i=n.diameterY||n.diameter||1,r=n.diameterZ||n.diameter||1,s=n.arc&&(n.arc<=0||n.arc>1)?1:n.arc||1,a=n.slice&&n.slice<=0?1:n.slice||1,o=n.sideOrientation===0?0:n.sideOrientation||Ie.DEFAULTSIDE,l=!!n.dedupTopBottomIndices,c=new b(t/2,i/2,r/2),f=2+e,d=2*f,u=[],h=[],m=[],g=[];for(let _=0;_<=f;_++){let v=_/f,E=v*Math.PI*a;for(let S=0;S<=d;S++){let T=S/d,A=T*Math.PI*2*s,R=Q.RotationZ(-E),M=Q.RotationY(A),I=b.TransformCoordinates(b.Up(),R),C=b.TransformCoordinates(I,M),L=C.multiply(c),w=C.divide(c).normalize();h.push(L.x,L.y,L.z),m.push(w.x,w.y,w.z),g.push(T,Ot?1-v:v)}if(_>0){let S=h.length/3;for(let T=S-2*(d+1);T+d+2<S;T++)l?(_>1&&(u.push(T),u.push(T+1),u.push(T+d+1)),(_<f||a<1)&&(u.push(T+d+1),u.push(T+1),u.push(T+d+2))):(u.push(T),u.push(T+1),u.push(T+d+1),u.push(T+d+1),u.push(T+1),u.push(T+d+2))}}Ie._ComputeSides(o,h,u,m,g,n.frontUVs,n.backUVs);let p=new Ie;return p.indices=u,p.positions=h,p.normals=m,p.uvs=g,p}function xO(n,e={},t=null){let i=new $(n,t);return e.sideOrientation=$._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,x4(e).applyToMesh(i,e.updatable),i}var R4=y(()=>{He();ki();vr();vn();Ie.CreateSphere=x4;$.CreateSphere=(n,e,t,i,r,s)=>xO(n,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:s,updatable:r},i)});function b4(n){let e=n.height||2,t=n.diameterTop===0?0:n.diameterTop||n.diameter||1,i=n.diameterBottom===0?0:n.diameterBottom||n.diameter||1;t=t||1e-5,i=i||1e-5;let r=(n.tessellation||24)|0,s=(n.subdivisions||1)|0,a=!!n.hasRings,o=!!n.enclose,l=n.cap===0?0:n.cap||$.CAP_ALL,c=n.arc&&(n.arc<=0||n.arc>1)?1:n.arc||1,f=n.sideOrientation===0?0:n.sideOrientation||Ie.DEFAULTSIDE,d=n.faceUV||new Array(3),u=n.faceColors,h=c!==1&&o?2:0,m=a?s:1,g=2+(1+h)*m,p;for(p=0;p<g;p++)u&&u[p]===void 0&&(u[p]=new ht(1,1,1,1));for(p=0;p<g;p++)d&&d[p]===void 0&&(d[p]=new Vi(0,0,1,1));let _=[],v=[],E=[],S=[],T=[],A=Math.PI*2*c/r,R,M,I,C=(i-t)/2/e,L=b.Zero(),w=b.Zero(),G=b.Zero(),O=b.Zero(),N=b.Zero(),B=ta.Y,V,q,K,J,Y=1,j=0,ue;for(V=0;V<=s;V++)for(M=V/s,I=(M*(t-i)+i)/2,J=a&&V!==0&&V!==s?2:1,K=0;K<J;K++){for(a&&(Y+=K),o&&(Y+=2*K),q=0;q<=r;q++)R=q*A,L.x=Math.cos(-R)*I,L.y=-e/2+M*e,L.z=Math.sin(-R)*I,t===0&&V===s?(w.x=E[E.length-(r+1)*3],w.y=E[E.length-(r+1)*3+1],w.z=E[E.length-(r+1)*3+2]):(w.x=L.x,w.z=L.z,w.y=Math.sqrt(w.x*w.x+w.z*w.z)*C,w.normalize()),q===0&&(G.copyFrom(L),O.copyFrom(w)),v.push(L.x,L.y,L.z),E.push(w.x,w.y,w.z),a?ue=j!==Y?d[Y].y:d[Y].w:ue=d[Y].y+(d[Y].w-d[Y].y)*M,S.push(d[Y].x+(d[Y].z-d[Y].x)*q/r,Ot?1-ue:ue),u&&T.push(u[Y].r,u[Y].g,u[Y].b,u[Y].a);c!==1&&o&&(v.push(L.x,L.y,L.z),v.push(0,L.y,0),v.push(0,L.y,0),v.push(G.x,G.y,G.z),b.CrossToRef(B,w,N),N.normalize(),E.push(N.x,N.y,N.z,N.x,N.y,N.z),b.CrossToRef(O,B,N),N.normalize(),E.push(N.x,N.y,N.z,N.x,N.y,N.z),a?ue=j!==Y?d[Y+1].y:d[Y+1].w:ue=d[Y+1].y+(d[Y+1].w-d[Y+1].y)*M,S.push(d[Y+1].x,Ot?1-ue:ue),S.push(d[Y+1].z,Ot?1-ue:ue),a?ue=j!==Y?d[Y+2].y:d[Y+2].w:ue=d[Y+2].y+(d[Y+2].w-d[Y+2].y)*M,S.push(d[Y+2].x,Ot?1-ue:ue),S.push(d[Y+2].z,Ot?1-ue:ue),u&&(T.push(u[Y+1].r,u[Y+1].g,u[Y+1].b,u[Y+1].a),T.push(u[Y+1].r,u[Y+1].g,u[Y+1].b,u[Y+1].a),T.push(u[Y+2].r,u[Y+2].g,u[Y+2].b,u[Y+2].a),T.push(u[Y+2].r,u[Y+2].g,u[Y+2].b,u[Y+2].a))),j!==Y&&(j=Y)}let Ee=c!==1&&o?r+4:r;for(V=0,Y=0;Y<s;Y++){let ve=0,ne=0,me=0,Le=0;for(q=0;q<r;q++)ve=V*(Ee+1)+q,ne=(V+1)*(Ee+1)+q,me=V*(Ee+1)+(q+1),Le=(V+1)*(Ee+1)+(q+1),_.push(ve,ne,me),_.push(Le,me,ne);c!==1&&o&&(_.push(ve+2,ne+2,me+2),_.push(Le+2,me+2,ne+2),_.push(ve+4,ne+4,me+4),_.push(Le+4,me+4,ne+4)),V=a?V+2:V+1}let Ue=ve=>{let ne=ve?t/2:i/2;if(ne===0)return;let me,Le,de,be=ve?d[g-1]:d[0],we=null;u&&(we=ve?u[g-1]:u[0]);let dt=v.length/3,Ve=ve?e/2:-e/2,Ze=new b(0,Ve,0);v.push(Ze.x,Ze.y,Ze.z),E.push(0,ve?1:-1,0);let Kt=be.y+(be.w-be.y)*.5;S.push(be.x+(be.z-be.x)*.5,Ot?1-Kt:Kt),we&&T.push(we.r,we.g,we.b,we.a);let Bt=new Fe(.5,.5);for(de=0;de<=r;de++){me=Math.PI*2*de*c/r;let wi=Math.cos(-me),ae=Math.sin(-me);Le=new b(wi*ne,Ve,ae*ne);let Ti=new Fe(wi*Bt.x+.5,ae*Bt.y+.5);v.push(Le.x,Le.y,Le.z),E.push(0,ve?1:-1,0);let hi=be.y+(be.w-be.y)*Ti.y;S.push(be.x+(be.z-be.x)*Ti.x,Ot?1-hi:hi),we&&T.push(we.r,we.g,we.b,we.a)}for(de=0;de<r;de++)ve?(_.push(dt),_.push(dt+(de+2)),_.push(dt+(de+1))):(_.push(dt),_.push(dt+(de+1)),_.push(dt+(de+2)))};(l===$.CAP_START||l===$.CAP_ALL)&&Ue(!1),(l===$.CAP_END||l===$.CAP_ALL)&&Ue(!0),Ie._ComputeSides(f,v,_,E,S,n.frontUVs,n.backUVs);let se=new Ie;return se.indices=_,se.positions=v,se.normals=E,se.uvs=S,u&&(se.colors=T),se}function RO(n,e={},t){let i=new $(n,t);return e.sideOrientation=$._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,b4(e).applyToMesh(i,e.updatable),i}var M4=y(()=>{He();$t();ki();vr();na();sp();vn();Ie.CreateCylinder=b4;$.CreateCylinder=(n,e,t,i,r,s,a,o,l)=>((a===void 0||!(a instanceof ai))&&(a!==void 0&&(l=o||$.DEFAULTSIDE,o=a),a=s,s=1),RO(n,{height:e,diameterTop:t,diameterBottom:i,tessellation:r,subdivisions:s,sideOrientation:l,updatable:o},a))});function y4(n){let e=[],t=[],i=[],r=[],s=n.diameter||1,a=n.thickness||.5,o=(n.tessellation||16)|0,l=n.sideOrientation===0?0:n.sideOrientation||Ie.DEFAULTSIDE,c=o+1;for(let d=0;d<=o;d++){let u=d/o,h=d*Math.PI*2/o-Math.PI/2,m=Q.Translation(s/2,0,0).multiply(Q.RotationY(h));for(let g=0;g<=o;g++){let p=1-g/o,_=g*Math.PI*2/o+Math.PI,v=Math.cos(_),E=Math.sin(_),S=new b(v,E,0),T=S.scale(a/2),A=new Fe(u,p);T=b.TransformCoordinates(T,m),S=b.TransformNormal(S,m),t.push(T.x,T.y,T.z),i.push(S.x,S.y,S.z),r.push(A.x,Ot?1-A.y:A.y);let R=(d+1)%c,M=(g+1)%c;e.push(d*c+g),e.push(d*c+M),e.push(R*c+g),e.push(d*c+M),e.push(R*c+M),e.push(R*c+g)}}Ie._ComputeSides(l,t,e,i,r,n.frontUVs,n.backUVs);let f=new Ie;return f.indices=e,f.positions=t,f.normals=i,f.uvs=r,f}function bO(n,e={},t){let i=new $(n,t);return e.sideOrientation=$._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,y4(e).applyToMesh(i,e.updatable),i}var I4=y(()=>{He();ki();vr();vn();Ie.CreateTorus=y4;$.CreateTorus=(n,e,t,i,r,s,a)=>bO(n,{diameter:e,thickness:t,tessellation:i,sideOrientation:a,updatable:s},r)});function C4(n){let e=[],t=[],i=[],r=[],s=n.radius||2,a=n.tube||.5,o=n.radialSegments||32,l=n.tubularSegments||32,c=n.p||2,f=n.q||3,d=n.sideOrientation===0?0:n.sideOrientation||Ie.DEFAULTSIDE,u=p=>{let _=Math.cos(p),v=Math.sin(p),E=f/c*p,S=Math.cos(E),T=s*(2+S)*.5*_,A=s*(2+S)*v*.5,R=s*Math.sin(E)*.5;return new b(T,A,R)},h,m;for(h=0;h<=o;h++){let _=h%o/o*2*c*Math.PI,v=u(_),E=u(_+.01),S=E.subtract(v),T=E.add(v),A=b.Cross(S,T);for(T=b.Cross(A,S),A.normalize(),T.normalize(),m=0;m<l;m++){let M=m%l/l*2*Math.PI,I=-a*Math.cos(M),C=a*Math.sin(M);t.push(v.x+I*T.x+C*A.x),t.push(v.y+I*T.y+C*A.y),t.push(v.z+I*T.z+C*A.z),r.push(h/o),r.push(Ot?1-m/l:m/l)}}for(h=0;h<o;h++)for(m=0;m<l;m++){let p=(m+1)%l,_=h*l+m,v=(h+1)*l+m,E=(h+1)*l+p,S=h*l+p;e.push(S),e.push(v),e.push(_),e.push(S),e.push(E),e.push(v)}Ie.ComputeNormals(t,e,i),Ie._ComputeSides(d,t,e,i,r,n.frontUVs,n.backUVs);let g=new Ie;return g.indices=e,g.positions=t,g.normals=i,g.uvs=r,g}function MO(n,e={},t){let i=new $(n,t);return e.sideOrientation=$._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,C4(e).applyToMesh(i,e.updatable),i}var P4=y(()=>{He();ki();vr();vn();Ie.CreateTorusKnot=C4;$.CreateTorusKnot=(n,e,t,i,r,s,a,o,l,c)=>MO(n,{radius:e,tube:t,radialSegments:i,tubularSegments:r,p:s,q:a,sideOrientation:c,updatable:l},o)});var zc,yO=y(()=>{He();wt();Pp();ki();bv();cd();qi();Gi();ir();$._instancedMeshFactory=(n,e)=>{let t=new zc(n,e);if(e.instancedBuffers){t.instancedBuffers={};for(let i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};zc=class extends Ir{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(let i of t.getAnimationRanges())i!=null&&this.createAnimationRange(i.name,i.from,i.to);if(this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),!t.skeleton&&!t.morphTargetManager&&t.hasBoundingInfo){let i=t.getBoundingInfo();this.buildBoundingInfo(i.minimum,i.maximum)}else this.refreshBoundingInfo(!0,!0);this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){var t;((t=this._sourceMesh)==null?void 0:t.receiveShadows)!==e&&pe.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;((t=this._sourceMesh)==null?void 0:t.material)!==e&&pe.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;((t=this._sourceMesh)==null?void 0:t.visibility)!==e&&pe.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;((t=this._sourceMesh)==null?void 0:t.skeleton)!==e&&pe.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){!this._sourceMesh||e===this._sourceMesh.renderingGroupId||te.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}get geometry(){return this._sourceMesh._geometry}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}copyVerticesData(e,t){this._sourceMesh.copyVerticesData(e,t)}getVertexBuffer(e,t){return this._sourceMesh.getVertexBuffer(e,t)}setVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i;typeof e=="object"?i=e:i={applySkeleton:e,applyMorph:t};let r=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getData(i,null,D.PositionKind),r),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||te.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD!==this._sourceMesh&&this._currentLOD.billboardMode!==ii.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new Q);let e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,ee.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(ee.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;let t=this.sourceMesh.getLODLevels();if(!t||t.length===0)this._currentLOD=this.sourceMesh;else{let i=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,i.boundingSphere)}return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh);return this}_generatePointsArray(){return this._sourceMesh._generatePointsArray()}_updateBoundingInfo(){return this.hasBoundingInfo?this.getBoundingInfo().update(this.worldMatrixFromCache):this.buildBoundingInfo(this.absolutePosition,this.absolutePosition,this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}clone(e,t=null,i,r){let s=(r||this._sourceMesh).createInstance(e);if(Ul.DeepCopy(this,s,["name","subMeshes","uniqueId","parent","lightSources","receiveShadows","material","visibility","skeleton","sourceMesh","isAnInstance","facetNb","isFacetDataEnabled","isBlocked","useBones","hasInstances","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","hasBoundingInfo","geometry"],[]),t&&(s.parent=t),!i)for(let a=0;a<this.getScene().meshes.length;a++){let o=this.getScene().meshes[a];o.parent===this&&o.clone(o.name,s)}return s.computeWorldMatrix(!0),this.onClonedObservable.notifyObservers(s),s}dispose(e,t=!1){this._sourceMesh.removeInstance(this),super.dispose(e,t)}_serializeAsParent(e){super._serializeAsParent(e),e.parentId=this._sourceMesh.uniqueId,e.parentInstanceIndex=this._indexInSourceMeshInstanceArray}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0,t&&t.newSourcedMesh);r&&i&&i(this,r);for(let s of this.getChildTransformNodes(!0))s.instantiateHierarchy(r,t,i);return r}};$.prototype.registerInstancedBuffer=function(n,e){var t,i,r,s;if((i=(t=this._userInstancedBuffersStorage)==null?void 0:t.vertexBuffers[n])==null||i.dispose(),(r=this._userInstancedBuffersStorage)!=null&&r.renderPasses)for(let a in this._userInstancedBuffersStorage.renderPasses){let o=this._userInstancedBuffersStorage.renderPasses[a];(s=o[n])==null||s.dispose(),delete o[n]}if(!this.instancedBuffers){this.instancedBuffers={};for(let a of this.instances)a.instancedBuffers={}}this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this.instancedBuffers[n]=null,this._userInstancedBuffersStorage.strides[n]=e,this._userInstancedBuffersStorage.sizes[n]=e*32,this._userInstancedBuffersStorage.data[n]=new Float32Array(this._userInstancedBuffersStorage.sizes[n]),this._userInstancedBuffersStorage.vertexBuffers[n]=this._instanceDataStorage.useMonoDataStorageRenderPass?new D(this.getEngine(),this._userInstancedBuffersStorage.data[n],n,!0,!1,e,!0):null;for(let a of this.instances)a.instancedBuffers[n]=null;this._invalidateInstanceVertexArrayObject(),this._markSubMeshesAsAttributesDirty()};$.prototype._processInstancedBuffers=function(n,e){var s,a;let t=n?n.length:0,i=!this._instanceDataStorage.useMonoDataStorageRenderPass,r;if(i){let o=this._instanceDataStorage.engine.currentRenderPassId;this._userInstancedBuffersStorage.renderPasses||(this._userInstancedBuffersStorage.renderPasses={}),this._userInstancedBuffersStorage.renderPasses[o]||(this._userInstancedBuffersStorage.renderPasses[o]={}),r=this._userInstancedBuffersStorage.renderPasses[o]}for(let o in this.instancedBuffers){let l=this._userInstancedBuffersStorage.sizes[o],c=this._userInstancedBuffersStorage.strides[o],f=(t+1)*c;for(;l<f;)l*=2;this._userInstancedBuffersStorage.data[o].length!=l&&(this._userInstancedBuffersStorage.data[o]=new Float32Array(l),this._userInstancedBuffersStorage.sizes[o]=l,i?r[o]&&(r[o].dispose(),r[o]=null):this._userInstancedBuffersStorage.vertexBuffers[o]&&(this._userInstancedBuffersStorage.vertexBuffers[o].dispose(),this._userInstancedBuffersStorage.vertexBuffers[o]=null));let d=this._userInstancedBuffersStorage.data[o],u=0;if(e){let h=(s=this.instancedBuffers[o])!=null?s:0;h.toArray?h.toArray(d,u):h.copyToArray?h.copyToArray(d,u):d[u]=h,u+=c}for(let h=0;h<t;h++){let g=(a=n[h].instancedBuffers[o])!=null?a:0;g.toArray?g.toArray(d,u):g.copyToArray?g.copyToArray(d,u):d[u]=g,u+=c}i?r[o]?r[o].updateDirectly(d,0):(r[o]=new D(this.getEngine(),this._userInstancedBuffersStorage.data[o],o,!0,!1,c,!0),this._invalidateInstanceVertexArrayObject()):this._userInstancedBuffersStorage.vertexBuffers[o]?this._userInstancedBuffersStorage.vertexBuffers[o].updateDirectly(d,0):(this._userInstancedBuffersStorage.vertexBuffers[o]=new D(this.getEngine(),this._userInstancedBuffersStorage.data[o],o,!0,!1,c,!0),this._invalidateInstanceVertexArrayObject())}};$.prototype._invalidateInstanceVertexArrayObject=function(){if(!(!this._userInstancedBuffersStorage||this._userInstancedBuffersStorage.vertexArrayObjects===void 0)){for(let n in this._userInstancedBuffersStorage.vertexArrayObjects)this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[n]);this._userInstancedBuffersStorage.vertexArrayObjects={}}};$.prototype._disposeInstanceSpecificData=function(){var n,e,t;for(let i in this._instanceDataStorage.renderPasses)(n=this._instanceDataStorage.renderPasses[i].instancesBuffer)==null||n.dispose();for(this._instanceDataStorage.renderPasses={},(t=(e=this._instanceDataStorage.dataStorageRenderPass)==null?void 0:e.instancesBuffer)==null||t.dispose();this.instances.length;)this.instances[0].dispose();for(let i in this.instancedBuffers)this._userInstancedBuffersStorage.vertexBuffers[i]&&this._userInstancedBuffersStorage.vertexBuffers[i].dispose();this._invalidateInstanceVertexArrayObject(),this.instancedBuffers={}};zt("BABYLON.InstancedMesh",zc)});var ds,Td=y(()=>{ds=class{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;let i=this._mesh.getScene();for(let r=0;r<i.meshes.length;r++){let s=i.meshes[r];if(!s.material){!this._mesh.material&&s.computeBonesUsingShaders&&s.numBoneInfluencers>0&&(s.computeBonesUsingShaders=!1);continue}if(!(!s.computeBonesUsingShaders||s.numBoneInfluencers===0)){if(s.material.getEffect()===t)s.computeBonesUsingShaders=!1;else if(s.subMeshes){for(let a of s.subMeshes)if(a.effect===t){s.computeBonesUsingShaders=!1;break}}}}}else{let i=this._defines[this._currentRank];if(i)for(let r=0;r<i.length;r++)e=e.replace("#define "+i[r],"");this._currentRank++}return e}}});var jl,$v=y(()=>{He();ls();jl=class extends Ae{constructor(e,t,i=!0,r=!1){super(e,t,void 0,r),this._normalMatrix=new Q,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return e?!this._storeEffectOnSubMeshes||!e.subMeshes||e.subMeshes.length===0?!0:this.isReadyForSubMesh(e,e.subMeshes[0],t):!1}_isReadyForSubMesh(e){let t=e.materialDefines;return!!(!this.checkReadyOnEveryCall&&e.effect&&t&&t._renderId===this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,r=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,r)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}});function Ad(n){let e=n.getVertexBuffers();if(!e)return null;let t=L4.get(n);if(!t)t=new Map,L4.set(n,t);else{let i=!1;for(let r in e)if(!t.has(r)){i=!0;break}if(!i)return t}for(let i in e){let r=e[i];if(r){let s=r.byteOffset,a=r.byteStride,o=r.type,l=r.normalized;t.set(i,{offset:s,stride:a,type:o,normalized:l})}}return t}function xd(n,e){e.forEach((t,i)=>{let r=`vp_${i}_info`;n.setFloat4(r,t.offset,t.stride,t.type,t.normalized?1:0)})}var L4,Jv=y(()=>{L4=new WeakMap});var IO,tl,CO=y(()=>{Or();na();He();qi();Kr();ir();Td();Wu();$v();Yi();Hl();os();Jv();IO={effect:null,subMesh:null},tl=class n extends jl{constructor(e,t,i,r={},s=!0){super(e,t,s),this._textures={},this._internalTextures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new Q,this._cachedWorldViewProjectionMatrix=new Q,this._multiview=!1,this._vertexPullingMetadata=null,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...r}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){this._options.uniforms.indexOf(e)===-1&&this._options.uniforms.push(e)}setTexture(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._textures[e]=t,this}setInternalTexture(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._internalTextures[e]=t,this}removeTexture(e){delete this._textures[e]}setTextureArray(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return this._options.externalTextures.indexOf(e)===-1&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((i,r)=>(i.push(r.r,r.g,r.b),i),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((i,r)=>(i.push(r.r,r.g,r.b,r.a),i),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((i,r)=>(r.toArray(i,i.length),i),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);let i=new Float32Array(t.length*16);for(let r=0;r<t.length;r++)t[r].copyToArray(i,r*16);return this._matrixArrays[e]=i,this}setMatrix3x3(e,t){return this._checkUniform(e),this._matrices3x3[e]=t,this}setMatrix2x2(e,t){return this._checkUniform(e),this._matrices2x2[e]=t,this}setArray2(e,t){return this._checkUniform(e),this._vectors2Arrays[e]=t,this}setArray3(e,t){return this._checkUniform(e),this._vectors3Arrays[e]=t,this}setArray4(e,t){return this._checkUniform(e),this._vectors4Arrays[e]=t,this}setUniformBuffer(e,t){return this._options.uniformBuffers.indexOf(e)===-1&&this._options.uniformBuffers.push(e),this._uniformBuffers[e]=t,this}setTextureSampler(e,t){return this._options.samplerObjects.indexOf(e)===-1&&this._options.samplerObjects.push(e),this._textureSamplers[e]=t,this}setStorageBuffer(e,t){return this._options.storageBuffers.indexOf(e)===-1&&this._options.storageBuffers.push(e),this._storageBuffers[e]=t,this}setDefine(e,t){let i=e.trimEnd()+" ",r=this.options.defines.findIndex(s=>s===e||s.startsWith(i));return r>=0&&this.options.defines.splice(r,1),(typeof t!="boolean"||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var A,R,M,I;let r=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){let C=r?i._drawWrapper:this._drawWrapper;if(C.effect&&C._wasPreviouslyReady&&C._wasPreviouslyUsingInstances===t)return!0}let s=this.getScene(),a=s.getEngine(),o=[],l=[],c=null,f=this._shaderPath,d=this._options.uniforms,u=this._options.uniformBuffers,h=this._options.samplers;a.getCaps().multiview&&s.activeCamera&&s.activeCamera.outputRenderTarget&&s.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),d.indexOf("viewProjection")!==-1&&d.indexOf("viewProjectionR")===-1&&d.push("viewProjectionR"));for(let C=0;C<this._options.defines.length;C++){let L=this._options.defines[C].indexOf("#define")===0?this._options.defines[C]:`#define ${this._options.defines[C]}`;o.push(L)}for(let C=0;C<this._options.attributes.length;C++)l.push(this._options.attributes[C]);if(e&&e.isVerticesDataPresent(D.ColorKind)&&(l.indexOf(D.ColorKind)===-1&&l.push(D.ColorKind),o.push("#define VERTEXCOLOR")),t&&(o.push("#define INSTANCES"),Qo(l,this._materialHelperNeedsPreviousMatrices),e!=null&&e.hasThinInstances&&(o.push("#define THIN_INSTANCES"),e&&e.isVerticesDataPresent(D.ColorInstanceKind)&&(l.push(D.ColorInstanceKind),o.push("#define INSTANCESCOLOR")))),e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton){l.push(D.MatricesIndicesKind),l.push(D.MatricesWeightsKind),e.numBoneInfluencers>4&&(l.push(D.MatricesIndicesExtraKind),l.push(D.MatricesWeightsExtraKind));let C=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),c=new ds,c.addCPUSkinningFallback(0,e),C.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),d.indexOf("boneTextureInfo")===-1&&d.push("boneTextureInfo"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(C.bones.length+1)),d.indexOf("mBones")===-1&&d.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let m=0,g=e?e.morphTargetManager:null;if(g){let C=o.indexOf("#define UV1")!==-1,L=o.indexOf("#define UV2")!==-1,w=o.indexOf("#define TANGENT")!==-1,G=o.indexOf("#define NORMAL")!==-1,O=o.indexOf("#define VERTEXCOLOR")!==-1;m=Xl(g,o,l,e,!0,G,w,C,L,O),g.isUsingTextureForTargets&&(d.indexOf("morphTargetTextureIndices")===-1&&d.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),m>0&&(d=d.slice(),d.push("morphTargetInfluences"),d.push("morphTargetCount"),d.push("morphTargetTextureInfo"),d.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){let C=e.bakedVertexAnimationManager;C&&C.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),d.indexOf("bakedVertexAnimationSettings")===-1&&d.push("bakedVertexAnimationSettings"),d.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&d.push("bakedVertexAnimationTextureSizeInverted"),d.indexOf("bakedVertexAnimationTime")===-1&&d.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture"),t&&l.push("bakedVertexAnimationSettingsInstanced"))}for(let C in this._textures)if(!this._textures[C].isReady())return!1;for(let C in this._internalTextures)if(!this._internalTextures[C].isReady)return!1;e&&this.needAlphaTestingForMesh(e)&&o.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(ns(d),Wl(this,s,o)),s.fogEnabled&&(e!=null&&e.applyFog)&&s.fogMode!==ai.FOGMODE_NONE&&(o.push("#define FOG"),d.indexOf("view")===-1&&d.push("view"),d.indexOf("vFogInfos")===-1&&d.push("vFogInfos"),d.indexOf("vFogColor")===-1&&d.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),d.indexOf("logarithmicDepthConstant")===-1&&d.push("logarithmicDepthConstant"));let p=i?i.getRenderingMesh():e;if(p&&this.useVertexPulling){let C=p.geometry;C&&(this._vertexPullingMetadata=Ad(C),this._vertexPullingMetadata&&this._vertexPullingMetadata.forEach((w,G)=>{d.push(`vp_${G}_info`)})),o.push("#define USE_VERTEX_PULLING");let L=(A=p.geometry)==null?void 0:A.getIndexBuffer();L&&!p.isUnIndexed&&(o.push("#define VERTEX_PULLING_USE_INDEX_BUFFER"),L.is32Bits&&o.push("#define VERTEX_PULLING_INDEX_BUFFER_32BITS"))}this.customShaderNameResolve&&(d=d.slice(),u=u.slice(),h=h.slice(),f=this.customShaderNameResolve(this.name,d,u,h,o,l));let _=r?i._getDrawWrapper(void 0,!0):this._drawWrapper,v=(R=_==null?void 0:_.effect)!=null?R:null,E=(M=_==null?void 0:_.defines)!=null?M:null,S=o.join(`
`),T=v;return E!==S&&(T=a.createEffect(f,{attributes:l,uniformsNames:d,uniformBuffersNames:u,samplers:h,defines:S,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:m},shaderLanguage:this._options.shaderLanguage,extraInitializationsAsync:this._options.extraInitializationsAsync},a),r?i.setEffect(T,S,this._materialContext):_&&_.setEffect(T,S),this._onEffectCreatedObservable&&(IO.effect=T,IO.subMesh=(I=i!=null?i:e==null?void 0:e.subMeshes[0])!=null?I:null,this._onEffectCreatedObservable.notifyObservers(IO))),_._wasPreviouslyUsingInstances=!!t,T!=null&&T.isReady()?(v!==T&&s.resetCachedMaterial(),_._wasPreviouslyReady=!0,!0):!1}bindOnlyWorldMatrix(e,t){let i=t!=null?t:this.getEffect();if(!i)return;let r=this._options.uniforms;r.indexOf("world")!==-1&&i.setMatrix("world",e);let s=this.getScene();r.indexOf("worldView")!==-1&&(e.multiplyToRef(s.getViewMatrix(),this._cachedWorldViewMatrix),i.setMatrix("worldView",this._cachedWorldViewMatrix)),r.indexOf("worldViewProjection")!==-1&&(e.multiplyToRef(s.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),i.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),r.indexOf("view")!==-1&&i.setMatrix("view",s.getViewMatrix())}bindForSubMesh(e,t,i){var r;this.bind(e,t,(r=i._drawWrapperOverride)==null?void 0:r.effect,i)}bind(e,t,i,r){var d;let s=r&&this._storeEffectOnSubMeshes,a=i!=null?i:s?r.effect:this.getEffect();if(!a)return;let o=this.getScene();this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);let l=this._options.uniformBuffers,c=!1;if(a&&l&&l.length>0&&o.getEngine().supportsUniformBuffers)for(let u=0;u<l.length;++u)switch(l[u]){case"Mesh":t&&(t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e));break;case"Scene":ud(a,o.getSceneUniformBuffer()),o.finalizeSceneUbo(),c=!0;break}let f=t&&s?this._mustRebind(o,a,r,t.visibility):o.getCachedMaterial()!==this;if(a&&f){!c&&this._options.uniforms.indexOf("view")!==-1&&a.setMatrix("view",o.getViewMatrix()),!c&&this._options.uniforms.indexOf("projection")!==-1&&a.setMatrix("projection",o.getProjectionMatrix()),!c&&this._options.uniforms.indexOf("viewProjection")!==-1&&(a.setMatrix("viewProjection",o.getTransformMatrix()),this._multiview&&a.setMatrix("viewProjectionR",o._transformMatrixR)),o.activeCamera&&this._options.uniforms.indexOf("cameraPosition")!==-1&&a.setVector3("cameraPosition",o.activeCamera.globalPosition),aa(t,a),ss(a,this,o),this._vertexPullingMetadata&&xd(a,this._vertexPullingMetadata),this._useLogarithmicDepth&&fd(s?r.materialDefines:a.defines,a,o),t&&dd(o,t,a);let u;for(u in this._textures)a.setTexture(u,this._textures[u]);for(u in this._internalTextures)a._bindTexture(u,this._internalTextures[u]);for(u in this._textureArrays)a.setTextureArray(u,this._textureArrays[u]);for(u in this._ints)a.setInt(u,this._ints[u]);for(u in this._uints)a.setUInt(u,this._uints[u]);for(u in this._floats)a.setFloat(u,this._floats[u]);for(u in this._floatsArrays)a.setArray(u,this._floatsArrays[u]);for(u in this._colors3)a.setColor3(u,this._colors3[u]);for(u in this._colors3Arrays)a.setArray3(u,this._colors3Arrays[u]);for(u in this._colors4){let _=this._colors4[u];a.setFloat4(u,_.r,_.g,_.b,_.a)}for(u in this._colors4Arrays)a.setArray4(u,this._colors4Arrays[u]);for(u in this._vectors2)a.setVector2(u,this._vectors2[u]);for(u in this._vectors3)a.setVector3(u,this._vectors3[u]);for(u in this._vectors4)a.setVector4(u,this._vectors4[u]);for(u in this._quaternions)a.setQuaternion(u,this._quaternions[u]);for(u in this._matrices)a.setMatrix(u,this._matrices[u]);for(u in this._matrixArrays)a.setMatrices(u,this._matrixArrays[u]);for(u in this._matrices3x3)a.setMatrix3x3(u,this._matrices3x3[u]);for(u in this._matrices2x2)a.setMatrix2x2(u,this._matrices2x2[u]);for(u in this._vectors2Arrays)a.setArray2(u,this._vectors2Arrays[u]);for(u in this._vectors3Arrays)a.setArray3(u,this._vectors3Arrays[u]);for(u in this._vectors4Arrays)a.setArray4(u,this._vectors4Arrays[u]);for(u in this._quaternionsArrays)a.setArray4(u,this._quaternionsArrays[u]);for(u in this._uniformBuffers){let _=this._uniformBuffers[u].getBuffer();_&&a.bindUniformBuffer(_,u)}let h=o.getEngine(),m=h.setExternalTexture;if(m)for(u in this._externalTextures)m.call(h,u,this._externalTextures[u]);let g=h.setTextureSampler;if(g)for(u in this._textureSamplers)g.call(h,u,this._textureSamplers[u]);let p=h.setStorageBuffer;if(p)for(u in this._storageBuffers)p.call(h,u,this._storageBuffers[u])}if(a&&t&&(f||!this.isFrozen)){as(t,a),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(a);let u=t.bakedVertexAnimationManager;if(u&&u.isEnabled){let h=s?r._drawWrapper:this._drawWrapper;(d=t.bakedVertexAnimationManager)==null||d.bind(a,!!h._wasPreviouslyUsingInstances)}}this._afterBind(t,a,r)}getActiveTextures(){let e=super.getActiveTextures();for(let t in this._textures)e.push(this._textures[t]);for(let t in this._textureArrays){let i=this._textureArrays[t];for(let r=0;r<i.length;r++)e.push(i[r])}return e}hasTexture(e){if(super.hasTexture(e))return!0;for(let i in this._textures)if(this._textures[i]===e)return!0;let t=e.getInternalTexture();for(let i in this._internalTextures)if(this._internalTextures[i]===t)return!0;for(let i in this._textureArrays){let r=this._textureArrays[i];for(let s=0;s<r.length;s++)if(r[s]===e)return!0}return!1}clone(e){let t=at.Clone(()=>new n(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,typeof t._shaderPath=="object"&&(t._shaderPath={...t._shaderPath}),this._options={...this._options};let i=Object.keys(this._options);for(let r of i){let s=this._options[r];Array.isArray(s)&&(this._options[r]=s.slice(0))}this.stencil.copyTo(t.stencil);for(let r in this._textures)t.setTexture(r,this._textures[r]);for(let r in this._internalTextures)t.setInternalTexture(r,this._internalTextures[r]);for(let r in this._textureArrays)t.setTextureArray(r,this._textureArrays[r]);for(let r in this._externalTextures)t.setExternalTexture(r,this._externalTextures[r]);for(let r in this._ints)t.setInt(r,this._ints[r]);for(let r in this._uints)t.setUInt(r,this._uints[r]);for(let r in this._floats)t.setFloat(r,this._floats[r]);for(let r in this._floatsArrays)t.setFloats(r,this._floatsArrays[r]);for(let r in this._colors3)t.setColor3(r,this._colors3[r]);for(let r in this._colors3Arrays)t._colors3Arrays[r]=this._colors3Arrays[r];for(let r in this._colors4)t.setColor4(r,this._colors4[r]);for(let r in this._colors4Arrays)t._colors4Arrays[r]=this._colors4Arrays[r];for(let r in this._vectors2)t.setVector2(r,this._vectors2[r]);for(let r in this._vectors3)t.setVector3(r,this._vectors3[r]);for(let r in this._vectors4)t.setVector4(r,this._vectors4[r]);for(let r in this._quaternions)t.setQuaternion(r,this._quaternions[r]);for(let r in this._quaternionsArrays)t._quaternionsArrays[r]=this._quaternionsArrays[r];for(let r in this._matrices)t.setMatrix(r,this._matrices[r]);for(let r in this._matrixArrays)t._matrixArrays[r]=this._matrixArrays[r].slice();for(let r in this._matrices3x3)t.setMatrix3x3(r,this._matrices3x3[r]);for(let r in this._matrices2x2)t.setMatrix2x2(r,this._matrices2x2[r]);for(let r in this._vectors2Arrays)t.setArray2(r,this._vectors2Arrays[r]);for(let r in this._vectors3Arrays)t.setArray3(r,this._vectors3Arrays[r]);for(let r in this._vectors4Arrays)t.setArray4(r,this._vectors4Arrays[r]);for(let r in this._uniformBuffers)t.setUniformBuffer(r,this._uniformBuffers[r]);for(let r in this._textureSamplers)t.setTextureSampler(r,this._textureSamplers[r]);for(let r in this._storageBuffers)t.setStorageBuffer(r,this._storageBuffers[r]);return t}dispose(e,t,i){if(t){let r;for(r in this._textures)this._textures[r].dispose();for(r in this._internalTextures)this._internalTextures[r].dispose();for(r in this._textureArrays){let s=this._textureArrays[r];for(let a=0;a<s.length;a++)s[a].dispose()}}this._textures={},this._internalTextures={},super.dispose(e,t,i)}serialize(){let e=at.Serialize(this);e.customType="BABYLON.ShaderMaterial",e.uniqueId=this.uniqueId,e.options=this._options,e.shaderPath=this._shaderPath,e.storeEffectOnSubMeshes=this._storeEffectOnSubMeshes;let t;e.stencil=this.stencil.serialize(),e.textures={};for(t in this._textures)e.textures[t]=this._textures[t].serialize();e.textureArrays={};for(t in this._textureArrays){e.textureArrays[t]=[];let i=this._textureArrays[t];for(let r=0;r<i.length;r++)e.textureArrays[t].push(i[r].serialize())}e.ints={};for(t in this._ints)e.ints[t]=this._ints[t];e.uints={};for(t in this._uints)e.uints[t]=this._uints[t];e.floats={};for(t in this._floats)e.floats[t]=this._floats[t];e.floatsArrays={};for(t in this._floatsArrays)e.floatsArrays[t]=this._floatsArrays[t];e.colors3={};for(t in this._colors3){let i=this._colors3[t];e.colors3[t]=[i.r,i.g,i.b]}e.colors3Arrays={};for(t in this._colors3Arrays)e.colors3Arrays[t]=this._colors3Arrays[t];e.colors4={};for(t in this._colors4){let i=this._colors4[t];e.colors4[t]=[i.r,i.g,i.b,i.a]}e.colors4Arrays={};for(t in this._colors4Arrays)e.colors4Arrays[t]=this._colors4Arrays[t];e.vectors2={};for(t in this._vectors2){let i=this._vectors2[t];e.vectors2[t]=[i.x,i.y]}e.vectors3={};for(t in this._vectors3){let i=this._vectors3[t];e.vectors3[t]=[i.x,i.y,i.z]}e.vectors4={};for(t in this._vectors4){let i=this._vectors4[t];e.vectors4[t]=[i.x,i.y,i.z,i.w]}e.quaternions={};for(t in this._quaternions)e.quaternions[t]=this._quaternions[t].asArray();e.matrices={};for(t in this._matrices)e.matrices[t]=this._matrices[t].asArray();e.matrixArray={};for(t in this._matrixArrays)e.matrixArray[t]=this._matrixArrays[t];e.matrices3x3={};for(t in this._matrices3x3)e.matrices3x3[t]=this._matrices3x3[t];e.matrices2x2={};for(t in this._matrices2x2)e.matrices2x2[t]=this._matrices2x2[t];e.vectors2Arrays={};for(t in this._vectors2Arrays)e.vectors2Arrays[t]=this._vectors2Arrays[t];e.vectors3Arrays={};for(t in this._vectors3Arrays)e.vectors3Arrays[t]=this._vectors3Arrays[t];e.vectors4Arrays={};for(t in this._vectors4Arrays)e.vectors4Arrays[t]=this._vectors4Arrays[t];e.quaternionsArrays={};for(t in this._quaternionsArrays)e.quaternionsArrays[t]=this._quaternionsArrays[t];return e}static Parse(e,t,i){let r=at.Parse(()=>new n(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i),s;e.stencil&&r.stencil.parse(e.stencil,t,i);for(s in e.textures)r.setTexture(s,_e.Parse(e.textures[s],t,i));for(s in e.textureArrays){let a=e.textureArrays[s],o=[];for(let l=0;l<a.length;l++)o.push(_e.Parse(a[l],t,i));r.setTextureArray(s,o)}for(s in e.ints)r.setInt(s,e.ints[s]);for(s in e.uints)r.setUInt(s,e.uints[s]);for(s in e.floats)r.setFloat(s,e.floats[s]);for(s in e.floatsArrays)r.setFloats(s,e.floatsArrays[s]);for(s in e.colors3){let a=e.colors3[s];r.setColor3(s,{r:a[0],g:a[1],b:a[2]})}for(s in e.colors3Arrays){let a=e.colors3Arrays[s].reduce((o,l,c)=>(c%3===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>({r:o[0],g:o[1],b:o[2]}));r.setColor3Array(s,a)}for(s in e.colors4){let a=e.colors4[s];r.setColor4(s,{r:a[0],g:a[1],b:a[2],a:a[3]})}for(s in e.colors4Arrays){let a=e.colors4Arrays[s].reduce((o,l,c)=>(c%4===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>({r:o[0],g:o[1],b:o[2],a:o[3]}));r.setColor4Array(s,a)}for(s in e.vectors2){let a=e.vectors2[s];r.setVector2(s,{x:a[0],y:a[1]})}for(s in e.vectors3){let a=e.vectors3[s];r.setVector3(s,{x:a[0],y:a[1],z:a[2]})}for(s in e.vectors4){let a=e.vectors4[s];r.setVector4(s,{x:a[0],y:a[1],z:a[2],w:a[3]})}for(s in e.quaternions)r.setQuaternion(s,je.FromArray(e.quaternions[s]));for(s in e.matrices)r.setMatrix(s,Q.FromArray(e.matrices[s]));for(s in e.matrixArray)r._matrixArrays[s]=new Float32Array(e.matrixArray[s]);for(s in e.matrices3x3)r.setMatrix3x3(s,e.matrices3x3[s]);for(s in e.matrices2x2)r.setMatrix2x2(s,e.matrices2x2[s]);for(s in e.vectors2Arrays)r.setArray2(s,e.vectors2Arrays[s]);for(s in e.vectors3Arrays)r.setArray3(s,e.vectors3Arrays[s]);for(s in e.vectors4Arrays)r.setArray4(s,e.vectors4Arrays[s]);for(s in e.quaternionsArrays)r.setArray4(s,e.quaternionsArrays[s]);return r}static async ParseFromFileAsync(e,t,i,r=""){return await new Promise((s,a)=>{let o=new Ur;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){let l=JSON.parse(o.responseText),c=this.Parse(l,i||Oe.LastCreatedScene,r);e&&(c.name=e),s(c)}else a("Unable to load the ShaderMaterial")}),o.open("GET",t),o.send()})}static async ParseFromSnippetAsync(e,t,i=""){return await new Promise((r,s)=>{let a=new Ur;a.addEventListener("readystatechange",()=>{if(a.readyState==4)if(a.status==200){let o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.shaderMaterial),c=this.Parse(l,t||Oe.LastCreatedScene,i);c.snippetId=e,r(c)}else s("Unable to load the snippet "+e)}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}};tl.SnippetUrl="https://snippet.babylonjs.com";tl.CreateFromSnippetAsync=tl.ParseFromSnippetAsync;zt("BABYLON.ShaderMaterial",tl)});var D4,Ehe,Wc=y(()=>{k();D4="bonesDeclaration",Ehe=`#if NUM_BONE_INFLUENCERS>0
#ifndef USE_VERTEX_PULLING
attribute matricesIndices : vec4f;attribute matricesWeights : vec4f;
#if NUM_BONE_INFLUENCERS>4
attribute matricesIndicesExtra : vec4f;attribute matricesWeightsExtra : vec4f;
#endif
#endif
#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#ifdef BONETEXTURE
var boneSampler : texture_2d<f32>;uniform boneTextureInfo : vec2f;
#else
uniform mBones : array<mat4x4f,BonesPerMesh>;
#endif
#ifdef BONES_VELOCITY_ENABLED
uniform mPreviousBones : array<mat4x4f,BonesPerMesh>;
#endif
#ifdef BONETEXTURE
fn readMatrixFromRawSampler(smp : texture_2d<f32>,index : f32)->mat4x4f
{let offset=i32(index)*4;
let textureWidth=i32(uniforms.boneTextureInfo.x);let y=offset/textureWidth;let x=offset % textureWidth;let m0=textureLoad(smp,vec2<i32>(x+0,y),0);let m1=textureLoad(smp,vec2<i32>(x+1,y),0);let m2=textureLoad(smp,vec2<i32>(x+2,y),0);let m3=textureLoad(smp,vec2<i32>(x+3,y),0);return mat4x4f(m0,m1,m2,m3);}
#endif
#endif
#endif
`;x.IncludesShadersStoreWGSL[D4]||(x.IncludesShadersStoreWGSL[D4]=Ehe)});var O4,She,Hc=y(()=>{k();O4="bakedVertexAnimationDeclaration",She=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationSettings: vec4<f32>;var bakedVertexAnimationTexture : texture_2d<f32>;
#ifdef INSTANCES
attribute bakedVertexAnimationSettingsInstanced : vec4<f32>;
#endif
fn readMatrixFromRawSamplerVAT(smp : texture_2d<f32>,index : f32,frame : f32)->mat4x4<f32>
{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2<i32>(offset+0,frameUV),0);let m1=textureLoad(smp,vec2<i32>(offset+1,frameUV),0);let m2=textureLoad(smp,vec2<i32>(offset+2,frameUV),0);let m3=textureLoad(smp,vec2<i32>(offset+3,frameUV),0);return mat4x4<f32>(m0,m1,m2,m3);}
#endif
`;x.IncludesShadersStoreWGSL[O4]||(x.IncludesShadersStoreWGSL[O4]=She)});var N4,The,Xc=y(()=>{k();N4="clipPlaneVertexDeclaration",The=`#ifdef CLIPPLANE
uniform vClipPlane: vec4<f32>;varying fClipDistance: f32;
#endif
#ifdef CLIPPLANE2
uniform vClipPlane2: vec4<f32>;varying fClipDistance2: f32;
#endif
#ifdef CLIPPLANE3
uniform vClipPlane3: vec4<f32>;varying fClipDistance3: f32;
#endif
#ifdef CLIPPLANE4
uniform vClipPlane4: vec4<f32>;varying fClipDistance4: f32;
#endif
#ifdef CLIPPLANE5
uniform vClipPlane5: vec4<f32>;varying fClipDistance5: f32;
#endif
#ifdef CLIPPLANE6
uniform vClipPlane6: vec4<f32>;varying fClipDistance6: f32;
#endif
`;x.IncludesShadersStoreWGSL[N4]||(x.IncludesShadersStoreWGSL[N4]=The)});var w4,Ahe,eE=y(()=>{k();w4="fogVertexDeclaration",Ahe=`#ifdef FOG
varying vFogDistance: vec3f;
#endif
`;x.IncludesShadersStoreWGSL[w4]||(x.IncludesShadersStoreWGSL[w4]=Ahe)});var F4,xhe,Rd=y(()=>{k();F4="instancesDeclaration",xhe=`#ifdef INSTANCES
attribute world0 : vec4<f32>;attribute world1 : vec4<f32>;attribute world2 : vec4<f32>;attribute world3 : vec4<f32>;
#ifdef INSTANCESCOLOR
attribute instanceColor : vec4<f32>;
#endif
#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)
uniform world : mat4x4<f32>;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
attribute previousWorld0 : vec4<f32>;attribute previousWorld1 : vec4<f32>;attribute previousWorld2 : vec4<f32>;attribute previousWorld3 : vec4<f32>;
#ifdef THIN_INSTANCES
uniform previousWorld : mat4x4<f32>;
#endif
#endif
#else
#if !defined(WORLD_UBO)
uniform world : mat4x4<f32>;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
uniform previousWorld : mat4x4<f32>;
#endif
#endif
`;x.IncludesShadersStoreWGSL[F4]||(x.IncludesShadersStoreWGSL[F4]=xhe)});var B4,Rhe,Yc=y(()=>{k();B4="instancesVertex",Rhe=`#ifdef INSTANCES
var finalWorld=mat4x4<f32>(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
var finalPreviousWorld=mat4x4<f32>(
vertexInputs.previousWorld0,vertexInputs.previousWorld1,
vertexInputs.previousWorld2,vertexInputs.previousWorld3);
#endif
#ifdef THIN_INSTANCES
#if !defined(WORLD_UBO)
finalWorld=uniforms.world*finalWorld;
#else
finalWorld=mesh.world*finalWorld;
#endif
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
finalPreviousWorld=uniforms.previousWorld*finalPreviousWorld;
#endif
#endif
#else
#if !defined(WORLD_UBO)
var finalWorld=uniforms.world;
#else
var finalWorld=mesh.world;
#endif
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
var finalPreviousWorld=uniforms.previousWorld;
#endif
#endif
`;x.IncludesShadersStoreWGSL[B4]||(x.IncludesShadersStoreWGSL[B4]=Rhe)});var U4,bhe,Kc=y(()=>{k();U4="bonesVertex",bhe=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#if NUM_BONE_INFLUENCERS>0
var influence : mat4x4<f32>;
#ifdef BONETEXTURE
influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];
#endif
#else
influence=uniforms.mBones[i32(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];
#endif
#endif
finalWorld=finalWorld*influence;
#endif
#endif
`;x.IncludesShadersStoreWGSL[U4]||(x.IncludesShadersStoreWGSL[U4]=bhe)});var V4,Mhe,jc=y(()=>{k();V4="bakedVertexAnimation",Mhe=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
{
#ifdef INSTANCES
let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;
#else
let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;
#endif
let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4<f32>;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];
#endif
finalWorld=finalWorld*VATInfluence;}
#endif
`;x.IncludesShadersStoreWGSL[V4]||(x.IncludesShadersStoreWGSL[V4]=Mhe)});var G4,yhe,Zc=y(()=>{k();G4="clipPlaneVertex",yhe=`#ifdef CLIPPLANE
vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);
#endif
#ifdef CLIPPLANE2
vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);
#endif
#ifdef CLIPPLANE3
vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);
#endif
#ifdef CLIPPLANE4
vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);
#endif
#ifdef CLIPPLANE5
vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);
#endif
#ifdef CLIPPLANE6
vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);
#endif
`;x.IncludesShadersStoreWGSL[G4]||(x.IncludesShadersStoreWGSL[G4]=yhe)});var k4,Ihe,tE=y(()=>{k();k4="fogVertex",Ihe=`#ifdef FOG
#ifdef SCENE_UBO
vertexOutputs.vFogDistance=(scene.view*worldPos).xyz;
#else
vertexOutputs.vFogDistance=(uniforms.view*worldPos).xyz;
#endif
#endif
`;x.IncludesShadersStoreWGSL[k4]||(x.IncludesShadersStoreWGSL[k4]=Ihe)});var z4,Che,iE=y(()=>{k();z4="vertexColorMixing",Che=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
vertexOutputs.vColor=vec4f(1.0);
#ifdef VERTEXCOLOR
#ifdef VERTEXALPHA
vertexOutputs.vColor*=colorUpdated;
#else
vertexOutputs.vColor=vec4f(vertexOutputs.vColor.rgb*colorUpdated.rgb,vertexOutputs.vColor.a);
#endif
#endif
#ifdef INSTANCESCOLOR
vertexOutputs.vColor*=vertexInputs.instanceColor;
#endif
#endif
`;x.IncludesShadersStoreWGSL[z4]||(x.IncludesShadersStoreWGSL[z4]=Che)});var H4={};Be(H4,{colorVertexShaderWGSL:()=>Phe});var PO,W4,Phe,X4=y(()=>{k();Wc();Hc();Xc();eE();Rd();Yc();Kc();jc();Zc();tE();iE();PO="colorVertexShader",W4=`attribute position: vec3f;
#ifdef VERTEXCOLOR
attribute color: vec4f;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#ifdef FOG
uniform view: mat4x4f;
#endif
#include<instancesDeclaration>
uniform viewProjection: mat4x4f;
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vColor: vec4f;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef VERTEXCOLOR
var colorUpdated: vec4f=vertexInputs.color;
#endif
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f=finalWorld* vec4f(vertexInputs.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos;
#include<clipPlaneVertex>
#include<fogVertex>
#include<vertexColorMixing>
#define CUSTOM_VERTEX_MAIN_END
}`;x.ShadersStoreWGSL[PO]||(x.ShadersStoreWGSL[PO]=W4);Phe={name:PO,shader:W4}});var Y4,Lhe,qc=y(()=>{k();Y4="clipPlaneFragmentDeclaration",Lhe=`#ifdef CLIPPLANE
varying fClipDistance: f32;
#endif
#ifdef CLIPPLANE2
varying fClipDistance2: f32;
#endif
#ifdef CLIPPLANE3
varying fClipDistance3: f32;
#endif
#ifdef CLIPPLANE4
varying fClipDistance4: f32;
#endif
#ifdef CLIPPLANE5
varying fClipDistance5: f32;
#endif
#ifdef CLIPPLANE6
varying fClipDistance6: f32;
#endif
`;x.IncludesShadersStoreWGSL[Y4]||(x.IncludesShadersStoreWGSL[Y4]=Lhe)});var K4,Dhe,rE=y(()=>{k();K4="fogFragmentDeclaration",Dhe=`#ifdef FOG
#define FOGMODE_NONE 0.
#define FOGMODE_EXP 1.
#define FOGMODE_EXP2 2.
#define FOGMODE_LINEAR 3.
const E=2.71828;uniform vFogInfos: vec4f;uniform vFogColor: vec3f;varying vFogDistance: vec3f;fn CalcFogFactor()->f32
{var fogCoeff: f32=1.0;var fogStart: f32=uniforms.vFogInfos.y;var fogEnd: f32=uniforms.vFogInfos.z;var fogDensity: f32=uniforms.vFogInfos.w;var fogDistance: f32=length(fragmentInputs.vFogDistance);if (FOGMODE_LINEAR==uniforms.vFogInfos.x)
{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}
else if (FOGMODE_EXP==uniforms.vFogInfos.x)
{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}
else if (FOGMODE_EXP2==uniforms.vFogInfos.x)
{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}
return clamp(fogCoeff,0.0,1.0);}
#endif
`;x.IncludesShadersStoreWGSL[K4]||(x.IncludesShadersStoreWGSL[K4]=Dhe)});var j4,Ohe,Qc=y(()=>{k();j4="clipPlaneFragment",Ohe=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
if (false) {}
#endif
#ifdef CLIPPLANE
else if (fragmentInputs.fClipDistance>0.0)
{discard;}
#endif
#ifdef CLIPPLANE2
else if (fragmentInputs.fClipDistance2>0.0)
{discard;}
#endif
#ifdef CLIPPLANE3
else if (fragmentInputs.fClipDistance3>0.0)
{discard;}
#endif
#ifdef CLIPPLANE4
else if (fragmentInputs.fClipDistance4>0.0)
{discard;}
#endif
#ifdef CLIPPLANE5
else if (fragmentInputs.fClipDistance5>0.0)
{discard;}
#endif
#ifdef CLIPPLANE6
else if (fragmentInputs.fClipDistance6>0.0)
{discard;}
#endif
`;x.IncludesShadersStoreWGSL[j4]||(x.IncludesShadersStoreWGSL[j4]=Ohe)});var Z4,Nhe,nE=y(()=>{k();Z4="fogFragment",Nhe=`#ifdef FOG
var fog: f32=CalcFogFactor();
#ifdef PBR
fog=toLinearSpace(fog);
#endif
color= vec4f(mix(uniforms.vFogColor,color.rgb,fog),color.a);
#endif
`;x.IncludesShadersStoreWGSL[Z4]||(x.IncludesShadersStoreWGSL[Z4]=Nhe)});var Q4={};Be(Q4,{colorPixelShaderWGSL:()=>whe});var LO,q4,whe,$4=y(()=>{k();qc();rE();Qc();nE();LO="colorPixelShader",q4=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
#define VERTEXCOLOR
varying vColor: vec4f;
#else
uniform color: vec4f;
#endif
#include<clipPlaneFragmentDeclaration>
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
fragmentOutputs.color=input.vColor;
#else
fragmentOutputs.color=uniforms.color;
#endif
#include<fogFragment>(color,fragmentOutputs.color)
#define CUSTOM_FRAGMENT_MAIN_END
}`;x.ShadersStoreWGSL[LO]||(x.ShadersStoreWGSL[LO]=q4);whe={name:LO,shader:q4}});var J4,Fhe,$c=y(()=>{k();J4="bonesDeclaration",Fhe=`#if NUM_BONE_INFLUENCERS>0
attribute vec4 matricesIndices;attribute vec4 matricesWeights;
#if NUM_BONE_INFLUENCERS>4
attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra;
#endif
#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#ifdef BONETEXTURE
uniform highp sampler2D boneSampler;uniform vec2 boneTextureInfo;
#else
uniform mat4 mBones[BonesPerMesh];
#endif
#ifdef BONES_VELOCITY_ENABLED
uniform mat4 mPreviousBones[BonesPerMesh];
#endif
#ifdef BONETEXTURE
#define inline
mat4 readMatrixFromRawSampler(sampler2D smp,float index)
{
#if defined(WEBGL2) || defined(WEBGPU)
int offset=int(index)*4;
int textureWidth=int(boneTextureInfo.x);int y=int(offset)/textureWidth;int x=int(offset) % textureWidth;vec4 m0=texelFetch(smp,ivec2(x+0,y),0);vec4 m1=texelFetch(smp,ivec2(x+1,y),0);vec4 m2=texelFetch(smp,ivec2(x+2,y),0);vec4 m3=texelFetch(smp,ivec2(x+3,y),0);return mat4(m0,m1,m2,m3);
#else
float offset=index*4.0;float y=floor(offset/boneTextureInfo.x);float x=offset-y*boneTextureInfo.x;float dy=1.0/boneTextureInfo.y;float dx=1.0/boneTextureInfo.x;vec4 m0=texture2D(smp,vec2(dx*(x+0.5),dy*(y+0.5)));vec4 m1=texture2D(smp,vec2(dx*(x+1.5),dy*(y+0.5)));vec4 m2=texture2D(smp,vec2(dx*(x+2.5),dy*(y+0.5)));vec4 m3=texture2D(smp,vec2(dx*(x+3.5),dy*(y+0.5)));
return mat4(m0,m1,m2,m3);
#endif
}
#endif
#endif
#endif
`;x.IncludesShadersStore[J4]||(x.IncludesShadersStore[J4]=Fhe)});var eX,Bhe,Jc=y(()=>{k();eX="bakedVertexAnimationDeclaration",Bhe=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
uniform float bakedVertexAnimationTime;
#if !defined(WEBGL2) && !defined(WEBGPU)
uniform vec2 bakedVertexAnimationTextureSizeInverted;
#endif
uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture;
#ifdef INSTANCES
attribute vec4 bakedVertexAnimationSettingsInstanced;
#endif
#define inline
mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame)
{
#if defined(WEBGL2) || defined(WEBGPU)
int offset=int(index)*4;int frameUV=int(frame);vec4 m0=texelFetch(smp,ivec2(offset+0,frameUV),0);vec4 m1=texelFetch(smp,ivec2(offset+1,frameUV),0);vec4 m2=texelFetch(smp,ivec2(offset+2,frameUV),0);vec4 m3=texelFetch(smp,ivec2(offset+3,frameUV),0);return mat4(m0,m1,m2,m3);
#else
float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);
#endif
}
#endif
`;x.IncludesShadersStore[eX]||(x.IncludesShadersStore[eX]=Bhe)});var tX,Uhe,ef=y(()=>{k();tX="clipPlaneVertexDeclaration",Uhe=`#ifdef CLIPPLANE
uniform vec4 vClipPlane;varying float fClipDistance;
#endif
#ifdef CLIPPLANE2
uniform vec4 vClipPlane2;varying float fClipDistance2;
#endif
#ifdef CLIPPLANE3
uniform vec4 vClipPlane3;varying float fClipDistance3;
#endif
#ifdef CLIPPLANE4
uniform vec4 vClipPlane4;varying float fClipDistance4;
#endif
#ifdef CLIPPLANE5
uniform vec4 vClipPlane5;varying float fClipDistance5;
#endif
#ifdef CLIPPLANE6
uniform vec4 vClipPlane6;varying float fClipDistance6;
#endif
`;x.IncludesShadersStore[tX]||(x.IncludesShadersStore[tX]=Uhe)});var iX,Vhe,sE=y(()=>{k();iX="fogVertexDeclaration",Vhe=`#ifdef FOG
varying vec3 vFogDistance;
#endif
`;x.IncludesShadersStore[iX]||(x.IncludesShadersStore[iX]=Vhe)});var rX,Ghe,bd=y(()=>{k();rX="instancesDeclaration",Ghe=`#ifdef INSTANCES
attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;
#ifdef INSTANCESCOLOR
attribute vec4 instanceColor;
#endif
#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)
uniform mat4 world;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3;
#ifdef THIN_INSTANCES
uniform mat4 previousWorld;
#endif
#endif
#else
#if !defined(WORLD_UBO)
uniform mat4 world;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
uniform mat4 previousWorld;
#endif
#endif
`;x.IncludesShadersStore[rX]||(x.IncludesShadersStore[rX]=Ghe)});var nX,khe,tf=y(()=>{k();nX="instancesVertex",khe=`#ifdef INSTANCES
mat4 finalWorld=mat4(world0,world1,world2,world3);
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,
previousWorld2,previousWorld3);
#endif
#ifdef THIN_INSTANCES
finalWorld=world*finalWorld;
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
finalPreviousWorld=previousWorld*finalPreviousWorld;
#endif
#endif
#else
mat4 finalWorld=world;
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
mat4 finalPreviousWorld=previousWorld;
#endif
#endif
`;x.IncludesShadersStore[nX]||(x.IncludesShadersStore[nX]=khe)});var sX,zhe,rf=y(()=>{k();sX="bonesVertex",zhe=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#if NUM_BONE_INFLUENCERS>0
mat4 influence;
#ifdef BONETEXTURE
influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];
#endif
#else
influence=mBones[int(matricesIndices[0])]*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence+=mBones[int(matricesIndices[1])]*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence+=mBones[int(matricesIndices[2])]*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence+=mBones[int(matricesIndices[3])]*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
#endif
#endif
finalWorld=finalWorld*influence;
#endif
#endif
`;x.IncludesShadersStore[sX]||(x.IncludesShadersStore[sX]=zhe)});var aX,Whe,nf=y(()=>{k();aX="bakedVertexAnimation",Whe=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
{
#ifdef INSTANCES
#define BVASNAME bakedVertexAnimationSettingsInstanced
#else
#define BVASNAME bakedVertexAnimationSettings
#endif
float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];
#endif
finalWorld=finalWorld*VATInfluence;}
#endif
`;x.IncludesShadersStore[aX]||(x.IncludesShadersStore[aX]=Whe)});var oX,Hhe,sf=y(()=>{k();oX="clipPlaneVertex",Hhe=`#ifdef CLIPPLANE
fClipDistance=dot(worldPos,vClipPlane);
#endif
#ifdef CLIPPLANE2
fClipDistance2=dot(worldPos,vClipPlane2);
#endif
#ifdef CLIPPLANE3
fClipDistance3=dot(worldPos,vClipPlane3);
#endif
#ifdef CLIPPLANE4
fClipDistance4=dot(worldPos,vClipPlane4);
#endif
#ifdef CLIPPLANE5
fClipDistance5=dot(worldPos,vClipPlane5);
#endif
#ifdef CLIPPLANE6
fClipDistance6=dot(worldPos,vClipPlane6);
#endif
`;x.IncludesShadersStore[oX]||(x.IncludesShadersStore[oX]=Hhe)});var lX,Xhe,aE=y(()=>{k();lX="fogVertex",Xhe=`#ifdef FOG
vFogDistance=(view*worldPos).xyz;
#endif
`;x.IncludesShadersStore[lX]||(x.IncludesShadersStore[lX]=Xhe)});var cX,Yhe,oE=y(()=>{k();cX="vertexColorMixing",Yhe=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
vColor=vec4(1.0);
#ifdef VERTEXCOLOR
#ifdef VERTEXALPHA
vColor*=colorUpdated;
#else
vColor.rgb*=colorUpdated.rgb;
#endif
#endif
#ifdef INSTANCESCOLOR
vColor*=instanceColor;
#endif
#endif
`;x.IncludesShadersStore[cX]||(x.IncludesShadersStore[cX]=Yhe)});var dX={};Be(dX,{colorVertexShader:()=>Khe});var DO,fX,Khe,uX=y(()=>{k();$c();Jc();ef();sE();bd();tf();rf();nf();sf();aE();oE();DO="colorVertexShader",fX=`attribute vec3 position;
#ifdef VERTEXCOLOR
attribute vec4 color;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#ifdef FOG
uniform mat4 view;
#endif
#include<instancesDeclaration>
uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef VERTEXCOLOR
vec4 colorUpdated=color;
#endif
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(position,1.0);
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}
#else
gl_Position=viewProjection*worldPos;
#endif
#include<clipPlaneVertex>
#include<fogVertex>
#include<vertexColorMixing>
#define CUSTOM_VERTEX_MAIN_END
}`;x.ShadersStore[DO]||(x.ShadersStore[DO]=fX);Khe={name:DO,shader:fX}});var hX,jhe,af=y(()=>{k();hX="clipPlaneFragmentDeclaration",jhe=`#ifdef CLIPPLANE
varying float fClipDistance;
#endif
#ifdef CLIPPLANE2
varying float fClipDistance2;
#endif
#ifdef CLIPPLANE3
varying float fClipDistance3;
#endif
#ifdef CLIPPLANE4
varying float fClipDistance4;
#endif
#ifdef CLIPPLANE5
varying float fClipDistance5;
#endif
#ifdef CLIPPLANE6
varying float fClipDistance6;
#endif
`;x.IncludesShadersStore[hX]||(x.IncludesShadersStore[hX]=jhe)});var mX,Zhe,lE=y(()=>{k();mX="fogFragmentDeclaration",Zhe=`#ifdef FOG
#define FOGMODE_NONE 0.
#define FOGMODE_EXP 1.
#define FOGMODE_EXP2 2.
#define FOGMODE_LINEAR 3.
#define E 2.71828
uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor()
{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x)
{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}
else if (FOGMODE_EXP==vFogInfos.x)
{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}
else if (FOGMODE_EXP2==vFogInfos.x)
{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}
return clamp(fogCoeff,0.0,1.0);}
#endif
`;x.IncludesShadersStore[mX]||(x.IncludesShadersStore[mX]=Zhe)});var pX,qhe,of=y(()=>{k();pX="clipPlaneFragment",qhe=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
if (false) {}
#endif
#ifdef CLIPPLANE
else if (fClipDistance>0.0)
{discard;}
#endif
#ifdef CLIPPLANE2
else if (fClipDistance2>0.0)
{discard;}
#endif
#ifdef CLIPPLANE3
else if (fClipDistance3>0.0)
{discard;}
#endif
#ifdef CLIPPLANE4
else if (fClipDistance4>0.0)
{discard;}
#endif
#ifdef CLIPPLANE5
else if (fClipDistance5>0.0)
{discard;}
#endif
#ifdef CLIPPLANE6
else if (fClipDistance6>0.0)
{discard;}
#endif
`;x.IncludesShadersStore[pX]||(x.IncludesShadersStore[pX]=qhe)});var gX,Qhe,cE=y(()=>{k();gX="fogFragment",Qhe=`#ifdef FOG
float fog=CalcFogFactor();
#ifdef PBR
fog=toLinearSpace(fog);
#endif
color.rgb=mix(vFogColor,color.rgb,fog);
#endif
`;x.IncludesShadersStore[gX]||(x.IncludesShadersStore[gX]=Qhe)});var vX={};Be(vX,{colorPixelShader:()=>$he});var OO,_X,$he,EX=y(()=>{k();af();lE();of();cE();OO="colorPixelShader",_X=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
#define VERTEXCOLOR
varying vec4 vColor;
#else
uniform vec4 color;
#endif
#include<clipPlaneFragmentDeclaration>
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
gl_FragColor=vColor;
#else
gl_FragColor=color;
#endif
#include<fogFragment>(color,gl_FragColor)
#define CUSTOM_FRAGMENT_MAIN_END
}`;x.ShadersStore[OO]||(x.ShadersStore[OO]=_X);$he={name:OO,shader:_X}});var nh,NO,SX=y(()=>{$t();qi();ki();yO();ls();CO();$._LinesMeshParser=(n,e)=>nh.Parse(n,e);nh=class n extends ${_isShaderMaterial(e){return e?e.getClassName()==="ShaderMaterial":!1}constructor(e,t=null,i=null,r=null,s,a,o,l){super(e,t,i,r,s),this.useVertexColor=a,this.useVertexAlpha=o,this.color=new he(1,1,1),this.alpha=1,this._shaderLanguage=0,this._ownsMaterial=!1,r&&(this.color=r.color.clone(),this.alpha=r.alpha,this.useVertexColor=r.useVertexColor,this.useVertexAlpha=r.useVertexAlpha),this.intersectionThreshold=.1;let c=[],f={attributes:[D.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:c,useClipPlane:null,shaderLanguage:0};if(this.useVertexAlpha?f.defines.push("#define VERTEXALPHA"):f.needAlphaBlending=!1,this.useVertexColor?(f.defines.push("#define VERTEXCOLOR"),f.attributes.push(D.ColorKind)):(f.uniforms.push("color"),this._color4=new ht),l)this.material=l;else{this.getScene().getEngine().isWebGPU&&!n.ForceGLSL&&(this._shaderLanguage=1),f.shaderLanguage=this._shaderLanguage,f.extraInitializationsAsync=async()=>{this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(X4(),H4)),Promise.resolve().then(()=>($4(),Q4))]):await Promise.all([Promise.resolve().then(()=>(uX(),dX)),Promise.resolve().then(()=>(EX(),vX))])};let u=new tl("colorShader",this.getScene(),"color",f,!1);u.doNotSerialize=!0,this._ownsMaterial=!0,this._setInternalMaterial(u)}}getClassName(){return"LinesMesh"}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){let t=this.material;if(t===e)return;let i=t&&this._ownsMaterial;this._ownsMaterial=!1,this._setInternalMaterial(e),i&&(t==null||t.dispose())}_setInternalMaterial(e){this._setMaterial(e),this.material&&(this.material.fillMode=Ae.LineListDrawMode,this.material.disableLighting=!0)}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;let i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this.material)){let{r,g:s,b:a}=this.color;this._color4.set(r,s,a,this.alpha),this.material.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(Ae.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(Ae.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){var r,s;i||(this._ownsMaterial?(r=this.material)==null||r.dispose(!1,!1,!0):t&&((s=this.material)==null||s.dispose(!1,!1,!0))),super.dispose(e)}clone(e,t=null,i){if(t&&t._addToSceneRootNodes===void 0){let r=t;return r.source=this,new n(e,this.getScene(),r.parent,r.source,r.doNotCloneChildren)}return new n(e,this.getScene(),t,this,i)}createInstance(e){let t=new NO(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(let i in this.instancedBuffers)t.instancedBuffers[i]=this.instancedBuffers[i]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){let i=new n(e.name,t);return i.color=he.FromArray(e.color),i.alpha=e.alpha,i}};nh.ForceGLSL=!1;NO=class extends zc{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}});function TX(n){let e=[],t=[],i=n.lines,r=n.colors,s=[],a=0;for(let l=0;l<i.length;l++){let c=i[l];for(let f=0;f<c.length;f++){let{x:d,y:u,z:h}=c[f];if(t.push(d,u,h),r){let m=r[l],{r:g,g:p,b:_,a:v}=m[f];s.push(g,p,_,v)}f>0&&(e.push(a-1),e.push(a)),a++}}let o=new Ie;return o.indices=e,o.positions=t,r&&(o.colors=s),o}function AX(n){let e=n.dashSize||3,t=n.gapSize||1,i=n.dashNb||200,r=n.points,s=[],a=[],o=b.Zero(),l=0,c,f,d=0,u;for(u=0;u<r.length-1;u++)r[u+1].subtractToRef(r[u],o),l+=o.length();let h=l/i,m=e*h/(e+t);for(u=0;u<r.length-1;u++){r[u+1].subtractToRef(r[u],o),c=Math.floor(o.length()/h),o.normalize();for(let p=0;p<c;p++)f=h*p,s.push(r[u].x+f*o.x,r[u].y+f*o.y,r[u].z+f*o.z),s.push(r[u].x+(f+m)*o.x,r[u].y+(f+m)*o.y,r[u].z+(f+m)*o.z),a.push(d,d+1),d+=2}let g=new Ie;return g.positions=s,g.indices=a,g}function wO(n,e,t=null){let i=e.instance,r=e.lines,s=e.colors;if(i){let c=i.getVerticesData(D.PositionKind),f,d;s&&(f=i.getVerticesData(D.ColorKind));let u=0,h=0;for(let m=0;m<r.length;m++){let g=r[m];for(let p=0;p<g.length;p++)c[u]=g[p].x,c[u+1]=g[p].y,c[u+2]=g[p].z,s&&f&&(d=s[m],f[h]=d[p].r,f[h+1]=d[p].g,f[h+2]=d[p].b,f[h+3]=d[p].a,h+=4),u+=3}return i.updateVerticesData(D.PositionKind,c,!1,!1),s&&f&&i.updateVerticesData(D.ColorKind,f,!1,!1),i.refreshBoundingInfo(),i}let a=!!s,o=new nh(n,t,null,void 0,void 0,a,e.useVertexAlpha,e.material);return TX(e).applyToMesh(o,e.updatable),o}function FO(n,e,t=null){let i=e.colors?[e.colors]:null;return wO(n,{lines:[e.points],updatable:e.updatable,instance:e.instance,colors:i,useVertexAlpha:e.useVertexAlpha,material:e.material},t)}function BO(n,e,t=null){let i=e.points,r=e.instance,s=e.gapSize||1,a=e.dashSize||3;if(r){let c=f=>{let d=b.Zero(),u=f.length/6,h=0,m,g,p=0,_,v;for(_=0;_<i.length-1;_++)i[_+1].subtractToRef(i[_],d),h+=d.length();let E=h/u,S=r._creationDataStorage.dashSize,T=r._creationDataStorage.gapSize,A=S*E/(S+T);for(_=0;_<i.length-1;_++)for(i[_+1].subtractToRef(i[_],d),m=Math.floor(d.length()/E),d.normalize(),v=0;v<m&&p<f.length;)g=E*v,f[p]=i[_].x+g*d.x,f[p+1]=i[_].y+g*d.y,f[p+2]=i[_].z+g*d.z,f[p+3]=i[_].x+(g+A)*d.x,f[p+4]=i[_].y+(g+A)*d.y,f[p+5]=i[_].z+(g+A)*d.z,p+=6,v++;for(;p<f.length;)f[p]=i[_].x,f[p+1]=i[_].y,f[p+2]=i[_].z,p+=3};return(e.dashNb||e.dashSize||e.gapSize||e.useVertexAlpha||e.material)&&te.Warn("You have used an option other than points with the instance option. Please be aware that these other options will be ignored."),r.updateMeshPositions(c,!1),r}let o=new nh(n,t,null,void 0,void 0,void 0,e.useVertexAlpha,e.material);return AX(e).applyToMesh(o,e.updatable),o._creationDataStorage=new Zp,o._creationDataStorage.dashSize=a,o._creationDataStorage.gapSize=s,o}var xX=y(()=>{He();ki();vr();SX();qi();wt();Ie.CreateLineSystem=TX;Ie.CreateDashedLines=AX;$.CreateLines=(n,e,t=null,i=!1,r=null)=>FO(n,{points:e,updatable:i,instance:r},t);$.CreateDashedLines=(n,e,t,i,r,s=null,a,o)=>BO(n,{points:e,dashSize:t,gapSize:i,dashNb:r,updatable:a,instance:o},s)});var UO,fE,Rb,RX=y(()=>{wt();He();qi();ki();vr();zu();es();Yi();UO=class extends Fe{constructor(e,t){super(e.x,e.y),this.index=t}},fE=class{constructor(){this.elements=[]}add(e){let t=[];for(let i of e){let r=new UO(i,this.elements.length);t.push(r),this.elements.push(r)}return t}computeBounds(){let e=new Fe(this.elements[0].x,this.elements[0].y),t=new Fe(this.elements[0].x,this.elements[0].y);for(let i of this.elements)i.x<e.x?e.x=i.x:i.x>t.x&&(t.x=i.x),i.y<e.y?e.y=i.y:i.y>t.y&&(t.y=i.y);return{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}},Rb=class{_addToepoint(e){for(let t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){this._points=new fE,this._outlinepoints=new fE,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=r,this._name=e,this._scene=i||Oe.LastCreatedScene;let s;t instanceof dp?s=t.getPoints():s=t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),typeof this.bjsEarcut=="undefined"&&te.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);let t=new fE;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){let r=new $(this._name,this._scene),s=this.buildVertexData(t,i);return r.setVerticesData(D.PositionKind,s.positions,e),r.setVerticesData(D.NormalKind,s.normals,e),r.setVerticesData(D.UVKind,s.uvs,e),r.setIndices(s.indices),r}buildVertexData(e=0,t=2){let i=new Ie,r=[],s=[],a=[],o=this._points.computeBounds();for(let f of this._points.elements)r.push(0,1,0),s.push(f.x,0,f.y),a.push((f.x-o.min.x)/o.width,(f.y-o.min.y)/o.height);let l=[],c=this.bjsEarcut(this._epoints,this._eholes,2);for(let f=0;f<c.length;f++)l.push(c[f]);if(e>0){let f=s.length/3;for(let u of this._points.elements)r.push(0,-1,0),s.push(u.x,-e,u.y),a.push(1-(u.x-o.min.x)/o.width,1-(u.y-o.min.y)/o.height);let d=l.length;for(let u=0;u<d;u+=3){let h=l[u+0],m=l[u+1],g=l[u+2];l.push(g+f),l.push(m+f),l.push(h+f)}this._addSide(s,r,a,l,o,this._outlinepoints,e,!1,t);for(let u of this._holes)this._addSide(s,r,a,l,o,u,e,!0,t)}return i.indices=l,i.positions=s,i.normals=r,i.uvs=a,i}_addSide(e,t,i,r,s,a,o,l,c){let f=e.length/3,d=0;for(let u=0;u<a.elements.length;u++){let h=a.elements[u],m=a.elements[(u+1)%a.elements.length];e.push(h.x,0,h.y),e.push(h.x,-o,h.y),e.push(m.x,0,m.y),e.push(m.x,-o,m.y);let g=a.elements[(u+a.elements.length-1)%a.elements.length],p=a.elements[(u+2)%a.elements.length],_=new b(-(m.y-h.y),0,m.x-h.x),v=new b(-(h.y-g.y),0,h.x-g.x),E=new b(-(p.y-m.y),0,p.x-m.x);l||(_=_.scale(-1),v=v.scale(-1),E=E.scale(-1));let S=_.normalizeToNew(),T=v.normalizeToNew(),A,R=b.Dot(T,S);R>c?R<Vt-1?T=new b(h.x,0,h.y).subtract(new b(m.x,0,m.y)).normalize():T=v.add(_).normalize():T=S;let M=b.Dot(E,_);M>c?M<Vt-1?A=new b(m.x,0,m.y).subtract(new b(h.x,0,h.y)).normalize():A=E.add(_).normalize():A=S,i.push(d/s.width,0),i.push(d/s.width,1),d+=_.length(),i.push(d/s.width,0),i.push(d/s.width,1),t.push(T.x,T.y,T.z),t.push(T.x,T.y,T.z),t.push(A.x,A.y,A.z),t.push(A.x,A.y,A.z),l?(r.push(f),r.push(f+2),r.push(f+1),r.push(f+1),r.push(f+2),r.push(f+3)):(r.push(f),r.push(f+1),r.push(f+2),r.push(f+1),r.push(f+3),r.push(f+2)),f+=4}}}});function bX(n,e,t,i,r,s,a){let o=t||new Array(3),l=i,c=[],f=a||!1;for(let I=0;I<3;I++)o[I]===void 0&&(o[I]=new Vi(0,0,1,1)),l&&l[I]===void 0&&(l[I]=new ht(1,1,1,1));let d=n.getVerticesData(D.PositionKind),u=n.getVerticesData(D.NormalKind),h=n.getVerticesData(D.UVKind),m=n.getIndices(),g=d.length/9,p,_,v,E,S=0,T=[0];if(f)for(let I=g;I<d.length/3;I+=4)_=d[3*(I+2)]-d[3*I],v=d[3*(I+2)+2]-d[3*I+2],E=Math.sqrt(_*_+v*v),S+=E,T.push(S);let A,R=0;for(let I=0;I<u.length;I+=3)Math.abs(u[I+1])<.001&&(R=1),Math.abs(u[I+1]-1)<.001&&(R=0),Math.abs(u[I+1]+1)<.001&&(R=2),A=I/3,R===1?(p=A-g,p%4<1.5?f?h[2*A]=o[R].x+(o[R].z-o[R].x)*T[Math.floor(p/4)]/S:h[2*A]=o[R].x:f?h[2*A]=o[R].x+(o[R].z-o[R].x)*T[Math.floor(p/4)+1]/S:h[2*A]=o[R].z,p%2===0?h[2*A+1]=Ot?1-o[R].w:o[R].w:h[2*A+1]=Ot?1-o[R].y:o[R].y):(h[2*A]=(1-h[2*A])*o[R].x+h[2*A]*o[R].z,h[2*A+1]=(1-h[2*A+1])*o[R].y+h[2*A+1]*o[R].w,Ot&&(h[2*A+1]=1-h[2*A+1])),l&&c.push(l[R].r,l[R].g,l[R].b,l[R].a);Ie._ComputeSides(e,d,m,u,h,r,s);let M=new Ie;if(M.indices=m,M.positions=d,M.normals=u,M.uvs=h,l){let I=e===Ie.DOUBLESIDE?c.concat(c):c;M.colors=I}return M}function bb(n,e,t=null,i=earcut){e.sideOrientation=$._GetDefaultSideOrientation(e.sideOrientation);let r=e.shape,s=e.holes||[],a=e.depth||0,o=e.smoothingThreshold||2,l=[],c;for(let m=0;m<r.length;m++)l[m]=new Fe(r[m].x,r[m].z);l[0].equalsWithEpsilon(l[l.length-1],1e-8)&&l.pop();let d=new Rb(n,l,t||Oe.LastCreatedScene,i);for(let m=0;m<s.length;m++){c=[];for(let g=0;g<s[m].length;g++)c.push(new Fe(s[m][g].x,s[m][g].z));d.addHole(c)}let u=d.build(!1,a,o);return u._originalBuilderSideOrientation=e.sideOrientation,bX(u,e.sideOrientation,e.faceUV,e.faceColors,e.frontUVs,e.backUVs,e.wrap).applyToMesh(u,e.updatable),u}function dE(n,e,t=null,i=earcut){return bb(n,e,t,i)}var VO=y(()=>{He();$t();ki();vr();RX();qi();Yi();vn();Ie.CreatePolygon=bX;$.CreatePolygon=(n,e,t,i,r,s,a=earcut)=>bb(n,{shape:e,holes:i,updatable:r,sideOrientation:s},t,a);$.ExtrudePolygon=(n,e,t,i,r,s,a,o=earcut)=>dE(n,{shape:e,holes:r,depth:t,updatable:s,sideOrientation:a},i,o)});function GO(n,e,t=null){let i=e.path,r=e.shape,s=e.scale||1,a=e.rotation||0,o=e.cap===0?0:e.cap||$.NO_CAP,l=e.updatable,c=$._GetDefaultSideOrientation(e.sideOrientation),f=e.instance||null,d=e.invertUV||!1,u=e.closeShape||!1,h=e.closePath||!1,m=e.capFunction||null;return MX(n,r,i,s,a,null,null,h,u,o,!1,t,!!l,c,f,d,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame,m)}function kO(n,e,t=null){var v;let i=e.path,r=e.shape,s=b.Zero(),a=(E,S)=>{var A,R;let T=(R=(A=e.scaleFunction)==null?void 0:A.call(e,E,S))!=null?R:1;return s.copyFromFloats(T,T,T)},o=e.rotationFunction||(()=>0),l=e.closePath||e.ribbonCloseArray||!1,c=e.closeShape||e.ribbonClosePath||!1,f=e.cap===0?0:e.cap||$.NO_CAP,d=e.updatable,u=e.firstNormal||null,h=e.adjustFrame||!1,m=$._GetDefaultSideOrientation(e.sideOrientation),g=e.instance,p=e.invertUV||!1,_=e.capFunction||null;return MX(n,r,i,null,null,(v=e.scaleVectorFunction)!=null?v:a,o,l,c,f,!0,t,!!d,m,g||null,p,e.frontUVs||null,e.backUVs||null,u,h,_||null)}function MX(n,e,t,i,r,s,a,o,l,c,f,d,u,h,m,g,p,_,v,E,S){let T=(L,w,G,O,N,B,V,q,K,J,Y)=>{let j=G.getTangents(),ue=G.getNormals(),Ee=G.getBinormals(),Ue=G.getDistances();if(Y){for(let Ve=0;Ve<j.length;Ve++)if(j[Ve].x==0&&j[Ve].y==0&&j[Ve].z==0&&j[Ve].copyFrom(j[Ve-1]),ue[Ve].x==0&&ue[Ve].y==0&&ue[Ve].z==0&&ue[Ve].copyFrom(ue[Ve-1]),Ee[Ve].x==0&&Ee[Ve].y==0&&Ee[Ve].z==0&&Ee[Ve].copyFrom(Ee[Ve-1]),Ve>0){let Ze=j[Ve-1];b.Dot(Ze,j[Ve])<0&&j[Ve].scaleInPlace(-1),Ze=ue[Ve-1],b.Dot(Ze,ue[Ve])<0&&ue[Ve].scaleInPlace(-1),Ze=Ee[Ve-1],b.Dot(Ze,Ee[Ve])<0&&Ee[Ve].scaleInPlace(-1)}}let se=0,ve=()=>N!==null?N:b.OneReadOnly,me=J&&q?q:()=>B!==null?B:0,Le=J&&V?V:ve,de=K===$.NO_CAP||K===$.CAP_END?0:2,be=ee.Matrix[0];for(let Ve=0;Ve<w.length;Ve++){let Ze=[],Kt=me(Ve,Ue[Ve]),Bt=Le(Ve,Ue[Ve]);Q.RotationAxisToRef(j[Ve],se,be);for(let wi=0;wi<L.length;wi++){let ae=j[Ve].scale(L[wi].z).add(ue[Ve].scale(L[wi].x)).add(Ee[Ve].scale(L[wi].y)),Ti=b.Zero();b.TransformCoordinatesToRef(ae,be,Ti),Ti.multiplyInPlace(Bt).addInPlace(w[Ve]),Ze[wi]=Ti}O[de]=Ze,se+=Kt,de++}let dt=S||(Ve=>{let Ze=Array(),Kt=b.Zero(),Bt;for(Bt=0;Bt<Ve.length;Bt++)Kt.addInPlace(Ve[Bt]);for(Kt.scaleInPlace(1/Ve.length),Bt=0;Bt<Ve.length;Bt++)Ze.push(Kt);return Ze});switch(K){case $.NO_CAP:break;case $.CAP_START:O[0]=dt(O[2]),O[1]=O[2];break;case $.CAP_END:O[de]=O[de-1],O[de+1]=dt(O[de-1]);break;case $.CAP_ALL:O[0]=dt(O[2]),O[1]=O[2],O[de]=O[de-1],O[de+1]=dt(O[de-1]);break;default:break}return O},A=i!==null?new b(i,i,i):null,R;if(m){let L=m._creationDataStorage;return v?L.path3D.update(t,v):L.path3D.update(t),R=T(e,t,L.path3D,L.pathArray,A,r,s,a,L.cap,f,E),m=el("",{pathArray:R,closeArray:!1,closePath:!1,offset:0,updatable:!1,sideOrientation:0,instance:m},d||void 0),m}let M=v?new ku(t,v):new ku(t),I=new Array;c=c<0||c>3?0:c,R=T(e,t,M,I,A,r,s,a,c,f,E);let C=el(n,{pathArray:R,closeArray:o,closePath:l,updatable:u,sideOrientation:h,invertUV:g,frontUVs:p||void 0,backUVs:_||void 0},d);return C._creationDataStorage.pathArray=R,C._creationDataStorage.path3D=M,C._creationDataStorage.cap=c,C}var yX=y(()=>{He();ki();Qv();zu();$.ExtrudeShape=(n,e,t,i,r,s,a=null,o,l,c)=>{let f={shape:e,path:t,scale:i,rotation:r,cap:s===0?0:s||$.NO_CAP,sideOrientation:l,instance:c,updatable:o};return GO(n,f,a)};$.ExtrudeShapeCustom=(n,e,t,i,r,s,a,o,l,c,f,d)=>{let u={shape:e,path:t,scaleFunction:i,rotationFunction:r,ribbonCloseArray:s,ribbonClosePath:a,cap:o===0?0:o||$.NO_CAP,sideOrientation:f,instance:d,updatable:c};return kO(n,u,l)}});function zO(n,e,t=null){let i=e.arc?e.arc<=0||e.arc>1?1:e.arc:1,r=e.closed===void 0?!0:e.closed,s=e.shape,a=e.radius||1,o=e.tessellation||64,l=e.clip||0,c=e.updatable,f=$._GetDefaultSideOrientation(e.sideOrientation),d=e.cap||$.NO_CAP,u=Math.PI*2,h=[],m=e.invertUV||!1,g,p,_=u/o*i,v,E;for(g=0;g<=o-l;g++){for(E=[],(d==$.CAP_START||d==$.CAP_ALL)&&(E.push(new b(0,s[0].y,0)),E.push(new b(Math.cos(g*_)*s[0].x*a,s[0].y,Math.sin(g*_)*s[0].x*a))),p=0;p<s.length;p++)v=new b(Math.cos(g*_)*s[p].x*a,s[p].y,Math.sin(g*_)*s[p].x*a),E.push(v);(d==$.CAP_END||d==$.CAP_ALL)&&(E.push(new b(Math.cos(g*_)*s[s.length-1].x*a,s[s.length-1].y,Math.sin(g*_)*s[s.length-1].x*a)),E.push(new b(0,s[s.length-1].y,0))),h.push(E)}return el(n,{pathArray:h,closeArray:r,sideOrientation:f,updatable:c,invertUV:m,frontUVs:e.frontUVs,backUVs:e.backUVs},t)}var IX=y(()=>{He();ki();Qv();$.CreateLathe=(n,e,t,i,r,s,a)=>zO(n,{shape:e,radius:t,tessellation:i,sideOrientation:a,updatable:s},r)});function CX(n){let e=[],t=[],i=[],r=[],s=n.width!==void 0?n.width:n.size!==void 0?n.size:1,a=n.height!==void 0?n.height:n.size!==void 0?n.size:1,o=n.sideOrientation===0?0:n.sideOrientation||Ie.DEFAULTSIDE,l=s/2,c=a/2;t.push(-l,-c,0),i.push(0,0,-1),r.push(0,Ot?1:0),t.push(l,-c,0),i.push(0,0,-1),r.push(1,Ot?1:0),t.push(l,c,0),i.push(0,0,-1),r.push(1,Ot?0:1),t.push(-l,c,0),i.push(0,0,-1),r.push(0,Ot?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),Ie._ComputeSides(o,t,e,i,r,n.frontUVs,n.backUVs);let f=new Ie;return f.indices=e,f.positions=t,f.normals=i,f.uvs=r,f}function WO(n,e={},t=null){let i=new $(n,t);return e.sideOrientation=$._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,CX(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}var PX=y(()=>{ki();vr();vn();Ie.CreatePlane=CX;$.CreatePlane=(n,e,t,i,r)=>WO(n,{size:e,width:e,height:e,sideOrientation:r,updatable:i},t)});function HO(n,e,t=null){let i=e.path,r=e.instance,s=1;e.radius!==void 0?s=e.radius:r&&(s=r._creationDataStorage.radius);let a=e.tessellation||64,o=e.radiusFunction||null,l=e.cap||$.NO_CAP,c=e.invertUV||!1,f=e.updatable,d=$._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;let u=(_,v,E,S,T,A,R,M)=>{let I=v.getTangents(),C=v.getNormals(),L=v.getDistances(),G=Math.PI*2/T*M,N=A||(()=>S),B,V,q,K,J=ee.Matrix[0],Y=R===$.NO_CAP||R===$.CAP_END?0:2;for(let ue=0;ue<_.length;ue++){V=N(ue,L[ue]),B=Array(),q=C[ue];for(let Ee=0;Ee<T;Ee++)Q.RotationAxisToRef(I[ue],G*Ee,J),K=B[Ee]?B[Ee]:b.Zero(),b.TransformCoordinatesToRef(q,J,K),K.scaleInPlace(V).addInPlace(_[ue]),B[Ee]=K;E[Y]=B,Y++}let j=(ue,Ee)=>{let Ue=Array();for(let se=0;se<ue;se++)Ue.push(_[Ee]);return Ue};switch(R){case $.NO_CAP:break;case $.CAP_START:E[0]=j(T,0),E[1]=E[2].slice(0);break;case $.CAP_END:E[Y]=E[Y-1].slice(0),E[Y+1]=j(T,_.length-1);break;case $.CAP_ALL:E[0]=j(T,0),E[1]=E[2].slice(0),E[Y]=E[Y-1].slice(0),E[Y+1]=j(T,_.length-1);break;default:break}return E},h,m;if(r){let _=r._creationDataStorage,v=e.arc||_.arc;return h=_.path3D.update(i),m=u(i,h,_.pathArray,s,_.tessellation,o,_.cap,v),r=el("",{pathArray:m,instance:r}),_.path3D=h,_.pathArray=m,_.arc=v,_.radius=s,r}h=new ku(i);let g=new Array;l=l<0||l>3?0:l,m=u(i,h,g,s,a,o,l,e.arc);let p=el(n,{pathArray:m,closePath:!0,closeArray:!1,updatable:f,sideOrientation:d,invertUV:c,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return p._creationDataStorage.pathArray=m,p._creationDataStorage.path3D=h,p._creationDataStorage.tessellation=a,p._creationDataStorage.cap=l,p._creationDataStorage.arc=e.arc,p._creationDataStorage.radius=s,p}var LX=y(()=>{He();ki();Qv();zu();$.CreateTube=(n,e,t,i,r,s,a,o,l,c)=>HO(n,{path:e,radius:t,tessellation:i,radiusFunction:r,arc:1,cap:s,updatable:o,sideOrientation:l,instance:c},a)});function DX(n){let e=[];e[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},e[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},e[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},e[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},e[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},e[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},e[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},e[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},e[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},e[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},e[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},e[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},e[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},e[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},e[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};let t=n.type&&(n.type<0||n.type>=e.length)?0:n.type||0,i=n.size,r=n.sizeX||i||1,s=n.sizeY||i||1,a=n.sizeZ||i||1,o=n.custom||e[t],l=o.face.length,c=n.faceUV||new Array(l),f=n.faceColors,d=n.flat===void 0?!0:n.flat,u=n.sideOrientation===0?0:n.sideOrientation||Ie.DEFAULTSIDE,h=[],m=[],g=[],p=[],_=[],v=0,E=0,S=[],T,A,R,M,I,C,L,w;if(d)for(A=0;A<l;A++)f&&f[A]===void 0&&(f[A]=new ht(1,1,1,1)),c&&c[A]===void 0&&(c[A]=new Vi(0,0,1,1));if(d)for(A=0;A<l;A++){let O=o.face[A].length;for(I=2*Math.PI/O,C=.5*Math.tan(I/2),L=.5,T=0;T<O;T++)h.push(o.vertex[o.face[A][T]][0]*r,o.vertex[o.face[A][T]][1]*s,o.vertex[o.face[A][T]][2]*a),S.push(v),v++,R=c[A].x+(c[A].z-c[A].x)*(.5+C),M=c[A].y+(c[A].w-c[A].y)*(L-.5),p.push(R,Ot?1-M:M),w=C*Math.cos(I)-L*Math.sin(I),L=C*Math.sin(I)+L*Math.cos(I),C=w,f&&_.push(f[A].r,f[A].g,f[A].b,f[A].a);for(T=0;T<O-2;T++)m.push(S[0+E],S[T+2+E],S[T+1+E]);E+=O}else{for(T=0;T<o.vertex.length;T++)h.push(o.vertex[T][0]*r,o.vertex[T][1]*s,o.vertex[T][2]*a),p.push(0,Ot?1:0);for(A=0;A<l;A++)for(T=0;T<o.face[A].length-2;T++)m.push(o.face[A][0],o.face[A][T+2],o.face[A][T+1])}Ie.ComputeNormals(h,m,g),Ie._ComputeSides(u,h,m,g,p,n.frontUVs,n.backUVs);let G=new Ie;return G.positions=h,G.indices=m,G.normals=g,G.uvs=p,f&&d&&(G.colors=_),G}function uE(n,e={},t=null){let i=new $(n,t);return e.sideOrientation=$._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,DX(e).applyToMesh(i,e.updatable),i}var XO=y(()=>{He();$t();ki();vr();vn();Ie.CreatePolyhedron=DX;$.CreatePolyhedron=(n,e,t)=>uE(n,e,t)});function OX(n){let e=n.sideOrientation||Ie.DEFAULTSIDE,t=n.radius||1,i=n.flat===void 0?!0:n.flat,r=(n.subdivisions||4)|0,s=n.radiusX||t,a=n.radiusY||t,o=n.radiusZ||t,l=(1+Math.sqrt(5))/2,c=[-1,l,-0,1,l,0,-1,-l,0,1,-l,0,0,-1,-l,0,1,-l,0,-1,l,0,1,l,l,0,1,l,0,-1,-l,0,1,-l,0,-1],f=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],d=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],u=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],h=138/1024,m=239/1024,g=60/1024,p=26/1024,_=-40/1024,v=20/1024,E=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],S=[],T=[],A=[],R=[],M=0,I=new Array(3),C=new Array(3),L;for(L=0;L<3;L++)I[L]=b.Zero(),C[L]=Fe.Zero();for(let G=0;G<20;G++){for(L=0;L<3;L++){let N=f[3*G+L];I[L].copyFromFloats(c[3*d[N]],c[3*d[N]+1],c[3*d[N]+2]),I[L].normalize(),C[L].copyFromFloats(u[2*N]*h+g+E[G]*_,u[2*N+1]*m+p+E[G]*v)}let O=(N,B,V,q)=>{let K=b.Lerp(I[0],I[2],B/r),J=b.Lerp(I[1],I[2],B/r),Y=r===B?I[2]:b.Lerp(K,J,N/(r-B));Y.normalize();let j;if(i){let se=b.Lerp(I[0],I[2],q/r),ve=b.Lerp(I[1],I[2],q/r);j=b.Lerp(se,ve,V/(r-q))}else j=new b(Y.x,Y.y,Y.z);j.x/=s,j.y/=a,j.z/=o,j.normalize();let ue=Fe.Lerp(C[0],C[2],B/r),Ee=Fe.Lerp(C[1],C[2],B/r),Ue=r===B?C[2]:Fe.Lerp(ue,Ee,N/(r-B));T.push(Y.x*s,Y.y*a,Y.z*o),A.push(j.x,j.y,j.z),R.push(Ue.x,Ot?1-Ue.y:Ue.y),S.push(M),M++};for(let N=0;N<r;N++)for(let B=0;B+N<r;B++)O(B,N,B+1/3,N+1/3),O(B+1,N,B+1/3,N+1/3),O(B,N+1,B+1/3,N+1/3),B+N+1<r&&(O(B+1,N,B+2/3,N+2/3),O(B+1,N+1,B+2/3,N+2/3),O(B,N+1,B+2/3,N+2/3))}Ie._ComputeSides(e,T,S,A,R,n.frontUVs,n.backUVs);let w=new Ie;return w.indices=S,w.positions=T,w.normals=A,w.uvs=R,w}function YO(n,e={},t=null){let i=new $(n,t);return e.sideOrientation=$._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,OX(e).applyToMesh(i,e.updatable),i}var NX=y(()=>{He();ki();vr();vn();Ie.CreateIcoSphere=OX;$.CreateIcoSphere=(n,e,t)=>YO(n,e,t)});function KO(n,e,t){var V,q,K,J,Y;let i=!!e.skeleton,r=!!((V=e.morphTargetManager)!=null&&V.numTargets),s=t.localMode||i,a=e.getIndices(),o=i||r?e.getPositionData(!0,!0):e.getVerticesData(D.PositionKind),l=i||r?e.getNormalsData(!0,!0):e.getVerticesData(D.NormalKind),c=s?i?e.getVerticesData(D.PositionKind):o:null,f=s?i?e.getVerticesData(D.NormalKind):l:null,d=e.getVerticesData(D.UVKind),u=i?e.getVerticesData(D.MatricesIndicesKind):null,h=i?e.getVerticesData(D.MatricesWeightsKind):null,m=i?e.getVerticesData(D.MatricesIndicesExtraKind):null,g=i?e.getVerticesData(D.MatricesWeightsExtraKind):null,p=t.position||b.Zero(),_=t.normal||b.Up(),v=t.size||b.One(),E=t.angle||0;if(!_){let j=new b(0,0,1),ue=e.getScene().activeCamera,Ee=b.TransformCoordinates(j,ue.getWorldMatrix());_=ue.globalPosition.subtract(Ee)}let S=-Math.atan2(_.z,_.x)-Math.PI/2,T=Math.sqrt(_.x*_.x+_.z*_.z),A=Math.atan2(_.y,T),R=new Ie;R.indices=[],R.positions=[],R.normals=[],R.uvs=[],R.matricesIndices=i?[]:null,R.matricesWeights=i?[]:null,R.matricesIndicesExtra=m?[]:null,R.matricesWeightsExtra=g?[]:null;let M=0,I=(j,ue)=>{let Ee=new Mb;if(!a||!o||!l)return Ee;let Ue=a[j];if(Ee.vertexIdx=Ue*3,Ee.vertexIdxForBones=Ue*4,Ee.position=new b(o[Ue*3],o[Ue*3+1],o[Ue*3+2]),b.TransformCoordinatesToRef(Ee.position,ue,Ee.position),Ee.normal=new b(l[Ue*3],l[Ue*3+1],l[Ue*3+2]),b.TransformNormalToRef(Ee.normal,ue,Ee.normal),t.captureUVS&&d){let se=d[Ue*2+1];Ee.uv=new Fe(d[Ue*2],Ot?1-se:se)}return Ee},C=[0,0,0,0],L=(j,ue)=>{if(j.length===0)return j;let Ee=.5*Math.abs(b.Dot(v,ue)),Ue=(ne,me,Le,de)=>{for(let be=0;be<de;++be)if(ne[Le+be]===me)return Le+be;return-1},se=(ne,me)=>{var De,ke,it,Qe,Me,Pe,ut,bt,qe,Je,Wt,Ut,yi,oe,rt,Ce;let Le=b.GetClipFactor(ne.position,me.position,ue,Ee),de=C,be=C;if(u&&h){let ft=ne.matrixIndicesOverride?0:ne.vertexIdxForBones,nt=(De=ne.matrixIndicesOverride)!=null?De:u,Ge=(ke=ne.matrixWeightsOverride)!=null?ke:h,Mt=me.matrixIndicesOverride?0:me.vertexIdxForBones,qt=(it=me.matrixIndicesOverride)!=null?it:u,Er=(Qe=me.matrixWeightsOverride)!=null?Qe:h;de=[0,0,0,0],be=[0,0,0,0];let _i=0;for(let cr=0;cr<4;++cr)if(Ge[ft+cr]>0){let Bs=Ue(qt,nt[ft+cr],Mt,4);de[_i]=nt[ft+cr],be[_i]=Uo(Ge[ft+cr],Bs>=0?Er[Bs]:0,Le),_i++}for(let cr=0;cr<4&&_i<4;++cr){let Bs=qt[Mt+cr];Ue(nt,Bs,ft,4)===-1&&(de[_i]=Bs,be[_i]=Uo(0,Er[Mt+cr],Le),_i++)}let Gr=be[0]+be[1]+be[2]+be[3];be[0]/=Gr,be[1]/=Gr,be[2]/=Gr,be[3]/=Gr}let we=ne.localPositionOverride?ne.localPositionOverride[0]:(Me=c==null?void 0:c[ne.vertexIdx])!=null?Me:0,dt=ne.localPositionOverride?ne.localPositionOverride[1]:(Pe=c==null?void 0:c[ne.vertexIdx+1])!=null?Pe:0,Ve=ne.localPositionOverride?ne.localPositionOverride[2]:(ut=c==null?void 0:c[ne.vertexIdx+2])!=null?ut:0,Ze=me.localPositionOverride?me.localPositionOverride[0]:(bt=c==null?void 0:c[me.vertexIdx])!=null?bt:0,Kt=me.localPositionOverride?me.localPositionOverride[1]:(qe=c==null?void 0:c[me.vertexIdx+1])!=null?qe:0,Bt=me.localPositionOverride?me.localPositionOverride[2]:(Je=c==null?void 0:c[me.vertexIdx+2])!=null?Je:0,wi=ne.localNormalOverride?ne.localNormalOverride[0]:(Wt=f==null?void 0:f[ne.vertexIdx])!=null?Wt:0,ae=ne.localNormalOverride?ne.localNormalOverride[1]:(Ut=f==null?void 0:f[ne.vertexIdx+1])!=null?Ut:0,Ti=ne.localNormalOverride?ne.localNormalOverride[2]:(yi=f==null?void 0:f[ne.vertexIdx+2])!=null?yi:0,hi=me.localNormalOverride?me.localNormalOverride[0]:(oe=f==null?void 0:f[me.vertexIdx])!=null?oe:0,rr=me.localNormalOverride?me.localNormalOverride[1]:(rt=f==null?void 0:f[me.vertexIdx+1])!=null?rt:0,Ke=me.localNormalOverride?me.localNormalOverride[2]:(Ce=f==null?void 0:f[me.vertexIdx+2])!=null?Ce:0,ar=wi+(hi-wi)*Le,Z=ae+(rr-ae)*Le,U=Ti+(Ke-Ti)*Le,ge=Math.sqrt(ar*ar+Z*Z+U*U);return new Mb(b.Lerp(ne.position,me.position,Le),b.Lerp(ne.normal,me.normal,Le).normalize(),Fe.Lerp(ne.uv,me.uv,Le),-1,-1,c?[we+(Ze-we)*Le,dt+(Kt-dt)*Le,Ve+(Bt-Ve)*Le]:null,f?[ar/ge,Z/ge,U/ge]:null,de,be)},ve=null;j.length>3&&(ve=[]);for(let ne=0;ne<j.length;ne+=3){let me=null,Le=null,de=null,be=null,we=b.Dot(j[ne].position,ue)-Ee,dt=b.Dot(j[ne+1].position,ue)-Ee,Ve=b.Dot(j[ne+2].position,ue)-Ee,Ze=we>0,Kt=dt>0,Bt=Ve>0;switch((Ze?1:0)+(Kt?1:0)+(Bt?1:0)){case 0:j.length>3?(ve.push(j[ne]),ve.push(j[ne+1]),ve.push(j[ne+2])):ve=j;break;case 1:if(ve=ve!=null?ve:new Array,Ze&&(me=j[ne+1],Le=j[ne+2],de=se(j[ne],me),be=se(j[ne],Le)),Kt){me=j[ne],Le=j[ne+2],de=se(j[ne+1],me),be=se(j[ne+1],Le),ve.push(de),ve.push(Le.clone()),ve.push(me.clone()),ve.push(Le.clone()),ve.push(de.clone()),ve.push(be);break}Bt&&(me=j[ne],Le=j[ne+1],de=se(j[ne+2],me),be=se(j[ne+2],Le)),me&&Le&&de&&be&&(ve.push(me.clone()),ve.push(Le.clone()),ve.push(de),ve.push(be),ve.push(de.clone()),ve.push(Le.clone()));break;case 2:ve=ve!=null?ve:new Array,Ze||(me=j[ne].clone(),Le=se(me,j[ne+1]),de=se(me,j[ne+2]),ve.push(me),ve.push(Le),ve.push(de)),Kt||(me=j[ne+1].clone(),Le=se(me,j[ne+2]),de=se(me,j[ne]),ve.push(me),ve.push(Le),ve.push(de)),Bt||(me=j[ne+2].clone(),Le=se(me,j[ne]),de=se(me,j[ne+1]),ve.push(me),ve.push(Le),ve.push(de));break;case 3:break}}return ve},w=e instanceof $?e:null,G=w==null?void 0:w._thinInstanceDataStorage.matrixData,O=(w==null?void 0:w.thinInstanceCount)||1,N=ee.Matrix[0];N.copyFrom(Q.IdentityReadOnly);for(let j=0;j<O;++j){if(w!=null&&w.hasThinInstances&&G){let ne=j*16;N.setRowFromFloats(0,G[ne+0],G[ne+1],G[ne+2],G[ne+3]),N.setRowFromFloats(1,G[ne+4],G[ne+5],G[ne+6],G[ne+7]),N.setRowFromFloats(2,G[ne+8],G[ne+9],G[ne+10],G[ne+11]),N.setRowFromFloats(3,G[ne+12],G[ne+13],G[ne+14],G[ne+15])}let ue=Q.RotationYawPitchRoll(S,A,E).multiply(Q.Translation(p.x,p.y,p.z)),Ee=Q.Invert(ue),Ue=e.getWorldMatrix(),se=N.multiply(Ue).multiply(Ee),ve=new Array(3);for(let ne=0;ne<a.length;ne+=3){let me=ve;if(me[0]=I(ne,se),me[1]=I(ne+1,se),me[2]=I(ne+2,se),!(t.cullBackFaces&&-me[0].normal.z<=0&&-me[1].normal.z<=0&&-me[2].normal.z<=0)&&(me=L(me,Jhe),!!me&&(me=L(me,eme),!!me&&(me=L(me,tme),!!me&&(me=L(me,ime),!!me&&(me=L(me,rme),!!me&&(me=L(me,nme),!!me)))))))for(let Le=0;Le<me.length;Le++){let de=me[Le];if(R.indices.push(M),s?(de.localPositionOverride?(R.positions[M*3]=de.localPositionOverride[0],R.positions[M*3+1]=de.localPositionOverride[1],R.positions[M*3+2]=de.localPositionOverride[2]):c&&(R.positions[M*3]=c[de.vertexIdx],R.positions[M*3+1]=c[de.vertexIdx+1],R.positions[M*3+2]=c[de.vertexIdx+2]),de.localNormalOverride?(R.normals[M*3]=de.localNormalOverride[0],R.normals[M*3+1]=de.localNormalOverride[1],R.normals[M*3+2]=de.localNormalOverride[2]):f&&(R.normals[M*3]=f[de.vertexIdx],R.normals[M*3+1]=f[de.vertexIdx+1],R.normals[M*3+2]=f[de.vertexIdx+2])):(de.position.toArray(R.positions,M*3),de.normal.toArray(R.normals,M*3)),R.matricesIndices&&R.matricesWeights&&(de.matrixIndicesOverride?(R.matricesIndices[M*4]=de.matrixIndicesOverride[0],R.matricesIndices[M*4+1]=de.matrixIndicesOverride[1],R.matricesIndices[M*4+2]=de.matrixIndicesOverride[2],R.matricesIndices[M*4+3]=de.matrixIndicesOverride[3]):(u&&(R.matricesIndices[M*4]=u[de.vertexIdxForBones],R.matricesIndices[M*4+1]=u[de.vertexIdxForBones+1],R.matricesIndices[M*4+2]=u[de.vertexIdxForBones+2],R.matricesIndices[M*4+3]=u[de.vertexIdxForBones+3]),m&&R.matricesIndicesExtra&&(R.matricesIndicesExtra[M*4]=m[de.vertexIdxForBones],R.matricesIndicesExtra[M*4+1]=m[de.vertexIdxForBones+1],R.matricesIndicesExtra[M*4+2]=m[de.vertexIdxForBones+2],R.matricesIndicesExtra[M*4+3]=m[de.vertexIdxForBones+3])),de.matrixWeightsOverride?(R.matricesWeights[M*4]=de.matrixWeightsOverride[0],R.matricesWeights[M*4+1]=de.matrixWeightsOverride[1],R.matricesWeights[M*4+2]=de.matrixWeightsOverride[2],R.matricesWeights[M*4+3]=de.matrixWeightsOverride[3]):(h&&(R.matricesWeights[M*4]=h[de.vertexIdxForBones],R.matricesWeights[M*4+1]=h[de.vertexIdxForBones+1],R.matricesWeights[M*4+2]=h[de.vertexIdxForBones+2],R.matricesWeights[M*4+3]=h[de.vertexIdxForBones+3]),g&&R.matricesWeightsExtra&&(R.matricesWeightsExtra[M*4]=g[de.vertexIdxForBones],R.matricesWeightsExtra[M*4+1]=g[de.vertexIdxForBones+1],R.matricesWeightsExtra[M*4+2]=g[de.vertexIdxForBones+2],R.matricesWeightsExtra[M*4+3]=g[de.vertexIdxForBones+3]))),t.captureUVS)de.uv.toArray(R.uvs,M*2);else{R.uvs.push(.5+de.position.x/v.x);let be=.5+de.position.y/v.y;R.uvs.push(Ot?1-be:be)}M++}}}R.indices.length===0&&(R.indices=null),R.positions.length===0&&(R.positions=null),R.normals.length===0&&(R.normals=null),R.uvs.length===0&&(R.uvs=null),((q=R.matricesIndices)==null?void 0:q.length)===0&&(R.matricesIndices=null),((K=R.matricesWeights)==null?void 0:K.length)===0&&(R.matricesWeights=null),((J=R.matricesIndicesExtra)==null?void 0:J.length)===0&&(R.matricesIndicesExtra=null),((Y=R.matricesWeightsExtra)==null?void 0:Y.length)===0&&(R.matricesWeightsExtra=null);let B=new $(n,e.getScene());return R.applyToMesh(B),s?(B.skeleton=e.skeleton,B.parent=e):(B.position=p.clone(),B.rotation=new b(A,S,E)),B.computeWorldMatrix(!0),B.refreshBoundingInfo(!0,!0),B}var Jhe,eme,tme,ime,rme,nme,Mb,wX=y(()=>{He();ts();ki();qi();vr();vn();Jhe=new b(1,0,0),eme=new b(-1,0,0),tme=new b(0,1,0),ime=new b(0,-1,0),rme=new b(0,0,1),nme=new b(0,0,-1),Mb=class n{constructor(e=b.Zero(),t=b.Up(),i=Fe.Zero(),r=0,s=0,a=null,o=null,l=null,c=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=s,this.localPositionOverride=a,this.localNormalOverride=o,this.matrixIndicesOverride=l,this.matrixWeightsOverride=c}clone(){var e,t,i,r;return new n(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,(e=this.localPositionOverride)==null?void 0:e.slice(),(t=this.localNormalOverride)==null?void 0:t.slice(),(i=this.matrixIndicesOverride)==null?void 0:i.slice(),(r=this.matrixWeightsOverride)==null?void 0:r.slice())}};$.CreateDecal=(n,e,t,i,r,s)=>KO(n,e,{position:t,normal:i,size:r,angle:s})});function FX(n={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){let e=Math.max(n.subdivisions?n.subdivisions:2,1)|0,t=Math.max(n.tessellation?n.tessellation:16,3)|0,i=Math.max(n.height?n.height:1,0),r=Math.max(n.radius?n.radius:.25,0),s=Math.max(n.capSubdivisions?n.capSubdivisions:6,1)|0,a=t,o=e,l=Math.max(n.radiusTop?n.radiusTop:r,0),c=Math.max(n.radiusBottom?n.radiusBottom:r,0),f=i-(l+c),d=0,u=2*Math.PI,h=Math.max(n.topCapSubdivisions?n.topCapSubdivisions:s,1),m=Math.max(n.bottomCapSubdivisions?n.bottomCapSubdivisions:s,1),g=Math.acos((c-l)/i),p=[],_=[],v=[],E=[],S=0,T=[],A=f*.5,R=Math.PI*.5,M,I,C=b.Zero(),L=b.Zero(),w=Math.cos(g),G=Math.sin(g),O=new Fe(l*G,A+l*w).subtract(new Fe(c*G,-A+c*w)).length(),N=l*g+O+c*(R-g),B=0;for(I=0;I<=h;I++){let J=[],Y=R-g*(I/h);B+=l*g/h;let j=Math.cos(Y),ue=Math.sin(Y),Ee=j*l;for(M=0;M<=a;M++){let Ue=M/a,se=Ue*u+d,ve=Math.sin(se),ne=Math.cos(se);L.x=Ee*ve,L.y=A+ue*l,L.z=Ee*ne,_.push(L.x,L.y,L.z),C.set(j*ve,ue,j*ne),v.push(C.x,C.y,C.z),E.push(Ue,Ot?B/N:1-B/N),J.push(S),S++}T.push(J)}let V=i-l-c+w*l-w*c,q=G*(c-l)/V;for(I=1;I<=o;I++){let J=[];B+=O/o;let Y=G*(I*(c-l)/o+l);for(M=0;M<=a;M++){let j=M/a,ue=j*u+d,Ee=Math.sin(ue),Ue=Math.cos(ue);L.x=Y*Ee,L.y=A+w*l-I*V/o,L.z=Y*Ue,_.push(L.x,L.y,L.z),C.set(Ee,q,Ue).normalize(),v.push(C.x,C.y,C.z),E.push(j,Ot?B/N:1-B/N),J.push(S),S++}T.push(J)}for(I=1;I<=m;I++){let J=[],Y=R-g-(Math.PI-g)*(I/m);B+=c*g/m;let j=Math.cos(Y),ue=Math.sin(Y),Ee=j*c;for(M=0;M<=a;M++){let Ue=M/a,se=Ue*u+d,ve=Math.sin(se),ne=Math.cos(se);L.x=Ee*ve,L.y=-A+ue*c,L.z=Ee*ne,_.push(L.x,L.y,L.z),C.set(j*ve,ue,j*ne),v.push(C.x,C.y,C.z),E.push(Ue,Ot?B/N:1-B/N),J.push(S),S++}T.push(J)}for(M=0;M<a;M++)for(I=0;I<h+o+m;I++){let J=T[I][M],Y=T[I+1][M],j=T[I+1][M+1],ue=T[I][M+1];p.push(J),p.push(Y),p.push(ue),p.push(Y),p.push(j),p.push(ue)}if(p=p.reverse(),n.orientation&&!n.orientation.equals(b.Up())){let J=new Q;n.orientation.clone().scale(Math.PI*.5).cross(b.Up()).toQuaternion().toRotationMatrix(J);let Y=b.Zero();for(let j=0;j<_.length;j+=3)Y.set(_[j],_[j+1],_[j+2]),b.TransformCoordinatesToRef(Y.clone(),J,Y),_[j]=Y.x,_[j+1]=Y.y,_[j+2]=Y.z}let K=new Ie;return K.positions=_,K.normals=v,K.uvs=E,K.indices=p,K}function jO(n,e={orientation:b.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6,updatable:!1},t=null){let i=new $(n,t);return FX(e).applyToMesh(i,e.updatable),i}var BX=y(()=>{vr();He();ki();vn();$.CreateCapsule=(n,e,t)=>jO(n,e,t);Ie.CreateCapsule=FX});var lr,UX=y(()=>{wt();He();lr=class n{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(e=Math.floor(e),te.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(t=Math.floor(t),te.Warn("y is not an integer, floor(y) used"))}clone(){return new n(this.x,this.y)}rotate60About(e){let t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){let t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),te.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),te.Warn("n not an integer only floor(n) used"));let i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),te.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),te.Warn("n is not an integer, floor(n) used"));let i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){let i=b.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new n(0,0)}}});var tg,hE,ig,ZO=y(()=>{He();ts();es();UX();tg=class{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new hE("icosahedron","Regular",[[0,Mr,-1],[-Mr,1,0],[-1,0,-Mr],[1,0,-Mr],[Mr,1,0],[0,Mr,1],[-1,0,Mr],[-Mr,-1,0],[0,-Mr,-1],[Mr,-1,0],[1,0,Mr],[0,-Mr,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12,t={},i=this.m,r=this.n,s=i;r!==0&&(s=mR(i,r));let a=i/s,o=r/s,l,c,f,d,u,h=lr.Zero(),m=new lr(i,r),g=new lr(-r,i+r),p=lr.Zero(),_=lr.Zero(),v=lr.Zero(),E=[],S,T,A,R,M=[],I=this.vertByDist,C=(L,w,G,O)=>{S=L+"|"+G,T=w+"|"+O,S in t||T in t?S in t&&!(T in t)?t[T]=t[S]:T in t&&!(S in t)&&(t[S]=t[T]):(t[S]=e,t[T]=e,e++),I[G][0]>2?M[t[S]]=[-I[G][0],I[G][1],t[S]]:M[t[S]]=[E[I[G][0]],I[G][1],t[S]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let L=0;L<20;L++){if(E=this.IDATA.face[L],f=E[2],d=E[1],u=E[0],A=h.x+"|"+h.y,S=L+"|"+A,S in t||(t[S]=f,M[f]=[E[I[A][0]],I[A][1]]),A=m.x+"|"+m.y,S=L+"|"+A,S in t||(t[S]=d,M[d]=[E[I[A][0]],I[A][1]]),A=g.x+"|"+g.y,S=L+"|"+A,S in t||(t[S]=u,M[u]=[E[I[A][0]],I[A][1]]),l=this.IDATA.edgematch[L][0],c=this.IDATA.edgematch[L][1],c==="B")for(let w=1;w<s;w++)_.x=i-w*(a+o),_.y=r+w*a,v.x=-w*o,v.y=w*(a+o),A=_.x+"|"+_.y,R=v.x+"|"+v.y,C(L,l,A,R);if(c==="O")for(let w=1;w<s;w++)v.x=-w*o,v.y=w*(a+o),p.x=w*a,p.y=w*o,A=v.x+"|"+v.y,R=p.x+"|"+p.y,C(L,l,A,R);if(l=this.IDATA.edgematch[L][2],c=this.IDATA.edgematch[L][3],c&&c==="A")for(let w=1;w<s;w++)p.x=w*a,p.y=w*o,_.x=i-(s-w)*(a+o),_.y=r+(s-w)*a,A=p.x+"|"+p.y,R=_.x+"|"+_.y,C(L,l,A,R);for(let w=0;w<this.vertices.length;w++)A=this.vertices[w].x+"|"+this.vertices[w].y,S=L+"|"+A,S in t||(t[S]=e++,I[A][0]>2?M[t[S]]=[-I[A][0],I[A][1],t[S]]:M[t[S]]=[E[I[A][0]],I[A][1],t[S]])}this.closestTo=M,this.vecToidx=t}calcCoeffs(){let e=this.m,t=this.n,i=Math.sqrt(3)/3,r=e*e+t*t+e*t;this.coau=(e+t)/r,this.cobu=-t/r,this.coav=-i*(e-t)/r,this.cobv=i*(2*e+t)/r}createInnerFacets(){let e=this.m,t=this.n;for(let i=0;i<t+e+1;i++)for(let r=this.min[i];r<this.max[i]+1;r++)r<this.max[i]&&r<this.max[i+1]+1&&this.innerFacets.push(["|"+r+"|"+i,"|"+r+"|"+(i+1),"|"+(r+1)+"|"+i]),i>0&&r<this.max[i-1]&&r+1<this.max[i]+1&&this.innerFacets.push(["|"+r+"|"+i,"|"+(r+1)+"|"+i,"|"+(r+1)+"|"+(i-1)])}edgeVecsABOB(){let e=this.m,t=this.n,i=new lr(-t,e+t);for(let r=1;r<e+t;r++){let s=new lr(this.min[r],r),a=new lr(this.min[r-1],r-1),o=new lr(this.min[r+1],r+1),l=s.clone(),c=a.clone(),f=o.clone();l.rotate60About(i),c.rotate60About(i),f.rotate60About(i);let d=new lr(this.max[l.y],l.y),u=new lr(this.max[l.y-1],l.y-1),h=new lr(this.max[l.y-1]-1,l.y-1);(l.x!==d.x||l.y!==d.y)&&(l.x!==u.x?(this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([s,u,h]),this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([s,h,d])):l.y===f.y?(this.vertexTypes.push([1,1,0]),this.isoVecsABOB.push([s,a,u]),this.vertexTypes.push([1,0,1]),this.isoVecsABOB.push([s,u,o])):(this.vertexTypes.push([1,1,0]),this.isoVecsABOB.push([s,a,u]),this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([s,u,d])))}}mapABOBtoOBOA(){let e=new lr(0,0);for(let t=0;t<this.isoVecsABOB.length;t++){let i=[];for(let r=0;r<3;r++)e.x=this.isoVecsABOB[t][r].x,e.y=this.isoVecsABOB[t][r].y,this.vertexTypes[t][r]===0&&e.rotateNeg120(this.m,this.n),i.push(e.clone());this.isoVecsOBOA.push(i)}}mapABOBtoBAOA(){let e=new lr(0,0);for(let t=0;t<this.isoVecsABOB.length;t++){let i=[];for(let r=0;r<3;r++)e.x=this.isoVecsABOB[t][r].x,e.y=this.isoVecsABOB[t][r].y,this.vertexTypes[t][r]===1&&e.rotate120(this.m,this.n),i.push(e.clone());this.isoVecsBAOA.push(i)}}MapToFace(e,t){let i=this.IDATA.face[e],r=i[2],s=i[1],a=i[0],o=b.FromArray(this.IDATA.vertex[r]),l=b.FromArray(this.IDATA.vertex[s]),c=b.FromArray(this.IDATA.vertex[a]),f=l.subtract(o),d=c.subtract(o),u=f.scale(this.coau).add(d.scale(this.cobu)),h=f.scale(this.coav).add(d.scale(this.cobv)),m=[],g,p;for(let _=0;_<this.cartesian.length;_++)p=u.scale(this.cartesian[_].x).add(h.scale(this.cartesian[_].y)).add(o),m[_]=[p.x,p.y,p.z],g=e+"|"+this.vertices[_].x+"|"+this.vertices[_].y,t.vertex[this.vecToidx[g]]=[p.x,p.y,p.z]}build(e,t){let i=[],r=lr.Zero(),s=new lr(e,t),a=new lr(-t,e+t);i.push(r,s,a);for(let T=t;T<e+1;T++)for(let A=0;A<e+1-T;A++)i.push(new lr(A,T));if(t>0){let T=mR(e,t),A=e/T,R=t/T;for(let I=1;I<T;I++)i.push(new lr(I*A,I*R)),i.push(new lr(-I*R,I*(A+R))),i.push(new lr(e-I*(A+R),t+I*A));let M=e/t;for(let I=1;I<t;I++)for(let C=0;C<I*M;C++)i.push(new lr(C,I)),i.push(new lr(C,I).rotate120(e,t)),i.push(new lr(C,I).rotateNeg120(e,t))}i.sort((T,A)=>T.x-A.x),i.sort((T,A)=>T.y-A.y);let o=new Array(e+t+1),l=new Array(e+t+1);for(let T=0;T<o.length;T++)o[T]=1/0,l[T]=-1/0;let c,f,d=i.length;for(let T=0;T<d;T++)f=i[T].x,c=i[T].y,o[c]=Math.min(f,o[c]),l[c]=Math.max(f,l[c]);let u=(T,A)=>{let R=T.clone();return A==="A"&&R.rotateNeg120(e,t),A==="B"&&R.rotate120(e,t),R.x<0?R.y:R.x+R.y},h=[],m=[],g=[],p=[],_={},v=[],E=-1,S=-1;for(let T=0;T<d;T++)h[T]=i[T].toCartesianOrigin(new lr(0,0),.5),m[T]=u(i[T],"O"),g[T]=u(i[T],"A"),p[T]=u(i[T],"B"),m[T]===g[T]&&g[T]===p[T]?(E=3,S=m[T]):m[T]===g[T]?(E=4,S=m[T]):g[T]===p[T]?(E=5,S=g[T]):p[T]===m[T]&&(E=6,S=m[T]),m[T]<g[T]&&m[T]<p[T]&&(E=2,S=m[T]),g[T]<m[T]&&g[T]<p[T]&&(E=1,S=g[T]),p[T]<g[T]&&p[T]<m[T]&&(E=0,S=p[T]),v.push([E,S,i[T].x,i[T].y]);v.sort((T,A)=>T[2]-A[2]),v.sort((T,A)=>T[3]-A[3]),v.sort((T,A)=>T[1]-A[1]),v.sort((T,A)=>T[0]-A[0]);for(let T=0;T<v.length;T++)_[v[T][2]+"|"+v[T][3]]=[v[T][0],v[T][1],T];return this.m=e,this.n=t,this.vertices=i,this.vertByDist=_,this.cartesian=h,this.min=o,this.max=l,this}},hE=class{constructor(e,t,i,r){this.name=e,this.category=t,this.vertex=i,this.face=r}},ig=class n extends hE{innerToData(e,t){for(let i=0;i<t.innerFacets.length;i++)this.face.push(t.innerFacets[i].map(r=>t.vecToidx[e+r]))}mapABOBtoDATA(e,t){let i=t.IDATA.edgematch[e][0];for(let r=0;r<t.isoVecsABOB.length;r++){let s=[];for(let a=0;a<3;a++)t.vertexTypes[r][a]===0?s.push(e+"|"+t.isoVecsABOB[r][a].x+"|"+t.isoVecsABOB[r][a].y):s.push(i+"|"+t.isoVecsABOB[r][a].x+"|"+t.isoVecsABOB[r][a].y);this.face.push([t.vecToidx[s[0]],t.vecToidx[s[1]],t.vecToidx[s[2]]])}}mapOBOAtoDATA(e,t){let i=t.IDATA.edgematch[e][0];for(let r=0;r<t.isoVecsOBOA.length;r++){let s=[];for(let a=0;a<3;a++)t.vertexTypes[r][a]===1?s.push(e+"|"+t.isoVecsOBOA[r][a].x+"|"+t.isoVecsOBOA[r][a].y):s.push(i+"|"+t.isoVecsOBOA[r][a].x+"|"+t.isoVecsOBOA[r][a].y);this.face.push([t.vecToidx[s[0]],t.vecToidx[s[1]],t.vecToidx[s[2]]])}}mapBAOAtoDATA(e,t){let i=t.IDATA.edgematch[e][2];for(let r=0;r<t.isoVecsBAOA.length;r++){let s=[];for(let a=0;a<3;a++)t.vertexTypes[r][a]===1?s.push(e+"|"+t.isoVecsBAOA[r][a].x+"|"+t.isoVecsBAOA[r][a].y):s.push(i+"|"+t.isoVecsBAOA[r][a].x+"|"+t.isoVecsBAOA[r][a].y);this.face.push([t.vecToidx[s[0]],t.vecToidx[s[1]],t.vecToidx[s[2]]])}}orderData(e){let t=[];for(let a=0;a<13;a++)t[a]=[];let i=e.closestTo;for(let a=0;a<i.length;a++)i[a][0]>-1?i[a][1]>0&&t[i[a][0]].push([a,i[a][1]]):t[12].push([a,i[a][0]]);let r=[];for(let a=0;a<12;a++)r[a]=a;let s=12;for(let a=0;a<12;a++){t[a].sort((o,l)=>o[1]-l[1]);for(let o=0;o<t[a].length;o++)r[t[a][o][0]]=s++}for(let a=0;a<t[12].length;a++)r[t[12][a][0]]=s++;for(let a=0;a<this.vertex.length;a++)this.vertex[a].push(r[a]);this.vertex.sort((a,o)=>a[3]-o[3]);for(let a=0;a<this.vertex.length;a++)this.vertex[a].pop();for(let a=0;a<this.face.length;a++)for(let o=0;o<this.face[a].length;o++)this.face[a][o]=r[this.face[a][o]];this.sharedNodes=t[12].length,this.poleNodes=this.vertex.length-this.sharedNodes}setOrder(e,t){let i=[],r=[],s=t.pop();r.push(s);let a=this.face[s].indexOf(e);a=(a+2)%3;let o=this.face[s][a];i.push(o);let l=0;for(;t.length>0;)s=t[l],this.face[s].indexOf(o)>-1?(a=(this.face[s].indexOf(o)+1)%3,o=this.face[s][a],i.push(o),r.push(s),t.splice(l,1),l=0):l++;return this.adjacentFaces.push(i),r}toGoldbergPolyhedronData(){let e=new hE("GeoDual","Goldberg",[],[]);e.name="GD dual";let t=this.vertex.length,i=new Array(t);for(let c=0;c<t;c++)i[c]=[];for(let c=0;c<this.face.length;c++)for(let f=0;f<3;f++)i[this.face[c][f]].push(c);let r,s,a,o,l;this.adjacentFaces=[];for(let c=0;c<i.length;c++){e.face[c]=this.setOrder(c,i[c].concat([]));for(let f of i[c]){r=0,s=0,a=0,o=this.face[f];for(let d=0;d<3;d++)l=this.vertex[o[d]],r+=l[0],s+=l[1],a+=l[2];e.vertex[f]=[r/3,s/3,a/3]}}return e}static BuildGeodesicData(e){let t=new n("Geodesic-m-n","Geodesic",[[0,Mr,-1],[-Mr,1,0],[-1,0,-Mr],[1,0,-Mr],[Mr,1,0],[0,Mr,1],[-1,0,Mr],[-Mr,-1,0],[0,-Mr,-1],[Mr,-1,0],[1,0,Mr],[0,-Mr,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let r=0;r<e.IDATA.face.length;r++)e.MapToFace(r,t),t.innerToData(r,e),e.IDATA.edgematch[r][1]==="B"&&t.mapABOBtoDATA(r,e),e.IDATA.edgematch[r][1]==="O"&&t.mapOBOAtoDATA(r,e),e.IDATA.edgematch[r][3]==="A"&&t.mapBAOAtoDATA(r,e);t.orderData(e);let i=1;return t.vertex=t.vertex.map(function(r){let s=r[0],a=r[1],o=r[2],l=Math.sqrt(s*s+a*a+o*o);return r[0]*=i/l,r[1]*=i/l,r[2]*=i/l,r}),t}}});function VX(n,e,t=null){let i=e.m||1;i!==Math.floor(i)&&(i=Math.floor(i),te.Warn("m not an integer only floor(m) used"));let r=e.n||0;if(r!==Math.floor(r)&&(r=Math.floor(r),te.Warn("n not an integer only floor(n) used")),r>i){let c=r;r=i,i=c,te.Warn("n > m therefore m and n swapped")}let s=new tg;s.build(i,r);let o={custom:ig.BuildGeodesicData(s),size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,faceUV:e.faceUV,faceColors:e.faceColors,flat:e.flat,updatable:e.updatable,sideOrientation:e.sideOrientation,frontUVs:e.frontUVs,backUVs:e.backUVs};return uE(n,o,t)}var GX=y(()=>{XO();wt();ZO()});var mE,kX=y(()=>{He();qi();ki();$t();wt();$._GoldbergMeshParser=(n,e)=>mE.Parse(n,e);mE=class n extends ${constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return t===void 0?(e>this.goldbergData.nbUnsharedFaces-1&&(te.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(te.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(te.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let i=0;i<e.length;i++){let r=e[i][0],s=e[i][1],a=e[i][2];for(let o=r;o<s+1;o++)this.goldbergData.faceColors[o]=a}let t=[];for(let i=0;i<12;i++)for(let r=0;r<5;r++)t.push(this.goldbergData.faceColors[i].r,this.goldbergData.faceColors[i].g,this.goldbergData.faceColors[i].b,this.goldbergData.faceColors[i].a);for(let i=12;i<this.goldbergData.faceColors.length;i++)for(let r=0;r<6;r++)t.push(this.goldbergData.faceColors[i].r,this.goldbergData.faceColors[i].g,this.goldbergData.faceColors[i].b,this.goldbergData.faceColors[i].a);return t}setGoldbergFaceColors(e){let t=this._changeGoldbergFaceColors(e);this.setVerticesData(D.ColorKind,t)}updateGoldbergFaceColors(e){let t=this._changeGoldbergFaceColors(e);this.updateVerticesData(D.ColorKind,t)}_changeGoldbergFaceUVs(e){let t=this.getVerticesData(D.UVKind);for(let i=0;i<e.length;i++){let r=e[i][0],s=e[i][1],a=e[i][2],o=e[i][3],l=e[i][4],c=[],f=[],d,u;for(let h=0;h<5;h++)d=a.x+o*Math.cos(l+h*Math.PI/2.5),u=a.y+o*Math.sin(l+h*Math.PI/2.5),d<0&&(d=0),d>1&&(d=1),c.push(d,u);for(let h=0;h<6;h++)d=a.x+o*Math.cos(l+h*Math.PI/3),u=a.y+o*Math.sin(l+h*Math.PI/3),d<0&&(d=0),d>1&&(d=1),f.push(d,u);for(let h=r;h<Math.min(12,s+1);h++)for(let m=0;m<5;m++)t[10*h+2*m]=c[2*m],t[10*h+2*m+1]=c[2*m+1];for(let h=Math.max(12,r);h<s+1;h++)for(let m=0;m<6;m++)t[12*h-24+2*m]=f[2*m],t[12*h-23+2*m]=f[2*m+1]}return t}setGoldbergFaceUVs(e){let t=this._changeGoldbergFaceUVs(e);this.setVerticesData(D.UVKind,t)}updateGoldbergFaceUVs(e){let t=this._changeGoldbergFaceUVs(e);this.updateVerticesData(D.UVKind,t)}placeOnGoldbergFaceAt(e,t,i){let r=b.RotationFromAxis(this.goldbergData.faceXaxis[t],this.goldbergData.faceYaxis[t],this.goldbergData.faceZaxis[t]);e.rotation=r,e.position=this.goldbergData.faceCenters[t].add(this.goldbergData.faceXaxis[t].scale(i.x)).add(this.goldbergData.faceYaxis[t].scale(i.y)).add(this.goldbergData.faceZaxis[t].scale(i.z))}serialize(e){super.serialize(e),e.type="GoldbergMesh";let t={};if(t.adjacentFaces=this.goldbergData.adjacentFaces,t.nbSharedFaces=this.goldbergData.nbSharedFaces,t.nbUnsharedFaces=this.goldbergData.nbUnsharedFaces,t.nbFaces=this.goldbergData.nbFaces,t.nbFacesAtPole=this.goldbergData.nbFacesAtPole,this.goldbergData.faceColors){t.faceColors=[];for(let i of this.goldbergData.faceColors)t.faceColors.push(i.asArray())}if(this.goldbergData.faceCenters){t.faceCenters=[];for(let i of this.goldbergData.faceCenters)t.faceCenters.push(i.asArray())}if(this.goldbergData.faceZaxis){t.faceZaxis=[];for(let i of this.goldbergData.faceZaxis)t.faceZaxis.push(i.asArray())}if(this.goldbergData.faceYaxis){t.faceYaxis=[];for(let i of this.goldbergData.faceYaxis)t.faceYaxis.push(i.asArray())}if(this.goldbergData.faceXaxis){t.faceXaxis=[];for(let i of this.goldbergData.faceXaxis)t.faceXaxis.push(i.asArray())}e.goldbergData=t}static Parse(e,t){let i=e.goldbergData;i.faceColors=i.faceColors.map(s=>ht.FromArray(s)),i.faceCenters=i.faceCenters.map(s=>b.FromArray(s)),i.faceZaxis=i.faceZaxis.map(s=>b.FromArray(s)),i.faceXaxis=i.faceXaxis.map(s=>b.FromArray(s)),i.faceYaxis=i.faceYaxis.map(s=>b.FromArray(s));let r=new n(e.name,t);return r.goldbergData=i,r}}});function sme(n,e){let t=n.size,i=n.sizeX||t||1,r=n.sizeY||t||1,s=n.sizeZ||t||1,a=n.sideOrientation===0?0:n.sideOrientation||Ie.DEFAULTSIDE,o=[],l=[],c=[],f=[],d=1/0,u=-1/0,h=1/0,m=-1/0;for(let _=0;_<e.vertex.length;_++)d=Math.min(d,e.vertex[_][0]*i),u=Math.max(u,e.vertex[_][0]*i),h=Math.min(h,e.vertex[_][1]*r),m=Math.max(m,e.vertex[_][1]*r);let g=0;for(let _=0;_<e.face.length;_++){let v=e.face[_],E=b.FromArray(e.vertex[v[0]]),S=b.FromArray(e.vertex[v[2]]),T=b.FromArray(e.vertex[v[1]]),A=S.subtract(E),R=T.subtract(E),M=b.Cross(R,A).normalize();for(let I=0;I<v.length;I++){c.push(M.x,M.y,M.z);let C=e.vertex[v[I]];o.push(C[0]*i,C[1]*r,C[2]*s);let L=(C[1]*r-h)/(m-h);f.push((C[0]*i-d)/(u-d),Ot?1-L:L)}for(let I=0;I<v.length-2;I++)l.push(g,g+I+2,g+I+1);g+=v.length}Ie._ComputeSides(a,o,l,c,f);let p=new Ie;return p.positions=o,p.indices=l,p.normals=c,p.uvs=f,p}function zX(n,e,t=null){let i=e.size,r=e.sizeX||i||1,s=e.sizeY||i||1,a=e.sizeZ||i||1,o=e.m||1;o!==Math.floor(o)&&(o=Math.floor(o),te.Warn("m not an integer only floor(m) used"));let l=e.n||0;if(l!==Math.floor(l)&&(l=Math.floor(l),te.Warn("n not an integer only floor(n) used")),l>o){let m=l;l=o,o=m,te.Warn("n > m therefore m and n swapped")}let c=new tg;c.build(o,l);let f=ig.BuildGeodesicData(c),d=f.toGoldbergPolyhedronData(),u=new mE(n,t);e.sideOrientation=$._GetDefaultSideOrientation(e.sideOrientation),u._originalBuilderSideOrientation=e.sideOrientation,sme(e,d).applyToMesh(u,e.updatable),u.goldbergData.nbSharedFaces=f.sharedNodes,u.goldbergData.nbUnsharedFaces=f.poleNodes,u.goldbergData.adjacentFaces=f.adjacentFaces,u.goldbergData.nbFaces=u.goldbergData.nbSharedFaces+u.goldbergData.nbUnsharedFaces,u.goldbergData.nbFacesAtPole=(u.goldbergData.nbUnsharedFaces-12)/12;for(let m=0;m<f.vertex.length;m++)u.goldbergData.faceCenters.push(b.FromArray(f.vertex[m])),u.goldbergData.faceCenters[m].x*=r,u.goldbergData.faceCenters[m].y*=s,u.goldbergData.faceCenters[m].z*=a,u.goldbergData.faceColors.push(new ht(1,1,1,1));for(let m=0;m<d.face.length;m++){let g=d.face[m],p=b.FromArray(d.vertex[g[0]]),_=b.FromArray(d.vertex[g[2]]),v=b.FromArray(d.vertex[g[1]]),E=_.subtract(p),S=v.subtract(p),T=b.Cross(S,E).normalize(),A=b.Cross(S,T).normalize();u.goldbergData.faceXaxis.push(S.normalize()),u.goldbergData.faceYaxis.push(T),u.goldbergData.faceZaxis.push(A)}return u}var WX=y(()=>{He();$t();ki();vr();wt();ZO();kX();vn()});function ame(n,e,t,i,r,s){let a=s.glyphs[n]||s.glyphs["?"];if(!a)return null;let o=new qO(r);if(a.o){let l=a.o.split(" ");for(let c=0,f=l.length;c<f;)switch(l[c++]){case"m":{let u=parseInt(l[c++])*e+t,h=parseInt(l[c++])*e+i;o.moveTo(u,h);break}case"l":{let u=parseInt(l[c++])*e+t,h=parseInt(l[c++])*e+i;o.lineTo(u,h);break}case"q":{let u=parseInt(l[c++])*e+t,h=parseInt(l[c++])*e+i,m=parseInt(l[c++])*e+t,g=parseInt(l[c++])*e+i;o.quadraticCurveTo(m,g,u,h);break}case"b":{let u=parseInt(l[c++])*e+t,h=parseInt(l[c++])*e+i,m=parseInt(l[c++])*e+t,g=parseInt(l[c++])*e+i,p=parseInt(l[c++])*e+t,_=parseInt(l[c++])*e+i;o.bezierCurveTo(m,g,p,_,u,h);break}}}return o.extractHoles(),{offsetX:a.ha*e,shapePath:o}}function ome(n,e,t,i){let r=Array.from(n),s=e/i.resolution,a=(i.boundingBox.yMax-i.boundingBox.yMin+i.underlineThickness)*s,o=[],l=0,c=0;for(let f=0;f<r.length;f++){let d=r[f];if(d===`
`)l=0,c-=a;else{let u=ame(d,s,l,c,t,i);u&&(l+=u.offsetX,o.push(u.shapePath))}}return o}function HX(n,e,t,i={size:50,resolution:8,depth:1},r=null,s=earcut){var f,d;let a=ome(e,i.size||50,i.resolution||8,t),o=[],l=0;for(let u of a){if(!u.paths.length)continue;let h=u.holes.slice();for(let m of u.paths){let g=[],p=[],_=m.getPoints();for(let S of _)p.push(new b(S.x,0,S.y));let v=h.slice();for(let S of v){let T=S.getPoints(),A=!1;for(let M of T)if(m.isPointInside(M)){A=!0;break}if(!A)continue;let R=[];for(let M of T)R.push(new b(M.x,0,M.y));g.push(R),h.splice(h.indexOf(S),1)}if(!g.length&&h.length)for(let S of h){let T=S.getPoints(),A=[];for(let R of T)A.push(new b(R.x,0,R.y));g.push(A)}let E=dE(n,{shape:p,holes:g.length?g:void 0,depth:i.depth||1,faceUV:i.faceUV||((f=i.perLetterFaceUV)==null?void 0:f.call(i,l)),faceColors:i.faceColors||((d=i.perLetterFaceColors)==null?void 0:d.call(i,l)),sideOrientation:$._GetDefaultSideOrientation(i.sideOrientation||$.DOUBLESIDE)},r,s);o.push(E),l++}}let c=$.MergeMeshes(o,!0,!0);if(c){let u=c.getBoundingInfo().boundingBox;c.position.x+=-(u.minimumWorld.x+u.maximumWorld.x)/2,c.position.y+=-(u.minimumWorld.y+u.maximumWorld.y)/2,c.position.z+=-(u.minimumWorld.z+u.maximumWorld.z)/2+u.extendSize.z,c.name=n;let h=new ii("pivot",r);h.rotation.x=-Math.PI/2,c.parent=h,c.bakeCurrentTransformIntoVertices(),c.parent=null,h.dispose()}return c}var qO,XX=y(()=>{zu();He();ki();cd();VO();qO=class{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new dp(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,r){this._currentPath.addQuadraticCurveTo(e,t,i,r,this._resolution)}bezierCurveTo(e,t,i,r,s,a){this._currentPath.addBezierCurveTo(e,t,i,r,s,a,this._resolution)}extractHoles(){for(let e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){let e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}});var Pn,QO=y(()=>{Qv();p4();SO();A4();R4();M4();I4();P4();xX();VO();yX();IX();PX();TO();vO();LX();XO();NX();wX();BX();GX();WX();XX();Pn={CreateBox:EO,CreateTiledBox:T4,CreateSphere:xO,CreateDisc:hO,CreateIcoSphere:YO,CreateRibbon:el,CreateCylinder:RO,CreateTorus:bO,CreateTorusKnot:MO,CreateLineSystem:wO,CreateLines:FO,CreateDashedLines:BO,ExtrudeShape:GO,ExtrudeShapeCustom:kO,CreateLathe:zO,CreateTiledPlane:E4,CreatePlane:WO,CreateGround:pO,CreateTiledGround:gO,CreateGroundFromHeightMap:_O,CreatePolygon:bb,ExtrudePolygon:dE,CreateTube:HO,CreatePolyhedron:uE,CreateGeodesic:VX,CreateGoldberg:zX,CreateDecal:KO,CreateCapsule:jO,CreateText:HX}});var fa,yb=y(()=>{fa=class{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&(t.prePassRenderer.getIndex(2)!==-1||t.prePassRenderer.getIndex(11)!==-1)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());let a=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=a.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==a.frameId&&(this._lastUpdateFrameId=a.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}}});var wr,uo=y(()=>{wr=class{constructor(e){if(this.VERTEXOUTPUT_INVARIANT=!1,this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(let e of Object.keys(this))e[0]!=="_"&&this._keys.push(e);if(this._externalProperties)for(let e in this._externalProperties)this._keys.indexOf(e)===-1&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;t<this._keys.length;t++){let i=this._keys[t];if(this[i]!==e[i])return!1}return!0}cloneTo(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(let t=0;t<this._keys.length;t++){let i=this._keys[t];e[i]=this[i]}}reset(){for(let e of this._keys)this._setDefaultValue(e)}_setDefaultValue(e){var r,s,a,o,l;let t=(a=(s=(r=this._externalProperties)==null?void 0:r[e])==null?void 0:s.type)!=null?a:typeof this[e],i=(l=(o=this._externalProperties)==null?void 0:o[e])==null?void 0:l.default;switch(t){case"number":this[e]=i!=null?i:0;break;case"string":this[e]=i!=null?i:"";break;default:this[e]=i!=null?i:!1;break}}toString(){let e="";for(let t=0;t<this._keys.length;t++){let i=this._keys[t],r=this[i];switch(typeof r){case"number":case"string":e+="#define "+i+" "+r+`
`;break;default:r&&(e+="#define "+i+`
`);break}}return e}}});function rg(n){return class extends n{constructor(){super(...arguments),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1}}}var Ib=y(()=>{uo()});function dme(){cme.length=0,fme=!1,Ae.OnEventObservable.remove(YX),YX=null}var lme,ng,cme,fme,YX,KX=y(()=>{ls();Yi();eR();k();lme=new RegExp("^([gimus]+)!"),ng=class n{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let r=0;r<this._plugins.length;++r)if(this._plugins[r].name===e.name)return!1;if(this._material._uniformBufferLayoutBuilt&&(this._material.resetDrawCache(),this._material._createUniformBuffer()),!e.isCompatible(this._material.shaderLanguage))throw`The plugin "${e.name}" can't be added to the material "${this._material.name}" because the plugin is not compatible with the shader language of the material.`;let t=e.getClassName();n._MaterialPluginClassToMainDefine[t]||(n._MaterialPluginClassToMainDefine[t]="MATERIALPLUGIN_"+ ++n._MaterialPluginCounter),this._material._callbackPluginEventGeneric=(r,s)=>this._handlePluginEvent(r,s),this._plugins.push(e),this._plugins.sort((r,s)=>r.priority-s.priority),this._codeInjectionPoints={};let i={};i[n._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(let r of this._plugins)r.collectDefines(i),this._collectPointNames("vertex",r.getCustomCode("vertex",this._material.shaderLanguage)),this._collectPointNames("fragment",r.getCustomCode("fragment",this._material.shaderLanguage));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){this._activePlugins.indexOf(e)===-1&&(this._activePlugins.push(e),this._activePlugins.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e)return this._plugins[t];return null}_handlePluginEventIsReadyForSubMesh(e){let t=!0;for(let i of this._activePlugins)t=t&&i.isReadyForSubMesh(e.defines,this._scene,this._engine,e.subMesh);e.isReadyForSubMesh=t}_handlePluginEventPrepareDefinesBeforeAttributes(e){for(let t of this._activePlugins)t.prepareDefinesBeforeAttributes(e.defines,this._scene,e.mesh)}_handlePluginEventPrepareDefines(e){for(let t of this._activePlugins)t.prepareDefines(e.defines,this._scene,e.mesh)}_handlePluginEventHardBindForSubMesh(e){for(let t of this._activePluginsForExtraEvents)t.hardBindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventBindForSubMesh(e){for(let t of this._activePlugins)t.bindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventHasRenderTargetTextures(e){let t=!1;for(let i of this._activePluginsForExtraEvents)if(t=i.hasRenderTargetTextures(),t)break;e.hasRenderTargetTextures=t}_handlePluginEventFillRenderTargetTextures(e){for(let t of this._activePluginsForExtraEvents)t.fillRenderTargetTextures(e.renderTargets)}_handlePluginEvent(e,t){var i;switch(e){case 512:{let r=t;for(let s of this._activePlugins)s.getActiveTextures(r.activeTextures);break}case 256:{let r=t;for(let s of this._activePlugins)s.getAnimatables(r.animatables);break}case 1024:{let r=t,s=!1;for(let a of this._activePlugins)if(s=a.hasTexture(r.texture),s)break;r.hasTexture=s;break}case 2:{let r=t;for(let s of this._plugins)s.dispose(r.forceDisposeTextures);break}case 4:{let r=t;r.defineNames=this._defineNamesFromPlugins;break}case 128:{let r=t;for(let s of this._activePlugins)r.fallbackRank=s.addFallbacks(r.defines,r.fallbacks,r.fallbackRank),s.getAttributes(r.attributes,this._scene,r.mesh);this._uniformList.length>0&&r.uniforms.push(...this._uniformList),this._samplerList.length>0&&r.samplers.push(...this._samplerList),this._uboList.length>0&&r.uniformBuffersNames.push(...this._uboList),r.customCode=this._injectCustomCode(r,r.customCode);break}case 8:{let r=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];let s=this._material.shaderLanguage===1;for(let a of this._plugins){let o=a.getUniforms(this._material.shaderLanguage);if(o){if(o.ubo)for(let l of o.ubo){if(l.size&&l.type){let c=(i=l.arraySize)!=null?i:0;if(r.ubo.addUniform(l.name,l.size,c),s){let f;switch(l.type){case"mat4":f="mat4x4f";break;case"float":f="f32";break;default:f=`${l.type}f`;break}c>0?this._uboDeclaration+=`uniform ${l.name}: array<${f}, ${c}>;
`:this._uboDeclaration+=`uniform ${l.name}: ${f};
`}else this._uboDeclaration+=`${l.type} ${l.name}${c>0?`[${c}]`:""};
`}this._uniformList.push(l.name)}o.vertex&&(this._vertexDeclaration+=o.vertex+`
`),o.fragment&&(this._fragmentDeclaration+=o.fragment+`
`),o.externalUniforms&&this._uniformList.push(...o.externalUniforms)}a.getSamplers(this._samplerList),a.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(let i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,r)=>{var o,l;t&&(r=t(i,r)),this._uboDeclaration&&(r=r.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(r=r.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(r=r.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));let s=(o=this._codeInjectionPoints)==null?void 0:o[i];if(!s)return r;let a=null;for(let c in s){let f="";for(let d of this._activePlugins){let u=this._material.shaderLanguage,h=(l=d.getCustomCode(i,u))==null?void 0:l[c];h&&(d.resolveIncludes&&(a===null&&(a={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:x.GetShadersRepository(u),includesShadersStore:x.GetIncludesShadersStore(u),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}),a.isFragment=i==="fragment",mv(h,a,m=>h=m)),f+=h+`
`)}if(f.length>0)if(c.charAt(0)==="!"){c=c.substring(1);let d="g";if(c.charAt(0)==="!")d="",c=c.substring(1);else{let g=lme.exec(c);g&&g.length>=2&&(d=g[1],c=c.substring(d.length+1))}d.indexOf("g")<0&&(d+="g");let u=r,h=new RegExp(c,d),m=h.exec(u);for(;m!==null;){let g=f;for(let p=0;p<m.length;++p)g=g.replace("$"+p,m[p]);r=r.replace(m[0],g),m=h.exec(u)}}else{let d="#define "+c;r=r.replace(d,`
`+f+`
`+d)}}return r}}};ng._MaterialPluginClassToMainDefine={};ng._MaterialPluginCounter=0;Oe.OnEnginesDisposedObservable.add(()=>{dme()});cme=[],fme=!1,YX=null});var qr,Md=y(()=>{jt();Yt();KX();Or();ir();qr=class{isCompatible(e){return e===0}_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,r,s=!0,a=!1,o=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this.doNotSerialize=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=o,e.pluginManager||(e.pluginManager=new ng(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),a&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[127]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e,t=0){return null}collectDefines(e){if(this._pluginDefineNames)for(let t of Object.keys(this._pluginDefineNames)){if(t[0]==="_")continue;let i=typeof this._pluginDefineNames[t];e[t]={type:i==="number"?"number":i==="string"?"string":i==="boolean"?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(e=0){return{}}copyTo(e){at.Clone(()=>e,this)}serialize(){return at.Serialize(this)}parse(e,t,i){at.Parse(()=>this,e,t,i)}};P([F()],qr.prototype,"name",void 0);P([F()],qr.prototype,"priority",void 0);P([F()],qr.prototype,"resolveIncludes",void 0);P([F()],qr.prototype,"registerForExtraEvents",void 0);zt("BABYLON.MaterialPluginBase",qr)});var $O,ho,JO=y(()=>{jt();ls();Yt();co();uo();Md();os();$O=class extends wr{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}},ho=class extends qr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"DetailMap",140,new $O,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Ae.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&fe.DetailTextureEnabled&&!this._texture.isReady()):!0}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;let i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&fe.DetailTextureEnabled&&this._isEnabled?(fi(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;let i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&this._texture&&fe.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),di(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&fe.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){var t;e&&((t=this._texture)==null||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}};P([Xt("detailTexture"),le("_markAllSubMeshesAsTexturesDirty")],ho.prototype,"texture",void 0);P([F()],ho.prototype,"diffuseBlendLevel",void 0);P([F()],ho.prototype,"roughnessBlendLevel",void 0);P([F()],ho.prototype,"bumpLevel",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],ho.prototype,"normalBlendMethod",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],ho.prototype,"isEnabled",void 0)});var jX,us,Cb=y(()=>{He();(function(n){n[n.Zero=0]="Zero",n[n.One=1]="One",n[n.MaxViewZ=2]="MaxViewZ",n[n.NoClear=3]="NoClear"})(jX||(jX={}));us=class n{static CreateConfiguration(e){return n._Configurations[e]={defines:{},previousWorldMatrices:{},previousViewProjection:Q.Zero(),currentViewProjection:Q.Zero(),previousBones:{},lastUpdateFrameId:-1,excludedSkinnedMesh:[],reverseCulling:!1},n._Configurations[e]}static DeleteConfiguration(e){delete n._Configurations[e]}static GetConfiguration(e){return n._Configurations[e]}static AddUniformsAndSamplers(e,t){e.push("previousWorld","previousViewProjection","mPreviousBones")}static MarkAsDirty(e,t){for(let i of t)if(i.subMeshes)for(let r of i.subMeshes)r._removeDrawWrapper(e)}static PrepareDefines(e,t,i){if(!i._arePrePassDirty)return;let r=n._Configurations[e];if(!r)return;i.PREPASS=!0;let s=0;for(let a=0;a<n.GeometryTextureDescriptions.length;a++){let o=n.GeometryTextureDescriptions[a],l=o.define,c=o.defineIndex,f=r.defines[c];f!==void 0?(i[l]=!0,i[c]=f,s++):(i[l]=!1,delete i[c])}i.SCENE_MRT_COUNT=s,i.BONES_VELOCITY_ENABLED=t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&!t.skeleton.isUsingTextureForMatrices&&r.excludedSkinnedMesh.indexOf(t)===-1}static Bind(e,t,i,r,s){let a=n._Configurations[e];if(!a)return;let o=i.getScene(),l=o.getEngine();if(a.reverseCulling&&l.setStateCullFaceType(o._mirroredCameraPosition?s.cullBackFaces:!s.cullBackFaces),(a.defines.PREPASS_VELOCITY_INDEX!==void 0||a.defines.PREPASS_VELOCITY_LINEAR_INDEX!==void 0)&&(a.previousWorldMatrices[i.uniqueId]||(a.previousWorldMatrices[i.uniqueId]=r.clone()),a.previousViewProjection||(a.previousViewProjection=o.getTransformMatrix().clone(),a.currentViewProjection=o.getTransformMatrix().clone()),a.currentViewProjection.updateFlag!==o.getTransformMatrix().updateFlag?(a.lastUpdateFrameId=l.frameId,a.previousViewProjection.copyFrom(a.currentViewProjection),a.currentViewProjection.copyFrom(o.getTransformMatrix())):a.lastUpdateFrameId!==l.frameId&&(a.lastUpdateFrameId=l.frameId,a.previousViewProjection.copyFrom(a.currentViewProjection)),t.setMatrix("previousWorld",a.previousWorldMatrices[i.uniqueId]),t.setMatrix("previousViewProjection",a.previousViewProjection),a.previousWorldMatrices[i.uniqueId]=r.clone(),i.useBones&&i.computeBonesUsingShaders&&i.skeleton)){let c=i.skeleton;if(!c.isUsingTextureForMatrices||t.getUniformIndex("boneTextureInfo")===-1){let f=c.getTransformMatrices(i);f&&(a.previousBones[i.uniqueId]||(a.previousBones[i.uniqueId]=f.slice()),t.setMatrices("mPreviousBones",a.previousBones[i.uniqueId]),a.previousBones[i.uniqueId].set(f))}}}};us.GeometryTextureDescriptions=[{type:0,name:"IrradianceLegacy",clearType:0,define:"PREPASS_IRRADIANCE_LEGACY",defineIndex:"PREPASS_IRRADIANCE_LEGACY_INDEX"},{type:1,name:"WorldPosition",clearType:0,define:"PREPASS_POSITION",defineIndex:"PREPASS_POSITION_INDEX"},{type:2,name:"Velocity",clearType:0,define:"PREPASS_VELOCITY",defineIndex:"PREPASS_VELOCITY_INDEX"},{type:3,name:"Reflectivity",clearType:0,define:"PREPASS_REFLECTIVITY",defineIndex:"PREPASS_REFLECTIVITY_INDEX"},{type:5,name:"ViewDepth",clearType:2,define:"PREPASS_DEPTH",defineIndex:"PREPASS_DEPTH_INDEX"},{type:6,name:"ViewNormal",clearType:0,define:"PREPASS_NORMAL",defineIndex:"PREPASS_NORMAL_INDEX"},{type:7,name:"AlbedoSqrt",clearType:0,define:"PREPASS_ALBEDO_SQRT",defineIndex:"PREPASS_ALBEDO_SQRT_INDEX"},{type:8,name:"WorldNormal",clearType:0,define:"PREPASS_WORLD_NORMAL",defineIndex:"PREPASS_WORLD_NORMAL_INDEX"},{type:9,name:"LocalPosition",clearType:0,define:"PREPASS_LOCAL_POSITION",defineIndex:"PREPASS_LOCAL_POSITION_INDEX"},{type:10,name:"ScreenDepth",clearType:1,define:"PREPASS_SCREENSPACE_DEPTH",defineIndex:"PREPASS_SCREENSPACE_DEPTH_INDEX"},{type:11,name:"LinearVelocity",clearType:0,define:"PREPASS_VELOCITY_LINEAR",defineIndex:"PREPASS_VELOCITY_LINEAR_INDEX"},{type:12,name:"Albedo",clearType:0,define:"PREPASS_ALBEDO",defineIndex:"PREPASS_ALBEDO_INDEX"},{type:13,name:"NormalizedViewDepth",clearType:1,define:"PREPASS_NORMALIZED_VIEW_DEPTH",defineIndex:"PREPASS_NORMALIZED_VIEW_DEPTH_INDEX"},{type:4,name:"Color",clearType:3,define:"PREPASS_COLOR",defineIndex:"PREPASS_COLOR_INDEX"},{type:14,name:"Irradiance",clearType:0,define:"PREPASS_IRRADIANCE",defineIndex:"PREPASS_IRRADIANCE_INDEX"}];us._Configurations={}});function sg(n){return class extends n{constructor(){super(...arguments),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1}}}var Pb=y(()=>{});function ag(n){return class extends n{constructor(){super(...arguments),this.PREPASS=!1,this.PREPASS_COLOR=!1,this.PREPASS_COLOR_INDEX=-1,this.PREPASS_IRRADIANCE_LEGACY=!1,this.PREPASS_IRRADIANCE_LEGACY_INDEX=-1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO=!1,this.PREPASS_ALBEDO_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_SCREENSPACE_DEPTH=!1,this.PREPASS_SCREENSPACE_DEPTH_INDEX=-1,this.PREPASS_NORMALIZED_VIEW_DEPTH=!1,this.PREPASS_NORMALIZED_VIEW_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_WORLD_NORMAL=!1,this.PREPASS_WORLD_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_LOCAL_POSITION=!1,this.PREPASS_LOCAL_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_VELOCITY_LINEAR=!1,this.PREPASS_VELOCITY_LINEAR_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0}}}var Lb=y(()=>{});function og(n){return class extends n{constructor(...e){super(...e),lk()(this,"_imageProcessingConfiguration")}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsImageProcessingDirty&&this._markAllSubMeshesAsImageProcessingDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),!e&&this.getScene?this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration:e&&(this._imageProcessingConfiguration=e),this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty&&this._markAllSubMeshesAsImageProcessingDirty()})))}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}}}var Db=y(()=>{Yt()});var ZX,ume,sh=y(()=>{k();ZX="sceneUboDeclaration",ume=`struct Scene {viewProjection : mat4x4<f32>,
#ifdef MULTIVIEW
viewProjectionR : mat4x4<f32>,
#endif
view : mat4x4<f32>,
projection : mat4x4<f32>,
vEyePosition : vec4<f32>,
inverseProjection : mat4x4<f32>,};
#define SCENE_UBO
var<uniform> scene : Scene;
`;x.IncludesShadersStoreWGSL[ZX]||(x.IncludesShadersStoreWGSL[ZX]=ume)});var qX,hme,pE=y(()=>{k();qX="meshUboDeclaration",hme=`struct Mesh {world : mat4x4<f32>,
visibility : f32,};var<uniform> mesh : Mesh;
#define WORLD_UBO
`;x.IncludesShadersStoreWGSL[qX]||(x.IncludesShadersStoreWGSL[qX]=hme)});var QX,mme,eN=y(()=>{k();sh();pE();QX="defaultUboDeclaration",mme=`uniform diffuseLeftColor: vec4f;uniform diffuseRightColor: vec4f;uniform opacityParts: vec4f;uniform reflectionLeftColor: vec4f;uniform reflectionRightColor: vec4f;uniform refractionLeftColor: vec4f;uniform refractionRightColor: vec4f;uniform emissiveLeftColor: vec4f;uniform emissiveRightColor: vec4f;uniform vDiffuseInfos: vec2f;uniform vAmbientInfos: vec2f;uniform vOpacityInfos: vec2f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vSpecularInfos: vec2f;uniform vBumpInfos: vec3f;uniform diffuseMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform specularMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform pointSize: f32;uniform alphaCutOff: f32;uniform refractionMatrix: mat4x4f;uniform vRefractionInfos: vec4f;uniform vRefractionPosition: vec3f;uniform vRefractionSize: vec3f;uniform vSpecularColor: vec4f;uniform vEmissiveColor: vec3f;uniform vDiffuseColor: vec4f;uniform vAmbientColor: vec3f;uniform cameraInfo: vec4f;uniform vReflectionInfos: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;
#define ADDITIONAL_UBO_DECLARATION
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;x.IncludesShadersStoreWGSL[QX]||(x.IncludesShadersStoreWGSL[QX]=mme)});var $X,pme,Ob=y(()=>{k();$X="uvAttributeDeclaration",pme=`#if defined(UV{X}) && !defined(USE_VERTEX_PULLING)
attribute uv{X}: vec2f;
#endif
`;x.IncludesShadersStoreWGSL[$X]||(x.IncludesShadersStoreWGSL[$X]=pme)});var JX,gme,Nb=y(()=>{k();JX="prePassVertexDeclaration",gme=`#ifdef PREPASS
#ifdef PREPASS_LOCAL_POSITION
varying vPosition : vec3f;
#endif
#ifdef PREPASS_DEPTH
varying vViewPos: vec3f;
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
varying vNormViewDepth: f32;
#endif
#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)
uniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;
#endif
#endif
`;x.IncludesShadersStoreWGSL[JX]||(x.IncludesShadersStoreWGSL[JX]=gme)});var e5,_me,lg=y(()=>{k();e5="mainUVVaryingDeclaration",_me=`#ifdef MAINUV{X}
varying vMainUV{X}: vec2f;
#endif
`;x.IncludesShadersStoreWGSL[e5]||(x.IncludesShadersStoreWGSL[e5]=_me)});var t5,vme,wb=y(()=>{k();t5="samplerVertexDeclaration",vme=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0
varying v_VARYINGNAME_UV: vec2f;
#endif
`;x.IncludesShadersStoreWGSL[t5]||(x.IncludesShadersStoreWGSL[t5]=vme)});var i5,Eme,tN=y(()=>{k();i5="bumpVertexDeclaration",Eme=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f;
#endif
#endif
`;x.IncludesShadersStoreWGSL[i5]||(x.IncludesShadersStoreWGSL[i5]=Eme)});var r5,Sme,n5=y(()=>{k();r5="lightVxFragmentDeclaration",Sme=`#ifdef LIGHT{X}
uniform vLightData{X}: vec4f;uniform vLightDiffuse{X}: vec4f;
#ifdef SPECULARTERM
uniform vLightSpecular{X}: vec4f;
#else
var vLightSpecular{X}: vec4f= vec4f(0.);
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform lightMatrix{X}: mat4x4f[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromLight{X}: vec4f[SHADOWCSMNUM_CASCADES{X}];varying var vDepthMetric{X}: f32[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromCamera{X}: vec4f;
#elif defined(SHADOWCUBE{X})
#else
varying var vPositionFromLight{X}: vec4f;varying var vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f;
#endif
uniform shadowsInfo{X}: vec4f;uniform depthValues{X}: vec2f;
#endif
#ifdef SPOTLIGHT{X}
uniform vLightDirection{X}: vec4f;uniform vLightFalloff{X}: vec4f;
#elif defined(POINTLIGHT{X})
uniform vLightFalloff{X}: vec4f;
#elif defined(HEMILIGHT{X})
uniform vLightGround{X}: vec3f;
#endif
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
uniform vLightWidth{X}: vec4f;uniform vLightHeight{X}: vec4f;
#endif
#endif
`;x.IncludesShadersStoreWGSL[r5]||(x.IncludesShadersStoreWGSL[r5]=Sme)});var s5,Tme,Fb=y(()=>{k();s5="lightVxUboDeclaration",Tme=`#ifdef LIGHT{X}
struct Light{X}
{vLightData: vec4f,
vLightDiffuse: vec4f,
vLightSpecular: vec4f,
#ifdef SPOTLIGHT{X}
vLightDirection: vec4f,
vLightFalloff: vec4f,
#elif defined(POINTLIGHT{X})
vLightFalloff: vec4f,
#elif defined(HEMILIGHT{X})
vLightGround: vec3f,
#elif defined(CLUSTLIGHT{X})
vSliceData: vec2f,
vSliceRanges: array<vec4f,CLUSTLIGHT_SLICES>,
#endif
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
vLightWidth: vec4f,
vLightHeight: vec4f,
#endif
shadowsInfo: vec4f,
depthValues: vec2f} ;var<uniform> light{X} : Light{X};
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform lightMatrix{X}: array<mat4x4f,SHADOWCSMNUM_CASCADES{X}>;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;
#elif defined(SHADOWCUBE{X})
#else
varying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f;
#endif
#endif
#endif
`;x.IncludesShadersStoreWGSL[s5]||(x.IncludesShadersStoreWGSL[s5]=Tme)});var a5,Ame,yd=y(()=>{k();a5="morphTargetsVertexGlobalDeclaration",Ame=`#ifdef MORPHTARGETS
uniform morphTargetInfluences : array<f32,NUM_MORPH_INFLUENCERS>;
#ifdef MORPHTARGETS_TEXTURE
uniform morphTargetTextureIndices : array<f32,NUM_MORPH_INFLUENCERS>;uniform morphTargetTextureInfo : vec3<f32>;var morphTargets : texture_2d_array<f32>;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3<f32>
{
let textureWidth: i32=i32(uniforms.morphTargetTextureInfo.y);let y: i32=i32(vertexIndex)/textureWidth;let x: i32=i32(vertexIndex) % textureWidth;return textureLoad(morphTargets,vec2i(x,y),i32(uniforms.morphTargetTextureIndices[targetIndex]),0).xyz;}
fn readVector4FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec4<f32>
{
let textureWidth: i32=i32(uniforms.morphTargetTextureInfo.y);
let y: i32=i32(vertexIndex)/textureWidth;let x: i32=i32(vertexIndex) % textureWidth;return textureLoad(morphTargets,vec2i(x,y),i32(uniforms.morphTargetTextureIndices[targetIndex]),0);}
#endif
#endif
`;x.IncludesShadersStoreWGSL[a5]||(x.IncludesShadersStoreWGSL[a5]=Ame)});var o5,xme,Id=y(()=>{k();o5="morphTargetsVertexDeclaration",xme=`#ifdef MORPHTARGETS
#ifndef MORPHTARGETS_TEXTURE
#ifdef MORPHTARGETS_POSITION
attribute position{X} : vec3<f32>;
#endif
#ifdef MORPHTARGETS_NORMAL
attribute normal{X} : vec3<f32>;
#endif
#ifdef MORPHTARGETS_TANGENT
attribute tangent{X} : vec3<f32>;
#endif
#ifdef MORPHTARGETS_UV
attribute uv_{X} : vec2<f32>;
#endif
#ifdef MORPHTARGETS_UV2
attribute uv2_{X} : vec2<f32>;
#endif
#ifdef MORPHTARGETS_COLOR
attribute color{X} : vec4<f32>;
#endif
#elif {X}==0
uniform morphTargetCount: f32;
#endif
#endif
`;x.IncludesShadersStoreWGSL[o5]||(x.IncludesShadersStoreWGSL[o5]=xme)});var l5,Rme,ah=y(()=>{k();l5="logDepthDeclaration",Rme=`#ifdef LOGARITHMICDEPTH
uniform logarithmicDepthConstant: f32;varying vFragmentDepth: f32;
#endif
`;x.IncludesShadersStoreWGSL[l5]||(x.IncludesShadersStoreWGSL[l5]=Rme)});var c5,bme,Bb=y(()=>{k();c5="vertexPullingDeclaration",bme=`#ifdef USE_VERTEX_PULLING
#ifdef VERTEX_PULLING_USE_INDEX_BUFFER
var<storage,read> indices : array<u32>;
#endif
var<storage,read> position : array<f32>;uniform vp_position_info : vec4f;
#ifdef NORMAL
var<storage,read> normal : array<f32>;uniform vp_normal_info : vec4f;
#endif
#ifdef TANGENT
var<storage,read> tangent : array<f32>;uniform vp_tangent_info : vec4f;
#endif
#ifdef UV1
var<storage,read> uv : array<f32>;uniform vp_uv_info : vec4f;
#define VP_UV1_SUPPORTED
#endif
#ifdef UV2
var<storage,read> uv2 : array<f32>;uniform vp_uv2_info : vec4f;
#define VP_UV2_SUPPORTED
#endif
#ifdef UV3
var<storage,read> uv3 : array<f32>;uniform vp_uv3_info : vec4f;
#define VP_UV3_SUPPORTED
#endif
#ifdef UV4
var<storage,read> uv4 : array<f32>;uniform vp_uv4_info : vec4f;
#define VP_UV4_SUPPORTED
#endif
#ifdef UV5
var<storage,read> uv5 : array<f32>;uniform vp_uv5_info : vec4f;
#define VP_UV5_SUPPORTED
#endif
#ifdef UV6
var<storage,read> uv6 : array<f32>;uniform vp_uv6_info : vec4f;
#define VP_UV6_SUPPORTED
#endif
#ifdef VERTEXCOLOR
var<storage,read> color : array<f32>;uniform vp_color_info : vec4f;
#endif
#if NUM_BONE_INFLUENCERS>0
var<storage,read> matricesIndices : array<u32>;var<storage,read> matricesWeights : array<f32>;uniform vp_matricesIndices_info : vec4f;uniform vp_matricesWeights_info : vec4f;
#if NUM_BONE_INFLUENCERS>4
var<storage,read> matricesIndicesExtra : array<u32>;var<storage,read> matricesWeightsExtra : array<f32>;uniform vp_matricesIndicesExtra_info : vec4f;uniform vp_matricesWeightsExtra_info : vec4f;
#endif
#endif
fn vp_convertToFloat(word : u32,byteInWord : u32,dataType : u32,normalized : bool)->f32 {switch (dataType) {case 5120u: {
let shift=byteInWord*8u;let value=(word>>shift) & 0xFFu;let signedValue=f32(i32(value<<24u)>>24u);if (normalized) { return signedValue/127.0; }
return signedValue;}
case 5121u: {
let shift=byteInWord*8u;let value=(word>>shift) & 0xFFu;if (normalized) { return f32(value)/255.0; }
return f32(value);}
case 5122u: {
let shift=(byteInWord & 0xFFFFFFFEu)*8u;let value=(word>>shift) & 0xFFFFu;let signedValue=f32(i32(value<<16u)>>16u);if (normalized) { return signedValue/32767.0; }
return signedValue;}
case 5123u: {
let shift=(byteInWord & 0xFFFFFFFEu)*8u;let value=(word>>shift) & 0xFFFFu;if (normalized) { return f32(value)/65535.0; }
return f32(value);}
case 5126u: {
return bitcast<f32>(word);}
default: { return 0.0; }}}
fn vp_componentSize(dataType : u32)->u32 {return select(select(2u,1u,dataType==5120u || dataType==5121u),4u,dataType==5126u);}
fn vp_readVertexIndex(index : u32)->u32 {
#ifndef VERTEX_PULLING_USE_INDEX_BUFFER
return index;
#else
#ifdef VERTEX_PULLING_INDEX_BUFFER_32BITS
return indices[index];
#else
let u32_index=index/2u;let bit_offset=(index & 1u)*16u;return (indices[u32_index]>>bit_offset) & 0xFFFFu;
#endif
#endif
}
fn vp_readPositionValue(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(bitcast<u32>(position[byteOffset/4u]),byteOffset % 4u,dataType,normalized);}
fn vp_readPosition(info : vec4f,vertexIndex : u32)->vec3f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec3f(
vp_readPositionValue(offset,dataType,normalized),
vp_readPositionValue(offset+cs,dataType,normalized),
vp_readPositionValue(offset+cs*2u,dataType,normalized)
);}
#ifdef NORMAL
fn vp_readNormalValue(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(bitcast<u32>(normal[byteOffset/4u]),byteOffset % 4u,dataType,normalized);}
fn vp_readNormal(info : vec4f,vertexIndex : u32)->vec3f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec3f(
vp_readNormalValue(offset,dataType,normalized),
vp_readNormalValue(offset+cs,dataType,normalized),
vp_readNormalValue(offset+cs*2u,dataType,normalized)
);}
#endif
#ifdef TANGENT
fn vp_readTangentValue(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(bitcast<u32>(tangent[byteOffset/4u]),byteOffset % 4u,dataType,normalized);}
fn vp_readTangent(info : vec4f,vertexIndex : u32)->vec4f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec4f(
vp_readTangentValue(offset,dataType,normalized),
vp_readTangentValue(offset+cs,dataType,normalized),
vp_readTangentValue(offset+cs*2u,dataType,normalized),
vp_readTangentValue(offset+cs*3u,dataType,normalized)
);}
#endif
#ifdef UV1
fn vp_readUVValue(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(bitcast<u32>(uv[byteOffset/4u]),byteOffset % 4u,dataType,normalized);}
fn vp_readUV(info : vec4f,vertexIndex : u32)->vec2f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec2f(
vp_readUVValue(offset,dataType,normalized),
vp_readUVValue(offset+cs,dataType,normalized)
);}
#endif
#ifdef UV2
fn vp_readUV2Value(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(bitcast<u32>(uv2[byteOffset/4u]),byteOffset % 4u,dataType,normalized);}
fn vp_readUV2(info : vec4f,vertexIndex : u32)->vec2f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec2f(
vp_readUV2Value(offset,dataType,normalized),
vp_readUV2Value(offset+cs,dataType,normalized)
);}
#endif
#ifdef UV3
fn vp_readUV3Value(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(bitcast<u32>(uv3[byteOffset/4u]),byteOffset % 4u,dataType,normalized);}
fn vp_readUV3(info : vec4f,vertexIndex : u32)->vec2f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec2f(
vp_readUV3Value(offset,dataType,normalized),
vp_readUV3Value(offset+cs,dataType,normalized)
);}
#endif
#ifdef UV4
fn vp_readUV4Value(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(bitcast<u32>(uv4[byteOffset/4u]),byteOffset % 4u,dataType,normalized);}
fn vp_readUV4(info : vec4f,vertexIndex : u32)->vec2f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec2f(
vp_readUV4Value(offset,dataType,normalized),
vp_readUV4Value(offset+cs,dataType,normalized)
);}
#endif
#ifdef UV5
fn vp_readUV5Value(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(bitcast<u32>(uv5[byteOffset/4u]),byteOffset % 4u,dataType,normalized);}
fn vp_readUV5(info : vec4f,vertexIndex : u32)->vec2f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec2f(
vp_readUV5Value(offset,dataType,normalized),
vp_readUV5Value(offset+cs,dataType,normalized)
);}
#endif
#ifdef UV6
fn vp_readUV6Value(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(bitcast<u32>(uv6[byteOffset/4u]),byteOffset % 4u,dataType,normalized);}
fn vp_readUV6(info : vec4f,vertexIndex : u32)->vec2f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec2f(
vp_readUV6Value(offset,dataType,normalized),
vp_readUV6Value(offset+cs,dataType,normalized)
);}
#endif
#ifdef VERTEXCOLOR
fn vp_readColorValue(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(bitcast<u32>(color[byteOffset/4u]),byteOffset % 4u,dataType,normalized);}
fn vp_readColor(info : vec4f,vertexIndex : u32)->vec4f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec4f(
vp_readColorValue(offset,dataType,normalized),
vp_readColorValue(offset+cs,dataType,normalized),
vp_readColorValue(offset+cs*2u,dataType,normalized),
vp_readColorValue(offset+cs*3u,dataType,normalized)
);}
#endif
#if NUM_BONE_INFLUENCERS>0
fn vp_readMatrixIndexValue(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(matricesIndices[byteOffset/4u],byteOffset % 4u,dataType,normalized);}
fn vp_readBoneIndices(info : vec4f,vertexIndex : u32)->vec4f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec4f(
vp_readMatrixIndexValue(offset,dataType,normalized),
vp_readMatrixIndexValue(offset+cs,dataType,normalized),
vp_readMatrixIndexValue(offset+cs*2u,dataType,normalized),
vp_readMatrixIndexValue(offset+cs*3u,dataType,normalized)
);}
fn vp_readMatrixWeightValue(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(bitcast<u32>(matricesWeights[byteOffset/4u]),byteOffset % 4u,dataType,normalized);}
fn vp_readBoneWeights(info : vec4f,vertexIndex : u32)->vec4f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec4f(
vp_readMatrixWeightValue(offset,dataType,normalized),
vp_readMatrixWeightValue(offset+cs,dataType,normalized),
vp_readMatrixWeightValue(offset+cs*2u,dataType,normalized),
vp_readMatrixWeightValue(offset+cs*3u,dataType,normalized)
);}
#if NUM_BONE_INFLUENCERS>4
fn vp_readMatrixIndexExtraValue(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(matricesIndicesExtra[byteOffset/4u],byteOffset % 4u,dataType,normalized);}
fn vp_readBoneIndicesExtra(info : vec4f,vertexIndex : u32)->vec4f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec4f(
vp_readMatrixIndexExtraValue(offset,dataType,normalized),
vp_readMatrixIndexExtraValue(offset+cs,dataType,normalized),
vp_readMatrixIndexExtraValue(offset+cs*2u,dataType,normalized),
vp_readMatrixIndexExtraValue(offset+cs*3u,dataType,normalized)
);}
fn vp_readMatrixWeightExtraValue(byteOffset : u32,dataType : u32,normalized : bool)->f32 {return vp_convertToFloat(bitcast<u32>(matricesWeightsExtra[byteOffset/4u]),byteOffset % 4u,dataType,normalized);}
fn vp_readBoneWeightsExtra(info : vec4f,vertexIndex : u32)->vec4f {let baseOffset=u32(info.x);let stride=u32(info.y);let dataType=u32(info.z);let normalized=info.w != 0.0;let offset=baseOffset+vertexIndex*stride;let cs=vp_componentSize(dataType);return vec4f(
vp_readMatrixWeightExtraValue(offset,dataType,normalized),
vp_readMatrixWeightExtraValue(offset+cs,dataType,normalized),
vp_readMatrixWeightExtraValue(offset+cs*2u,dataType,normalized),
vp_readMatrixWeightExtraValue(offset+cs*3u,dataType,normalized)
);}
#endif
#endif
#endif
`;x.IncludesShadersStoreWGSL[c5]||(x.IncludesShadersStoreWGSL[c5]=bme)});var f5,Mme,Ub=y(()=>{k();f5="vertexPullingVertex",Mme=`#ifdef USE_VERTEX_PULLING
let vpVertexIndex: u32=vp_readVertexIndex(vertexInputs.vertexIndex);positionUpdated=vp_readPosition(uniforms.vp_position_info,vpVertexIndex);
#ifdef NORMAL
normalUpdated=vp_readNormal(uniforms.vp_normal_info,vpVertexIndex);
#endif
#ifdef TANGENT
tangentUpdated=vp_readTangent(uniforms.vp_tangent_info,vpVertexIndex);
#endif
#ifdef UV1
uvUpdated=vp_readUV(uniforms.vp_uv_info,vpVertexIndex);
#endif
#ifdef UV2
uv2Updated=vp_readUV2(uniforms.vp_uv2_info,vpVertexIndex);
#endif
#ifdef UV3
var uv3Updated: vec2f=vp_readUV3(uniforms.vp_uv3_info,vpVertexIndex);
#endif
#ifdef UV4
var uv4Updated: vec2f=vp_readUV4(uniforms.vp_uv4_info,vpVertexIndex);
#endif
#ifdef UV5
var uv5Updated: vec2f=vp_readUV5(uniforms.vp_uv5_info,vpVertexIndex);
#endif
#ifdef UV6
var uv6Updated: vec2f=vp_readUV6(uniforms.vp_uv6_info,vpVertexIndex);
#endif
#ifdef VERTEXCOLOR
colorUpdated=vp_readColor(uniforms.vp_color_info,vpVertexIndex);
#endif
#ifdef MORPHTARGETS
let vp_basePosition: vec3f=positionUpdated;
#ifdef NORMAL
let vp_baseNormal: vec3f=normalUpdated;
#endif
#ifdef TANGENT
let vp_baseTangent: vec4f=tangentUpdated;
#endif
#ifdef UV1
let vp_baseUV: vec2f=uvUpdated;
#endif
#ifdef UV2
let vp_baseUV2: vec2f=uv2Updated;
#endif
#ifdef VERTEXCOLOR
let vp_baseColor: vec4f=colorUpdated;
#endif
#endif
#if NUM_BONE_INFLUENCERS>0
var vp_matricesIndices: vec4f=vp_readBoneIndices(uniforms.vp_matricesIndices_info,vpVertexIndex);var vp_matricesWeights: vec4f=vp_readBoneWeights(uniforms.vp_matricesWeights_info,vpVertexIndex);
#if NUM_BONE_INFLUENCERS>4
var vp_matricesIndicesExtra: vec4f=vp_readBoneIndicesExtra(uniforms.vp_matricesIndicesExtra_info,vpVertexIndex);var vp_matricesWeightsExtra: vec4f=vp_readBoneWeightsExtra(uniforms.vp_matricesWeightsExtra_info,vpVertexIndex);
#endif
#endif
#endif
`;x.IncludesShadersStoreWGSL[f5]||(x.IncludesShadersStoreWGSL[f5]=Mme)});var d5,yme,Cd=y(()=>{k();d5="morphTargetsVertexGlobal",yme=`#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
var vertexID : f32;
#endif
#endif
`;x.IncludesShadersStoreWGSL[d5]||(x.IncludesShadersStoreWGSL[d5]=yme)});var u5,Ime,Pd=y(()=>{k();u5="morphTargetsVertex",Ime=`#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
#if {X}==0
for (var i=0; i<NUM_MORPH_INFLUENCERS; i=i+1) {if (f32(i)>=uniforms.morphTargetCount) {break;}
#ifdef USE_VERTEX_PULLING
vertexID=f32(vpVertexIndex)*uniforms.morphTargetTextureInfo.x;
#else
vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;
#endif
#ifdef MORPHTARGETS_POSITION
#ifdef USE_VERTEX_PULLING
positionUpdated=positionUpdated+(readVector3FromRawSampler(i,vertexID)-vp_basePosition)*uniforms.morphTargetInfluences[i];
#else
positionUpdated=positionUpdated+(readVector3FromRawSampler(i,vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[i];
#endif
#endif
#ifdef MORPHTARGETTEXTURE_HASPOSITIONS
vertexID=vertexID+1.0;
#endif
#ifdef MORPHTARGETS_NORMAL
#ifdef USE_VERTEX_PULLING
normalUpdated=normalUpdated+(readVector3FromRawSampler(i,vertexID) -vp_baseNormal)*uniforms.morphTargetInfluences[i];
#else
normalUpdated=normalUpdated+(readVector3FromRawSampler(i,vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[i];
#endif
#endif
#ifdef MORPHTARGETTEXTURE_HASNORMALS
vertexID=vertexID+1.0;
#endif
#ifdef MORPHTARGETS_UV
#ifdef USE_VERTEX_PULLING
uvUpdated=uvUpdated+(readVector3FromRawSampler(i,vertexID).xy-vp_baseUV)*uniforms.morphTargetInfluences[i];
#else
uvUpdated=uvUpdated+(readVector3FromRawSampler(i,vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[i];
#endif
#endif
#ifdef MORPHTARGETTEXTURE_HASUVS
vertexID=vertexID+1.0;
#endif
#ifdef MORPHTARGETS_TANGENT
#ifdef USE_VERTEX_PULLING
tangentUpdated=vec4f(tangentUpdated.xyz+(readVector3FromRawSampler(i,vertexID) -vp_baseTangent.xyz)*uniforms.morphTargetInfluences[i],tangentUpdated.a);
#else
tangentUpdated=vec4f(tangentUpdated.xyz+(readVector3FromRawSampler(i,vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[i],tangentUpdated.a);
#endif
#endif
#ifdef MORPHTARGETTEXTURE_HASTANGENTS
vertexID=vertexID+1.0;
#endif
#ifdef MORPHTARGETS_UV2
#ifdef USE_VERTEX_PULLING
uv2Updated=uv2Updated+(readVector3FromRawSampler(i,vertexID).xy-vp_baseUV2)*uniforms.morphTargetInfluences[i];
#else
uv2Updated=uv2Updated+(readVector3FromRawSampler(i,vertexID).xy-vertexInputs.uv2)*uniforms.morphTargetInfluences[i];
#endif
#endif
#ifdef MORPHTARGETS_COLOR
#ifdef USE_VERTEX_PULLING
colorUpdated=colorUpdated+(readVector4FromRawSampler(i,vertexID)-vp_baseColor)*uniforms.morphTargetInfluences[i];
#else
colorUpdated=colorUpdated+(readVector4FromRawSampler(i,vertexID)-vertexInputs.color)*uniforms.morphTargetInfluences[i];
#endif
#endif
}
#endif
#else
#ifdef MORPHTARGETS_POSITION
#ifdef USE_VERTEX_PULLING
positionUpdated=positionUpdated+(vertexInputs.position{X}-vp_basePosition)*uniforms.morphTargetInfluences[{X}];
#else
positionUpdated=positionUpdated+(vertexInputs.position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];
#endif
#endif
#ifdef MORPHTARGETS_NORMAL
#ifdef USE_VERTEX_PULLING
normalUpdated=normalUpdated+(vertexInputs.normal{X}-vp_baseNormal)*uniforms.morphTargetInfluences[{X}];
#else
normalUpdated=normalUpdated+(vertexInputs.normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];
#endif
#endif
#ifdef MORPHTARGETS_TANGENT
#ifdef USE_VERTEX_PULLING
tangentUpdated=vec4f(tangentUpdated.xyz+(vertexInputs.tangent{X}-vp_baseTangent.xyz)*uniforms.morphTargetInfluences[{X}],tangentUpdated.a);
#else
tangentUpdated=vec4f(tangentUpdated.xyz+(vertexInputs.tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}],tangentUpdated.a);
#endif
#endif
#ifdef MORPHTARGETS_UV
#ifdef USE_VERTEX_PULLING
uvUpdated=uvUpdated+(vertexInputs.uv_{X}-vp_baseUV)*uniforms.morphTargetInfluences[{X}];
#else
uvUpdated=uvUpdated+(vertexInputs.uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];
#endif
#endif
#ifdef MORPHTARGETS_UV2
#ifdef USE_VERTEX_PULLING
uv2Updated=uv2Updated+(vertexInputs.uv2_{X}-vp_baseUV2)*uniforms.morphTargetInfluences[{X}];
#else
uv2Updated=uv2Updated+(vertexInputs.uv2_{X}-vertexInputs.uv2)*uniforms.morphTargetInfluences[{X}];
#endif
#endif
#ifdef MORPHTARGETS_COLOR
#ifdef USE_VERTEX_PULLING
colorUpdated=colorUpdated+(vertexInputs.color{X}-vp_baseColor)*uniforms.morphTargetInfluences[{X}];
#else
colorUpdated=colorUpdated+(vertexInputs.color{X}-vertexInputs.color)*uniforms.morphTargetInfluences[{X}];
#endif
#endif
#endif
#endif
`;x.IncludesShadersStoreWGSL[u5]||(x.IncludesShadersStoreWGSL[u5]=Ime)});var h5,Cme,Vb=y(()=>{k();h5="prePassVertex",Cme=`#ifdef PREPASS_DEPTH
vertexOutputs.vViewPos=(scene.view*worldPos).rgb;
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
vertexOutputs.vNormViewDepth=((scene.view*worldPos).z-uniforms.cameraInfo.x)/(uniforms.cameraInfo.y-uniforms.cameraInfo.x);
#endif
#ifdef PREPASS_LOCAL_POSITION
vertexOutputs.vPosition=positionUpdated.xyz;
#endif
#if (defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)
vertexOutputs.vCurrentPosition=scene.viewProjection*worldPos;
#if NUM_BONE_INFLUENCERS>0
var previousInfluence: mat4x4f;previousInfluence=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];
#endif
vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0);
#else
vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0);
#endif
#endif
`;x.IncludesShadersStoreWGSL[h5]||(x.IncludesShadersStoreWGSL[h5]=Cme)});var m5,Pme,Gb=y(()=>{k();m5="uvVariableDeclaration",Pme=`#ifdef MAINUV{X}
#if !defined(UV{X})
var uv{X}: vec2f=vec2f(0.,0.);
#elif defined(USE_VERTEX_PULLING)
var uv{X}: vec2f=uv{X}Updated;
#else
var uv{X}: vec2f=vertexInputs.uv{X};
#endif
vertexOutputs.vMainUV{X}=uv{X};
#endif
`;x.IncludesShadersStoreWGSL[m5]||(x.IncludesShadersStoreWGSL[m5]=Pme)});var p5,Lme,kb=y(()=>{k();p5="samplerVertexImplementation",Lme=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0
if (uniforms.v_INFONAME_==0.)
{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(uvUpdated,1.0,0.0)).xy;}
#ifdef UV2
else if (uniforms.v_INFONAME_==1.)
{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(uv2Updated,1.0,0.0)).xy;}
#endif
#ifdef UV3
else if (uniforms.v_INFONAME_==2.)
{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv3,1.0,0.0)).xy;}
#endif
#ifdef UV4
else if (uniforms.v_INFONAME_==3.)
{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv4,1.0,0.0)).xy;}
#endif
#ifdef UV5
else if (uniforms.v_INFONAME_==4.)
{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv5,1.0,0.0)).xy;}
#endif
#ifdef UV6
else if (uniforms.v_INFONAME_==5.)
{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv6,1.0,0.0)).xy;}
#endif
#endif
`;x.IncludesShadersStoreWGSL[p5]||(x.IncludesShadersStoreWGSL[p5]=Lme)});var g5,Dme,zb=y(()=>{k();g5="bumpVertex",Dme=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
var tbnNormal: vec3f=normalize(normalUpdated);var tbnTangent: vec3f=normalize(tangentUpdated.xyz);var tbnBitangent: vec3f=cross(tbnNormal,tbnTangent)*tangentUpdated.w;var matTemp= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz)* mat3x3f(tbnTangent,tbnBitangent,tbnNormal);vertexOutputs.vTBN0=matTemp[0];vertexOutputs.vTBN1=matTemp[1];vertexOutputs.vTBN2=matTemp[2];
#endif
#endif
`;x.IncludesShadersStoreWGSL[g5]||(x.IncludesShadersStoreWGSL[g5]=Dme)});var _5,Ome,Wb=y(()=>{k();_5="shadowsVertex",Ome=`#ifdef SHADOWS
#if defined(SHADOWCSM{X})
#ifdef SCENE_UBO
vertexOutputs.vPositionFromCamera{X}=scene.view*worldPos;
#else
vertexOutputs.vPositionFromCamera{X}=uniforms.view*worldPos;
#endif
#if SHADOWCSMNUM_CASCADES{X}>0
vertexOutputs.vPositionFromLight{X}_0=uniforms.lightMatrix{X}[0]*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetric{X}_0=(-vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vertexOutputs.vDepthMetric{X}_0= (vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#if SHADOWCSMNUM_CASCADES{X}>1
vertexOutputs.vPositionFromLight{X}_1=uniforms.lightMatrix{X}[1]*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetric{X}_1=(-vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vertexOutputs.vDepthMetric{X}_1= (vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#if SHADOWCSMNUM_CASCADES{X}>2
vertexOutputs.vPositionFromLight{X}_2=uniforms.lightMatrix{X}[2]*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetric{X}_2=(-vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vertexOutputs.vDepthMetric{X}_2= (vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#if SHADOWCSMNUM_CASCADES{X}>3
vertexOutputs.vPositionFromLight{X}_3=uniforms.lightMatrix{X}[3]*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetric{X}_3=(-vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vertexOutputs.vDepthMetric{X}_3= (vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})
vertexOutputs.vPositionFromLight{X}=uniforms.lightMatrix{X}*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetric{X}=(-vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vertexOutputs.vDepthMetric{X}=(vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#endif
`;x.IncludesShadersStoreWGSL[_5]||(x.IncludesShadersStoreWGSL[_5]=Ome)});var v5,Nme,Hb=y(()=>{k();v5="logDepthVertex",Nme=`#ifdef LOGARITHMICDEPTH
vertexOutputs.vFragmentDepth=1.0+vertexOutputs.position.w;vertexOutputs.position.z=log2(max(0.000001,vertexOutputs.vFragmentDepth))*uniforms.logarithmicDepthConstant;
#endif
`;x.IncludesShadersStoreWGSL[v5]||(x.IncludesShadersStoreWGSL[v5]=Nme)});var S5={};Be(S5,{defaultVertexShaderWGSL:()=>wme});var iN,E5,wme,T5=y(()=>{k();eN();Ob();ao();Wc();Hc();Rd();Nb();lg();wb();tN();Xc();eE();n5();Fb();yd();Id();ah();Bb();Ub();Cd();Pd();Yc();Kc();jc();Vb();Gb();kb();zb();Zc();tE();Wb();iE();Hb();iN="defaultVertexShader",E5=`#include<defaultUboDeclaration>
#define CUSTOM_VERTEX_BEGIN
#ifndef USE_VERTEX_PULLING
attribute position: vec3f;
#ifdef NORMAL
attribute normal: vec3f;
#endif
#ifdef TANGENT
attribute tangent: vec4f;
#endif
#ifdef UV1
attribute uv: vec2f;
#endif
#include<uvAttributeDeclaration>[2..7]
#ifdef VERTEXCOLOR
attribute color: vec4f;
#endif
#endif
#include<helperFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<mainUVVaryingDeclaration>[1..7]
#include<samplerVertexDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
#if defined(SPECULARTERM)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)
#endif
#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)
varying vPositionW: vec3f;
#ifdef NORMAL
varying vNormalW: vec3f;
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vColor: vec4f;
#endif
#include<bumpVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vPositionUVW: vec3f;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vDirectionW: vec3f;
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
varying vViewDepth: f32;
#endif
#include<logDepthDeclaration>
#include<vertexPullingDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef USE_VERTEX_PULLING
var positionUpdated: vec3f=vec3f(0.0);
#ifdef NORMAL
var normalUpdated: vec3f=vec3f(0.0);
#endif
#ifdef TANGENT
var tangentUpdated: vec4f=vec4f(0.0);
#endif
#ifdef UV1
var uvUpdated: vec2f=vec2f(0.0);
#endif
#ifdef UV2
var uv2Updated: vec2f=vec2f(0.0);
#endif
#ifdef VERTEXCOLOR
var colorUpdated: vec4f=vec4f(0.0);
#endif
#else
var positionUpdated: vec3f=vertexInputs.position;
#ifdef NORMAL
var normalUpdated: vec3f=vertexInputs.normal;
#endif
#ifdef TANGENT
var tangentUpdated: vec4f=vertexInputs.tangent;
#endif
#ifdef UV1
var uvUpdated: vec2f=vertexInputs.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=vertexInputs.uv2;
#endif
#ifdef VERTEXCOLOR
var colorUpdated: vec4f=vertexInputs.color;
#endif
#endif
#include<vertexPullingVertex>
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vertexOutputs.vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)
vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*vec4f(positionUpdated,1.0);
#endif
#ifdef USE_VERTEX_PULLING
#include<bonesVertex>(vertexInputs.matricesIndices,vp_matricesIndices,vertexInputs.matricesWeights,vp_matricesWeights,vertexInputs.matricesIndicesExtra,vp_matricesIndicesExtra,vertexInputs.matricesWeightsExtra,vp_matricesWeightsExtra)
#include<bakedVertexAnimation>(vertexInputs.matricesIndices,vp_matricesIndices,vertexInputs.matricesWeights,vp_matricesWeights,vertexInputs.matricesIndicesExtra,vp_matricesIndicesExtra,vertexInputs.matricesWeightsExtra,vp_matricesWeightsExtra)
#else
#include<bonesVertex>
#include<bakedVertexAnimation>
#endif
var worldPos: vec4f=finalWorld*vec4f(positionUpdated,1.0);
#ifdef NORMAL
var normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;}
#else
vertexOutputs.position=scene.viewProjection*worldPos;
#endif
vertexOutputs.vPositionW= worldPos.xyz;
#ifdef PREPASS
#include<prePassVertex>
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vertexOutputs.vDirectionW=normalize((finalWorld* vec4f(positionUpdated,0.0)).xyz);
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
#ifdef RIGHT_HANDED
vertexOutputs.vViewDepth=-(scene.view*worldPos).z;
#else
vertexOutputs.vViewDepth=(scene.view*worldPos).z;
#endif
#endif
#ifndef UV1
var uvUpdated: vec2f=vec2f(0.,0.);
#endif
#ifdef MAINUV1
vertexOutputs.vMainUV1=uvUpdated;
#endif
#ifndef UV2
var uv2Updated: vec2f=vec2f(0.,0.);
#endif
#ifdef MAINUV2
vertexOutputs.vMainUV2=uv2Updated;
#endif
#include<uvVariableDeclaration>[3..7]
#include<samplerVertexImplementation>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
#if defined(SPECULARTERM)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)
#endif
#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)
#include<bumpVertex>
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#include<vertexColorMixing>
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}
`;x.ShadersStoreWGSL[iN]||(x.ShadersStoreWGSL[iN]=E5);wme={name:iN,shader:E5}});var A5,Fme,Xb=y(()=>{k();A5="prePassDeclaration",Fme=`#ifdef PREPASS
#ifdef PREPASS_LOCAL_POSITION
varying vPosition : vec3f;
#endif
#ifdef PREPASS_DEPTH
varying vViewPos: vec3f;
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
varying vNormViewDepth: f32;
#endif
#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)
varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;
#endif
#endif
`;x.IncludesShadersStoreWGSL[A5]||(x.IncludesShadersStoreWGSL[A5]=Fme)});var x5,Bme,Yb=y(()=>{k();x5="oitDeclaration",Bme=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY
#define MAX_DEPTH 99999.0
var oitDepthSamplerSampler: sampler;var oitDepthSampler: texture_2d<f32>;var oitFrontColorSamplerSampler: sampler;var oitFrontColorSampler: texture_2d<f32>;
#endif
`;x.IncludesShadersStoreWGSL[x5]||(x.IncludesShadersStoreWGSL[x5]=Bme)});var R5,Ume,Kb=y(()=>{k();R5="lightUboDeclaration",Ume=`#ifdef LIGHT{X}
struct Light{X}
{vLightData: vec4f,
vLightDiffuse: vec4f,
vLightSpecular: vec4f,
#ifdef SPOTLIGHT{X}
vLightDirection: vec4f,
vLightFalloff: vec4f,
#elif defined(POINTLIGHT{X})
vLightFalloff: vec4f,
#elif defined(HEMILIGHT{X})
vLightGround: vec3f,
#elif defined(CLUSTLIGHT{X})
vSliceData: vec2f,
vSliceRanges: array<vec4f,CLUSTLIGHT_SLICES>,
#endif
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
vLightWidth: vec4f,
vLightHeight: vec4f,
#endif
shadowsInfo: vec4f,
depthValues: vec2f} ;var<uniform> light{X} : Light{X};
#ifdef IESLIGHTTEXTURE{X}
var iesLightTexture{X}Sampler: sampler;var iesLightTexture{X}: texture_2d<f32>;
#endif
#ifdef RECTAREALIGHTEMISSIONTEXTURE{X}
var rectAreaLightEmissionTexture{X}Sampler: sampler;var rectAreaLightEmissionTexture{X}: texture_2d<f32>;
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
uniform textureProjectionMatrix{X}: mat4x4f;var projectionLightTexture{X}Sampler: sampler;var projectionLightTexture{X}: texture_2d<f32>;
#endif
#ifdef CLUSTLIGHT{X}
var lightDataTexture{X}: texture_2d<f32>;var<storage,read> tileMaskBuffer{X}: array<u32>;
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform lightMatrix{X}: array<mat4x4f,SHADOWCSMNUM_CASCADES{X}>;uniform viewFrustumZ{X}: array<f32,SHADOWCSMNUM_CASCADES{X}>;uniform frustumLengths{X}: array<f32,SHADOWCSMNUM_CASCADES{X}>;uniform cascadeBlendFactor{X}: f32;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;var<private> vPositionFromLight{X}: array<vec4f,4>;var<private> vDepthMetric{X} : array<f32,4>;
#if defined(SHADOWPCSS{X})
var shadowTexture{X}Sampler: sampler_comparison;
var shadowTexture{X}: texture_depth_2d_array;var depthTexture{X}Sampler: sampler;var depthTexture{X}: texture_2d_array<f32>;uniform lightSizeUVCorrection{X}: array<vec2f,SHADOWCSMNUM_CASCADES{X}>;uniform depthCorrection{X}: array<f32,SHADOWCSMNUM_CASCADES{X}>;uniform penumbraDarkness{X}: f32;
#elif defined(SHADOWPCF{X})
var shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d_array;
#else
var shadowTexture{X}Sampler: sampler;
var shadowTexture{X}: texture_2d_array<f32>;
#endif
#ifdef SHADOWCSMDEBUG{X}
const vCascadeColorsMultiplier{X}: array<vec3f,8>=array<vec3f,8>
(
vec3f ( 1.5,0.0,0.0 ),
vec3f ( 0.0,1.5,0.0 ),
vec3f ( 0.0,0.0,5.5 ),
vec3f ( 1.5,0.0,5.5 ),
vec3f ( 1.5,1.5,0.0 ),
vec3f ( 1.0,1.0,1.0 ),
vec3f ( 0.0,1.0,5.5 ),
vec3f ( 0.5,3.5,0.75 )
);
#endif
#elif defined(SHADOWCUBE{X})
var shadowTexture{X}Sampler: sampler;var shadowTexture{X}: texture_cube<f32>;
#else
varying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;
#if defined(SHADOWPCSS{X})
var shadowTexture{X}Sampler: sampler_comparison;
var shadowTexture{X}: texture_depth_2d;var depthTexture{X}Sampler: sampler;
var depthTexture{X}: texture_2d<f32>;
#elif defined(SHADOWPCF{X})
var shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d;
#else
var shadowTexture{X}Sampler: sampler;
var shadowTexture{X}: texture_2d<f32>;
#endif
uniform lightMatrix{X}: mat4x4f;
#endif
#endif
#endif
`;x.IncludesShadersStoreWGSL[R5]||(x.IncludesShadersStoreWGSL[R5]=Ume)});var b5,Vme,rN=y(()=>{k();b5="ltcHelperFunctions",Vme=`fn LTCUv(N: vec3f,V: vec3f,roughness: f32)->vec2f {var LUTSIZE: f32=64.0;var LUTSCALE: f32=( LUTSIZE-1.0 )/LUTSIZE;var LUTBIAS:f32=0.5/LUTSIZE;var dotNV:f32=saturate( dot( N,V ) );var uv:vec2f=vec2f( roughness,sqrt( 1.0-dotNV ) );uv=uv*LUTSCALE+LUTBIAS;return uv;}
fn LTCClippedSphereFormFactor( f:vec3f )->f32 {var l: f32=length( f );return max( ( l*l+f.z )/( l+1.0 ),0.0 );}
fn LTCEdgeVectorFormFactor( v1:vec3f,v2:vec3f )->vec3f {var x:f32=dot( v1,v2 );var y:f32=abs( x );var a:f32=0.8543985+( 0.4965155+0.0145206*y )*y;var b:f32=3.4175940+( 4.1616724+y )*y;var v:f32=a/b;var thetaSintheta:f32=0.0;if( x>0.0 )
{thetaSintheta=v;}
else
{thetaSintheta=0.5*inverseSqrt( max( 1.0-x*x,0.00000001 ) )-v;}
return cross( v1,v2 )*thetaSintheta;}
fn LTCEvaluate( N:vec3f,V:vec3f,P:vec3f,mInv: mat3x3<f32>,rectCoords0:vec3f,rectCoords1:vec3f,rectCoords2:vec3f,rectCoords3:vec3f )->vec3f {var v1:vec3f=rectCoords1-rectCoords0;var v2:vec3f=rectCoords3-rectCoords0;var lightNormal:vec3f=cross( v1,v2 );if( dot( lightNormal,P-rectCoords0 )<0.0 ){return vec3f( 0.0 );}
var T1:vec3f=normalize( V-N*dot( V,N ) );var T2:vec3f=- cross( N,T1 );
var mat: mat3x3<f32>=mInv*transposeMat3( mat3x3<f32>( T1,T2,N ) );var coords0: vec3f=mat*( rectCoords0-P );var coords1: vec3f=mat*( rectCoords1-P );var coords2: vec3f=mat*( rectCoords2-P );var coords3: vec3f=mat*( rectCoords3-P );coords0=normalize( coords0 );coords1=normalize( coords1 );coords2=normalize( coords2 );coords3=normalize( coords3 );var vectorFormFactor:vec3f=vec3( 0.0 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords0,coords1 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords1,coords2 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords2,coords3 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords3,coords0 );var result:f32=LTCClippedSphereFormFactor( vectorFormFactor );return vec3f( result );}
struct areaLightData
{Diffuse: vec3f,
Specular: vec3f,
Fresnel: vec4f};fn computeAreaLightSpecularDiffuseFresnel(ltc1: texture_2d<f32>,ltc1Sampler:sampler,ltc2:texture_2d<f32>,ltc2Sampler:sampler,viewDir: vec3f,normal:vec3f,position:vec3f,lightPos:vec3f,halfWidth:vec3f, halfHeight:vec3f,roughness:f32)->areaLightData {var result: areaLightData;var rectCoords0:vec3f=lightPos+halfWidth-halfHeight;
var rectCoords1:vec3f=lightPos-halfWidth-halfHeight;var rectCoords2:vec3f=lightPos-halfWidth+halfHeight;var rectCoords3:vec3f=lightPos+halfWidth+halfHeight;
#ifdef SPECULARTERM
var uv:vec2f=LTCUv( normal,viewDir,roughness );var t1:vec4f=textureSample( ltc1,ltc1Sampler,uv );var t2:vec4f=textureSample( ltc2,ltc2Sampler,uv );var mInv:mat3x3<f32>=mat3x3<f32>(
vec3f( t1.x,0,t1.y ),
vec3f( 0,1, 0 ),
vec3f( t1.z,0,t1.w )
);result.Fresnel=t2;result.Specular=LTCEvaluate( normal,viewDir,position,mInv,rectCoords0,rectCoords1,rectCoords2,rectCoords3 );
#endif
var mInvEmpty:mat3x3<f32>=mat3x3<f32>(
vec3f( 1,0,0 ),
vec3f( 0,1,0 ),
vec3f( 0,0,1 )
);result.Diffuse+=LTCEvaluate( normal,viewDir,position,mInvEmpty,rectCoords0,rectCoords1,rectCoords2,rectCoords3 );return result;}
fn FetchDiffuseFilteredTexture(texLightFiltered: texture_2d<f32>,texLightFilteredSampler: sampler,p1_: vec3f,p2_: vec3f,p3_: vec3f,p4_: vec3f)->vec3f {var V1: vec3f=p2_-p1_;var V2: vec3f=p4_-p1_;var planeOrtho: vec3f=cross(V1,V2);var planeAreaSquared: f32=dot(planeOrtho,planeOrtho);var planeDistxPlaneArea: f32=dot(planeOrtho,p1_);var P: vec3f=planeDistxPlaneArea*planeOrtho/planeAreaSquared-p1_;var dot_V1_V2: f32=dot(V1,V2);var inv_dot_V1_V1: f32=1.0/dot(V1,V1);var V2_: vec3f=V2-V1*dot_V1_V2*inv_dot_V1_V1;var Puv: vec2f;Puv.y=dot(V2_,P)/dot(V2_,V2_);Puv.x=dot(V1,P)*inv_dot_V1_V1-dot_V1_V2*inv_dot_V1_V1*Puv.y;var d: f32=abs(planeDistxPlaneArea)/pow(planeAreaSquared,0.75);var sampleLOD: f32=log(2048.0*d)/log(3.0);var sampleUV: vec2f=vec2f(0.125,0.125)+(vec2f(0.75)*Puv);sampleUV.x=1.0-sampleUV.x;return textureSampleLevel(texLightFiltered,texLightFilteredSampler,sampleUV,sampleLOD).rgb;}
fn LTCEvaluateWithEmission(N: vec3f,V: vec3f,P: vec3f,mInv: mat3x3<f32>,rectCoords0: vec3f,rectCoords1: vec3f,rectCoords2: vec3f,rectCoords3: vec3f,texFilteredMap: texture_2d<f32>,texFilteredMapSampler: sampler)->vec3f {var v1: vec3f=rectCoords1-rectCoords0;var v2: vec3f=rectCoords3-rectCoords0;var lightNormal: vec3f=cross(v1,v2);if (dot(lightNormal,P-rectCoords0)<0.0) {return vec3f(0.0);}
var T1: vec3f=normalize(V-N*dot(V,N));var T2: vec3f=-cross(N,T1);var mat: mat3x3<f32>=mInv*transposeMat3(mat3x3<f32>(T1,T2,N));var coords0: vec3f=mat*(rectCoords0-P);var coords1: vec3f=mat*(rectCoords1-P);var coords2: vec3f=mat*(rectCoords2-P);var coords3: vec3f=mat*(rectCoords3-P);var textureLight: vec3f=FetchDiffuseFilteredTexture(texFilteredMap,texFilteredMapSampler,coords0,coords1,coords2,coords3);coords0=normalize(coords0);coords1=normalize(coords1);coords2=normalize(coords2);coords3=normalize(coords3);var vectorFormFactor: vec3f=vec3f(0.0);vectorFormFactor+=LTCEdgeVectorFormFactor(coords0,coords1);vectorFormFactor+=LTCEdgeVectorFormFactor(coords1,coords2);vectorFormFactor+=LTCEdgeVectorFormFactor(coords2,coords3);vectorFormFactor+=LTCEdgeVectorFormFactor(coords3,coords0);var result: f32=LTCClippedSphereFormFactor(vectorFormFactor);return vec3f(result)*textureLight;}
fn computeAreaLightSpecularDiffuseFresnelWithEmission(ltc1: texture_2d<f32>,ltc1Sampler:sampler,ltc2:texture_2d<f32>,ltc2Sampler:sampler,emissionTexture: texture_2d<f32>,emissionTextureSampler:sampler,viewDir: vec3f,normal:vec3f,position:vec3f,lightPos:vec3f,halfWidth:vec3f, halfHeight:vec3f,roughness:f32)->areaLightData {var result: areaLightData;var rectCoords0: vec3f=lightPos+halfWidth-halfHeight;
var rectCoords1: vec3f=lightPos-halfWidth-halfHeight;var rectCoords2: vec3f=lightPos-halfWidth+halfHeight;var rectCoords3: vec3f=lightPos+halfWidth+halfHeight;
#ifdef SPECULARTERM
var uv: vec2f=LTCUv(normal,viewDir,roughness);var t1: vec4f=textureSample(ltc1,ltc1Sampler,uv);var t2: vec4f=textureSample(ltc2,ltc2Sampler,uv);var mInv: mat3x3<f32>=mat3x3<f32>(
vec3f(t1.x,0,t1.y),
vec3f(0,1,0),
vec3f(t1.z,0,t1.w)
);result.Specular=LTCEvaluateWithEmission(normal,viewDir,position,mInv,rectCoords0,rectCoords1,rectCoords2,rectCoords3,emissionTexture,emissionTextureSampler);result.Fresnel=t2;
#endif
var mInvEmpty: mat3x3<f32>=mat3x3<f32>(
vec3f(1,0,0),
vec3f(0,1,0),
vec3f(0,0,1)
);result.Diffuse=LTCEvaluateWithEmission(normal,viewDir,position,mInvEmpty,rectCoords0,rectCoords1,rectCoords2,rectCoords3,emissionTexture,emissionTextureSampler);return result;}
`;x.IncludesShadersStoreWGSL[b5]||(x.IncludesShadersStoreWGSL[b5]=Vme)});var M5,Gme,nN=y(()=>{k();M5="clusteredLightingFunctions",Gme=`struct ClusteredLight {vLightData: vec4f,
vLightDiffuse: vec4f,
vLightSpecular: vec4f,
vLightDirection: vec4f,
vLightFalloff: vec4f,}
fn getClusteredLight(lightDataTexture: texture_2d<f32>,index: u32)->ClusteredLight {return ClusteredLight(
textureLoad(lightDataTexture,vec2u(0,index),0),
textureLoad(lightDataTexture,vec2u(1,index),0),
textureLoad(lightDataTexture,vec2u(2,index),0),
textureLoad(lightDataTexture,vec2u(3,index),0),
textureLoad(lightDataTexture,vec2u(4,index),0)
);}
fn getClusteredSliceIndex(sliceData: vec2f,viewDepth: f32)->i32 {return i32(log(viewDepth)*sliceData.x+sliceData.y);}
`;x.IncludesShadersStoreWGSL[M5]||(x.IncludesShadersStoreWGSL[M5]=Gme)});var y5,kme,I5=y(()=>{k();rN();nN();y5="lightsFragmentFunctions",kme=`struct lightingInfo
{diffuse: vec3f,
#ifdef SPECULARTERM
specular: vec3f,
#endif
#ifdef NDOTL
ndl: f32,
#endif
};fn computeLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var lightVectorW: vec3f;var attenuation: f32=1.0;if (lightData.w==0.)
{var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}
else
{lightVectorW=normalize(-lightData.xyz);}
var ndl: f32=max(0.,dot(vNormal,lightVectorW));
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=ndl*diffuseColor*attenuation;
#ifdef SPECULARTERM
var angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;
#endif
return result;}
fn getAttenuation(cosAngle: f32,exponent: f32)->f32 {return max(0.,pow(cosAngle,exponent));}
fn getIESAttenuation(cosAngle: f32,iesLightTexture: texture_2d<f32>,iesLightTextureSampler: sampler)->f32 {var angle=acos(cosAngle)/PI;return textureSampleLevel(iesLightTexture,iesLightTextureSampler,vec2f(angle,0),0.).r;}
fn computeBasicSpotLighting(viewDirectionW: vec3f,lightVectorW: vec3f,vNormal: vec3f,attenuation: f32,diffuseColor: vec3f,specularColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=max(0.,dot(vNormal,lightVectorW));
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=ndl*diffuseColor*attenuation;
#ifdef SPECULARTERM
var angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;
#endif
return result;}
fn computeIESSpotLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32,iesLightTexture: texture_2d<f32>,iesLightTextureSampler: sampler)->lightingInfo {var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var dotProduct=dot(lightDirection.xyz,-lightVectorW);var cosAngle: f32=max(0.,dotProduct);if (cosAngle>=lightDirection.w)
{attenuation*=getIESAttenuation(dotProduct,iesLightTexture,iesLightTextureSampler);return computeBasicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);}
var result: lightingInfo;result.diffuse=vec3f(0.);
#ifdef SPECULARTERM
result.specular=vec3f(0.);
#endif
#ifdef NDOTL
result.ndl=0.;
#endif
return result;}
fn computeSpotLighting(viewDirectionW: vec3f,vNormal: vec3f ,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var cosAngle: f32=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)
{attenuation*=getAttenuation(cosAngle,lightData.w);return computeBasicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);}
var result: lightingInfo;result.diffuse=vec3f(0.);
#ifdef SPECULARTERM
result.specular=vec3f(0.);
#endif
#ifdef NDOTL
result.ndl=0.;
#endif
return result;}
fn computeHemisphericLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,groundColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=dot(vNormal,lightData.xyz)*0.5+0.5;
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=mix(groundColor,diffuseColor,ndl);
#ifdef SPECULARTERM
var angleW: vec3f=normalize(viewDirectionW+lightData.xyz);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;
#endif
return result;}
fn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d<f32>,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f,posW: vec3f)->vec3f {var strq: vec4f=textureProjectionMatrix*vec4f(posW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return textureColor;}
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
#include<ltcHelperFunctions>
var areaLightsLTC1SamplerSampler: sampler;var areaLightsLTC1Sampler: texture_2d<f32>;var areaLightsLTC2SamplerSampler: sampler;var areaLightsLTC2Sampler: texture_2d<f32>;fn computeAreaLighting(ltc1: texture_2d<f32>,ltc1Sampler:sampler,ltc2:texture_2d<f32>,ltc2Sampler:sampler,viewDirectionW: vec3f,vNormal:vec3f,vPosition:vec3f,lightPosition:vec3f,halfWidth:vec3f, halfHeight:vec3f,diffuseColor:vec3f,specularColor:vec3f,roughness:f32 )->lightingInfo
{var result: lightingInfo;var data: areaLightData=computeAreaLightSpecularDiffuseFresnel(ltc1,ltc1Sampler,ltc2,ltc2Sampler,viewDirectionW,vNormal,vPosition,lightPosition,halfWidth,halfHeight,roughness);
#ifdef SPECULARTERM
var fresnel:vec3f=( specularColor*data.Fresnel.x+( vec3f( 1.0 )-specularColor )*data.Fresnel.y );result.specular+=specularColor*fresnel*data.Specular;
#endif
result.diffuse+=diffuseColor*data.Diffuse;return result;}
fn computeAreaLightingWithTexture(ltc1: texture_2d<f32>,ltc1Sampler:sampler,ltc2:texture_2d<f32>,ltc2Sampler:sampler,emissionTexture: texture_2d<f32>,emissionTextureSampler:sampler,viewDirectionW: vec3f,vNormal:vec3f,vPosition:vec3f,lightPosition:vec3f,halfWidth:vec3f, halfHeight:vec3f,diffuseColor:vec3f,specularColor:vec3f,roughness:f32 )->lightingInfo
{var result: lightingInfo;var data: areaLightData=computeAreaLightSpecularDiffuseFresnelWithEmission(ltc1,ltc1Sampler,ltc2,ltc2Sampler,emissionTexture,emissionTextureSampler,viewDirectionW,vNormal,vPosition,lightPosition,halfWidth,halfHeight,roughness);
#ifdef SPECULARTERM
var fresnel: vec3f=( specularColor*data.Fresnel.x+( vec3f( 1.0 )-specularColor )*data.Fresnel.y );result.specular+=specularColor*fresnel*data.Specular;
#endif
result.diffuse+=diffuseColor*data.Diffuse;return result;}
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
#include<clusteredLightingFunctions>
fn computeClusteredLighting(
lightDataTexture: texture_2d<f32>,
tileMaskBuffer: ptr<storage,array<u32>>,
viewDirectionW: vec3f,
vNormal: vec3f,
lightData: vec4f,
sliceRange: vec2u,
glossiness: f32
)->lightingInfo {var result: lightingInfo;let tilePosition=vec2u(fragmentInputs.position.xy*lightData.xy);let maskResolution=vec2u(lightData.zw);var tileIndex=(tilePosition.x*maskResolution.x+tilePosition.y)*maskResolution.y;let batchRange=sliceRange/CLUSTLIGHT_BATCH;var batchOffset=batchRange.x*CLUSTLIGHT_BATCH;tileIndex+=batchRange.x;for (var i=batchRange.x; i<=batchRange.y; i+=1) {var mask=tileMaskBuffer[tileIndex];tileIndex+=1;let maskOffset=max(sliceRange.x,batchOffset)-batchOffset;
let maskWidth=min(sliceRange.y-batchOffset+1,CLUSTLIGHT_BATCH);mask=extractBits(mask,maskOffset,maskWidth);while mask != 0 {let trailing=firstTrailingBit(mask);mask ^= 1u<<trailing;let light=getClusteredLight(lightDataTexture,batchOffset+maskOffset+trailing);var info: lightingInfo;if light.vLightDirection.w<0.0 {info=computeLighting(viewDirectionW,vNormal,light.vLightData,light.vLightDiffuse.rgb,light.vLightSpecular.rgb,light.vLightDiffuse.a,glossiness);} else {info=computeSpotLighting(viewDirectionW,vNormal,light.vLightData,light.vLightDirection,light.vLightDiffuse.rgb,light.vLightSpecular.rgb,light.vLightDiffuse.a,glossiness);}
result.diffuse+=info.diffuse;
#ifdef SPECULARTERM
result.specular+=info.specular;
#endif
}
batchOffset+=CLUSTLIGHT_BATCH;}
return result;}
#endif
`;x.IncludesShadersStoreWGSL[y5]||(x.IncludesShadersStoreWGSL[y5]=kme)});var C5,zme,jb=y(()=>{k();C5="shadowsFragmentFunctions",zme=`#ifdef SHADOWS
#ifndef SHADOWFLOAT
fn unpack(color: vec4f)->f32
{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}
#endif
fn computeFallOff(value: f32,clipSpace: vec2f,frustumEdgeFalloff: f32)->f32
{var mask: f32=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}
fn computeShadowCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube<f32>,shadowSampler: sampler,darkness: f32,depthValues: vec2f)->f32
{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
var shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));
#else
var shadow: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;
#endif
return select(1.0,darkness,depth>shadow);}
fn computeShadowWithPoissonSamplingCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube<f32>,shadowSampler: sampler,mapSize: f32,darkness: f32,depthValues: vec2f)->f32
{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;var visibility: f32=1.;var poissonDisk: array<vec3f,4>;poissonDisk[0]= vec3f(-1.0,1.0,-1.0);poissonDisk[1]= vec3f(1.0,-1.0,-1.0);poissonDisk[2]= vec3f(-1.0,-1.0,-1.0);poissonDisk[3]= vec3f(1.0,-1.0,1.0);
#ifndef SHADOWFLOAT
if (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) {visibility-=0.25;};if (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) {visibility-=0.25;};if (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) {visibility-=0.25;};if (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) {visibility-=0.25;};
#else
if (textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) {visibility-=0.25;};if (textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) {visibility-=0.25;};if (textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) {visibility-=0.25;};if (textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) {visibility-=0.25;};
#endif
return min(1.0,visibility+darkness);}
fn computeShadowWithESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube<f32>,shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32
{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
var shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));
#else
var shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;
#endif
var esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}
fn computeShadowWithCloseESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube<f32>,shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32
{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
var shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));
#else
var shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;
#endif
var esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}
fn computeShadowCSM(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d_array<f32>,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32
{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
var shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,uv,layer));
#else
var shadow: f32=textureSample(shadowTexture,shadowSampler,uv,layer).x;
#endif
return select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}
fn computeShadow(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d<f32>,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32
{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
var shadow: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));
#else
var shadow: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;
#endif
return select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}}
fn computeShadowWithPoissonSampling(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d<f32>,shadowSampler: sampler,mapSize: f32,darkness: f32,frustumEdgeFalloff: f32)->f32
{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);var visibility: f32=1.;var poissonDisk: array<vec2f,4>;poissonDisk[0]= vec2f(-0.94201624,-0.39906216);poissonDisk[1]= vec2f(0.94558609,-0.76890725);poissonDisk[2]= vec2f(-0.094184101,-0.92938870);poissonDisk[3]= vec2f(0.34495938,0.29387760);
#ifndef SHADOWFLOAT
if (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.))<shadowPixelDepth) {visibility-=0.25;}
if (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) {visibility-=0.25;}
if (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) {visibility-=0.25;}
if (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) {visibility-=0.25;}
#else
if (textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) {visibility-=0.25;}
if (textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) {visibility-=0.25;}
if (textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) {visibility-=0.25;}
if (textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) {visibility-=0.25;}
#endif
return computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);}}
fn computeShadowWithESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d<f32>,shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32
{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
var shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));
#else
var shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;
#endif
var esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}
fn computeShadowWithCloseESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d<f32>,shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32
{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
var shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));
#else
var shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;
#endif
var esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}
fn getZInClip(clipSpace: vec3f,uvDepth: vec3f)->f32
{
#ifdef IS_NDC_HALF_ZRANGE
return clipSpace.z;
#else
return uvDepth.z;
#endif
}
const GREATEST_LESS_THAN_ONE: f32=0.99999994;
#define DISABLE_UNIFORMITY_ANALYSIS
fn computeShadowWithCSMPCF1(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32
{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var shadow: f32=textureSampleCompare(shadowTexture,shadowSampler,uvDepth.xy,layer,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}
fn computeShadowWithCSMPCF3(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32
{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x;
uv+=0.5;
var st: vec2f=fract(uv);
var base_uv: vec2f=floor(uv)-0.5;
base_uv*=shadowMapSizeAndInverse.y;
var uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}
fn computeShadowWithCSMPCF5(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32
{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x;
uv+=0.5;
var st: vec2f=fract(uv);
var base_uv: vec2f=floor(uv)-0.5;
base_uv*=shadowMapSizeAndInverse.y;
var uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),layer,uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),layer,uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),layer,uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),layer,uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}
fn computeShadowWithPCF1(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32
{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);if (depthMetric<0.0 || depthMetric>1.0 || uvDepth.x<0. || uvDepth.x>1.0 || uvDepth.y<0. || uvDepth.y>1.0) {return 1.0;} else {var shadow: f32=textureSampleCompareLevel(shadowTexture,shadowSampler,uvDepth.xy,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
fn computeShadowWithPCF3(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32
{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);if (depthMetric<0.0 || depthMetric>1.0 || uvDepth.x<0. || uvDepth.x>1.0 || uvDepth.y<0. || uvDepth.y>1.0) {return 1.0;} else {var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x;
uv+=0.5;
var st: vec2f=fract(uv);
var base_uv: vec2f=floor(uv)-0.5;
base_uv*=shadowMapSizeAndInverse.y;
var uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
fn computeShadowWithPCF5(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32
{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);if (depthMetric<0.0 || depthMetric>1.0 || uvDepth.x<0. || uvDepth.x>1.0 || uvDepth.y<0. || uvDepth.y>1.0) {return 1.0;} else {var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x;
uv+=0.5;
var st: vec2f=fract(uv);
var base_uv: vec2f=floor(uv)-0.5;
base_uv*=shadowMapSizeAndInverse.y;
var uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
const PoissonSamplers32: array<vec3f,64>=array<vec3f,64> (
vec3f(0.06407013,0.05409927,0.),
vec3f(0.7366577,0.5789394,0.),
vec3f(-0.6270542,-0.5320278,0.),
vec3f(-0.4096107,0.8411095,0.),
vec3f(0.6849564,-0.4990818,0.),
vec3f(-0.874181,-0.04579735,0.),
vec3f(0.9989998,0.0009880066,0.),
vec3f(-0.004920578,-0.9151649,0.),
vec3f(0.1805763,0.9747483,0.),
vec3f(-0.2138451,0.2635818,0.),
vec3f(0.109845,0.3884785,0.),
vec3f(0.06876755,-0.3581074,0.),
vec3f(0.374073,-0.7661266,0.),
vec3f(0.3079132,-0.1216763,0.),
vec3f(-0.3794335,-0.8271583,0.),
vec3f(-0.203878,-0.07715034,0.),
vec3f(0.5912697,0.1469799,0.),
vec3f(-0.88069,0.3031784,0.),
vec3f(0.5040108,0.8283722,0.),
vec3f(-0.5844124,0.5494877,0.),
vec3f(0.6017799,-0.1726654,0.),
vec3f(-0.5554981,0.1559997,0.),
vec3f(-0.3016369,-0.3900928,0.),
vec3f(-0.5550632,-0.1723762,0.),
vec3f(0.925029,0.2995041,0.),
vec3f(-0.2473137,0.5538505,0.),
vec3f(0.9183037,-0.2862392,0.),
vec3f(0.2469421,0.6718712,0.),
vec3f(0.3916397,-0.4328209,0.),
vec3f(-0.03576927,-0.6220032,0.),
vec3f(-0.04661255,0.7995201,0.),
vec3f(0.4402924,0.3640312,0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.),
vec3f(0.)
);const PoissonSamplers64: array<vec3f,64>=array<vec3f,64> (
vec3f(-0.613392,0.617481,0.),
vec3f(0.170019,-0.040254,0.),
vec3f(-0.299417,0.791925,0.),
vec3f(0.645680,0.493210,0.),
vec3f(-0.651784,0.717887,0.),
vec3f(0.421003,0.027070,0.),
vec3f(-0.817194,-0.271096,0.),
vec3f(-0.705374,-0.668203,0.),
vec3f(0.977050,-0.108615,0.),
vec3f(0.063326,0.142369,0.),
vec3f(0.203528,0.214331,0.),
vec3f(-0.667531,0.326090,0.),
vec3f(-0.098422,-0.295755,0.),
vec3f(-0.885922,0.215369,0.),
vec3f(0.566637,0.605213,0.),
vec3f(0.039766,-0.396100,0.),
vec3f(0.751946,0.453352,0.),
vec3f(0.078707,-0.715323,0.),
vec3f(-0.075838,-0.529344,0.),
vec3f(0.724479,-0.580798,0.),
vec3f(0.222999,-0.215125,0.),
vec3f(-0.467574,-0.405438,0.),
vec3f(-0.248268,-0.814753,0.),
vec3f(0.354411,-0.887570,0.),
vec3f(0.175817,0.382366,0.),
vec3f(0.487472,-0.063082,0.),
vec3f(-0.084078,0.898312,0.),
vec3f(0.488876,-0.783441,0.),
vec3f(0.470016,0.217933,0.),
vec3f(-0.696890,-0.549791,0.),
vec3f(-0.149693,0.605762,0.),
vec3f(0.034211,0.979980,0.),
vec3f(0.503098,-0.308878,0.),
vec3f(-0.016205,-0.872921,0.),
vec3f(0.385784,-0.393902,0.),
vec3f(-0.146886,-0.859249,0.),
vec3f(0.643361,0.164098,0.),
vec3f(0.634388,-0.049471,0.),
vec3f(-0.688894,0.007843,0.),
vec3f(0.464034,-0.188818,0.),
vec3f(-0.440840,0.137486,0.),
vec3f(0.364483,0.511704,0.),
vec3f(0.034028,0.325968,0.),
vec3f(0.099094,-0.308023,0.),
vec3f(0.693960,-0.366253,0.),
vec3f(0.678884,-0.204688,0.),
vec3f(0.001801,0.780328,0.),
vec3f(0.145177,-0.898984,0.),
vec3f(0.062655,-0.611866,0.),
vec3f(0.315226,-0.604297,0.),
vec3f(-0.780145,0.486251,0.),
vec3f(-0.371868,0.882138,0.),
vec3f(0.200476,0.494430,0.),
vec3f(-0.494552,-0.711051,0.),
vec3f(0.612476,0.705252,0.),
vec3f(-0.578845,-0.768792,0.),
vec3f(-0.772454,-0.090976,0.),
vec3f(0.504440,0.372295,0.),
vec3f(0.155736,0.065157,0.),
vec3f(0.391522,0.849605,0.),
vec3f(-0.620106,-0.328104,0.),
vec3f(0.789239,-0.419965,0.),
vec3f(-0.545396,0.538133,0.),
vec3f(-0.178564,-0.596057,0.)
);fn computeShadowWithCSMPCSS(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array<f32>,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array<vec3f,64>,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32
{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uvDepthLayer: vec4f= vec4f(uvDepth.x,uvDepth.y,f32(layer),uvDepth.z);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;for (var i: i32=0; i<searchTapCount; i ++) {blockerDepth=textureSample(depthTexture,depthSampler, uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer).r;numBlocker+=select(0.,1.,blockerDepth<depthMetric);sumBlockerDepth+=select(0.,blockerDepth,blockerDepth<depthMetric);}
var avgBlockerDepth: f32=sumBlockerDepth/numBlocker;var AAOffset: f32=shadowMapSizeInverse*10.;var penumbraRatio: f32=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);var filterRadius: vec4f= vec4f(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);var random: f32=getRand(vPositionFromLight.xy);var rotationAngle: f32=random*3.1415926;var rotationVector: vec2f= vec2f(cos(rotationAngle),sin(rotationAngle));var shadow: f32=0.;for (var i: i32=0; i<pcfTapCount; i++) {var offset: vec4f= vec4f(poissonSamplers[i],0.);offset= vec4f(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);let coords=uvDepthLayer+offset*filterRadius;shadow+=textureSampleCompare(shadowTexture,shadowSampler,coords.xy,i32(coords.z),coords.w);}
shadow/= f32(pcfTapCount);shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));shadow=mix(darkness,1.,shadow);return select(computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff),1.0,numBlocker<1.0);}
fn computeShadowWithPCSS(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d<f32>,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array<vec3f,64>)->f32
{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);if (depthMetric<0.0 || depthMetric>1.0 || uvDepth.x<0. || uvDepth.x>1.0 || uvDepth.y<0. || uvDepth.y>1.0) {return 1.0;}
var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;for (var i: i32=0; i<searchTapCount; i ++) {blockerDepth=textureSampleLevel(depthTexture,depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0).r;numBlocker+=select(0.,1.,blockerDepth<depthMetric);sumBlockerDepth+=select(0.,blockerDepth,blockerDepth<depthMetric);}
if (numBlocker<1.0) {return 1.0;}
var avgBlockerDepth: f32=sumBlockerDepth/numBlocker;var AAOffset: f32=shadowMapSizeInverse*10.;var penumbraRatio: f32=((depthMetric-avgBlockerDepth)+AAOffset);var filterRadius: f32=penumbraRatio*lightSizeUV*shadowMapSizeInverse;var random: f32=getRand(vPositionFromLight.xy);var rotationAngle: f32=random*3.1415926;var rotationVector: vec2f= vec2f(cos(rotationAngle),sin(rotationAngle));var shadow: f32=0.;for (var i: i32=0; i<pcfTapCount; i++) {var offset: vec3f=poissonSamplers[i];offset= vec3f(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);let coords=uvDepth+offset*filterRadius;shadow+=textureSampleCompareLevel(shadowTexture,shadowSampler,coords.xy,coords.z);}
shadow/= f32(pcfTapCount);shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}
fn computeShadowWithPCSS16(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d<f32>,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32
{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}
fn computeShadowWithPCSS32(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d<f32>,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32
{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}
fn computeShadowWithPCSS64(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d<f32>,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32
{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}
fn computeShadowWithCSMPCSS16(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array<f32>,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32
{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}
fn computeShadowWithCSMPCSS32(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array<f32>,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32
{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}
fn computeShadowWithCSMPCSS64(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array<f32>,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32
{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}
#endif
`;x.IncludesShadersStoreWGSL[C5]||(x.IncludesShadersStoreWGSL[C5]=zme)});var P5,Wme,oh=y(()=>{k();P5="samplerFragmentDeclaration",Wme=`#ifdef _DEFINENAME_
#if _DEFINENAME_DIRECTUV==1
#define v_VARYINGNAME_UV vMainUV1
#elif _DEFINENAME_DIRECTUV==2
#define v_VARYINGNAME_UV vMainUV2
#elif _DEFINENAME_DIRECTUV==3
#define v_VARYINGNAME_UV vMainUV3
#elif _DEFINENAME_DIRECTUV==4
#define v_VARYINGNAME_UV vMainUV4
#elif _DEFINENAME_DIRECTUV==5
#define v_VARYINGNAME_UV vMainUV5
#elif _DEFINENAME_DIRECTUV==6
#define v_VARYINGNAME_UV vMainUV6
#else
varying v_VARYINGNAME_UV: vec2f;
#endif
var _SAMPLERNAME_SamplerSampler: sampler;var _SAMPLERNAME_Sampler: texture_2d<f32>;
#endif
`;x.IncludesShadersStoreWGSL[P5]||(x.IncludesShadersStoreWGSL[P5]=Wme)});var L5,Hme,D5=y(()=>{k();L5="fresnelFunction",Hme=`#ifdef FRESNEL
fn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32
{let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}
#endif
`;x.IncludesShadersStoreWGSL[L5]||(x.IncludesShadersStoreWGSL[L5]=Hme)});var O5,Xme,gE=y(()=>{k();O5="reflectionFunction",Xme=`fn computeFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f
{var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0); }
fn computeMirroredFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f
{var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(1.0-s,t,0); }
fn computeEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f
{var cameraToVertex: vec3f=normalize(worldPos.xyz-eyePosition);var r: vec3f=normalize(reflect(cameraToVertex,worldNormal));r= (reflectionMatrix* vec4f(r,0)).xyz;var lon: f32=atan2(r.z,r.x);var lat: f32=acos(r.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0);}
fn computeSphericalCoords(worldPos: vec4f,worldNormal: vec3f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f
{var viewDir: vec3f=normalize((view*worldPos).xyz);var viewNormal: vec3f=normalize((view* vec4f(worldNormal,0.0)).xyz);var r: vec3f=reflect(viewDir,viewNormal);r= (reflectionMatrix* vec4f(r,0)).xyz;r.z=r.z-1.0;var m: f32=2.0*length(r);return vec3f(r.x/m+0.5,1.0-r.y/m-0.5,0);}
fn computePlanarCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f
{var viewDir: vec3f=worldPos.xyz-eyePosition;var coords: vec3f=normalize(reflect(viewDir,worldNormal));return (reflectionMatrix* vec4f(coords,1)).xyz;}
fn computeCubicCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f
{var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords= (reflectionMatrix* vec4f(coords,0)).xyz;
#ifdef INVERTCUBICMAP
coords.y*=-1.0;
#endif
return coords;}
fn computeCubicLocalCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f,reflectionSize: vec3f,reflectionPosition: vec3f)->vec3f
{var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=(reflectionMatrix* vec4f(coords,0)).xyz;
#ifdef INVERTCUBICMAP
coords.y*=-1.0;
#endif
return coords;}
fn computeProjectionCoords(worldPos: vec4f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f
{return (reflectionMatrix*(view*worldPos)).xyz;}
fn computeSkyBoxCoords(positionW: vec3f,reflectionMatrix: mat4x4f)->vec3f
{return (reflectionMatrix* vec4f(positionW,1.)).xyz;}
#ifdef REFLECTION
fn computeReflectionCoords(worldPos: vec4f,worldNormal: vec3f)->vec3f
{
#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED
var direction: vec3f=normalize(fragmentInputs.vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);
#endif
#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED
var direction: vec3f=normalize(fragmentInputs.vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction);
#endif
#ifdef REFLECTIONMAP_EQUIRECTANGULAR
return computeEquirectangularCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_SPHERICAL
return computeSphericalCoords(worldPos,worldNormal,scene.view,uniforms.reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_PLANAR
return computePlanarCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_CUBIC
#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC
return computeCubicLocalCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix,uniforms.vReflectionSize,uniforms.vReflectionPosition);
#else
return computeCubicCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix);
#endif
#endif
#ifdef REFLECTIONMAP_PROJECTION
return computeProjectionCoords(worldPos,scene.view,uniforms.reflectionMatrix);
#endif
#ifndef REFLECTIONMAP_CUBIC
#ifdef REFLECTIONMAP_SKYBOX
return computeSkyBoxCoords(fragmentInputs.vPositionUVW,uniforms.reflectionMatrix);
#endif
#endif
#ifdef REFLECTIONMAP_EXPLICIT
return vec3f(0,0,0);
#endif
}
#endif
`;x.IncludesShadersStoreWGSL[O5]||(x.IncludesShadersStoreWGSL[O5]=Xme)});var N5,Yme,Zb=y(()=>{k();N5="imageProcessingDeclaration",Yme=`#ifdef EXPOSURE
uniform exposureLinear: f32;
#endif
#ifdef CONTRAST
uniform contrast: f32;
#endif
#if defined(VIGNETTE) || defined(DITHER)
uniform vInverseScreenSize: vec2f;
#endif
#ifdef VIGNETTE
uniform vignetteSettings1: vec4f;uniform vignetteSettings2: vec4f;
#endif
#ifdef COLORCURVES
uniform vCameraColorCurveNegative: vec4f;uniform vCameraColorCurveNeutral: vec4f;uniform vCameraColorCurvePositive: vec4f;
#endif
#ifdef COLORGRADING
#ifdef COLORGRADING3D
var txColorTransformSampler: sampler;var txColorTransform: texture_3d<f32>;
#else
var txColorTransformSampler: sampler;var txColorTransform: texture_2d<f32>;
#endif
uniform colorTransformSettings: vec4f;
#endif
#ifdef DITHER
uniform ditherIntensity: f32;
#endif
`;x.IncludesShadersStoreWGSL[N5]||(x.IncludesShadersStoreWGSL[N5]=Yme)});var w5,Kme,qb=y(()=>{k();w5="imageProcessingFunctions",Kme=`#if TONEMAPPING==3
const PBRNeutralStartCompression: f32=0.8-0.04;const PBRNeutralDesaturation: f32=0.15;fn PBRNeutralToneMapping( color: vec3f )->vec3f {var x: f32=min(color.r,min(color.g,color.b));var offset: f32=select(0.04,x-6.25*x*x,x<0.08);var result=color;result-=offset;var peak: f32=max(result.r,max(result.g,result.b));if (peak<PBRNeutralStartCompression) {return result;}
var d: f32=1.-PBRNeutralStartCompression;var newPeak: f32=1.-d*d/(peak+d-PBRNeutralStartCompression);result*=newPeak/peak;var g: f32=1.-1./(PBRNeutralDesaturation*(peak-newPeak)+1.);return mix(result,newPeak* vec3f(1,1,1),g);}
#endif
#if TONEMAPPING==2
const ACESInputMat: mat3x3f= mat3x3f(
vec3f(0.59719,0.07600,0.02840),
vec3f(0.35458,0.90834,0.13383),
vec3f(0.04823,0.01566,0.83777)
);const ACESOutputMat: mat3x3f= mat3x3f(
vec3f( 1.60475,-0.10208,-0.00327),
vec3f(-0.53108, 1.10813,-0.07276),
vec3f(-0.07367,-0.00605, 1.07602)
);fn RRTAndODTFit(v: vec3f)->vec3f
{var a: vec3f=v*(v+0.0245786)-0.000090537;var b: vec3f=v*(0.983729*v+0.4329510)+0.238081;return a/b;}
fn ACESFitted(color: vec3f)->vec3f
{var output=ACESInputMat*color;output=RRTAndODTFit(output);output=ACESOutputMat*output;output=saturateVec3(output);return output;}
#endif
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS
fn applyImageProcessing(result: vec4f)->vec4f {
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART
var rgb=result.rgb;;
#ifdef EXPOSURE
rgb*=uniforms.exposureLinear;
#endif
#ifdef VIGNETTE
var viewportXY: vec2f=fragmentInputs.position.xy*uniforms.vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;var vignetteXY1: vec3f= vec3f(viewportXY*uniforms.vignetteSettings1.xy+uniforms.vignetteSettings1.zw,1.0);var vignetteTerm: f32=dot(vignetteXY1,vignetteXY1);var vignette: f32=pow(vignetteTerm,uniforms.vignetteSettings2.w);var vignetteColor: vec3f=uniforms.vignetteSettings2.rgb;
#ifdef VIGNETTEBLENDMODEMULTIPLY
var vignetteColorMultiplier: vec3f=mix(vignetteColor, vec3f(1,1,1),vignette);rgb*=vignetteColorMultiplier;
#endif
#ifdef VIGNETTEBLENDMODEOPAQUE
rgb=mix(vignetteColor,rgb,vignette);
#endif
#endif
#if TONEMAPPING==3
rgb=PBRNeutralToneMapping(rgb);
#elif TONEMAPPING==2
rgb=ACESFitted(rgb);
#elif TONEMAPPING==1
const tonemappingCalibration: f32=1.590579;rgb=1.0-exp2(-tonemappingCalibration*rgb);
#endif
rgb=toGammaSpaceVec3(rgb);rgb=saturateVec3(rgb);
#ifdef CONTRAST
var resultHighContrast: vec3f=rgb*rgb*(3.0-2.0*rgb);if (uniforms.contrast<1.0) {rgb=mix( vec3f(0.5,0.5,0.5),rgb,uniforms.contrast);} else {rgb=mix(rgb,resultHighContrast,uniforms.contrast-1.0);}
rgb=max(rgb,vec3f(0.));
#endif
#ifdef COLORGRADING
var colorTransformInput: vec3f=rgb*uniforms.colorTransformSettings.xxx+uniforms.colorTransformSettings.yyy;
#ifdef COLORGRADING3D
var colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput).rgb;
#else
var colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput,uniforms.colorTransformSettings.yz).rgb;
#endif
rgb=mix(rgb,colorTransformOutput,uniforms.colorTransformSettings.www);
#endif
#ifdef COLORCURVES
var luma: f32=getLuminance(rgb);var curveMix: vec2f=clamp( vec2f(luma*3.0-1.5,luma*-3.0+1.5), vec2f(0.0), vec2f(1.0));var colorCurve: vec4f=uniforms.vCameraColorCurveNeutral+curveMix.x*uniforms.vCameraColorCurvePositive-curveMix.y*uniforms.vCameraColorCurveNegative;rgb*=colorCurve.rgb;rgb=mix( vec3f(luma),rgb,colorCurve.a);
#endif
#ifdef DITHER
var rand: f32=getRand(fragmentInputs.position.xy*uniforms.vInverseScreenSize);var dither: f32=mix(-uniforms.ditherIntensity,uniforms.ditherIntensity,rand);rgb=saturateVec3(rgb+ vec3f(dither));
#endif
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND
return vec4f(rgb,result.a);}`;x.IncludesShadersStoreWGSL[w5]||(x.IncludesShadersStoreWGSL[w5]=Kme)});var F5,jme,Qb=y(()=>{k();F5="bumpFragmentMainFunctions",jme=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)
#if defined(TANGENT) && defined(NORMAL)
varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f;
#endif
#ifdef OBJECTSPACE_NORMALMAP
uniform normalMatrix: mat4x4f;fn toNormalMatrix(m: mat4x4f)->mat4x4f
{var a00=m[0][0];var a01=m[0][1];var a02=m[0][2];var a03=m[0][3];var a10=m[1][0];var a11=m[1][1];var a12=m[1][2];var a13=m[1][3];var a20=m[2][0];
var a21=m[2][1];var a22=m[2][2];var a23=m[2][3];var a30=m[3][0];
var a31=m[3][1];var a32=m[3][2];var a33=m[3][3];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;var det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;var mi=mat4x4<f32>(
(a11*b11-a12*b10+a13*b09)/det,
(a02*b10-a01*b11-a03*b09)/det,
(a31*b05-a32*b04+a33*b03)/det,
(a22*b04-a21*b05-a23*b03)/det,
(a12*b08-a10*b11-a13*b07)/det,
(a00*b11-a02*b08+a03*b07)/det,
(a32*b02-a30*b05-a33*b01)/det,
(a20*b05-a22*b02+a23*b01)/det,
(a10*b10-a11*b08+a13*b06)/det,
(a01*b08-a00*b10-a03*b06)/det,
(a30*b04-a31*b02+a33*b00)/det,
(a21*b02-a20*b04-a23*b00)/det,
(a11*b07-a10*b09-a12*b06)/det,
(a00*b09-a01*b07+a02*b06)/det,
(a31*b01-a30*b03-a32*b00)/det,
(a20*b03-a21*b01+a22*b00)/det);return mat4x4<f32>(mi[0][0],mi[1][0],mi[2][0],mi[3][0],
mi[0][1],mi[1][1],mi[2][1],mi[3][1],
mi[0][2],mi[1][2],mi[2][2],mi[3][2],
mi[0][3],mi[1][3],mi[2][3],mi[3][3]);}
#endif
fn perturbNormalBase(cotangentFrame: mat3x3f,normal: vec3f,scale: f32)->vec3f
{var output=normal;
#ifdef NORMALXYSCALE
output=normalize(output* vec3f(scale,scale,1.0));
#endif
return normalize(cotangentFrame*output);}
fn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f
{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}
fn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f
{var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);}
#endif
`;x.IncludesShadersStoreWGSL[F5]||(x.IncludesShadersStoreWGSL[F5]=jme)});var B5,Zme,$b=y(()=>{k();oh();B5="bumpFragmentFunctions",Zme=`#if defined(BUMP)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)
#endif
#if defined(DETAIL)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)
#endif
#if defined(BUMP) && defined(PARALLAX)
const minSamples: f32=4.;const maxSamples: f32=15.;const iMaxSamples: i32=15;fn parallaxOcclusion(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32)->vec2f {var parallaxLimit: f32=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;var vOffsetDir: vec2f=normalize(vViewDirCoT.xy);var vMaxOffset: vec2f=vOffsetDir*parallaxLimit;var numSamples: f32=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));var stepSize: f32=1.0/numSamples;var currRayHeight: f32=1.0;var vCurrOffset: vec2f= vec2f(0,0);var vLastOffset: vec2f= vec2f(0,0);var lastSampledHeight: f32=1.0;var currSampledHeight: f32=1.0;var keepWorking: bool=true;for (var i: i32=0; i<iMaxSamples; i++)
{currSampledHeight=textureSample(bumpSampler,bumpSamplerSampler,texCoord+vCurrOffset).w;if (!keepWorking)
{}
else if (currSampledHeight>currRayHeight)
{var delta1: f32=currSampledHeight-currRayHeight;var delta2: f32=(currRayHeight+stepSize)-lastSampledHeight;var ratio: f32=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}
else
{currRayHeight-=stepSize;vLastOffset=vCurrOffset;
#ifdef PARALLAX_RHS
vCurrOffset-=stepSize*vMaxOffset;
#else
vCurrOffset+=stepSize*vMaxOffset;
#endif
lastSampledHeight=currSampledHeight;}}
return vCurrOffset;}
fn parallaxOffset(viewDir: vec3f,heightScale: f32)->vec2f
{var height: f32=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).w;var texCoordOffset: vec2f=heightScale*viewDir.xy*height;
#ifdef PARALLAX_RHS
return texCoordOffset;
#else
return -texCoordOffset;
#endif
}
#endif
`;x.IncludesShadersStoreWGSL[B5]||(x.IncludesShadersStoreWGSL[B5]=Zme)});var U5,qme,Jb=y(()=>{k();U5="bumpFragment",qme=`var uvOffset: vec2f= vec2f(0.0,0.0);
#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)
#ifdef NORMALXYSCALE
var normalScale: f32=1.0;
#elif defined(BUMP)
var normalScale: f32=uniforms.vBumpInfos.y;
#else
var normalScale: f32=1.0;
#endif
#if defined(TANGENT) && defined(NORMAL)
var TBN: mat3x3f=mat3x3<f32>(input.vTBN0,input.vTBN1,input.vTBN2);
#elif defined(BUMP)
var TBNUV: vec2f=select(-fragmentInputs.vBumpUV,fragmentInputs.vBumpUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV,uniforms.vTangentSpaceParams);
#else
var TBNUV: vec2f=select(-fragmentInputs.vDetailUV,fragmentInputs.vDetailUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV, vec2f(1.,1.));
#endif
#elif defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
var TBN: mat3x3f=mat3x3<f32>(input.vTBN0,input.vTBN1,input.vTBN2);
#else
var TBNUV: vec2f=select( -fragmentInputs.vMainUV1,fragmentInputs.vMainUV1,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW,input.vPositionW,TBNUV, vec2f(1.,1.));
#endif
#endif
#ifdef PARALLAX
var invTBN: mat3x3f=transposeMat3(TBN);
#ifdef PARALLAXOCCLUSION
uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,fragmentInputs.vBumpUV,uniforms.vBumpInfos.z);
#else
uvOffset=parallaxOffset(invTBN*viewDirectionW,uniforms.vBumpInfos.z);
#endif
#endif
#ifdef DETAIL
var detailColor: vec4f=textureSample(detailSampler,detailSamplerSampler,fragmentInputs.vDetailUV+uvOffset);var detailNormalRG: vec2f=detailColor.wy*2.0-1.0;var detailNormalB: f32=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));var detailNormal: vec3f= vec3f(detailNormalRG,detailNormalB);
#endif
#ifdef BUMP
#ifdef OBJECTSPACE_NORMALMAP
#define CUSTOM_FRAGMENT_BUMP_FRAGMENT
normalW=normalize(textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3x3f(uniforms.normalMatrix[0].xyz,uniforms.normalMatrix[1].xyz,uniforms.normalMatrix[2].xyz)*normalW);
#elif !defined(DETAIL)
normalW=perturbNormal(TBN,textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV+uvOffset).xyz,uniforms.vBumpInfos.y);
#else
var bumpNormal: vec3f=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV+uvOffset).xyz*2.0-1.0;
#if DETAIL_NORMALBLENDMETHOD==0
detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);var blendedNormal: vec3f=normalize( vec3f(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));
#elif DETAIL_NORMALBLENDMETHOD==1
detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);bumpNormal+= vec3f(0.0,0.0,1.0);detailNormal*= vec3f(-1.0,-1.0,1.0);var blendedNormal: vec3f=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;
#endif
normalW=perturbNormalBase(TBN,blendedNormal,uniforms.vBumpInfos.y);
#endif
#elif defined(DETAIL)
detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);normalW=perturbNormalBase(TBN,detailNormal,uniforms.vDetailInfos.z);
#endif
`;x.IncludesShadersStoreWGSL[U5]||(x.IncludesShadersStoreWGSL[U5]=qme)});var V5,Qme,sN=y(()=>{k();V5="decalFragment",Qme=`#ifdef DECAL
var decalTempColor=decalColor.rgb;var decalTempAlpha=decalColor.a;
#ifdef GAMMADECAL
decalTempColor=toLinearSpaceVec3(decalColor.rgb);
#endif
#ifdef DECAL_SMOOTHALPHA
decalTempAlpha=decalColor.a*decalColor.a;
#endif
surfaceAlbedo=mix(surfaceAlbedo.rgb,decalTempColor,decalTempAlpha);
#endif
`;x.IncludesShadersStoreWGSL[V5]||(x.IncludesShadersStoreWGSL[V5]=Qme)});var G5,$me,eM=y(()=>{k();G5="depthPrePass",$me=`#ifdef DEPTHPREPASS
#if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY)
fragmentOutputs.color= vec4f(0.,0.,0.,1.0);
#endif
return fragmentOutputs;
#endif
`;x.IncludesShadersStoreWGSL[G5]||(x.IncludesShadersStoreWGSL[G5]=$me)});var k5,Jme,aN=y(()=>{k();k5="lightFragment",Jme=`#ifdef LIGHT{X}
#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})
#else
var diffuse{X}: vec4f=light{X}.vLightDiffuse;
#define CUSTOM_LIGHT{X}_COLOR
#if defined(PBR) && defined(CLUSTLIGHT{X})
{let sliceIndex=min(getClusteredSliceIndex(light{X}.vSliceData,fragmentInputs.vViewDepth),CLUSTLIGHT_SLICES-1);info=computeClusteredLighting(
lightDataTexture{X},
&tileMaskBuffer{X},
light{X}.vLightData,
vec2u(light{X}.vSliceRanges[sliceIndex].xy),
viewDirectionW,
normalW,
fragmentInputs.vPositionW,
surfaceAlbedo,
reflectivityOut,
#ifdef IRIDESCENCE
iridescenceIntensity,
#endif
#ifdef SS_TRANSLUCENCY
subSurfaceOut,
#endif
#ifdef SPECULARTERM
AARoughnessFactors.x,
#endif
#ifdef ANISOTROPIC
anisotropicOut,
#endif
#ifdef SHEEN
sheenOut,
#endif
#ifdef CLEARCOAT
clearcoatOut,
#endif
);}
#elif defined(PBR)
#ifdef SPOTLIGHT{X}
preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,fragmentInputs.vPositionW);
#elif defined(POINTLIGHT{X})
preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,fragmentInputs.vPositionW);
#elif defined(HEMILIGHT{X})
preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
#elif defined(DIRLIGHT{X})
preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
#elif defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
#if defined(RECTAREALIGHTEMISSIONTEXTURE{X})
preInfo=computeAreaPreLightingInfoWithTexture(areaLightsLTC1Sampler,areaLightsLTC1SamplerSampler,areaLightsLTC2Sampler,areaLightsLTC2SamplerSampler,rectAreaLightEmissionTexture{X},rectAreaLightEmissionTexture{X}Sampler,viewDirectionW,normalW,fragmentInputs.vPositionW,light{X}.vLightData.xyz,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,roughness);
#else
preInfo=computeAreaPreLightingInfo(areaLightsLTC1Sampler,areaLightsLTC1SamplerSampler,areaLightsLTC2Sampler,areaLightsLTC2SamplerSampler,viewDirectionW,normalW,fragmentInputs.vPositionW,light{X}.vLightData.xyz,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,roughness);
#endif
#endif
preInfo.NdotV=NdotV;
#ifdef SPOTLIGHT{X}
#ifdef LIGHT_FALLOFF_GLTF{X}
preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);
#ifdef IESLIGHTTEXTURE{X}
preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X},iesLightTexture{X}Sampler);
#else
preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
#endif
#elif defined(LIGHT_FALLOFF_PHYSICAL{X})
preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);
#ifdef IESLIGHTTEXTURE{X}
preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X},iesLightTexture{X}Sampler);
#else
preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);
#endif
#elif defined(LIGHT_FALLOFF_STANDARD{X})
preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);
#ifdef IESLIGHTTEXTURE{X}
preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X},iesLightTexture{X}Sampler);
#else
preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);
#endif
#else
preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);
#ifdef IESLIGHTTEXTURE{X}
preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X},iesLightTexture{X}Sampler);
#else
preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
#endif
#endif
#elif defined(POINTLIGHT{X})
#ifdef LIGHT_FALLOFF_GLTF{X}
preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);
#elif defined(LIGHT_FALLOFF_PHYSICAL{X})
preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);
#elif defined(LIGHT_FALLOFF_STANDARD{X})
preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);
#else
preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);
#endif
#else
preInfo.attenuation=1.0;
#endif
#if defined(HEMILIGHT{X})
preInfo.roughness=roughness;
#elif defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
preInfo.roughness=roughness;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
#endif
preInfo.diffuseRoughness=diffuseRoughness;preInfo.surfaceAlbedo=surfaceAlbedo;
#ifdef IRIDESCENCE
preInfo.iridescenceIntensity=iridescenceIntensity;
#endif
#ifdef SS_TRANSLUCENCY
info.diffuseTransmission=vec3f(0.0);
#endif
#ifdef HEMILIGHT{X}
info.diffuse=computeHemisphericDiffuseLighting(preInfo,diffuse{X}.rgb,light{X}.vLightGround);
#elif defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
info.diffuse=computeAreaDiffuseLighting(preInfo,diffuse{X}.rgb);
#elif defined(SS_TRANSLUCENCY)
#ifndef SS_TRANSLUCENCY_LEGACY
info.diffuse=computeDiffuseLighting(preInfo,diffuse{X}.rgb)*(1.0-subSurfaceOut.translucencyIntensity);info.diffuseTransmission=computeDiffuseTransmittedLighting(preInfo,diffuse{X}.rgb,subSurfaceOut.transmittance);
#else
info.diffuse=computeDiffuseTransmittedLighting(preInfo,diffuse{X}.rgb,subSurfaceOut.transmittance);
#endif
#else
info.diffuse=computeDiffuseLighting(preInfo,diffuse{X}.rgb);
#endif
#ifdef SPECULARTERM
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
info.specular=computeAreaSpecularLighting(preInfo,light{X}.vLightSpecular.rgb,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90);
#else
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR)
{let metalFresnel: vec3f=vec3f(reflectivityOut.specularWeight)*getF82Specular(preInfo.VdotH,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90,reflectivityOut.roughness);let dielectricFresnel: vec3f=fresnelSchlickGGXVec3(preInfo.VdotH,reflectivityOut.dielectricColorF0,reflectivityOut.colorReflectanceF90);coloredFresnel=mix(dielectricFresnel,metalFresnel,reflectivityOut.metallic);}
#else
coloredFresnel=fresnelSchlickGGXVec3(preInfo.VdotH,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90);
#endif
#ifndef LEGACY_SPECULAR_ENERGY_CONSERVATION
{let NdotH: f32=dot(normalW,preInfo.H);let fresnel: vec3f=fresnelSchlickGGXVec3(NdotH,vec3f(reflectanceF0),specularEnvironmentR90);info.diffuse*=(vec3f(1.0)-fresnel);}
#endif
#ifdef ANISOTROPIC
info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);
#else
info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,coloredFresnel,AARoughnessFactors.x,diffuse{X}.rgb);
#endif
#endif
#endif
#ifndef AREALIGHT{X}
#ifdef SHEEN
#ifdef SHEEN_LINKWITHALBEDO
preInfo.roughness=sheenOut.sheenIntensity;
#else
#ifdef HEMILIGHT{X}
preInfo.roughness=sheenOut.sheenRoughness;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
#endif
#endif
info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);
#endif
#ifdef CLEARCOAT
#ifdef HEMILIGHT{X}
preInfo.roughness=clearcoatOut.clearCoatRoughness;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
#endif
info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,diffuse{X}.rgb);
#ifdef CLEARCOAT_TINT
absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;
#ifdef SS_TRANSLUCENCY
info.diffuseTransmission*=absorption;
#endif
#ifdef SPECULARTERM
info.specular*=absorption;
#endif
#endif
info.diffuse*=info.clearCoat.w;
#ifdef SS_TRANSLUCENCY
info.diffuseTransmission*=info.clearCoat.w;
#endif
#ifdef SPECULARTERM
info.specular*=info.clearCoat.w;
#endif
#ifdef SHEEN
info.sheen*=info.clearCoat.w;
#endif
#endif
#endif
#else
#ifdef SPOTLIGHT{X}
#ifdef IESLIGHTTEXTURE{X}
info=computeIESSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness,iesLightTexture{X},iesLightTexture{X}Sampler);
#else
info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness);
#endif
#elif defined(HEMILIGHT{X})
info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);
#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})
info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness);
#elif define(AREALIGHT{X}) && defined(AREALIGHTSUPPORTED)
#if defined(RECTAREALIGHTEMISSIONTEXTURE{X})
info=computeAreaLightingWithTexture(areaLightsLTC1Sampler,areaLightsLTC1SamplerSampler,areaLightsLTC2Sampler,areaLightsLTC2SamplerSampler,rectAreaLightEmissionTexture{X},rectAreaLightEmissionTexture{X}Sampler,viewDirectionW,normalW,fragmentInputs.vPositionW,light{X}.vLightData.xyz,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,
#ifdef AREALIGHTNOROUGHTNESS
0.5
#else
uniforms.vReflectionInfos.y
#endif
);
#else
info=computeAreaLighting(areaLightsLTC1Sampler,areaLightsLTC1SamplerSampler,areaLightsLTC2Sampler,areaLightsLTC2SamplerSampler,viewDirectionW,normalW,fragmentInputs.vPositionW,light{X}.vLightData.xyz,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,
#ifdef AREALIGHTNOROUGHTNESS
0.5
#else
uniforms.vReflectionInfos.y
#endif
);
#endif
#elif defined(CLUSTLIGHT{X})
{let sliceIndex=min(getClusteredSliceIndex(light{X}.vSliceData,fragmentInputs.vViewDepth),CLUSTLIGHT_SLICES-1);info=computeClusteredLighting(lightDataTexture{X},&tileMaskBuffer{X},viewDirectionW,normalW,light{X}.vLightData,vec2u(light{X}.vSliceRanges[sliceIndex].xy),glossiness);}
#endif
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},projectionLightTexture{X}Sampler,uniforms.textureProjectionMatrix{X},fragmentInputs.vPositionW);
#endif
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSMDEBUG{X}
var shadowDebug{X}: vec3f;
#endif
#ifdef SHADOWCSM{X}
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
var index{X}: i32=-1;
#else
var index{X}: i32=SHADOWCSMNUM_CASCADES{X}-1;
#endif
var diff{X}: f32=0.;vPositionFromLight{X}[0]=fragmentInputs.vPositionFromLight{X}_0;vPositionFromLight{X}[1]=fragmentInputs.vPositionFromLight{X}_1;vPositionFromLight{X}[2]=fragmentInputs.vPositionFromLight{X}_2;vPositionFromLight{X}[3]=fragmentInputs.vPositionFromLight{X}_3;vDepthMetric{X}[0]=fragmentInputs.vDepthMetric{X}_0;vDepthMetric{X}[1]=fragmentInputs.vDepthMetric{X}_1;vDepthMetric{X}[2]=fragmentInputs.vDepthMetric{X}_2;vDepthMetric{X}[3]=fragmentInputs.vDepthMetric{X}_3;for (var i:i32=0; i<SHADOWCSMNUM_CASCADES{X}; i++)
{
#ifdef SHADOWCSM_RIGHTHANDED{X}
diff{X}=uniforms.viewFrustumZ{X}[i]+fragmentInputs.vPositionFromCamera{X}.z;
#else
diff{X}=uniforms.viewFrustumZ{X}[i]-fragmentInputs.vPositionFromCamera{X}.z;
#endif
if (diff{X}>=0.) {index{X}=i;break;}}
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
if (index{X}>=0)
#endif
{
#if defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});
#else
shadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});
#endif
#else
shadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#ifdef SHADOWCSMDEBUG{X}
shadowDebug{X}=vec3f(shadow)*vCascadeColorsMultiplier{X}[index{X}];
#endif
#ifndef SHADOWCSMNOBLEND{X}
var frustumLength:f32=uniforms.frustumLengths{X}[index{X}];var diffRatio:f32=clamp(diff{X}/frustumLength,0.,1.)*uniforms.cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)
{index{X}+=1;var nextShadow: f32=0.;
#if defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
nextShadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
nextShadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
nextShadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
nextShadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});
#elif defined(SHADOWMEDIUMQUALITY{X})
nextShadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});
#else
nextShadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});
#endif
#else
nextShadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
shadow=mix(nextShadow,shadow,diffRatio);
#ifdef SHADOWCSMDEBUG{X}
shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);
#endif
}
#endif
}
#elif defined(SHADOWCLOSEESM{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithCloseESMCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);
#else
shadow=computeShadowWithCloseESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWESM{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithESMCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);
#else
shadow=computeShadowWithESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPOISSON{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithPoissonSamplingCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);
#else
shadow=computeShadowWithPoissonSampling(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithPCF1(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithPCF3(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithPCF5(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithPCSS16(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithPCSS32(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithPCSS64(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#else
#if defined(SHADOWCUBE{X})
shadow=computeShadowCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.depthValues);
#else
shadow=computeShadow(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#endif
#ifdef SHADOWONLY
#ifndef SHADOWINUSE
#define SHADOWINUSE
#endif
globalShadow+=shadow;shadowLightCount+=1.0;
#endif
#else
shadow=1.;
#endif
aggShadow+=shadow;numLights+=1.0;
#ifndef SHADOWONLY
#ifdef CUSTOMUSERLIGHTING
diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);
#ifdef SPECULARTERM
specularBase+=computeCustomSpecularLighting(info,specularBase,shadow);
#endif
#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})
diffuseBase+=lightmapColor.rgb*shadow;
#ifdef SPECULARTERM
#ifndef LIGHTMAPNOSPECULAR{X}
specularBase+=info.specular*shadow*lightmapColor.rgb;
#endif
#endif
#ifdef CLEARCOAT
#ifndef LIGHTMAPNOSPECULAR{X}
clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;
#endif
#endif
#ifdef SHEEN
#ifndef LIGHTMAPNOSPECULAR{X}
sheenBase+=info.sheen.rgb*shadow;
#endif
#endif
#else
#ifdef SHADOWCSMDEBUG{X}
diffuseBase+=info.diffuse*shadowDebug{X};
#else
diffuseBase+=info.diffuse*shadow;
#endif
#ifdef SS_TRANSLUCENCY
diffuseTransmissionBase+=info.diffuseTransmission*shadow;
#endif
#ifdef SPECULARTERM
specularBase+=info.specular*shadow;
#endif
#ifdef CLEARCOAT
clearCoatBase+=info.clearCoat.rgb*shadow;
#endif
#ifdef SHEEN
sheenBase+=info.sheen.rgb*shadow;
#endif
#endif
#endif
#endif
`;x.IncludesShadersStoreWGSL[k5]||(x.IncludesShadersStoreWGSL[k5]=Jme)});var z5,epe,tM=y(()=>{k();z5="logDepthFragment",epe=`#ifdef LOGARITHMICDEPTH
fragmentOutputs.fragDepth=log2(fragmentInputs.vFragmentDepth)*uniforms.logarithmicDepthConstant*0.5;
#endif
`;x.IncludesShadersStoreWGSL[z5]||(x.IncludesShadersStoreWGSL[z5]=epe)});var W5,tpe,iM=y(()=>{k();W5="oitFragment",tpe=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY
var fragDepth: f32=fragmentInputs.position.z;
#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS
var halfFloat: u32=pack2x16float( vec2f(fragDepth));var full: vec2f=unpack2x16float(halfFloat);fragDepth=full.x;
#endif
var fragCoord: vec2i=vec2i(fragmentInputs.position.xy);var lastDepth: vec2f=textureLoad(oitDepthSampler,fragCoord,0).rg;var lastFrontColor: vec4f=textureLoad(oitFrontColorSampler,fragCoord,0);fragmentOutputs.depth=vec2f(-MAX_DEPTH);fragmentOutputs.frontColor=lastFrontColor;fragmentOutputs.backColor= vec4f(0.0);
#ifdef USE_REVERSE_DEPTHBUFFER
var furthestDepth: f32=-lastDepth.x;var nearestDepth: f32=lastDepth.y;
#else
var nearestDepth: f32=-lastDepth.x;var furthestDepth: f32=lastDepth.y;
#endif
var alphaMultiplier: f32=1.0-lastFrontColor.a;
#ifdef USE_REVERSE_DEPTHBUFFER
if (fragDepth>nearestDepth || fragDepth<furthestDepth) {
#else
if (fragDepth<nearestDepth || fragDepth>furthestDepth) {
#endif
return fragmentOutputs;}
#ifdef USE_REVERSE_DEPTHBUFFER
if (fragDepth<nearestDepth && fragDepth>furthestDepth) {
#else
if (fragDepth>nearestDepth && fragDepth<furthestDepth) {
#endif
fragmentOutputs.depth=vec2f(-fragDepth,fragDepth);return fragmentOutputs;}
#endif
`;x.IncludesShadersStoreWGSL[W5]||(x.IncludesShadersStoreWGSL[W5]=tpe)});var X5={};Be(X5,{defaultPixelShaderWGSL:()=>ipe});var oN,H5,ipe,Y5=y(()=>{k();eN();Xb();Yb();lg();ao();Kb();I5();jb();oh();D5();gE();Zb();qb();Qb();$b();qc();ah();rE();Qc();Jb();sN();eM();aN();tM();nE();iM();oN="defaultPixelShader",H5=`#include<defaultUboDeclaration>
#include<prePassDeclaration>[SCENE_MRT_COUNT]
#include<oitDeclaration>
#define CUSTOM_FRAGMENT_BEGIN
varying vPositionW: vec3f;
#ifdef NORMAL
varying vNormalW: vec3f;
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vColor: vec4f;
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
varying vViewDepth: f32;
#endif
#include<mainUVVaryingDeclaration>[1..7]
#include<helperFunctions>
#include<lightUboDeclaration>[0..maxSimultaneousLights]
#include<lightsFragmentFunctions>
#include<shadowsFragmentFunctions>
#include<samplerFragmentDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)
#ifdef REFRACTION
#ifdef REFRACTIONMAP_3D
var refractionCubeSamplerSampler: sampler;var refractionCubeSampler: texture_cube<f32>;
#else
var refraction2DSamplerSampler: sampler;var refraction2DSampler: texture_2d<f32>;
#endif
#endif
#if defined(SPECULARTERM)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)
#endif
#include<fresnelFunction>
#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
var reflectionCubeSamplerSampler: sampler;var reflectionCubeSampler: texture_cube<f32>;
#else
var reflection2DSamplerSampler: sampler;var reflection2DSampler: texture_2d<f32>;
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vPositionUVW: vec3f;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vDirectionW: vec3f;
#endif
#endif
#include<reflectionFunction>
#endif
#include<imageProcessingDeclaration>
#include<imageProcessingFunctions>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-fragmentInputs.vPositionW);var baseColor: vec4f= vec4f(1.,1.,1.,1.);var diffuseColor: vec3f=uniforms.vDiffuseColor.rgb;var alpha: f32=uniforms.vDiffuseColor.a;
#ifdef NORMAL
var normalW: vec3f=normalize(fragmentInputs.vNormalW);
#else
var normalW: vec3f=normalize(cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW)))* scene.vEyePosition.w;
#endif
#include<bumpFragment>
#ifdef TWOSIDEDLIGHTING
normalW=select(-normalW,normalW,fragmentInputs.frontFacing);
#endif
#ifdef DIFFUSE
baseColor=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vDiffuseUV+uvOffset);
#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)
if (baseColor.a<uniforms.alphaCutOff) {discard;}
#endif
#ifdef ALPHAFROMDIFFUSE
alpha*=baseColor.a;
#endif
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
baseColor=vec4f(baseColor.rgb*uniforms.vDiffuseInfos.y,baseColor.a);
#endif
#if defined(DECAL) && !defined(DECAL_AFTER_DETAIL)
var decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset);
#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)
#endif
#include<depthPrePass>
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
baseColor=vec4f(baseColor.rgb*fragmentInputs.vColor.rgb,baseColor.a);
#endif
#ifdef DETAIL
baseColor=vec4f(baseColor.rgb*2.0*mix(0.5,detailColor.r,uniforms.vDetailInfos.y),baseColor.a);
#endif
#if defined(DECAL) && defined(DECAL_AFTER_DETAIL)
var decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset);
#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)
#endif
#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE
var baseAmbientColor: vec3f= vec3f(1.,1.,1.);
#ifdef AMBIENT
baseAmbientColor=textureSample(ambientSampler,ambientSamplerSampler,fragmentInputs.vAmbientUV+uvOffset).rgb*uniforms.vAmbientInfos.y;
#endif
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS
var glossiness: f32=uniforms.vSpecularColor.a;var specularColor: vec3f=uniforms.vSpecularColor.rgb;
#ifdef SPECULARTERM
#ifdef SPECULAR
var specularMapColor: vec4f=textureSample(specularSampler,specularSamplerSampler,fragmentInputs.vSpecularUV+uvOffset);specularColor=specularMapColor.rgb;
#ifdef GLOSSINESS
glossiness=glossiness*specularMapColor.a;
#endif
#endif
#endif
var diffuseBase: vec3f= vec3f(0.,0.,0.);var info: lightingInfo;
#ifdef SPECULARTERM
var specularBase: vec3f= vec3f(0.,0.,0.);
#endif
var shadow: f32=1.;var aggShadow: f32=0.;var numLights: f32=0.;
#ifdef LIGHTMAP
var lightmapColor: vec4f=textureSample(lightmapSampler,lightmapSamplerSampler,fragmentInputs.vLightmapUV+uvOffset);
#ifdef RGBDLIGHTMAP
lightmapColor=vec4f(fromRGBD(lightmapColor),lightmapColor.a);
#endif
lightmapColor=vec4f(lightmapColor.rgb*uniforms.vLightmapInfos.y,lightmapColor.a);
#endif
#include<lightFragment>[0..maxSimultaneousLights]
aggShadow=aggShadow/numLights;var refractionColor: vec4f= vec4f(0.,0.,0.,1.);
#ifdef REFRACTION
var refractionVector: vec3f=normalize(refract(-viewDirectionW,normalW,uniforms.vRefractionInfos.y));
#ifdef REFRACTIONMAP_3D
#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC
refractionVector=parallaxCorrectNormal(fragmentInputs.vPositionW,refractionVector,uniforms.vRefractionSize,uniforms.vRefractionPosition);
#endif
refractionVector.y=refractionVector.y*uniforms.vRefractionInfos.w;var refractionLookup: vec4f=textureSample(refractionCubeSampler,refractionCubeSamplerSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;}
#else
var vRefractionUVW: vec3f= (uniforms.refractionMatrix*(scene.view* vec4f(fragmentInputs.vPositionW+refractionVector*uniforms.vRefractionInfos.z,1.0))).xyz;var refractionCoords: vec2f=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=textureSample(refraction2DSampler,refraction2DSamplerSampler,refractionCoords);
#endif
#ifdef RGBDREFRACTION
refractionColor=vec4f(fromRGBD(refractionColor),refractionColor.a);
#endif
#ifdef IS_REFRACTION_LINEAR
refractionColor=vec4f(toGammaSpaceVec3(refractionColor.rgb),refractionColor.a);
#endif
refractionColor=vec4f(refractionColor.rgb*uniforms.vRefractionInfos.x,refractionColor.a);
#endif
var reflectionColor: vec4f= vec4f(0.,0.,0.,1.);
#ifdef REFLECTION
var vReflectionUVW: vec3f=computeReflectionCoords( vec4f(fragmentInputs.vPositionW,1.0),normalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
vReflectionUVW=vec3f(vReflectionUVW.x,vReflectionUVW.y,vReflectionUVW.z*-1.0);
#endif
#ifdef REFLECTIONMAP_3D
#ifdef ROUGHNESS
var bias: f32=uniforms.vReflectionInfos.y;
#ifdef SPECULARTERM
#ifdef SPECULAR
#ifdef GLOSSINESS
bias*=(1.0-specularMapColor.a);
#endif
#endif
#endif
reflectionColor=textureSampleLevel(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW,bias);
#else
reflectionColor=textureSample(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW);
#endif
#else
var coords: vec2f=vReflectionUVW.xy;
#ifdef REFLECTIONMAP_PROJECTION
coords/=vReflectionUVW.z;
#endif
coords.y=1.0-coords.y;reflectionColor=textureSample(reflection2DSampler,reflection2DSamplerSampler,coords);
#endif
#ifdef RGBDREFLECTION
reflectionColor=vec4f(fromRGBD(reflectionColor),reflectionColor.a);
#endif
#ifdef IS_REFLECTION_LINEAR
reflectionColor=vec4f(toGammaSpaceVec3(reflectionColor.rgb),reflectionColor.a);
#endif
reflectionColor=vec4f(reflectionColor.rgb*uniforms.vReflectionInfos.x,reflectionColor.a);
#ifdef REFLECTIONFRESNEL
var reflectionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.reflectionRightColor.a,uniforms.reflectionLeftColor.a);
#ifdef REFLECTIONFRESNELFROMSPECULAR
#ifdef SPECULARTERM
reflectionColor=vec4f(reflectionColor.rgb*specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a);
#else
reflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a);
#endif
#else
reflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a);
#endif
#endif
#endif
#ifdef REFRACTIONFRESNEL
var refractionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.refractionRightColor.a,uniforms.refractionLeftColor.a);refractionColor=vec4f(refractionColor.rgb*uniforms.refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*uniforms.refractionRightColor.rgb,refractionColor.a);
#endif
#ifdef OPACITY
var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vOpacityUV+uvOffset);
#ifdef OPACITYRGB
opacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* uniforms.vOpacityInfos.y;
#else
alpha*=opacityMap.a*uniforms.vOpacityInfos.y;
#endif
#endif
#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)
alpha*=fragmentInputs.vColor.a;
#endif
#ifdef OPACITYFRESNEL
var opacityFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.opacityParts.z,uniforms.opacityParts.w);alpha+=uniforms.opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*uniforms.opacityParts.y;
#endif
#ifdef ALPHATEST
#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS
if (alpha<uniforms.alphaCutOff) {discard;}
#endif
#ifndef ALPHABLEND
alpha=1.0;
#endif
#endif
var emissiveColor: vec3f=uniforms.vEmissiveColor;
#ifdef EMISSIVE
emissiveColor+=textureSample(emissiveSampler,emissiveSamplerSampler,fragmentInputs.vEmissiveUV+uvOffset).rgb*uniforms.vEmissiveInfos.y;
#endif
#ifdef EMISSIVEFRESNEL
var emissiveFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.emissiveRightColor.a,uniforms.emissiveLeftColor.a);emissiveColor*=uniforms.emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*uniforms.emissiveRightColor.rgb;
#endif
#ifdef DIFFUSEFRESNEL
var diffuseFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.diffuseRightColor.a,uniforms.diffuseLeftColor.a);diffuseBase*=uniforms.diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*uniforms.diffuseRightColor.rgb;
#endif
#ifdef EMISSIVEASILLUMINATION
var finalDiffuse: vec3f=clamp(diffuseBase*diffuseColor+uniforms.vAmbientColor,vec3f(0.0),vec3f(1.0))*baseColor.rgb;
#else
#ifdef LINKEMISSIVEWITHDIFFUSE
var finalDiffuse: vec3f=clamp((diffuseBase+emissiveColor)*diffuseColor+uniforms.vAmbientColor,vec3f(0.0),vec3f(1.0))*baseColor.rgb;
#else
var finalDiffuse: vec3f=clamp(diffuseBase*diffuseColor+emissiveColor+uniforms.vAmbientColor,vec3f(0.0),vec3f(1.0))*baseColor.rgb;
#endif
#endif
#ifdef SPECULARTERM
var finalSpecular: vec3f=specularBase*specularColor;
#ifdef SPECULAROVERALPHA
alpha=clamp(alpha+dot(finalSpecular, vec3f(0.3,0.59,0.11)),0.0,1.0);
#endif
#else
var finalSpecular: vec3f= vec3f(0.0);
#endif
#ifdef REFLECTIONOVERALPHA
alpha=clamp(alpha+dot(reflectionColor.rgb, vec3f(0.3,0.59,0.11)),0.0,1.0);
#endif
#ifdef EMISSIVEASILLUMINATION
var color: vec4f= vec4f(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+emissiveColor+refractionColor.rgb,vec3f(0.0),vec3f(1.0)),alpha);
#else
var color: vec4f= vec4f(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+refractionColor.rgb,alpha);
#endif
#ifdef LIGHTMAP
#ifndef LIGHTMAPEXCLUDED
#ifdef USELIGHTMAPASSHADOWMAP
color=vec4f(color.rgb*lightmapColor.rgb,color.a);
#else
color=vec4f(color.rgb+lightmapColor.rgb,color.a);
#endif
#endif
#endif
#define CUSTOM_FRAGMENT_BEFORE_FOG
color=vec4f(max(color.rgb,vec3f(0.)),color.a);
#include<logDepthFragment>
#include<fogFragment>
#ifdef IMAGEPROCESSINGPOSTPROCESS
color=vec4f(toLinearSpaceVec3(color.rgb),color.a);
#else
#ifdef IMAGEPROCESSING
color=vec4f(toLinearSpaceVec3(color.rgb),color.a);color=applyImageProcessing(color);
#endif
#endif
color=vec4f(color.rgb,color.a*mesh.visibility);
#ifdef PREMULTIPLYALPHA
color=vec4f(color.rgb*color.a, color.a);
#endif
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
#if SCENE_MRT_COUNT>0
var writeGeometryInfo: f32=select(0.0,1.0,color.a>0.4);var fragData: array<vec4<f32>,SCENE_MRT_COUNT>;
#ifdef PREPASS_COLOR
fragData[PREPASS_COLOR_INDEX]=color;
#endif
#ifdef PREPASS_POSITION
fragData[PREPASS_POSITION_INDEX]=vec4f(fragmentInputs.vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_LOCAL_POSITION
fragData[PREPASS_LOCAL_POSITION_INDEX]=vec4f(fragmentInputs.vPosition,writeGeometryInfo);
#endif
#ifdef PREPASS_VELOCITY
var a: vec2f=(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[PREPASS_VELOCITY_INDEX]= vec4f(velocity,0.0,writeGeometryInfo);
#elif defined(PREPASS_VELOCITY_LINEAR)
var velocity : vec2f=vec2f(0.5)*((fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w) -
(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w));fragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_IRRADIANCE
fragData[PREPASS_IRRADIANCE_INDEX]=vec4f(0.0,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_DEPTH
fragData[PREPASS_DEPTH_INDEX]=vec4f(fragmentInputs.vViewPos.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_SCREENSPACE_DEPTH
fragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
fragData[PREPASS_NORMALIZED_VIEW_DEPTH_INDEX]=vec4f(fragmentInputs.vNormViewDepth,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMAL
#ifdef PREPASS_NORMAL_WORLDSPACE
fragData[PREPASS_NORMAL_INDEX]=vec4f(normalW,writeGeometryInfo);
#else
fragData[PREPASS_NORMAL_INDEX]=vec4f(normalize((scene.view*vec4f(normalW,0.0)).rgb),writeGeometryInfo);
#endif
#endif
#ifdef PREPASS_WORLD_NORMAL
fragData[PREPASS_WORLD_NORMAL_INDEX]=vec4f(normalW*0.5+0.5,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO
fragData[PREPASS_ALBEDO_INDEX]=vec4f(baseColor.rgb,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
fragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4f(sqrt(baseColor.rgb),writeGeometryInfo);
#endif
#ifdef PREPASS_REFLECTIVITY
#if defined(SPECULAR)
fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(toLinearSpaceVec4(specularMapColor))*writeGeometryInfo;
#else
fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(toLinearSpaceVec3(specularColor),1.0)*writeGeometryInfo;
#endif
#endif
#if SCENE_MRT_COUNT>0
fragmentOutputs.fragData0=fragData[0];
#endif
#if SCENE_MRT_COUNT>1
fragmentOutputs.fragData1=fragData[1];
#endif
#if SCENE_MRT_COUNT>2
fragmentOutputs.fragData2=fragData[2];
#endif
#if SCENE_MRT_COUNT>3
fragmentOutputs.fragData3=fragData[3];
#endif
#if SCENE_MRT_COUNT>4
fragmentOutputs.fragData4=fragData[4];
#endif
#if SCENE_MRT_COUNT>5
fragmentOutputs.fragData5=fragData[5];
#endif
#if SCENE_MRT_COUNT>6
fragmentOutputs.fragData6=fragData[6];
#endif
#if SCENE_MRT_COUNT>7
fragmentOutputs.fragData7=fragData[7];
#endif
#endif
#endif
#if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY)
fragmentOutputs.color=color;
#endif
#include<oitFragment>
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+color.rgb*color.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-color.a));} else {fragmentOutputs.backColor+=color;}
#endif
#define CUSTOM_FRAGMENT_MAIN_END
}
`;x.ShadersStoreWGSL[oN]||(x.ShadersStoreWGSL[oN]=H5);ipe={name:oN,shader:H5}});var K5,rpe,rM=y(()=>{k();K5="decalVertexDeclaration",rpe=`#ifdef DECAL
uniform vec4 vDecalInfos;uniform mat4 decalMatrix;
#endif
`;x.IncludesShadersStore[K5]||(x.IncludesShadersStore[K5]=rpe)});var j5,npe,Z5=y(()=>{k();rM();j5="defaultVertexDeclaration",npe=`uniform mat4 viewProjection;
#ifdef MULTIVIEW
mat4 viewProjectionR;
#endif
uniform mat4 view;
#ifdef DIFFUSE
uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;
#endif
#ifdef AMBIENT
uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos;
#endif
#ifdef OPACITY
uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;
#endif
#if defined(SPECULAR) && defined(SPECULARTERM)
uniform vec2 vSpecularInfos;uniform mat4 specularMatrix;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform mat4 bumpMatrix;
#endif
#ifdef REFLECTION
uniform mat4 reflectionMatrix;
#endif
#ifdef POINTSIZE
uniform float pointSize;
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;uniform mat4 detailMatrix;
#endif
uniform vec4 cameraInfo;
#include<decalVertexDeclaration>
#define ADDITIONAL_VERTEX_DECLARATION
`;x.IncludesShadersStore[j5]||(x.IncludesShadersStore[j5]=npe)});var q5,spe,lh=y(()=>{k();q5="sceneUboDeclaration",spe=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;
#ifdef MULTIVIEW
mat4 viewProjectionR;
#endif
mat4 view;mat4 projection;vec4 vEyePosition;mat4 inverseProjection;};
`;x.IncludesShadersStore[q5]||(x.IncludesShadersStore[q5]=spe)});var Q5,ape,_E=y(()=>{k();Q5="meshUboDeclaration",ape=`#ifdef WEBGL2
uniform mat4 world;uniform float visibility;
#else
layout(std140,column_major) uniform;uniform Mesh
{mat4 world;float visibility;};
#endif
#define WORLD_UBO
`;x.IncludesShadersStore[Q5]||(x.IncludesShadersStore[Q5]=ape)});var $5,ope,lN=y(()=>{k();lh();_E();$5="defaultUboDeclaration",ope=`layout(std140,column_major) uniform;uniform Material
{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor;vec4 cameraInfo;vec2 vReflectionInfos;mat4 reflectionMatrix;vec3 vReflectionPosition;vec3 vReflectionSize;
#define ADDITIONAL_UBO_DECLARATION
};
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;x.IncludesShadersStore[$5]||(x.IncludesShadersStore[$5]=ope)});var J5,lpe,nM=y(()=>{k();J5="uvAttributeDeclaration",lpe=`#ifdef UV{X}
attribute vec2 uv{X};
#endif
`;x.IncludesShadersStore[J5]||(x.IncludesShadersStore[J5]=lpe)});var eY,cpe,sM=y(()=>{k();eY="prePassVertexDeclaration",cpe=`#ifdef PREPASS
#ifdef PREPASS_LOCAL_POSITION
varying vec3 vPosition;
#endif
#ifdef PREPASS_DEPTH
varying vec3 vViewPos;
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
varying float vNormViewDepth;
#endif
#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)
uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;
#endif
#endif
`;x.IncludesShadersStore[eY]||(x.IncludesShadersStore[eY]=cpe)});var tY,fpe,cg=y(()=>{k();tY="mainUVVaryingDeclaration",fpe=`#ifdef MAINUV{X}
varying vec2 vMainUV{X};
#endif
`;x.IncludesShadersStore[tY]||(x.IncludesShadersStore[tY]=fpe)});var iY,dpe,aM=y(()=>{k();iY="samplerVertexDeclaration",dpe=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0
varying vec2 v_VARYINGNAME_UV;
#endif
`;x.IncludesShadersStore[iY]||(x.IncludesShadersStore[iY]=dpe)});var rY,upe,cN=y(()=>{k();rY="bumpVertexDeclaration",upe=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
varying mat3 vTBN;
#endif
#endif
`;x.IncludesShadersStore[rY]||(x.IncludesShadersStore[rY]=upe)});var nY,hpe,oM=y(()=>{k();nY="lightVxFragmentDeclaration",hpe=`#ifdef LIGHT{X}
uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};
#ifdef SPECULARTERM
uniform vec4 vLightSpecular{X};
#else
vec4 vLightSpecular{X}=vec4(0.);
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};
#elif defined(SHADOWCUBE{X})
#else
varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};
#endif
uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};
#endif
#ifdef SPOTLIGHT{X}
uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};
#elif defined(POINTLIGHT{X})
uniform vec4 vLightFalloff{X};
#elif defined(HEMILIGHT{X})
uniform vec3 vLightGround{X};
#endif
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
uniform vec4 vLightWidth{X};uniform vec4 vLightHeight{X};
#endif
#endif
`;x.IncludesShadersStore[nY]||(x.IncludesShadersStore[nY]=hpe)});var sY,mpe,lM=y(()=>{k();sY="lightVxUboDeclaration",mpe=`#ifdef LIGHT{X}
uniform Light{X}
{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;
#ifdef SPOTLIGHT{X}
vec4 vLightDirection;vec4 vLightFalloff;
#elif defined(POINTLIGHT{X})
vec4 vLightFalloff;
#elif defined(HEMILIGHT{X})
vec3 vLightGround;
#elif defined(CLUSTLIGHT{X})
vec2 vSliceData;vec2 vSliceRanges[CLUSTLIGHT_SLICES];
#endif
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
vec4 vLightWidth;vec4 vLightHeight;
#endif
vec4 shadowsInfo;vec2 depthValues;} light{X};
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};
#elif defined(SHADOWCUBE{X})
#else
varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};
#endif
#endif
#endif
`;x.IncludesShadersStore[sY]||(x.IncludesShadersStore[sY]=mpe)});var aY,ppe,Ld=y(()=>{k();aY="morphTargetsVertexGlobalDeclaration",ppe=`#ifdef MORPHTARGETS
uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];
#ifdef MORPHTARGETS_TEXTURE
uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)
{
#if defined(WEBGL2) || defined(WEBGPU)
int textureWidth=int(morphTargetTextureInfo.y);int y=int(vertexIndex)/textureWidth;int x=int(vertexIndex) % textureWidth;return texelFetch(morphTargets,ivec3(x,y,int(morphTargetTextureIndices[targetIndex])),0).xyz;
#else
float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;
#endif
}
vec4 readVector4FromRawSampler(int targetIndex,float vertexIndex)
{
#if defined(WEBGL2) || defined(WEBGPU)
int textureWidth=int(morphTargetTextureInfo.y);int y=int(vertexIndex)/textureWidth;int x=int(vertexIndex) % textureWidth;return texelFetch(morphTargets,ivec3(x,y,int(morphTargetTextureIndices[targetIndex])),0);
#else
float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV);
#endif
}
#endif
#endif
`;x.IncludesShadersStore[aY]||(x.IncludesShadersStore[aY]=ppe)});var oY,gpe,Dd=y(()=>{k();oY="morphTargetsVertexDeclaration",gpe=`#ifdef MORPHTARGETS
#ifndef MORPHTARGETS_TEXTURE
#ifdef MORPHTARGETS_POSITION
attribute vec3 position{X};
#endif
#ifdef MORPHTARGETS_NORMAL
attribute vec3 normal{X};
#endif
#ifdef MORPHTARGETS_TANGENT
attribute vec3 tangent{X};
#endif
#ifdef MORPHTARGETS_UV
attribute vec2 uv_{X};
#endif
#ifdef MORPHTARGETS_UV2
attribute vec2 uv2_{X};
#endif
#ifdef MORPHTARGETS_COLOR
attribute vec4 color{X};
#endif
#elif {X}==0
uniform float morphTargetCount;
#endif
#endif
`;x.IncludesShadersStore[oY]||(x.IncludesShadersStore[oY]=gpe)});var lY,_pe,ch=y(()=>{k();lY="logDepthDeclaration",_pe=`#ifdef LOGARITHMICDEPTH
uniform float logarithmicDepthConstant;varying float vFragmentDepth;
#endif
`;x.IncludesShadersStore[lY]||(x.IncludesShadersStore[lY]=_pe)});var cY,vpe,Od=y(()=>{k();cY="morphTargetsVertexGlobal",vpe=`#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
float vertexID;
#endif
#endif
`;x.IncludesShadersStore[cY]||(x.IncludesShadersStore[cY]=vpe)});var fY,Epe,Nd=y(()=>{k();fY="morphTargetsVertex",Epe=`#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
#if {X}==0
for (int i=0; i<NUM_MORPH_INFLUENCERS; i++) {if (float(i)>=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;
#ifdef MORPHTARGETS_POSITION
positionUpdated+=(readVector3FromRawSampler(i,vertexID)-position)*morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETTEXTURE_HASPOSITIONS
vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_NORMAL
normalUpdated+=(readVector3FromRawSampler(i,vertexID) -normal)*morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETTEXTURE_HASNORMALS
vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_UV
uvUpdated+=(readVector3FromRawSampler(i,vertexID).xy-uv)*morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETTEXTURE_HASUVS
vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated.xyz+=(readVector3FromRawSampler(i,vertexID) -tangent.xyz)*morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETTEXTURE_HASTANGENTS
vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_UV2
uv2Updated+=(readVector3FromRawSampler(i,vertexID).xy-uv2)*morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETTEXTURE_HASUV2S
vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_COLOR
colorUpdated+=(readVector4FromRawSampler(i,vertexID)-color)*morphTargetInfluences[i];
#endif
}
#endif
#else
#ifdef MORPHTARGETS_POSITION
positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_NORMAL
normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_UV
uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_UV2
uv2Updated+=(uv2_{X}-uv2)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_COLOR
colorUpdated+=(color{X}-color)*morphTargetInfluences[{X}];
#endif
#endif
#endif
`;x.IncludesShadersStore[fY]||(x.IncludesShadersStore[fY]=Epe)});var dY,Spe,cM=y(()=>{k();dY="prePassVertex",Spe=`#ifdef PREPASS_DEPTH
vViewPos=(view*worldPos).rgb;
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
vNormViewDepth=((view*worldPos).z-cameraInfo.x)/(cameraInfo.y-cameraInfo.x);
#endif
#ifdef PREPASS_LOCAL_POSITION
vPosition=positionUpdated.xyz;
#endif
#if (defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*worldPos;
#if NUM_BONE_INFLUENCERS>0
mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
#endif
vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);
#else
vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#endif
`;x.IncludesShadersStore[dY]||(x.IncludesShadersStore[dY]=Spe)});var uY,Tpe,fM=y(()=>{k();uY="uvVariableDeclaration",Tpe=`#if !defined(UV{X}) && defined(MAINUV{X})
vec2 uv{X}=vec2(0.,0.);
#endif
#ifdef MAINUV{X}
vMainUV{X}=uv{X};
#endif
`;x.IncludesShadersStore[uY]||(x.IncludesShadersStore[uY]=Tpe)});var hY,Ape,dM=y(()=>{k();hY="samplerVertexImplementation",Ape=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0
if (v_INFONAME_==0.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));}
#ifdef UV2
else if (v_INFONAME_==1.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2Updated,1.0,0.0));}
#endif
#ifdef UV3
else if (v_INFONAME_==2.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));}
#endif
#ifdef UV4
else if (v_INFONAME_==3.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));}
#endif
#ifdef UV5
else if (v_INFONAME_==4.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));}
#endif
#ifdef UV6
else if (v_INFONAME_==5.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));}
#endif
#endif
`;x.IncludesShadersStore[hY]||(x.IncludesShadersStore[hY]=Ape)});var mY,xpe,uM=y(()=>{k();mY="bumpVertex",xpe=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);
#endif
#endif
`;x.IncludesShadersStore[mY]||(x.IncludesShadersStore[mY]=xpe)});var pY,Rpe,hM=y(()=>{k();pY="shadowsVertex",Rpe=`#ifdef SHADOWS
#if defined(SHADOWCSM{X})
vPositionFromCamera{X}=view*worldPos;for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {vPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetric{X}[i]=(-vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vDepthMetric{X}[i]=(vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
}
#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})
vPositionFromLight{X}=lightMatrix{X}*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetric{X}=(-vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vDepthMetric{X}=(vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#endif
`;x.IncludesShadersStore[pY]||(x.IncludesShadersStore[pY]=Rpe)});var gY,bpe,fN=y(()=>{k();gY="pointCloudVertex",bpe=`#if defined(POINTSIZE) && !defined(WEBGPU)
gl_PointSize=pointSize;
#endif
`;x.IncludesShadersStore[gY]||(x.IncludesShadersStore[gY]=bpe)});var _Y,Mpe,mM=y(()=>{k();_Y="logDepthVertex",Mpe=`#ifdef LOGARITHMICDEPTH
vFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;
#endif
`;x.IncludesShadersStore[_Y]||(x.IncludesShadersStore[_Y]=Mpe)});var EY={};Be(EY,{defaultVertexShader:()=>ype});var dN,vY,ype,SY=y(()=>{k();Z5();lN();nM();oo();$c();Jc();bd();sM();cg();aM();cN();ef();sE();oM();lM();Ld();Dd();ch();Od();Nd();tf();rf();nf();cM();fM();dM();uM();sf();aE();hM();oE();fN();mM();dN="defaultVertexShader",vY=`#define CUSTOM_VERTEX_EXTENSION
#include<__decl__defaultVertex>
#define CUSTOM_VERTEX_BEGIN
attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#ifdef TANGENT
attribute vec4 tangent;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#include<uvAttributeDeclaration>[2..7]
#ifdef VERTEXCOLOR
attribute vec4 color;
#endif
#include<helperFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<mainUVVaryingDeclaration>[1..7]
#include<samplerVertexDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
#if defined(SPECULARTERM)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)
#endif
#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)
varying vec3 vPositionW;
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#include<bumpVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
varying float vViewDepth;
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec3 positionUpdated=position;
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#ifdef TANGENT
vec4 tangentUpdated=tangent;
#endif
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#ifdef VERTEXCOLOR
vec4 colorUpdated=color;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#ifdef NORMAL
mat3 normalWorld=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vNormalW=normalize(normalWorld*normalUpdated);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}
#else
gl_Position=viewProjection*worldPos;
#endif
vPositionW=vec3(worldPos);
#ifdef PREPASS
#include<prePassVertex>
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
#ifdef RIGHT_HANDED
vViewDepth=-(view*worldPos).z;
#else
vViewDepth=(view*worldPos).z;
#endif
#endif
#ifndef UV1
vec2 uvUpdated=vec2(0.,0.);
#endif
#ifndef UV2
vec2 uv2Updated=vec2(0.,0.);
#endif
#ifdef MAINUV1
vMainUV1=uvUpdated;
#endif
#ifdef MAINUV2
vMainUV2=uv2Updated;
#endif
#include<uvVariableDeclaration>[3..7]
#include<samplerVertexImplementation>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
#if defined(SPECULARTERM)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)
#endif
#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)
#include<bumpVertex>
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#include<vertexColorMixing>
#include<pointCloudVertex>
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}
`;x.ShadersStore[dN]||(x.ShadersStore[dN]=vY);ype={name:dN,shader:vY}});var TY,Ipe,pM=y(()=>{k();TY="decalFragmentDeclaration",Ipe=`#ifdef DECAL
uniform vec4 vDecalInfos;
#endif
`;x.IncludesShadersStore[TY]||(x.IncludesShadersStore[TY]=Ipe)});var AY,Cpe,xY=y(()=>{k();pM();AY="defaultFragmentDeclaration",Cpe=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 vSpecularColor;uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility;
#ifdef DIFFUSE
uniform vec2 vDiffuseInfos;
#endif
#ifdef AMBIENT
uniform vec2 vAmbientInfos;
#endif
#ifdef OPACITY
uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;
#endif
#ifdef ALPHATEST
uniform float alphaCutOff;
#endif
#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)
uniform mat4 view;
#endif
#ifdef REFRACTION
uniform vec4 vRefractionInfos;
#ifndef REFRACTIONMAP_3D
uniform mat4 refractionMatrix;
#endif
#ifdef REFRACTIONFRESNEL
uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor;
#endif
#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)
uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize;
#endif
#endif
#if defined(SPECULAR) && defined(SPECULARTERM)
uniform vec2 vSpecularInfos;
#endif
#ifdef DIFFUSEFRESNEL
uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;
#endif
#ifdef OPACITYFRESNEL
uniform vec4 opacityParts;
#endif
#ifdef EMISSIVEFRESNEL
uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor;
#endif
#if defined(REFLECTION) || (defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED))
uniform vec2 vReflectionInfos;
#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)
uniform mat4 reflectionMatrix;
#endif
#ifndef REFLECTIONMAP_SKYBOX
#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)
uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;
#endif
#endif
#ifdef REFLECTIONFRESNEL
uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor;
#endif
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;
#endif
#include<decalFragmentDeclaration>
#define ADDITIONAL_FRAGMENT_DECLARATION
`;x.IncludesShadersStore[AY]||(x.IncludesShadersStore[AY]=Cpe)});var RY,Ppe,gM=y(()=>{k();RY="prePassDeclaration",Ppe=`#ifdef PREPASS
#extension GL_EXT_draw_buffers : require
layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;
#ifdef PREPASS_LOCAL_POSITION
varying highp vec3 vPosition;
#endif
#ifdef PREPASS_DEPTH
varying highp vec3 vViewPos;
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
varying highp float vNormViewDepth;
#endif
#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)
varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;
#endif
#endif
`;x.IncludesShadersStore[RY]||(x.IncludesShadersStore[RY]=Ppe)});var bY,Lpe,_M=y(()=>{k();bY="oitDeclaration",Lpe=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY
#extension GL_EXT_draw_buffers : require
layout(location=0) out vec2 depth;
layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor;
#define MAX_DEPTH 99999.0
highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler;
#endif
`;x.IncludesShadersStore[bY]||(x.IncludesShadersStore[bY]=Lpe)});var MY,Dpe,vM=y(()=>{k();MY="lightFragmentDeclaration",Dpe=`#ifdef LIGHT{X}
uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};
#ifdef SPECULARTERM
uniform vec4 vLightSpecular{X};
#else
vec4 vLightSpecular{X}=vec4(0.);
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DArrayShadow shadowTexture{X};
#else
uniform highp sampler2DArray shadowTexture{X};
#endif
#ifdef SHADOWCSMDEBUG{X}
const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]
(
vec3 ( 1.5,0.0,0.0 ),
vec3 ( 0.0,1.5,0.0 ),
vec3 ( 0.0,0.0,5.5 ),
vec3 ( 1.5,0.0,5.5 ),
vec3 ( 1.5,1.5,0.0 ),
vec3 ( 1.0,1.0,1.0 ),
vec3 ( 0.0,1.0,5.5 ),
vec3 ( 0.5,3.5,0.75 )
);vec3 shadowDebug{X};
#endif
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
int index{X}=-1;
#else
int index{X}=SHADOWCSMNUM_CASCADES{X}-1;
#endif
float diff{X}=0.;
#elif defined(SHADOWCUBE{X})
uniform samplerCube shadowTexture{X};
#else
varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DShadow shadowTexture{X};
#else
uniform sampler2D shadowTexture{X};
#endif
uniform mat4 lightMatrix{X};
#endif
uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};
#endif
#ifdef SPOTLIGHT{X}
uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};
#elif defined(POINTLIGHT{X})
uniform vec4 vLightFalloff{X};
#elif defined(HEMILIGHT{X})
uniform vec3 vLightGround{X};
#endif
#ifdef AREALIGHT{X}
uniform vec4 vLightWidth{X};uniform vec4 vLightHeight{X};
#ifdef RECTAREALIGHTEMISSIONTEXTURE{X}
uniform sampler2D rectAreaLightEmissionTexture{X};
#endif
#endif
#ifdef IESLIGHTTEXTURE{X}
uniform sampler2D iesLightTexture{X};
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};
#endif
#ifdef CLUSTLIGHT{X}
uniform vec2 vSliceData{X};uniform vec2 vSliceRanges{X}[CLUSTLIGHT_SLICES];uniform sampler2D lightDataTexture{X};uniform highp sampler2D tileMaskTexture{X};
#endif
#endif
`;x.IncludesShadersStore[MY]||(x.IncludesShadersStore[MY]=Dpe)});var yY,Ope,EM=y(()=>{k();yY="lightUboDeclaration",Ope=`#ifdef LIGHT{X}
uniform Light{X}
{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;
#ifdef SPOTLIGHT{X}
vec4 vLightDirection;vec4 vLightFalloff;
#elif defined(POINTLIGHT{X})
vec4 vLightFalloff;
#elif defined(HEMILIGHT{X})
vec3 vLightGround;
#elif defined(CLUSTLIGHT{X})
vec2 vSliceData;vec2 vSliceRanges[CLUSTLIGHT_SLICES];
#endif
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
vec4 vLightWidth;vec4 vLightHeight;
#endif
vec4 shadowsInfo;vec2 depthValues;} light{X};
#ifdef IESLIGHTTEXTURE{X}
uniform sampler2D iesLightTexture{X};
#endif
#ifdef RECTAREALIGHTEMISSIONTEXTURE{X}
uniform sampler2D rectAreaLightEmissionTexture{X};
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};
#endif
#ifdef CLUSTLIGHT{X}
uniform sampler2D lightDataTexture{X};uniform highp sampler2D tileMaskTexture{X};
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DArrayShadow shadowTexture{X};
#else
uniform highp sampler2DArray shadowTexture{X};
#endif
#ifdef SHADOWCSMDEBUG{X}
const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]
(
vec3 ( 1.5,0.0,0.0 ),
vec3 ( 0.0,1.5,0.0 ),
vec3 ( 0.0,0.0,5.5 ),
vec3 ( 1.5,0.0,5.5 ),
vec3 ( 1.5,1.5,0.0 ),
vec3 ( 1.0,1.0,1.0 ),
vec3 ( 0.0,1.0,5.5 ),
vec3 ( 0.5,3.5,0.75 )
);vec3 shadowDebug{X};
#endif
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
int index{X}=-1;
#else
int index{X}=SHADOWCSMNUM_CASCADES{X}-1;
#endif
float diff{X}=0.;
#elif defined(SHADOWCUBE{X})
uniform samplerCube shadowTexture{X};
#else
varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DShadow shadowTexture{X};
#else
uniform sampler2D shadowTexture{X};
#endif
uniform mat4 lightMatrix{X};
#endif
#endif
#endif
`;x.IncludesShadersStore[yY]||(x.IncludesShadersStore[yY]=Ope)});var IY,Npe,uN=y(()=>{k();IY="ltcHelperFunctions",Npe=`vec2 LTCUv( const in vec3 N,const in vec3 V,const in float roughness ) {const float LUTSIZE=64.0;const float LUTSCALE=( LUTSIZE-1.0 )/LUTSIZE;const float LUTBIAS=0.5/LUTSIZE;float dotNV=saturate( dot( N,V ) );vec2 uv=vec2( roughness,sqrt( 1.0-dotNV ) );uv=uv*LUTSCALE+LUTBIAS;return uv;}
float LTCClippedSphereFormFactor( const in vec3 f ) {float l=length( f );return max( ( l*l+f.z )/( l+1.0 ),0.0 );}
vec3 LTCEdgeVectorFormFactor( const in vec3 v1,const in vec3 v2 ) {float x=dot( v1,v2 );float y=abs( x );float a=0.8543985+( 0.4965155+0.0145206*y )*y;float b=3.4175940+( 4.1616724+y )*y;float v=a/b;float thetaSintheta=0.0;if( x>0.0 )
{thetaSintheta=v;}
else
{thetaSintheta=0.5*inversesqrt( max( 1.0-x*x,1e-7 ) )-v;}
return cross( v1,v2 )*thetaSintheta;}
vec3 LTCEvaluate( const in vec3 N,const in vec3 V,const in vec3 P,const in mat3 mInv,const in vec3 rectCoords[ 4 ] ) {vec3 v1=rectCoords[ 1 ]-rectCoords[ 0 ];vec3 v2=rectCoords[ 3 ]-rectCoords[ 0 ];vec3 lightNormal=cross( v1,v2 );if( dot( lightNormal,P-rectCoords[ 0 ] )<0.0 ) return vec3( 0.0 );vec3 T1,T2;T1=normalize( V-N*dot( V,N ) );T2=- cross( N,T1 );
mat3 mat=mInv*transposeMat3( mat3( T1,T2,N ) );vec3 coords[ 4 ];coords[ 0 ]=mat*( rectCoords[ 0 ]-P );coords[ 1 ]=mat*( rectCoords[ 1 ]-P );coords[ 2 ]=mat*( rectCoords[ 2 ]-P );coords[ 3 ]=mat*( rectCoords[ 3 ]-P );coords[ 0 ]=normalize( coords[ 0 ] );coords[ 1 ]=normalize( coords[ 1 ] );coords[ 2 ]=normalize( coords[ 2 ] );coords[ 3 ]=normalize( coords[ 3 ] );vec3 vectorFormFactor=vec3( 0.0 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 0 ],coords[ 1 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 1 ],coords[ 2 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 2 ],coords[ 3 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 3 ],coords[ 0 ] );float result=LTCClippedSphereFormFactor( vectorFormFactor );return vec3( result );}
vec3 FetchDiffuseFilteredTexture(sampler2D texLightFiltered,vec3 p1_,vec3 p2_,vec3 p3_,vec3 p4_)
{vec3 V1=p2_-p1_;vec3 V2=p4_-p1_;vec3 planeOrtho=(cross(V1,V2));float planeAreaSquared=dot(planeOrtho,planeOrtho);float planeDistxPlaneArea=dot(planeOrtho,p1_);vec3 P=planeDistxPlaneArea*planeOrtho/planeAreaSquared-p1_;float dot_V1_V2=dot(V1,V2);float inv_dot_V1_V1=1.0/dot(V1,V1);vec3 V2_=V2-V1*dot_V1_V2*inv_dot_V1_V1;vec2 Puv;Puv.y=dot(V2_,P)/dot(V2_,V2_);Puv.x=dot(V1,P)*inv_dot_V1_V1-dot_V1_V2*inv_dot_V1_V1*Puv.y ;float d=abs(planeDistxPlaneArea)/pow(planeAreaSquared,0.75);float sampleLOD=log(2048.0*d)/log(3.0);vec2 sampleUV=vec2(0.125,0.125)+(vec2(0.75)*Puv);sampleUV.x=1.0-sampleUV.x;return texture2DLodEXT(texLightFiltered,sampleUV,sampleLOD).rgb;}
vec3 LTCEvaluateWithEmission( const in vec3 N,const in vec3 V,const in vec3 P,const in mat3 mInv,const in vec3 rectCoords[ 4 ],const in sampler2D texFilteredMap ) {vec3 v1=rectCoords[ 1 ]-rectCoords[ 0 ];vec3 v2=rectCoords[ 3 ]-rectCoords[ 0 ];vec3 lightNormal=cross( v1,v2 );if( dot( lightNormal,P-rectCoords[ 0 ] )<0.0 ) return vec3( 0.0 );vec3 T1,T2;T1=normalize( V-N*dot( V,N ) );T2=- cross( N,T1 );
mat3 mat=mInv*transposeMat3( mat3( T1,T2,N ) );vec3 coords[ 4 ];coords[ 0 ]=mat*( rectCoords[ 0 ]-P );coords[ 1 ]=mat*( rectCoords[ 1 ]-P );coords[ 2 ]=mat*( rectCoords[ 2 ]-P );coords[ 3 ]=mat*( rectCoords[ 3 ]-P );vec3 textureLight=FetchDiffuseFilteredTexture(texFilteredMap,coords[0],coords[1],coords[2],coords[3]);coords[ 0 ]=normalize( coords[ 0 ] );coords[ 1 ]=normalize( coords[ 1 ] );coords[ 2 ]=normalize( coords[ 2 ] );coords[ 3 ]=normalize( coords[ 3 ] );vec3 vectorFormFactor=vec3( 0.0 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 0 ],coords[ 1 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 1 ],coords[ 2 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 2 ],coords[ 3 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 3 ],coords[ 0 ] );float result=LTCClippedSphereFormFactor( vectorFormFactor );return vec3( result )*textureLight;}
struct areaLightData
{vec3 Diffuse;vec3 Specular;vec4 Fresnel;};
#define inline
areaLightData computeAreaLightSpecularDiffuseFresnel(const in sampler2D ltc1,const in sampler2D ltc2,const in vec3 viewDir,const in vec3 normal,const in vec3 position,const in vec3 lightPos,const in vec3 halfWidth,const in vec3 halfHeight,const in float roughness)
{areaLightData result;vec3 rectCoords[ 4 ];rectCoords[ 0 ]=lightPos+halfWidth-halfHeight;
rectCoords[ 1 ]=lightPos-halfWidth-halfHeight;rectCoords[ 2 ]=lightPos-halfWidth+halfHeight;rectCoords[ 3 ]=lightPos+halfWidth+halfHeight;
#ifdef SPECULARTERM
vec2 uv=LTCUv( normal,viewDir,roughness );vec4 t1=texture2D( ltc1,uv );vec4 t2=texture2D( ltc2,uv );mat3 mInv=mat3(
vec3( t1.x,0,t1.y ),
vec3( 0,1, 0 ),
vec3( t1.z,0,t1.w )
);result.Specular=LTCEvaluate( normal,viewDir,position,mInv,rectCoords );result.Fresnel=t2;
#endif
result.Diffuse=LTCEvaluate( normal,viewDir,position,mat3( 1.0 ),rectCoords );return result;}
#define inline
areaLightData computeAreaLightSpecularDiffuseFresnelWithEmission(const in sampler2D ltc1,const in sampler2D ltc2,const in sampler2D texFilteredMap,const in vec3 viewDir,const in vec3 normal,const in vec3 position,const in vec3 lightPos,const in vec3 halfWidth,const in vec3 halfHeight,const in float roughness)
{areaLightData result;vec3 rectCoords[ 4 ];rectCoords[ 0 ]=lightPos+halfWidth-halfHeight;
rectCoords[ 1 ]=lightPos-halfWidth-halfHeight;rectCoords[ 2 ]=lightPos-halfWidth+halfHeight;rectCoords[ 3 ]=lightPos+halfWidth+halfHeight;
#ifdef SPECULARTERM
vec2 uv=LTCUv( normal,viewDir,roughness );vec4 t1=texture2D( ltc1,uv );vec4 t2=texture2D( ltc2,uv );mat3 mInv=mat3(
vec3( t1.x,0,t1.y ),
vec3( 0,1, 0 ),
vec3( t1.z,0,t1.w )
);result.Specular=LTCEvaluateWithEmission( normal,viewDir,position,mInv,rectCoords,texFilteredMap );result.Fresnel=t2;
#endif
result.Diffuse=LTCEvaluateWithEmission( normal,viewDir,position,mat3( 1.0 ),rectCoords,texFilteredMap );return result;}`;x.IncludesShadersStore[IY]||(x.IncludesShadersStore[IY]=Npe)});var CY,wpe,hN=y(()=>{k();CY="clusteredLightingFunctions",wpe=`struct ClusteredLight {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;vec4 vLightDirection;vec4 vLightFalloff;};
#define inline
ClusteredLight getClusteredLight(sampler2D lightDataTexture,int index) {return ClusteredLight(
texelFetch(lightDataTexture,ivec2(0,index),0),
texelFetch(lightDataTexture,ivec2(1,index),0),
texelFetch(lightDataTexture,ivec2(2,index),0),
texelFetch(lightDataTexture,ivec2(3,index),0),
texelFetch(lightDataTexture,ivec2(4,index),0)
);}
int getClusteredSliceIndex(vec2 sliceData,float viewDepth) {return int(log(viewDepth)*sliceData.x+sliceData.y);}
`;x.IncludesShadersStore[CY]||(x.IncludesShadersStore[CY]=wpe)});var PY,Fpe,LY=y(()=>{k();uN();hN();PY="lightsFragmentFunctions",Fpe=`struct lightingInfo
{vec3 diffuse;
#ifdef SPECULARTERM
vec3 specular;
#endif
#ifdef NDOTL
float ndl;
#endif
};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.)
{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}
else
{lightVectorW=normalize(-lightData.xyz);}
float ndl=max(0.,dot(vNormal,lightVectorW));
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=ndl*diffuseColor*attenuation;
#ifdef SPECULARTERM
vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;
#endif
return result;}
float getAttenuation(float cosAngle,float exponent) {return max(0.,pow(cosAngle,exponent));}
float getIESAttenuation(float cosAngle,sampler2D iesLightSampler) {float angle=acos(cosAngle)/PI;return texture2D(iesLightSampler,vec2(angle,0.)).r;}
lightingInfo basicSpotLighting(vec3 viewDirectionW,vec3 lightVectorW,vec3 vNormal,float attenuation,vec3 diffuseColor,vec3 specularColor,float glossiness) {lightingInfo result;
float ndl=max(0.,dot(vNormal,lightVectorW));
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=ndl*diffuseColor*attenuation;
#ifdef SPECULARTERM
vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;
#endif
return result;}
lightingInfo computeIESSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness,sampler2D iesLightSampler) {
vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float dotProduct=dot(lightDirection.xyz,-lightVectorW);float cosAngle=max(0.,dotProduct);if (cosAngle>=lightDirection.w)
{
attenuation*=getIESAttenuation(dotProduct,iesLightSampler);return basicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);}
lightingInfo result;result.diffuse=vec3(0.);
#ifdef SPECULARTERM
result.specular=vec3(0.);
#endif
#ifdef NDOTL
result.ndl=0.;
#endif
return result;}
lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)
{
attenuation*=getAttenuation(cosAngle,lightData.w);return basicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);}
lightingInfo result;result.diffuse=vec3(0.);
#ifdef SPECULARTERM
result.specular=vec3(0.);
#endif
#ifdef NDOTL
result.ndl=0.;
#endif
return result;}
lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5;
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=mix(groundColor,diffuseColor,ndl);
#ifdef SPECULARTERM
vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;
#endif
return result;}
#define inline
vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
#include<ltcHelperFunctions>
uniform sampler2D areaLightsLTC1Sampler;uniform sampler2D areaLightsLTC2Sampler;
#define inline
lightingInfo computeAreaLighting(sampler2D ltc1,sampler2D ltc2,vec3 viewDirectionW,vec3 vNormal,vec3 vPosition,vec3 lightPosition,vec3 halfWidth,vec3 halfHeight,vec3 diffuseColor,vec3 specularColor,float roughness)
{lightingInfo result;areaLightData data=computeAreaLightSpecularDiffuseFresnel(ltc1,ltc2,viewDirectionW,vNormal,vPosition,lightPosition,halfWidth,halfHeight,roughness);
#ifdef SPECULARTERM
vec3 fresnel=( specularColor*data.Fresnel.x+( vec3( 1.0 )-specularColor )*data.Fresnel.y );result.specular+=specularColor*fresnel*data.Specular;
#endif
result.diffuse+=diffuseColor*data.Diffuse;return result;}
lightingInfo computeAreaLightingWithTexture(sampler2D ltc1,sampler2D ltc2,sampler2D emissionTexture,vec3 viewDirectionW,vec3 vNormal,vec3 vPosition,vec3 lightPosition,vec3 halfWidth,vec3 halfHeight,vec3 diffuseColor,vec3 specularColor,float roughness)
{lightingInfo result;areaLightData data=computeAreaLightSpecularDiffuseFresnelWithEmission(ltc1,ltc2,emissionTexture,viewDirectionW,vNormal,vPosition,lightPosition,halfWidth,halfHeight,roughness);
#ifdef SPECULARTERM
vec3 fresnel=( specularColor*data.Fresnel.x+( vec3( 1.0 )-specularColor )*data.Fresnel.y );result.specular+=specularColor*fresnel*data.Specular;
#endif
result.diffuse+=diffuseColor*data.Diffuse;return result;}
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
#include<clusteredLightingFunctions>
#define inline
lightingInfo computeClusteredLighting(
sampler2D lightDataTexture,
sampler2D tileMaskTexture,
vec3 viewDirectionW,
vec3 vNormal,
vec4 lightData,
ivec2 sliceRange,
float glossiness
) {lightingInfo result;ivec2 tilePosition=ivec2(gl_FragCoord.xy*lightData.xy);int maskHeight=int(lightData.z);tilePosition.y=min(tilePosition.y,maskHeight-1);ivec2 batchRange=sliceRange/CLUSTLIGHT_BATCH;int batchOffset=batchRange.x*CLUSTLIGHT_BATCH;tilePosition.y+=maskHeight*batchRange.x;for (int i=batchRange.x; i<=batchRange.y; i+=1) {uint mask=uint(texelFetch(tileMaskTexture,tilePosition,0).r);tilePosition.y+=maskHeight;int maskOffset=max(sliceRange.x-batchOffset,0);int maskWidth=min(sliceRange.y-batchOffset+1,CLUSTLIGHT_BATCH);mask=extractBits(mask,maskOffset,maskWidth);while (mask != 0u) {uint bit=mask & -mask;mask ^= bit;int position=onlyBitPosition(bit);ClusteredLight light=getClusteredLight(lightDataTexture,batchOffset+maskOffset+position);lightingInfo info;if (light.vLightDirection.w<0.0) {info=computeLighting(viewDirectionW,vNormal,light.vLightData,light.vLightDiffuse.rgb,light.vLightSpecular.rgb,light.vLightDiffuse.a,glossiness);} else {info=computeSpotLighting(viewDirectionW,vNormal,light.vLightData,light.vLightDirection,light.vLightDiffuse.rgb,light.vLightSpecular.rgb,light.vLightDiffuse.a,glossiness);}
result.diffuse+=info.diffuse;
#ifdef SPECULARTERM
result.specular+=info.specular;
#endif
}
batchOffset+=CLUSTLIGHT_BATCH;}
return result;}
#endif
`;x.IncludesShadersStore[PY]||(x.IncludesShadersStore[PY]=Fpe)});var DY,Bpe,SM=y(()=>{k();DY="shadowsFragmentFunctions",Bpe=`#ifdef SHADOWS
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)
#else
#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)
#endif
#ifndef SHADOWFLOAT
float unpack(vec4 color)
{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}
#endif
float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)
{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}
#define inline
float computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)
{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
float shadow=unpack(textureCube(shadowSampler,directionToLight));
#else
float shadow=textureCube(shadowSampler,directionToLight).x;
#endif
return depth>shadow ? darkness : 1.0;}
#define inline
float computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)
{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0);
#ifndef SHADOWFLOAT
if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;
#else
if (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;
#endif
return min(1.0,visibility+darkness);}
#define inline
float computeShadowWithESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)
{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));
#else
float shadowMapSample=textureCube(shadowSampler,directionToLight).x;
#endif
float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}
#define inline
float computeShadowWithCloseESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)
{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));
#else
float shadowMapSample=textureCube(shadowSampler,directionToLight).x;
#endif
float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define inline
float computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);vec3 uvLayer=vec3(uv.x,uv.y,layer);float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadow=unpack(texture2D(shadowSampler,uvLayer));
#else
float shadow=texture2D(shadowSampler,uvLayer).x;
#endif
return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}
#endif
#define inline
float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));
#else
float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;
#endif
return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}}
#define inline
float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760);
#ifndef SHADOWFLOAT
if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;
#else
if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;
#endif
return computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));
#else
float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;
#endif
float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));
#else
float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;
#endif
float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}
#ifdef IS_NDC_HALF_ZRANGE
#define ZINCLIP clipSpace.z
#else
#define ZINCLIP uvDepth.z
#endif
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define SMALLEST_ABOVE_ZERO 1.1754943508e-38
#define GREATEST_LESS_THAN_ONE 0.99999994
#define DISABLE_UNIFORMITY_ANALYSIS
#define inline
float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
#ifdef USE_REVERSE_DEPTHBUFFER
uvDepth.z=clamp(ZINCLIP,SMALLEST_ABOVE_ZERO,1.);
#else
uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);
#endif
vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}
#define inline
float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
#ifdef USE_REVERSE_DEPTHBUFFER
uvDepth.z=clamp(ZINCLIP,SMALLEST_ABOVE_ZERO,1.);
#else
uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);
#endif
vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;
uv+=0.5;
vec2 st=fract(uv);
vec2 base_uv=floor(uv)-0.5;
base_uv*=shadowMapSizeAndInverse.y;
vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}
#define inline
float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
#ifdef USE_REVERSE_DEPTHBUFFER
uvDepth.z=clamp(ZINCLIP,SMALLEST_ABOVE_ZERO,1.);
#else
uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);
#endif
vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;
uv+=0.5;
vec2 st=fract(uv);
vec2 base_uv=floor(uv)-0.5;
base_uv*=shadowMapSizeAndInverse.y;
vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}
#define inline
float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;if (depthMetric<0.0 || depthMetric>1.0 || uvDepth.x<0. || uvDepth.x>1.0 || uvDepth.y<0. || uvDepth.y>1.0) {return 1.0;} else {float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;if (depthMetric<0.0 || depthMetric>1.0 || uvDepth.x<0. || uvDepth.x>1.0 || uvDepth.y<0. || uvDepth.y>1.0) {return 1.0;} else {vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;
uv+=0.5;
vec2 st=fract(uv);
vec2 base_uv=floor(uv)-0.5;
base_uv*=shadowMapSizeAndInverse.y;
vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;if (depthMetric<0.0 || depthMetric>1.0 || uvDepth.x<0. || uvDepth.x>1.0 || uvDepth.y<0. || uvDepth.y>1.0) {return 1.0;} else {vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;
uv+=0.5;
vec2 st=fract(uv);
vec2 base_uv=floor(uv)-0.5;
base_uv*=shadowMapSizeAndInverse.y;
vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
const vec3 PoissonSamplers32[64]=vec3[64](
vec3(0.06407013,0.05409927,0.),
vec3(0.7366577,0.5789394,0.),
vec3(-0.6270542,-0.5320278,0.),
vec3(-0.4096107,0.8411095,0.),
vec3(0.6849564,-0.4990818,0.),
vec3(-0.874181,-0.04579735,0.),
vec3(0.9989998,0.0009880066,0.),
vec3(-0.004920578,-0.9151649,0.),
vec3(0.1805763,0.9747483,0.),
vec3(-0.2138451,0.2635818,0.),
vec3(0.109845,0.3884785,0.),
vec3(0.06876755,-0.3581074,0.),
vec3(0.374073,-0.7661266,0.),
vec3(0.3079132,-0.1216763,0.),
vec3(-0.3794335,-0.8271583,0.),
vec3(-0.203878,-0.07715034,0.),
vec3(0.5912697,0.1469799,0.),
vec3(-0.88069,0.3031784,0.),
vec3(0.5040108,0.8283722,0.),
vec3(-0.5844124,0.5494877,0.),
vec3(0.6017799,-0.1726654,0.),
vec3(-0.5554981,0.1559997,0.),
vec3(-0.3016369,-0.3900928,0.),
vec3(-0.5550632,-0.1723762,0.),
vec3(0.925029,0.2995041,0.),
vec3(-0.2473137,0.5538505,0.),
vec3(0.9183037,-0.2862392,0.),
vec3(0.2469421,0.6718712,0.),
vec3(0.3916397,-0.4328209,0.),
vec3(-0.03576927,-0.6220032,0.),
vec3(-0.04661255,0.7995201,0.),
vec3(0.4402924,0.3640312,0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.)
);const vec3 PoissonSamplers64[64]=vec3[64](
vec3(-0.613392,0.617481,0.),
vec3(0.170019,-0.040254,0.),
vec3(-0.299417,0.791925,0.),
vec3(0.645680,0.493210,0.),
vec3(-0.651784,0.717887,0.),
vec3(0.421003,0.027070,0.),
vec3(-0.817194,-0.271096,0.),
vec3(-0.705374,-0.668203,0.),
vec3(0.977050,-0.108615,0.),
vec3(0.063326,0.142369,0.),
vec3(0.203528,0.214331,0.),
vec3(-0.667531,0.326090,0.),
vec3(-0.098422,-0.295755,0.),
vec3(-0.885922,0.215369,0.),
vec3(0.566637,0.605213,0.),
vec3(0.039766,-0.396100,0.),
vec3(0.751946,0.453352,0.),
vec3(0.078707,-0.715323,0.),
vec3(-0.075838,-0.529344,0.),
vec3(0.724479,-0.580798,0.),
vec3(0.222999,-0.215125,0.),
vec3(-0.467574,-0.405438,0.),
vec3(-0.248268,-0.814753,0.),
vec3(0.354411,-0.887570,0.),
vec3(0.175817,0.382366,0.),
vec3(0.487472,-0.063082,0.),
vec3(-0.084078,0.898312,0.),
vec3(0.488876,-0.783441,0.),
vec3(0.470016,0.217933,0.),
vec3(-0.696890,-0.549791,0.),
vec3(-0.149693,0.605762,0.),
vec3(0.034211,0.979980,0.),
vec3(0.503098,-0.308878,0.),
vec3(-0.016205,-0.872921,0.),
vec3(0.385784,-0.393902,0.),
vec3(-0.146886,-0.859249,0.),
vec3(0.643361,0.164098,0.),
vec3(0.634388,-0.049471,0.),
vec3(-0.688894,0.007843,0.),
vec3(0.464034,-0.188818,0.),
vec3(-0.440840,0.137486,0.),
vec3(0.364483,0.511704,0.),
vec3(0.034028,0.325968,0.),
vec3(0.099094,-0.308023,0.),
vec3(0.693960,-0.366253,0.),
vec3(0.678884,-0.204688,0.),
vec3(0.001801,0.780328,0.),
vec3(0.145177,-0.898984,0.),
vec3(0.062655,-0.611866,0.),
vec3(0.315226,-0.604297,0.),
vec3(-0.780145,0.486251,0.),
vec3(-0.371868,0.882138,0.),
vec3(0.200476,0.494430,0.),
vec3(-0.494552,-0.711051,0.),
vec3(0.612476,0.705252,0.),
vec3(-0.578845,-0.768792,0.),
vec3(-0.772454,-0.090976,0.),
vec3(0.504440,0.372295,0.),
vec3(0.155736,0.065157,0.),
vec3(0.391522,0.849605,0.),
vec3(-0.620106,-0.328104,0.),
vec3(0.789239,-0.419965,0.),
vec3(-0.545396,0.538133,0.),
vec3(-0.178564,-0.596057,0.)
);
#define inline
float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
#ifdef USE_REVERSE_DEPTHBUFFER
uvDepth.z=clamp(ZINCLIP,SMALLEST_ABOVE_ZERO,1.);
#else
uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);
#endif
vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=texture2D(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}}
float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);vec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec4 offset=vec4(poissonSamplers[i],0.);offset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);shadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);}
shadow/=float(pcfTapCount);shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));shadow=mix(darkness,1.,shadow);if (numBlocker<1.0) {return 1.0;}
else
{return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;if (depthMetric<0.0 || depthMetric>1.0 || uvDepth.x<0. || uvDepth.x>1.0 || uvDepth.y<0. || uvDepth.y>1.0) {return 1.0;} else {float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=TEXTUREFUNC(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0.).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}}
if (numBlocker<1.0) {return 1.0;}
else
{float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);float filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec3 offset=poissonSamplers[i];offset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);shadow+=TEXTUREFUNC(shadowSampler,uvDepth+offset*filterRadius,0.);}
shadow/=float(pcfTapCount);shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}}
#define inline
float computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}
#define inline
float computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}
#define inline
float computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}
#define inline
float computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}
#define inline
float computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}
#define inline
float computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}
#endif
#endif
`;x.IncludesShadersStore[DY]||(x.IncludesShadersStore[DY]=Bpe)});var OY,Upe,fh=y(()=>{k();OY="samplerFragmentDeclaration",Upe=`#ifdef _DEFINENAME_
#if _DEFINENAME_DIRECTUV==1
#define v_VARYINGNAME_UV vMainUV1
#elif _DEFINENAME_DIRECTUV==2
#define v_VARYINGNAME_UV vMainUV2
#elif _DEFINENAME_DIRECTUV==3
#define v_VARYINGNAME_UV vMainUV3
#elif _DEFINENAME_DIRECTUV==4
#define v_VARYINGNAME_UV vMainUV4
#elif _DEFINENAME_DIRECTUV==5
#define v_VARYINGNAME_UV vMainUV5
#elif _DEFINENAME_DIRECTUV==6
#define v_VARYINGNAME_UV vMainUV6
#else
varying vec2 v_VARYINGNAME_UV;
#endif
uniform sampler2D _SAMPLERNAME_Sampler;
#endif
`;x.IncludesShadersStore[OY]||(x.IncludesShadersStore[OY]=Upe)});var NY,Vpe,wY=y(()=>{k();NY="fresnelFunction",Vpe=`#ifdef FRESNEL
float computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)
{float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}
#endif
`;x.IncludesShadersStore[NY]||(x.IncludesShadersStore[NY]=Vpe)});var FY,Gpe,vE=y(()=>{k();FY="reflectionFunction",Gpe=`vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)
{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); }
vec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)
{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); }
vec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
{vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);vec3 r=normalize(reflect(cameraToVertex,worldNormal));r=vec3(reflectionMatrix*vec4(r,0));float lon=atan(r.z,r.x);float lat=acos(r.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0);}
vec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix)
{vec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r=vec3(reflectionMatrix*vec4(r,0));r.z=r.z-1.0;float m=2.0*length(r);return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);}
vec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
{vec3 viewDir=worldPos.xyz-eyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));}
vec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=vec3(reflectionMatrix*vec4(coords,0));
#ifdef INVERTCUBICMAP
coords.y*=-1.0;
#endif
return coords;}
vec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition)
{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=vec3(reflectionMatrix*vec4(coords,0));
#ifdef INVERTCUBICMAP
coords.y*=-1.0;
#endif
return coords;}
vec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix)
{return vec3(reflectionMatrix*(view*worldPos));}
vec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix)
{return vec3(reflectionMatrix*vec4(positionW,1.));}
#ifdef REFLECTION
vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)
{
#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED
vec3 direction=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);
#endif
#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED
vec3 direction=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction);
#endif
#ifdef REFLECTIONMAP_EQUIRECTANGULAR
return computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_SPHERICAL
return computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_PLANAR
return computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_CUBIC
#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC
return computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition);
#else
return computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
#endif
#endif
#ifdef REFLECTIONMAP_PROJECTION
return computeProjectionCoords(worldPos,view,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_SKYBOX
return computeSkyBoxCoords(vPositionUVW,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_EXPLICIT
return vec3(0,0,0);
#endif
}
#endif
`;x.IncludesShadersStore[FY]||(x.IncludesShadersStore[FY]=Gpe)});var BY,kpe,TM=y(()=>{k();BY="imageProcessingDeclaration",kpe=`#ifdef EXPOSURE
uniform float exposureLinear;
#endif
#ifdef CONTRAST
uniform float contrast;
#endif
#if defined(VIGNETTE) || defined(DITHER)
uniform vec2 vInverseScreenSize;
#endif
#ifdef VIGNETTE
uniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2;
#endif
#ifdef COLORCURVES
uniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive;
#endif
#ifdef COLORGRADING
#ifdef COLORGRADING3D
uniform highp sampler3D txColorTransform;
#else
uniform sampler2D txColorTransform;
#endif
uniform vec4 colorTransformSettings;
#endif
#ifdef DITHER
uniform float ditherIntensity;
#endif
`;x.IncludesShadersStore[BY]||(x.IncludesShadersStore[BY]=kpe)});var UY,zpe,AM=y(()=>{k();UY="imageProcessingFunctions",zpe=`#if defined(COLORGRADING) && !defined(COLORGRADING3D)
/**
* Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL.
* sampler3dSetting.x=textureOffset (0.5/textureSize).
* sampler3dSetting.y=textureSize.
*/
#define inline
vec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)
{float sliceSize=2.0*sampler3dSetting.x;
#ifdef SAMPLER3DGREENDEPTH
float sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;
#else
float sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;
#endif
float sliceInteger=floor(sliceContinuous);float sliceFraction=sliceContinuous-sliceInteger;
#ifdef SAMPLER3DGREENDEPTH
vec2 sliceUV=color.rb;
#else
vec2 sliceUV=color.rg;
#endif
sliceUV.x*=sliceSize;sliceUV.x+=sliceInteger*sliceSize;sliceUV=saturate(sliceUV);vec4 slice0Color=texture2D(colorTransform,sliceUV);sliceUV.x+=sliceSize;sliceUV=saturate(sliceUV);vec4 slice1Color=texture2D(colorTransform,sliceUV);vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);
#ifdef SAMPLER3DBGRMAP
color.rgb=result.rgb;
#else
color.rgb=result.bgr;
#endif
return color;}
#endif
#if TONEMAPPING==3
const float PBRNeutralStartCompression=0.8-0.04;const float PBRNeutralDesaturation=0.15;vec3 PBRNeutralToneMapping( vec3 color ) {float x=min(color.r,min(color.g,color.b));float offset=x<0.08 ? x-6.25*x*x : 0.04;color-=offset;float peak=max(color.r,max(color.g,color.b));if (peak<PBRNeutralStartCompression) return color;float d=1.-PBRNeutralStartCompression;float newPeak=1.-d*d/(peak+d-PBRNeutralStartCompression);color*=newPeak/peak;float g=1.-1./(PBRNeutralDesaturation*(peak-newPeak)+1.);return mix(color,newPeak*vec3(1,1,1),g);}
#endif
#if TONEMAPPING==2
const mat3 ACESInputMat=mat3(
vec3(0.59719,0.07600,0.02840),
vec3(0.35458,0.90834,0.13383),
vec3(0.04823,0.01566,0.83777)
);const mat3 ACESOutputMat=mat3(
vec3( 1.60475,-0.10208,-0.00327),
vec3(-0.53108, 1.10813,-0.07276),
vec3(-0.07367,-0.00605, 1.07602)
);vec3 RRTAndODTFit(vec3 v)
{vec3 a=v*(v+0.0245786)-0.000090537;vec3 b=v*(0.983729*v+0.4329510)+0.238081;return a/b;}
vec3 ACESFitted(vec3 color)
{color=ACESInputMat*color;color=RRTAndODTFit(color);color=ACESOutputMat*color;color=saturate(color);return color;}
#endif
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS
vec4 applyImageProcessing(vec4 result) {
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART
#ifdef EXPOSURE
result.rgb*=exposureLinear;
#endif
#ifdef VIGNETTE
vec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;vec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);float vignetteTerm=dot(vignetteXY1,vignetteXY1);float vignette=pow(vignetteTerm,vignetteSettings2.w);vec3 vignetteColor=vignetteSettings2.rgb;
#ifdef VIGNETTEBLENDMODEMULTIPLY
vec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);result.rgb*=vignetteColorMultiplier;
#endif
#ifdef VIGNETTEBLENDMODEOPAQUE
result.rgb=mix(vignetteColor,result.rgb,vignette);
#endif
#endif
#if TONEMAPPING==3
result.rgb=PBRNeutralToneMapping(result.rgb);
#elif TONEMAPPING==2
result.rgb=ACESFitted(result.rgb);
#elif TONEMAPPING==1
const float tonemappingCalibration=1.590579;result.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);
#endif
result.rgb=toGammaSpace(result.rgb);result.rgb=saturate(result.rgb);
#ifdef CONTRAST
vec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);if (contrast<1.0) {result.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);} else {result.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);}
result.rgb=max(result.rgb,0.);
#endif
#ifdef COLORGRADING
vec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;
#ifdef COLORGRADING3D
vec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;
#else
vec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;
#endif
result.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);
#endif
#ifdef COLORCURVES
float luma=getLuminance(result.rgb);vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));vec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;result.rgb*=colorCurve.rgb;result.rgb=mix(vec3(luma),result.rgb,colorCurve.a);
#endif
#ifdef DITHER
float rand=getRand(gl_FragCoord.xy*vInverseScreenSize);float dither=mix(-ditherIntensity,ditherIntensity,rand);result.rgb=saturate(result.rgb+vec3(dither));
#endif
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND
return result;}`;x.IncludesShadersStore[UY]||(x.IncludesShadersStore[UY]=zpe)});var VY,Wpe,xM=y(()=>{k();VY="bumpFragmentMainFunctions",Wpe=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)
#if defined(TANGENT) && defined(NORMAL)
varying mat3 vTBN;
#endif
#ifdef OBJECTSPACE_NORMALMAP
uniform mat4 normalMatrix;
#if defined(WEBGL2) || defined(WEBGPU)
mat4 toNormalMatrix(mat4 wMatrix)
{mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;}
#else
mat4 toNormalMatrix(mat4 m)
{float
a00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],
a10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],
a20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],
a30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],
b00=a00*a11-a01*a10,
b01=a00*a12-a02*a10,
b02=a00*a13-a03*a10,
b03=a01*a12-a02*a11,
b04=a01*a13-a03*a11,
b05=a02*a13-a03*a12,
b06=a20*a31-a21*a30,
b07=a20*a32-a22*a30,
b08=a20*a33-a23*a30,
b09=a21*a32-a22*a31,
b10=a21*a33-a23*a31,
b11=a22*a33-a23*a32,
det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4(
a11*b11-a12*b10+a13*b09,
a02*b10-a01*b11-a03*b09,
a31*b05-a32*b04+a33*b03,
a22*b04-a21*b05-a23*b03,
a12*b08-a10*b11-a13*b07,
a00*b11-a02*b08+a03*b07,
a32*b02-a30*b05-a33*b01,
a20*b05-a22*b02+a23*b01,
a10*b10-a11*b08+a13*b06,
a01*b08-a00*b10-a03*b06,
a30*b04-a31*b02+a33*b00,
a21*b02-a20*b04-a23*b00,
a11*b07-a10*b09-a12*b06,
a00*b09-a01*b07+a02*b06,
a31*b01-a30*b03-a32*b00,
a20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0],
mi[0][1],mi[1][1],mi[2][1],mi[3][1],
mi[0][2],mi[1][2],mi[2][2],mi[3][2],
mi[0][3],mi[1][3],mi[2][3],mi[3][3]);}
#endif
#endif
vec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale)
{
#ifdef NORMALXYSCALE
normal=normalize(normal*vec3(scale,scale,1.0));
#endif
return normalize(cotangentFrame*normal);}
vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale)
{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}
mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams)
{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);}
#endif
`;x.IncludesShadersStore[VY]||(x.IncludesShadersStore[VY]=Wpe)});var GY,Hpe,RM=y(()=>{k();fh();GY="bumpFragmentFunctions",Hpe=`#if defined(BUMP)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)
#endif
#if defined(DETAIL)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)
#endif
#if defined(BUMP) && defined(PARALLAX)
const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; i<iMaxSamples; i++)
{currSampledHeight=texture2D(bumpSampler,texCoord+vCurrOffset).w;if (!keepWorking)
{}
else if (currSampledHeight>currRayHeight)
{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}
else
{currRayHeight-=stepSize;vLastOffset=vCurrOffset;
#ifdef PARALLAX_RHS
vCurrOffset-=stepSize*vMaxOffset;
#else
vCurrOffset+=stepSize*vMaxOffset;
#endif
lastSampledHeight=currSampledHeight;}}
return vCurrOffset;}
vec2 parallaxOffset(vec3 viewDir,float heightScale)
{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height;
#ifdef PARALLAX_RHS
return texCoordOffset;
#else
return -texCoordOffset;
#endif
}
#endif
`;x.IncludesShadersStore[GY]||(x.IncludesShadersStore[GY]=Hpe)});var kY,Xpe,bM=y(()=>{k();kY="bumpFragment",Xpe=`vec2 uvOffset=vec2(0.0,0.0);
#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)
#ifdef NORMALXYSCALE
float normalScale=1.0;
#elif defined(BUMP)
float normalScale=vBumpInfos.y;
#else
float normalScale=1.0;
#endif
#if defined(TANGENT) && defined(NORMAL)
mat3 TBN=vTBN;
#elif defined(BUMP)
vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);
#else
vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.));
#endif
#elif defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
mat3 TBN=vTBN;
#else
vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.));
#endif
#endif
#ifdef PARALLAX
mat3 invTBN=transposeMat3(TBN);
#ifdef PARALLAXOCCLUSION
uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);
#else
uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);
#endif
#endif
#ifdef DETAIL
vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB);
#endif
#ifdef BUMP
#ifdef OBJECTSPACE_NORMALMAP
#define CUSTOM_FRAGMENT_BUMP_FRAGMENT
normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW);
#elif !defined(DETAIL)
normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);
#else
vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;
#if DETAIL_NORMALBLENDMETHOD==0
detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));
#elif DETAIL_NORMALBLENDMETHOD==1
detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;
#endif
normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);
#endif
#elif defined(DETAIL)
detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);
#endif
`;x.IncludesShadersStore[kY]||(x.IncludesShadersStore[kY]=Xpe)});var zY,Ype,mN=y(()=>{k();zY="decalFragment",Ype=`#ifdef DECAL
#ifdef GAMMADECAL
decalColor.rgb=toLinearSpace(decalColor.rgb);
#endif
#ifdef DECAL_SMOOTHALPHA
decalColor.a*=decalColor.a;
#endif
surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a);
#endif
`;x.IncludesShadersStore[zY]||(x.IncludesShadersStore[zY]=Ype)});var WY,Kpe,MM=y(()=>{k();WY="depthPrePass",Kpe=`#ifdef DEPTHPREPASS
gl_FragColor=vec4(0.,0.,0.,1.0);return;
#endif
`;x.IncludesShadersStore[WY]||(x.IncludesShadersStore[WY]=Kpe)});var HY,jpe,pN=y(()=>{k();HY="lightFragment",jpe=`#ifdef LIGHT{X}
#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})
#else
vec4 diffuse{X}=light{X}.vLightDiffuse;
#define CUSTOM_LIGHT{X}_COLOR
#if defined(PBR) && defined(CLUSTLIGHT{X}) && defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
{int sliceIndex=min(getClusteredSliceIndex(light{X}.vSliceData,vViewDepth),CLUSTLIGHT_SLICES-1);info=computeClusteredLighting(
lightDataTexture{X},
tileMaskTexture{X},
light{X}.vLightData,
ivec2(light{X}.vSliceRanges[sliceIndex]),
viewDirectionW,
normalW,
vPositionW,
surfaceAlbedo,
reflectivityOut
#ifdef IRIDESCENCE
,iridescenceIntensity
#endif
#ifdef SS_TRANSLUCENCY
,subSurfaceOut
#endif
#ifdef SPECULARTERM
,AARoughnessFactors.x
#endif
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#ifdef SHEEN
,sheenOut
#endif
#ifdef CLEARCOAT
,clearcoatOut
#endif
);}
#elif defined(PBR)
#ifdef SPOTLIGHT{X}
preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,vPositionW);
#elif defined(POINTLIGHT{X})
preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,vPositionW);
#elif defined(HEMILIGHT{X})
preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
#elif defined(DIRLIGHT{X})
preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
#elif defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
#if defined(RECTAREALIGHTEMISSIONTEXTURE{X})
preInfo=computeAreaPreLightingInfoWithTexture(areaLightsLTC1Sampler,areaLightsLTC2Sampler,rectAreaLightEmissionTexture{X},viewDirectionW,normalW,vPositionW,light{X}.vLightData,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,roughness);
#else
preInfo=computeAreaPreLightingInfo(areaLightsLTC1Sampler,areaLightsLTC2Sampler,viewDirectionW,normalW,vPositionW,light{X}.vLightData,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,roughness);
#endif
#endif
preInfo.NdotV=NdotV;
#ifdef SPOTLIGHT{X}
#ifdef LIGHT_FALLOFF_GLTF{X}
preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);
#ifdef IESLIGHTTEXTURE{X}
preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X});
#else
preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
#endif
#elif defined(LIGHT_FALLOFF_PHYSICAL{X})
preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);
#ifdef IESLIGHTTEXTURE{X}
preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X});
#else
preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);
#endif
#elif defined(LIGHT_FALLOFF_STANDARD{X})
preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);
#ifdef IESLIGHTTEXTURE{X}
preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X});
#else
preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);
#endif
#else
preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);
#ifdef IESLIGHTTEXTURE{X}
preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X});
#else
preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
#endif
#endif
#elif defined(POINTLIGHT{X})
#ifdef LIGHT_FALLOFF_GLTF{X}
preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);
#elif defined(LIGHT_FALLOFF_PHYSICAL{X})
preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);
#elif defined(LIGHT_FALLOFF_STANDARD{X})
preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);
#else
preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);
#endif
#else
preInfo.attenuation=1.0;
#endif
#if defined(HEMILIGHT{X})
preInfo.roughness=roughness;
#elif defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
preInfo.roughness=roughness;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
#endif
preInfo.diffuseRoughness=diffuseRoughness;preInfo.surfaceAlbedo=surfaceAlbedo;
#ifdef IRIDESCENCE
preInfo.iridescenceIntensity=iridescenceIntensity;
#endif
#ifdef SS_TRANSLUCENCY
info.diffuseTransmission=vec3(0.0);
#endif
#ifdef HEMILIGHT{X}
info.diffuse=computeHemisphericDiffuseLighting(preInfo,diffuse{X}.rgb,light{X}.vLightGround);
#elif defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
info.diffuse=computeAreaDiffuseLighting(preInfo,diffuse{X}.rgb);
#elif defined(SS_TRANSLUCENCY)
#ifndef SS_TRANSLUCENCY_LEGACY
info.diffuse=computeDiffuseLighting(preInfo,diffuse{X}.rgb)*(1.0-subSurfaceOut.translucencyIntensity);info.diffuseTransmission=computeDiffuseTransmittedLighting(preInfo,diffuse{X}.rgb,subSurfaceOut.transmittance);
#else
info.diffuse=computeDiffuseTransmittedLighting(preInfo,diffuse{X}.rgb,subSurfaceOut.transmittance);
#endif
#else
info.diffuse=computeDiffuseLighting(preInfo,diffuse{X}.rgb);
#endif
#ifdef SPECULARTERM
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
info.specular=computeAreaSpecularLighting(preInfo,light{X}.vLightSpecular.rgb,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90);
#else
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR)
{vec3 metalFresnel=reflectivityOut.specularWeight*getF82Specular(preInfo.VdotH,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90,reflectivityOut.roughness);vec3 dielectricFresnel=fresnelSchlickGGX(preInfo.VdotH,reflectivityOut.dielectricColorF0,reflectivityOut.colorReflectanceF90);coloredFresnel=mix(dielectricFresnel,metalFresnel,reflectivityOut.metallic);}
#else
coloredFresnel=fresnelSchlickGGX(preInfo.VdotH,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90);
#endif
#ifndef LEGACY_SPECULAR_ENERGY_CONSERVATION
{float NdotH=dot(normalW,preInfo.H);vec3 fresnel=fresnelSchlickGGX(NdotH,vec3(reflectanceF0),specularEnvironmentR90);info.diffuse*=(vec3(1.0)-fresnel);}
#endif
#ifdef ANISOTROPIC
info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);
#else
info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,coloredFresnel,AARoughnessFactors.x,diffuse{X}.rgb);
#endif
#endif
#endif
#ifndef AREALIGHT{X}
#ifdef SHEEN
#ifdef SHEEN_LINKWITHALBEDO
preInfo.roughness=sheenOut.sheenIntensity;
#else
#ifdef HEMILIGHT{X}
preInfo.roughness=sheenOut.sheenRoughness;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
#endif
#endif
info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);
#endif
#ifdef CLEARCOAT
#ifdef HEMILIGHT{X}
preInfo.roughness=clearcoatOut.clearCoatRoughness;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
#endif
info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,diffuse{X}.rgb);
#ifdef CLEARCOAT_TINT
absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;
#ifdef SS_TRANSLUCENCY
info.diffuseTransmission*=absorption;
#endif
#ifdef SPECULARTERM
info.specular*=absorption;
#endif
#endif
info.diffuse*=info.clearCoat.w;
#ifdef SS_TRANSLUCENCY
info.diffuseTransmission*=info.clearCoat.w;
#endif
#ifdef SPECULARTERM
info.specular*=info.clearCoat.w;
#endif
#ifdef SHEEN
info.sheen*=info.clearCoat.w;
#endif
#endif
#endif
#else
#ifdef SPOTLIGHT{X}
#ifdef IESLIGHTTEXTURE{X}
info=computeIESSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness,iesLightTexture{X});
#else
info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness);
#endif
#elif defined(HEMILIGHT{X})
info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);
#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})
info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness);
#elif defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
#if defined(RECTAREALIGHTEMISSIONTEXTURE{X})
info=computeAreaLightingWithTexture(areaLightsLTC1Sampler,areaLightsLTC2Sampler,rectAreaLightEmissionTexture{X},viewDirectionW,normalW,vPositionW,light{X}.vLightData.xyz,light{X}.vLightWidth.rgb,light{X}.vLightHeight.rgb,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,
#ifdef AREALIGHTNOROUGHTNESS
0.5
#else
vReflectionInfos.y
#endif
#else
info=computeAreaLighting(areaLightsLTC1Sampler,areaLightsLTC2Sampler,viewDirectionW,normalW,vPositionW,light{X}.vLightData.xyz,light{X}.vLightWidth.rgb,light{X}.vLightHeight.rgb,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,
#ifdef AREALIGHTNOROUGHTNESS
0.5
#else
vReflectionInfos.y
#endif
#endif
);
#elif defined(CLUSTLIGHT{X}) && CLUSTLIGHT_BATCH>0
{int sliceIndex=min(getClusteredSliceIndex(light{X}.vSliceData,vViewDepth),CLUSTLIGHT_SLICES-1);info=computeClusteredLighting(lightDataTexture{X},tileMaskTexture{X},viewDirectionW,normalW,light{X}.vLightData,ivec2(light{X}.vSliceRanges[sliceIndex]),glossiness);}
#endif
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},textureProjectionMatrix{X},vPositionW);
#endif
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++)
{
#ifdef SHADOWCSM_RIGHTHANDED{X}
diff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z;
#else
diff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z;
#endif
if (diff{X}>=0.) {index{X}=i;break;}}
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
if (index{X}>=0)
#endif
{
#if defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#else
shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#endif
#else
shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#ifdef SHADOWCSMDEBUG{X}
shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}];
#endif
#ifndef SHADOWCSMNOBLEND{X}
float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)
{index{X}+=1;float nextShadow=0.;
#if defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#elif defined(SHADOWMEDIUMQUALITY{X})
nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#else
nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#endif
#else
nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
shadow=mix(nextShadow,shadow,diffRatio);
#ifdef SHADOWCSMDEBUG{X}
shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);
#endif
}
#endif
}
#elif defined(SHADOWCLOSEESM{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);
#else
shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWESM{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);
#else
shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPOISSON{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);
#else
shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#else
#if defined(SHADOWCUBE{X})
shadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.depthValues);
#else
shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#endif
#ifdef SHADOWONLY
#ifndef SHADOWINUSE
#define SHADOWINUSE
#endif
globalShadow+=shadow;shadowLightCount+=1.0;
#endif
#else
shadow=1.;
#endif
aggShadow+=shadow;numLights+=1.0;
#ifndef SHADOWONLY
#ifdef CUSTOMUSERLIGHTING
diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);
#ifdef SPECULARTERM
specularBase+=computeCustomSpecularLighting(info,specularBase,shadow);
#endif
#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})
diffuseBase+=lightmapColor.rgb*shadow;
#ifdef SPECULARTERM
#ifndef LIGHTMAPNOSPECULAR{X}
specularBase+=info.specular*shadow*lightmapColor.rgb;
#endif
#endif
#ifdef CLEARCOAT
#ifndef LIGHTMAPNOSPECULAR{X}
clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;
#endif
#endif
#ifdef SHEEN
#ifndef LIGHTMAPNOSPECULAR{X}
sheenBase+=info.sheen.rgb*shadow;
#endif
#endif
#else
#ifdef SHADOWCSMDEBUG{X}
diffuseBase+=info.diffuse*shadowDebug{X};
#else
diffuseBase+=info.diffuse*shadow;
#endif
#ifdef SS_TRANSLUCENCY
diffuseTransmissionBase+=info.diffuseTransmission*shadow;
#endif
#ifdef SPECULARTERM
specularBase+=info.specular*shadow;
#endif
#ifdef CLEARCOAT
clearCoatBase+=info.clearCoat.rgb*shadow;
#endif
#ifdef SHEEN
sheenBase+=info.sheen.rgb*shadow;
#endif
#endif
#endif
#endif
`;x.IncludesShadersStore[HY]||(x.IncludesShadersStore[HY]=jpe)});var XY,Zpe,yM=y(()=>{k();XY="logDepthFragment",Zpe=`#ifdef LOGARITHMICDEPTH
gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;
#endif
`;x.IncludesShadersStore[XY]||(x.IncludesShadersStore[XY]=Zpe)});var YY,qpe,IM=y(()=>{k();YY="oitFragment",qpe=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY
float fragDepth=gl_FragCoord.z;
#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS
uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x;
#endif
ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0);
#ifdef USE_REVERSE_DEPTHBUFFER
float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y;
#else
float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y;
#endif
float alphaMultiplier=1.0-lastFrontColor.a;
#ifdef USE_REVERSE_DEPTHBUFFER
if (fragDepth>nearestDepth || fragDepth<furthestDepth) {
#else
if (fragDepth<nearestDepth || fragDepth>furthestDepth) {
#endif
return;}
#ifdef USE_REVERSE_DEPTHBUFFER
if (fragDepth<nearestDepth && fragDepth>furthestDepth) {
#else
if (fragDepth>nearestDepth && fragDepth<furthestDepth) {
#endif
depth.rg=vec2(-fragDepth,fragDepth);return;}
#endif
`;x.IncludesShadersStore[YY]||(x.IncludesShadersStore[YY]=qpe)});var jY={};Be(jY,{defaultPixelShader:()=>Qpe});var gN,KY,Qpe,ZY=y(()=>{k();xY();lN();gM();_M();cg();oo();vM();EM();LY();SM();fh();wY();vE();TM();AM();xM();RM();af();ch();lE();of();bM();mN();MM();pN();yM();cE();IM();gN="defaultPixelShader",KY=`#define CUSTOM_FRAGMENT_EXTENSION
#include<__decl__defaultFragment>
#if defined(BUMP) || !defined(NORMAL)
#extension GL_OES_standard_derivatives : enable
#endif
#include<prePassDeclaration>[SCENE_MRT_COUNT]
#include<oitDeclaration>
#define CUSTOM_FRAGMENT_BEGIN
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
varying vec3 vPositionW;
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
varying float vViewDepth;
#endif
#include<mainUVVaryingDeclaration>[1..7]
#include<helperFunctions>
#include<__decl__lightFragment>[0..maxSimultaneousLights]
#include<lightsFragmentFunctions>
#include<shadowsFragmentFunctions>
#include<samplerFragmentDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)
#ifdef REFRACTION
#ifdef REFRACTIONMAP_3D
uniform samplerCube refractionCubeSampler;
#else
uniform sampler2D refraction2DSampler;
#endif
#endif
#if defined(SPECULARTERM)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)
#endif
#include<fresnelFunction>
#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
uniform samplerCube reflectionCubeSampler;
#else
uniform sampler2D reflection2DSampler;
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#endif
#include<reflectionFunction>
#endif
#include<imageProcessingDeclaration>
#include<imageProcessingFunctions>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;
#ifdef NORMAL
vec3 normalW=normalize(vNormalW);
#else
vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;
#endif
#include<bumpFragment>
#ifdef TWOSIDEDLIGHTING
normalW=gl_FrontFacing ? normalW : -normalW;
#endif
#ifdef DIFFUSE
baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);
#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)
if (baseColor.a<alphaCutOff)
discard;
#endif
#ifdef ALPHAFROMDIFFUSE
alpha*=baseColor.a;
#endif
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
baseColor.rgb*=vDiffuseInfos.y;
#endif
#if defined(DECAL) && !defined(DECAL_AFTER_DETAIL)
vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);
#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)
#endif
#include<depthPrePass>
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
baseColor.rgb*=vColor.rgb;
#endif
#ifdef DETAIL
baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y);
#endif
#if defined(DECAL) && defined(DECAL_AFTER_DETAIL)
vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);
#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)
#endif
#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE
vec3 baseAmbientColor=vec3(1.,1.,1.);
#ifdef AMBIENT
baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;
#endif
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS
float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;
#ifdef SPECULARTERM
#ifdef SPECULAR
vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb;
#ifdef GLOSSINESS
glossiness=glossiness*specularMapColor.a;
#endif
#endif
#endif
vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;
#ifdef SPECULARTERM
vec3 specularBase=vec3(0.,0.,0.);
#endif
float shadow=1.;float aggShadow=0.;float numLights=0.;
#ifdef LIGHTMAP
vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);
#ifdef RGBDLIGHTMAP
lightmapColor.rgb=fromRGBD(lightmapColor);
#endif
lightmapColor.rgb*=vLightmapInfos.y;
#endif
#include<lightFragment>[0..maxSimultaneousLights]
aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.);
#ifdef REFRACTION
vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));
#ifdef REFRACTIONMAP_3D
#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC
refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition);
#endif
refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;}
#else
vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords);
#endif
#ifdef RGBDREFRACTION
refractionColor.rgb=fromRGBD(refractionColor);
#endif
#ifdef IS_REFRACTION_LINEAR
refractionColor.rgb=toGammaSpace(refractionColor.rgb);
#endif
refractionColor.rgb*=vRefractionInfos.x;
#endif
vec4 reflectionColor=vec4(0.,0.,0.,1.);
#ifdef REFLECTION
vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
vReflectionUVW.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
#ifdef ROUGHNESS
float bias=vReflectionInfos.y;
#ifdef SPECULARTERM
#ifdef SPECULAR
#ifdef GLOSSINESS
bias*=(1.0-specularMapColor.a);
#endif
#endif
#endif
reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias);
#else
reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW);
#endif
#else
vec2 coords=vReflectionUVW.xy;
#ifdef REFLECTIONMAP_PROJECTION
coords/=vReflectionUVW.z;
#endif
coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords);
#endif
#ifdef RGBDREFLECTION
reflectionColor.rgb=fromRGBD(reflectionColor);
#endif
#ifdef IS_REFLECTION_LINEAR
reflectionColor.rgb=toGammaSpace(reflectionColor.rgb);
#endif
reflectionColor.rgb*=vReflectionInfos.x;
#ifdef REFLECTIONFRESNEL
float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);
#ifdef REFLECTIONFRESNELFROMSPECULAR
#ifdef SPECULARTERM
reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
#else
reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
#endif
#else
reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
#endif
#endif
#endif
#ifdef REFRACTIONFRESNEL
float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;
#endif
#ifdef OPACITY
vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);
#ifdef OPACITYRGB
opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;
#else
alpha*=opacityMap.a*vOpacityInfos.y;
#endif
#endif
#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)
alpha*=vColor.a;
#endif
#ifdef OPACITYFRESNEL
float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;
#endif
#ifdef ALPHATEST
#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS
if (alpha<alphaCutOff)
discard;
#endif
#ifndef ALPHABLEND
alpha=1.0;
#endif
#endif
vec3 emissiveColor=vEmissiveColor;
#ifdef EMISSIVE
emissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;
#endif
#ifdef EMISSIVEFRESNEL
float emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);emissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;
#endif
#ifdef DIFFUSEFRESNEL
float diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);diffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;
#endif
#ifdef EMISSIVEASILLUMINATION
vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
#else
#ifdef LINKEMISSIVEWITHDIFFUSE
vec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
#else
vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
#endif
#endif
#ifdef SPECULARTERM
vec3 finalSpecular=specularBase*specularColor;
#ifdef SPECULAROVERALPHA
alpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);
#endif
#else
vec3 finalSpecular=vec3(0.0);
#endif
#ifdef REFLECTIONOVERALPHA
alpha=clamp(alpha+dot(reflectionColor.rgb,vec3(0.3,0.59,0.11)),0.,1.);
#endif
#ifdef EMISSIVEASILLUMINATION
vec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+emissiveColor+refractionColor.rgb,0.0,1.0),alpha);
#else
vec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+refractionColor.rgb,alpha);
#endif
#ifdef LIGHTMAP
#ifndef LIGHTMAPEXCLUDED
#ifdef USELIGHTMAPASSHADOWMAP
color.rgb*=lightmapColor.rgb;
#else
color.rgb+=lightmapColor.rgb;
#endif
#endif
#endif
#define CUSTOM_FRAGMENT_BEFORE_FOG
color.rgb=max(color.rgb,0.);
#include<logDepthFragment>
#include<fogFragment>
#ifdef IMAGEPROCESSINGPOSTPROCESS
color.rgb=toLinearSpace(color.rgb);
#else
#ifdef IMAGEPROCESSING
color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color);
#endif
#endif
color.a*=visibility;
#ifdef PREMULTIPLYALPHA
color.rgb*=color.a;
#endif
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
#if SCENE_MRT_COUNT>0
float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;
#ifdef PREPASS_COLOR
gl_FragData[PREPASS_COLOR_INDEX]=color;
#endif
#ifdef PREPASS_POSITION
gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_LOCAL_POSITION
gl_FragData[PREPASS_LOCAL_POSITION_INDEX]=vec4(vPosition,writeGeometryInfo);
#endif
#if defined(PREPASS_VELOCITY)
vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#elif defined(PREPASS_VELOCITY_LINEAR)
vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w)-(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_IRRADIANCE
gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_DEPTH
gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_SCREENSPACE_DEPTH
gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
gl_FragData[PREPASS_NORMALIZED_VIEW_DEPTH_INDEX]=vec4(vNormViewDepth,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMAL
#ifdef PREPASS_NORMAL_WORLDSPACE
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo);
#else
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo);
#endif
#endif
#ifdef PREPASS_WORLD_NORMAL
gl_FragData[PREPASS_WORLD_NORMAL_INDEX]=vec4(normalW*0.5+0.5,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO
gl_FragData[PREPASS_ALBEDO_INDEX]=vec4(baseColor.rgb,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqrt(baseColor.rgb),writeGeometryInfo);
#endif
#ifdef PREPASS_REFLECTIVITY
#if defined(SPECULAR)
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo;
#else
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo;
#endif
#endif
#endif
#endif
#if !defined(PREPASS) || defined(WEBGL2)
gl_FragColor=color;
#endif
#include<oitFragment>
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;}
#endif
#define CUSTOM_FRAGMENT_MAIN_END
}
`;x.ShadersStore[gN]||(x.ShadersStore[gN]=KY);Qpe={name:gN,shader:KY}});var _N,vN,EN,SN,We,lf=y(()=>{jt();Yt();Wo();na();$t();qi();yb();Ib();Dv();ls();uo();$v();ir();co();Td();JO();Hl();Jv();os();Or();Cb();Pb();Lb();Db();_N={effect:null,subMesh:null},vN=class extends ag(sg(wr)){},EN=class extends rg(vN){constructor(e){super(e),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_POSITION=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.MORPHTARGETS_UV2=!1,this.MORPHTARGETS_COLOR=!1,this.MORPHTARGETTEXTURE_HASPOSITIONS=!1,this.MORPHTARGETTEXTURE_HASNORMALS=!1,this.MORPHTARGETTEXTURE_HASTANGENTS=!1,this.MORPHTARGETTEXTURE_HASUVS=!1,this.MORPHTARGETTEXTURE_HASUV2S=!1,this.MORPHTARGETTEXTURE_HASCOLORS=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.AREALIGHTSUPPORTED=!0,this.USE_VERTEX_PULLING=!1,this.VERTEX_PULLING_USE_INDEX_BUFFER=!1,this.VERTEX_PULLING_INDEX_BUFFER_32BITS=!1,this.RIGHT_HANDED=!1,this.CLUSTLIGHT_SLICES=0,this.CLUSTLIGHT_BATCH=0,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}},SN=class extends og(jl){},We=class n extends SN{get isPrePassCapable(){return!this.disableDepthWrite}get canRenderToMRT(){return!0}constructor(e,t,i=!1){super(e,t,void 0,i||n.ForceGLSL),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new he(0,0,0),this.diffuseColor=new he(1,1,1),this.specularColor=new he(1,1,1),this.emissiveColor=new he(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._shadersLoaded=!1,this._vertexPullingMetadata=null,this._renderTargets=new Qi(16),this._globalAmbientColor=new he(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new ho(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new fa,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),n.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),n.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return n.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||n.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return this._hasTransparencyMode?this._transparencyModeIsBlend:this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled}needAlphaTesting(){return this._hasTransparencyMode?this._transparencyModeIsTest:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===Ae.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Ae.MATERIAL_OPAQUE}_hasAlphaChannel(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();let r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new EN(this._eventInfo.defineNames));let s=this.getScene(),a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let o=s.getEngine();if(a._needNormals=Gp(s,e,a,!0,this._maxSimultaneousLights,this._disableLighting),!Vp(s,e,this._maxSimultaneousLights,this._disableLighting))return!1;Wp(s,a);let l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Xp(s,a,this.canRenderToMRT&&!l),Hp(s,a,l),us.PrepareDefines(o.currentRenderPassId,e,a),a._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a._needUVs=!1;for(let f=1;f<=6;++f)a["MAINUV"+f]=!1;if(s.texturesEnabled){if(a.DIFFUSEDIRECTUV=0,a.BUMPDIRECTUV=0,a.AMBIENTDIRECTUV=0,a.OPACITYDIRECTUV=0,a.EMISSIVEDIRECTUV=0,a.SPECULARDIRECTUV=0,a.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&n.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())fi(this._diffuseTexture,a,"DIFFUSE");else return!1;else a.DIFFUSE=!1;if(this._ambientTexture&&n.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())fi(this._ambientTexture,a,"AMBIENT");else return!1;else a.AMBIENT=!1;if(this._opacityTexture&&n.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())fi(this._opacityTexture,a,"OPACITY"),a.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else a.OPACITY=!1;if(this._reflectionTexture&&n.ReflectionTextureEnabled?(a.ROUGHNESS=this._roughness>0,a.REFLECTIONOVERALPHA=this._useReflectionOverAlpha):(a.ROUGHNESS=!1,a.REFLECTIONOVERALPHA=!1),!hd(s,this._reflectionTexture,a))return!1;if(this._emissiveTexture&&n.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())fi(this._emissiveTexture,a,"EMISSIVE");else return!1;else a.EMISSIVE=!1;if(this._lightmapTexture&&n.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())fi(this._lightmapTexture,a,"LIGHTMAP"),a.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,a.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else a.LIGHTMAP=!1;if(this._specularTexture&&n.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())fi(this._specularTexture,a,"SPECULAR"),a.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else a.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&n.BumpTextureEnabled){if(this._bumpTexture.isReady())fi(this._bumpTexture,a,"BUMP"),a.PARALLAX=this._useParallax,a.PARALLAX_RHS=s.useRightHandedSystem,a.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;a.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else a.BUMP=!1,a.PARALLAX=!1,a.PARALLAX_RHS=!1,a.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&n.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())a._needUVs=!0,a.REFRACTION=!0,a.REFRACTIONMAP_3D=this._refractionTexture.isCube,a.RGBDREFRACTION=this._refractionTexture.isRGBD,a.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else a.REFRACTION=!1;a.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else a.DIFFUSE=!1,a.AMBIENT=!1,a.OPACITY=!1,a.REFLECTION=!1,a.EMISSIVE=!1,a.LIGHTMAP=!1,a.BUMP=!1,a.REFRACTION=!1;a.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),a.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,a.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,a.SPECULAROVERALPHA=this._useSpecularOverAlpha,a.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,a.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,a.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=a,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a),a.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,a.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}if(a._areFresnelDirty&&(n.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(a.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,a.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,a.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,a.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,a.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,a.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,a._needNormals=!0,a.FRESNEL=!0):a.FRESNEL=!1),a.AREALIGHTUSED||a.CLUSTLIGHT_BATCH){for(let f=0;f<e.lightSources.length;f++)if(!e.lightSources[f]._isReady())return!1}Up(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this.needAlphaTestingForMesh(e),a,this._applyDecalMapAfterDetailMap,this._useVertexPulling,t.getRenderingMesh(),this._isVertexOutputInvariant),kp(s,o,this,a,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=a,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),zp(e,a,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let c=!1;if(a.isDirty){let f=a._areLightsDisposed;a.markAsProcessed();let d=new ds;a.REFLECTION&&d.addFallback(0,"REFLECTION"),a.SPECULAR&&d.addFallback(0,"SPECULAR"),a.BUMP&&d.addFallback(0,"BUMP"),a.PARALLAX&&d.addFallback(1,"PARALLAX"),a.PARALLAX_RHS&&d.addFallback(1,"PARALLAX_RHS"),a.PARALLAXOCCLUSION&&d.addFallback(0,"PARALLAXOCCLUSION"),a.SPECULAROVERALPHA&&d.addFallback(0,"SPECULAROVERALPHA"),a.FOG&&d.addFallback(1,"FOG"),a.POINTSIZE&&d.addFallback(0,"POINTSIZE"),a.LOGARITHMICDEPTH&&d.addFallback(0,"LOGARITHMICDEPTH"),Bp(a,d,this._maxSimultaneousLights),a.SPECULARTERM&&d.addFallback(0,"SPECULARTERM"),a.DIFFUSEFRESNEL&&d.addFallback(1,"DIFFUSEFRESNEL"),a.OPACITYFRESNEL&&d.addFallback(2,"OPACITYFRESNEL"),a.REFLECTIONFRESNEL&&d.addFallback(3,"REFLECTIONFRESNEL"),a.EMISSIVEFRESNEL&&d.addFallback(4,"EMISSIVEFRESNEL"),a.FRESNEL&&d.addFallback(4,"FRESNEL"),a.MULTIVIEW&&d.addFallback(0,"MULTIVIEW");let u=[D.PositionKind];a.NORMAL&&u.push(D.NormalKind),a.TANGENT&&u.push(D.TangentKind);for(let A=1;A<=6;++A)a["UV"+A]&&u.push(`uv${A===1?"":A}`);a.VERTEXCOLOR&&u.push(D.ColorKind),wp(u,e,a,d),Fp(u,a),ih(u,e,a),Op(u,e,a);let h="default",m=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureInfo","morphTargetTextureInfo","morphTargetTextureIndices","cameraInfo"],g=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler","areaLightsLTC1Sampler","areaLightsLTC2Sampler"];md(m,g,!1);let p=["Material","Scene","Mesh"],_={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:a.NUM_MORPH_INFLUENCERS};if(this._eventInfo.fallbacks=d,this._eventInfo.fallbackRank=0,this._eventInfo.defines=a,this._eventInfo.uniforms=m,this._eventInfo.attributes=u,this._eventInfo.samplers=g,this._eventInfo.uniformBuffersNames=p,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(128,this._eventInfo),us.AddUniformsAndSamplers(m,g),fa.AddUniforms(m),fa.AddSamplers(g),Zt&&(Zt.PrepareUniforms(m,a),Zt.PrepareSamplers(g,a)),Yp({uniformsNames:m,uniformBuffersNames:p,samplers:g,defines:a,maxSimultaneousLights:this._maxSimultaneousLights,shaderLanguage:this._shaderLanguage}),ns(m),this._useVertexPulling){let A=t.getRenderingMesh(),R=A==null?void 0:A.geometry;R&&(this._vertexPullingMetadata=Ad(R),this._vertexPullingMetadata&&this._vertexPullingMetadata.forEach((M,I)=>{m.push(`vp_${I}_info`)}))}else this._vertexPullingMetadata=null;let v={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,m,p,g,a,u,v));let E=a.toString(),S=t.effect,T=s.getEngine().createEffect(h,{attributes:u,uniformsNames:m,uniformBuffersNames:p,samplers:g,defines:E,fallbacks:d,onCompiled:this.onCompiled,onError:this.onError,indexParameters:_,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:a.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(T5(),S5)),Promise.resolve().then(()=>(Y5(),X5))]):await Promise.all([Promise.resolve().then(()=>(SY(),EY)),Promise.resolve().then(()=>(ZY(),jY))]),this._shadersLoaded=!0}},o);if(this._eventInfo.customCode=void 0,T)if(this._onEffectCreatedObservable&&(_N.effect=T,_N.subMesh=t,this._onEffectCreatedObservable.notifyObservers(_N)),this.allowShaderHotSwapping&&S&&!T.isReady()){if(a.markAsUnprocessed(),c=this.isFrozen,f)return a._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(T,a,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(a._renderId=s.getRenderId(),r._wasPreviouslyReady=!c,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){let e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),e.addUniform("cameraInfo",4),Kp(e,!1,!0),super.buildUniformLayout()}bindForSubMesh(e,t,i){var f;let r=this.getScene(),s=i.materialDefines;if(!s)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),us.Bind(r.getEngine().currentRenderPassId,this._activeEffect,t,e,this);let o=r.activeCamera;o?this._uniformBuffer.updateFloat4("cameraInfo",o.minZ,o.maxZ,0,0):this._uniformBuffer.updateFloat4("cameraInfo",0,0,0,0),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let l=this._mustRebind(r,a,i,t.visibility);aa(t,a),this._vertexPullingMetadata&&xd(a,this._vertexPullingMetadata);let c=this._uniformBuffer;if(l){if(this.bindViewProjection(a),!c.useUbo||!this.isFrozen||!c.isSync||i._drawWrapper._forceRebindOnNextCall){if(n.FresnelEnabled&&s.FRESNEL){if(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(c.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),c.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled){let d=Gn.Color3[0];d.set(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),c.updateColor4("opacityParts",d,this.opacityFresnelParameters.power)}this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(c.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),c.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(c.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),c.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(c.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),c.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))}if(r.texturesEnabled&&(this._diffuseTexture&&n.DiffuseTextureEnabled&&(c.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),di(this._diffuseTexture,c,"diffuse")),this._ambientTexture&&n.AmbientTextureEnabled&&(c.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),di(this._ambientTexture,c,"ambient")),this._opacityTexture&&n.OpacityTextureEnabled&&(c.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),di(this._opacityTexture,c,"opacity")),this._hasAlphaChannel()&&c.updateFloat("alphaCutOff",this.alphaCutOff),Dp(r,s,c,he.White(),this._reflectionTexture,!1,!1,!0,!1,!1,!1,this.roughness),(!this._reflectionTexture||!n.ReflectionTextureEnabled)&&c.updateFloat2("vReflectionInfos",0,this.roughness),this._emissiveTexture&&n.EmissiveTextureEnabled&&(c.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),di(this._emissiveTexture,c,"emissive")),this._lightmapTexture&&n.LightmapTextureEnabled&&(c.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),di(this._lightmapTexture,c,"lightmap")),this._specularTexture&&n.SpecularTextureEnabled&&(c.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),di(this._specularTexture,c,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&n.BumpTextureEnabled&&(c.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),di(this._bumpTexture,c,"bump"),r._mirroredCameraPosition?c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&n.RefractionTextureEnabled)){let d=1;if(this._refractionTexture.isCube||(c.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(d=this._refractionTexture.depth)),c.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,d,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){let u=this._refractionTexture;c.updateVector3("vRefractionPosition",u.boundingBoxPosition),c.updateVector3("vRefractionSize",u.boundingBoxSize)}}this.pointsCloud&&c.updateFloat("pointSize",this.pointSize),c.updateColor4("vSpecularColor",this.specularColor,this.specularPower),c.updateColor3("vEmissiveColor",n.EmissiveTextureEnabled?this.emissiveColor:he.BlackReadOnly),c.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),c.updateColor3("vAmbientColor",this._globalAmbientColor)}r.texturesEnabled&&(this._diffuseTexture&&n.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&n.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&n.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&n.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&n.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&n.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&n.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&n.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&n.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),ss(a,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(l||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&Np(r,t,a,s,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==ai.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||s.PREPASS||s.CLUSTLIGHT_BATCH)&&this.bindView(a),dd(r,t,a),s.NUM_MORPH_INFLUENCERS&&as(t,a),s.BAKED_VERTEX_ANIMATION_TEXTURE&&((f=t.bakedVertexAnimationManager)==null||f.bind(a,s.INSTANCES)),this.useLogarithmicDepth&&fd(s,a,r),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),c.update()}getAnimatables(){let e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){let e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e)}dispose(e,t){var i,r,s,a,o,l,c,f,d;t&&((i=this._diffuseTexture)==null||i.dispose(),(r=this._ambientTexture)==null||r.dispose(),(s=this._opacityTexture)==null||s.dispose(),(a=this._reflectionTexture)==null||a.dispose(),(o=this._emissiveTexture)==null||o.dispose(),(l=this._specularTexture)==null||l.dispose(),(c=this._bumpTexture)==null||c.dispose(),(f=this._lightmapTexture)==null||f.dispose(),(d=this._refractionTexture)==null||d.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){let r=at.Clone(()=>new n(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){let r=at.Parse(()=>new n(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Ae._ParsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return fe.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){fe.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return fe.DetailTextureEnabled}static set DetailTextureEnabled(e){fe.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return fe.AmbientTextureEnabled}static set AmbientTextureEnabled(e){fe.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return fe.OpacityTextureEnabled}static set OpacityTextureEnabled(e){fe.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return fe.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){fe.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return fe.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){fe.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return fe.SpecularTextureEnabled}static set SpecularTextureEnabled(e){fe.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return fe.BumpTextureEnabled}static set BumpTextureEnabled(e){fe.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return fe.LightmapTextureEnabled}static set LightmapTextureEnabled(e){fe.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return fe.RefractionTextureEnabled}static set RefractionTextureEnabled(e){fe.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return fe.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){fe.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return fe.FresnelEnabled}static set FresnelEnabled(e){fe.FresnelEnabled=e}};We.ForceGLSL=!1;P([Xt("diffuseTexture")],We.prototype,"_diffuseTexture",void 0);P([le("_markAllSubMeshesAsTexturesAndMiscDirty")],We.prototype,"diffuseTexture",void 0);P([Xt("ambientTexture")],We.prototype,"_ambientTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"ambientTexture",void 0);P([Xt("opacityTexture")],We.prototype,"_opacityTexture",void 0);P([le("_markAllSubMeshesAsTexturesAndMiscDirty")],We.prototype,"opacityTexture",void 0);P([Xt("reflectionTexture")],We.prototype,"_reflectionTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"reflectionTexture",void 0);P([Xt("emissiveTexture")],We.prototype,"_emissiveTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"emissiveTexture",void 0);P([Xt("specularTexture")],We.prototype,"_specularTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"specularTexture",void 0);P([Xt("bumpTexture")],We.prototype,"_bumpTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"bumpTexture",void 0);P([Xt("lightmapTexture")],We.prototype,"_lightmapTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"lightmapTexture",void 0);P([Xt("refractionTexture")],We.prototype,"_refractionTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"refractionTexture",void 0);P([yr("ambient")],We.prototype,"ambientColor",void 0);P([yr("diffuse")],We.prototype,"diffuseColor",void 0);P([yr("specular")],We.prototype,"specularColor",void 0);P([yr("emissive")],We.prototype,"emissiveColor",void 0);P([F()],We.prototype,"specularPower",void 0);P([F("useAlphaFromDiffuseTexture")],We.prototype,"_useAlphaFromDiffuseTexture",void 0);P([le("_markAllSubMeshesAsTexturesAndMiscDirty")],We.prototype,"useAlphaFromDiffuseTexture",void 0);P([F("useEmissiveAsIllumination")],We.prototype,"_useEmissiveAsIllumination",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"useEmissiveAsIllumination",void 0);P([F("linkEmissiveWithDiffuse")],We.prototype,"_linkEmissiveWithDiffuse",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"linkEmissiveWithDiffuse",void 0);P([F("useSpecularOverAlpha")],We.prototype,"_useSpecularOverAlpha",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"useSpecularOverAlpha",void 0);P([F("useReflectionOverAlpha")],We.prototype,"_useReflectionOverAlpha",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"useReflectionOverAlpha",void 0);P([F("disableLighting")],We.prototype,"_disableLighting",void 0);P([le("_markAllSubMeshesAsLightsDirty")],We.prototype,"disableLighting",void 0);P([F("useObjectSpaceNormalMap")],We.prototype,"_useObjectSpaceNormalMap",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"useObjectSpaceNormalMap",void 0);P([F("useParallax")],We.prototype,"_useParallax",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"useParallax",void 0);P([F("useParallaxOcclusion")],We.prototype,"_useParallaxOcclusion",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"useParallaxOcclusion",void 0);P([F()],We.prototype,"parallaxScaleBias",void 0);P([F("roughness")],We.prototype,"_roughness",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"roughness",void 0);P([F()],We.prototype,"indexOfRefraction",void 0);P([F()],We.prototype,"invertRefractionY",void 0);P([F()],We.prototype,"alphaCutOff",void 0);P([F("useLightmapAsShadowmap")],We.prototype,"_useLightmapAsShadowmap",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"useLightmapAsShadowmap",void 0);P([hp("diffuseFresnelParameters")],We.prototype,"_diffuseFresnelParameters",void 0);P([le("_markAllSubMeshesAsFresnelDirty")],We.prototype,"diffuseFresnelParameters",void 0);P([hp("opacityFresnelParameters")],We.prototype,"_opacityFresnelParameters",void 0);P([le("_markAllSubMeshesAsFresnelAndMiscDirty")],We.prototype,"opacityFresnelParameters",void 0);P([hp("reflectionFresnelParameters")],We.prototype,"_reflectionFresnelParameters",void 0);P([le("_markAllSubMeshesAsFresnelDirty")],We.prototype,"reflectionFresnelParameters",void 0);P([hp("refractionFresnelParameters")],We.prototype,"_refractionFresnelParameters",void 0);P([le("_markAllSubMeshesAsFresnelDirty")],We.prototype,"refractionFresnelParameters",void 0);P([hp("emissiveFresnelParameters")],We.prototype,"_emissiveFresnelParameters",void 0);P([le("_markAllSubMeshesAsFresnelDirty")],We.prototype,"emissiveFresnelParameters",void 0);P([F("useReflectionFresnelFromSpecular")],We.prototype,"_useReflectionFresnelFromSpecular",void 0);P([le("_markAllSubMeshesAsFresnelDirty")],We.prototype,"useReflectionFresnelFromSpecular",void 0);P([F("useGlossinessFromSpecularMapAlpha")],We.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"useGlossinessFromSpecularMapAlpha",void 0);P([F("maxSimultaneousLights")],We.prototype,"_maxSimultaneousLights",void 0);P([le("_markAllSubMeshesAsLightsDirty")],We.prototype,"maxSimultaneousLights",void 0);P([F("invertNormalMapX")],We.prototype,"_invertNormalMapX",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"invertNormalMapX",void 0);P([F("invertNormalMapY")],We.prototype,"_invertNormalMapY",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"invertNormalMapY",void 0);P([F("twoSidedLighting")],We.prototype,"_twoSidedLighting",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],We.prototype,"twoSidedLighting",void 0);P([F("applyDecalMapAfterDetailMap")],We.prototype,"_applyDecalMapAfterDetailMap",void 0);P([le("_markAllSubMeshesAsMiscDirty")],We.prototype,"applyDecalMapAfterDetailMap",void 0);zt("BABYLON.StandardMaterial",We);ai.DefaultMaterialFactory=n=>new We("default material",n)});var qY=y(()=>{Bo();Is();ea();Pt.prototype.createDynamicTexture=function(n,e,t,i){let r=new Xi(this,4);return r.baseWidth=n,r.baseHeight=e,t&&(n=this.needPOTTextures?Un(n,this._caps.maxTextureSize):n,e=this.needPOTTextures?Un(e,this._caps.maxTextureSize):e),r.width=n,r.height=e,r.isReady=!1,r.generateMipMaps=t,r.samplingMode=i,this.updateTextureSamplingMode(i,r),this._internalTexturesCache.push(r),r};Pt.prototype.updateDynamicTexture=function(n,e,t,i=!1,r,s=!1,a=!1){if(!n)return;let o=this._gl,l=o.TEXTURE_2D,c=this._bindTextureDirectly(l,n,!0,s);this._unpackFlipY(t===void 0?n.invertY:t),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);let f=this._getWebGLTextureType(n.type),d=this._getInternalFormat(r||n.format),u=this._getRGBABufferInternalSizedFormat(n.type,d);o.texImage2D(l,0,u,d,f,e),n.generateMipMaps&&o.generateMipmap(l),c||this._bindTextureDirectly(l,null),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),r&&(n.format=r),n._dynamicTextureSource=e,n._premulAlpha=i,n.invertY=t||!1,n.isReady=!0}});var EE,QY=y(()=>{wt();Kr();qY();EE=class n extends _e{constructor(e,t,i,r=!1,s=3,a=5,o){let l=!i||i._isScene,c=l?i:i==null?void 0:i.scene,f=l?!r:i;super(null,c,f,o,s,void 0,void 0,void 0,void 0,a),this.name=e,this.wrapU=_e.CLAMP_ADDRESSMODE,this.wrapV=_e.CLAMP_ADDRESSMODE,this._generateMipMaps=r;let d=this._getEngine();if(!d)return;if(t.getContext)this._canvas=t,this._ownCanvas=!1,this._texture=d.createDynamicTexture(this._canvas.width,this._canvas.height,r,s);else{this._canvas=d.createCanvas(1,1),this._ownCanvas=!0;let h=t;h.width||h.width===0?this._texture=d.createDynamicTexture(h.width,h.height,r,s):this._texture=d.createDynamicTexture(t,t,r,s)}let u=this.getSize();this._canvas.width!==u.width&&(this._canvas.width=u.width),this._canvas.height!==u.height&&(this._canvas.height=u.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){let t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){let i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){let t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._texture&&this._getEngine().updateDynamicTexture(this._texture,this._canvas,e===void 0?!0:e,t,this._format||void 0,void 0,i)}drawText(e,t,i,r,s,a,o,l=!0){let c=this.getSize();if(a&&(this._context.fillStyle=a,this._context.fillRect(0,0,c.width,c.height)),this._context.font=r,t==null){let f=this._context.measureText(e);t=(c.width-f.width)/2}if(i==null){let f=parseInt(r.replace(/\D/g,""));i=c.height/2+f/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),l&&this.update(o)}dispose(){var e,t;super.dispose(),this._ownCanvas&&((t=(e=this._canvas)==null?void 0:e.remove)==null||t.call(e)),this._canvas=null,this._context=null}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new n(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){let e=this.getScene();e&&!e.isReady()&&te.Warn("The scene must be ready before serializing the dynamic texture");let t=super.serialize();return n._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return e.toDataURL!==void 0}_rebuild(){this.update()}}});function PM(n,e,t,i,r,s=!1){let a=on.Zero();return SE(n,e,t,i,a,r,s),a}function SE(n,e,t,i,r,s,a=!1,o=!1){let l=n.getEngine();if(!s&&!(s=n.activeCamera)&&!(s=n.cameraToUseForPointers))return n;let c=s.viewport,f=l.getRenderHeight(),{x:d,y:u,width:h,height:m}=c.toGlobal(l.getRenderWidth(),f),g=1/l.getHardwareScalingLevel();return e=e*g-d,t=t*g-(f-u-m),r.update(e,t,h,m,i||Q.IdentityReadOnly,a?Q.IdentityReadOnly:s.getViewMatrix(),s.getProjectionMatrix(),o),n}function e8(n,e,t,i){let r=on.Zero();return TN(n,e,t,r,i),r}function TN(n,e,t,i,r){if(!Ls)return n;let s=n.getEngine();if(!r&&!(r=n.activeCamera)&&!(r=n.cameraToUseForPointers))throw new Error("Active camera not set");let a=r.viewport,o=s.getRenderHeight(),{x:l,y:c,width:f,height:d}=a.toGlobal(s.getRenderWidth(),o),u=Q.Identity(),h=1/s.getHardwareScalingLevel();return e=e*h-l,t=t*h-(o-c-d),i.update(e,t,f,d,u,u,r.getProjectionMatrix()),n}function CM(n,e,t,i,r,s,a,o){let l=e(i,t.enableDistantPicking);return AN(n,t,i,l,r,s,a,o)}function AN(n,e,t,i,r,s,a,o){let l=e.intersects(i,r,a,s,t,o);return!l||!l.hit||!r&&n!=null&&l.distance>=n.distance?null:l}function $pe(n,e){return n==="InstancedLinesMesh"||n==="LinesMesh"?e.intersectionThreshold:0}function t8(n){let e=n.getClassName();if(e==="GreasedLineMesh")return{rawBoundingInfo:null,intersectionThreshold:0};let t=n.rawBoundingInfo;return{rawBoundingInfo:t,intersectionThreshold:t?$pe(e,n):0}}function i8(n,e,t,i,r){let s=n(t,e.enableDistantPicking);return!s.intersectsSphere(i.boundingSphere,r)||!s.intersectsBox(i.boundingBox,r)?null:s}function xN(n,e,t,i,r,s){let a=null,o=!!(n.activeCameras&&n.activeCameras.length>1&&n.cameraToUseForPointers!==n.activeCamera),l=n.cameraToUseForPointers||n.activeCamera,c=JY.internalPickerForMesh||CM,f=c===CM;for(let d=0;d<n.meshes.length;d++){let u=n.meshes[d];if(t){if(!t(u,-1))continue}else if(!u.isEnabled()||!u.isVisible||!u.isPickable)continue;let h=o&&u.isWorldMatrixCameraDependent(),m=u.computeWorldMatrix(h,l);if(u.hasThinInstances&&u.thinInstanceEnablePicking){let g=c(a,e,u,m,!0,!0,s);if(g){if(r)return g;let{rawBoundingInfo:p,intersectionThreshold:_}=t8(u),v=u._thinInstanceDataStorage.matrixData;if(v){let E=ee.Matrix[0],S=ee.Matrix[1],T=Math.min(u.thinInstanceCount,v.length>>4);for(let A=0;A<T;A++){if(t&&!t(u,A))continue;Q.FromArrayToRef(v,A<<4,E),E.multiplyToRef(m,S);let R=f&&p?i8(e,u,S,p,_):null;if(f&&p&&!R)continue;let M=f&&R?AN(a,u,S,R,i,r,s,!0):c(a,e,u,S,i,r,s,!0);if(M&&(a=M,a.thinInstanceIndex=A,i))return a}}}}else{let g=c(a,e,u,m,i,r,s);if(g&&(a=g,i))return a}}return a||new Ls}function r8(n,e,t,i){if(!Ls)return null;let r=[],s=!!(n.activeCameras&&n.activeCameras.length>1&&n.cameraToUseForPointers!==n.activeCamera),a=n.cameraToUseForPointers||n.activeCamera,o=JY.internalPickerForMesh||CM,l=o===CM;for(let c=0;c<n.meshes.length;c++){let f=n.meshes[c];if(t){if(!t(f,-1))continue}else if(!f.isEnabled()||!f.isVisible||!f.isPickable)continue;let d=s&&f.isWorldMatrixCameraDependent(),u=f.computeWorldMatrix(d,a);if(f.hasThinInstances&&f.thinInstanceEnablePicking){if(o(null,e,f,u,!0,!0,i)){let{rawBoundingInfo:m,intersectionThreshold:g}=t8(f),p=f._thinInstanceDataStorage.matrixData;if(p){let _=ee.Matrix[0],v=ee.Matrix[1],E=Math.min(f.thinInstanceCount,p.length>>4);for(let S=0;S<E;S++){if(t&&!t(f,S))continue;Q.FromArrayToRef(p,S<<4,_),_.multiplyToRef(u,v);let T=l&&m?i8(e,f,v,m,g):null;if(l&&m&&!T)continue;let A=l&&T?AN(null,f,v,T,!1,!1,i,!0):o(null,e,f,v,!1,!1,i,!0);A&&(A.thinInstanceIndex=S,r.push(A))}}}}else{let h=o(null,e,f,u,!1,!1,i);h&&r.push(h)}}return r}function n8(n,e,t,i,r,s){if(!Ls)return null;let a=xN(n,o=>(n._tempPickingRay||(n._tempPickingRay=on.Zero()),SE(n,e,t,o,n._tempPickingRay,s||null),n._tempPickingRay),i,r,!0);return a&&(a.ray=PM(n,e,t,Q.Identity(),s||null)),a}function s8(n,e,t,i,r,s,a,o=!1){let l=xN(n,(c,f)=>(n._tempPickingRay||(n._tempPickingRay=on.Zero()),SE(n,e,t,c,n._tempPickingRay,s||null,!1,f),n._tempPickingRay),i,r,!1,a);return l&&(l.ray=PM(n,e,t,Q.Identity(),s||null)),l}function a8(n,e,t,i,r){let s=xN(n,a=>(n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=Q.Identity()),a.invertToRef(n._pickWithRayInverseMatrix),n._cachedRayForTransform||(n._cachedRayForTransform=on.Zero()),on.TransformToRef(e,n._pickWithRayInverseMatrix,n._cachedRayForTransform),n._cachedRayForTransform),t,i,!1,r);return s&&(s.ray=e),s}function o8(n,e,t,i,r,s){return r8(n,a=>PM(n,e,t,a,r||null),i,s)}function l8(n,e,t,i){return r8(n,r=>(n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=Q.Identity()),r.invertToRef(n._pickWithRayInverseMatrix),n._cachedRayForTransform||(n._cachedRayForTransform=on.Zero()),on.TransformToRef(e,n._pickWithRayInverseMatrix,n._cachedRayForTransform),n._cachedRayForTransform),t,i)}function $Y(n,e,t=100,i,r){i||(i=n.getWorldMatrix()),e.length=t,r?e.origin.copyFrom(r):e.origin.copyFrom(n.position);let s=ee.Vector3[2];s.set(0,0,n._scene.useRightHandedSystem?-1:1);let a=ee.Vector3[3];return b.TransformNormalToRef(s,i,a),b.NormalizeToRef(a,e.direction),e}function c8(n,e){e&&(e.prototype.getForwardRay=function(t=100,i,r){return $Y(this,new on(b.Zero(),b.Zero(),t),t,i,r)},e.prototype.getForwardRayToRef=function(t,i=100,r,s){return $Y(this,t,i,r,s)}),n&&($u._IsPickingAvailable=!0,n.prototype.createPickingRay=function(t,i,r,s,a=!1){return PM(this,t,i,r,s,a)})}var JY,on,RN=y(()=>{es();He();Ol();YD();Ov();Yi();JL();JY={internalPickerForMesh:void 0},on=class n{constructor(e,t,i=Number.MAX_VALUE,r=Vt){this.origin=e,this.direction=t,this.length=i,this.epsilon=r}clone(){return new n(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){let r=n._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),s=n._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i),a=0,o=Number.MAX_VALUE,l,c,f,d;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<r.x||this.origin.x>s.x)return!1}else if(l=1/this.direction.x,c=(r.x-this.origin.x)*l,f=(s.x-this.origin.x)*l,f===-1/0&&(f=1/0),c>f&&(d=c,c=f,f=d),a=Math.max(c,a),o=Math.min(f,o),a>o)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<r.y||this.origin.y>s.y)return!1}else if(l=1/this.direction.y,c=(r.y-this.origin.y)*l,f=(s.y-this.origin.y)*l,f===-1/0&&(f=1/0),c>f&&(d=c,c=f,f=d),a=Math.max(c,a),o=Math.min(f,o),a>o)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<r.z||this.origin.z>s.z)return!1}else if(l=1/this.direction.z,c=(r.z-this.origin.z)*l,f=(s.z-this.origin.z)*l,f===-1/0&&(f=1/0),c>f&&(d=c,c=f,f=d),a=Math.max(c,a),o=Math.min(f,o),a>o)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){let i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,s=e.center.z-this.origin.z,a=i*i+r*r+s*s,o=e.radius+t,l=o*o;if(a<=l)return!0;let c=i*this.direction.x+r*this.direction.y+s*this.direction.z;return c<0?!1:a-c*c<=l}intersectsTriangle(e,t,i){let r=n._TmpVector3[0],s=n._TmpVector3[1],a=n._TmpVector3[2],o=n._TmpVector3[3],l=n._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,s),b.CrossToRef(this.direction,s,a);let c=b.Dot(r,a);if(c===0)return null;let f=1/c;this.origin.subtractToRef(e,o);let d=b.Dot(o,a)*f;if(d<-this.epsilon||d>1+this.epsilon)return null;b.CrossToRef(o,r,l);let u=b.Dot(this.direction,l)*f;if(u<-this.epsilon||d+u>1+this.epsilon)return null;let h=b.Dot(s,l)*f;return h>this.length||h<0?null:new eh(1-d-u,d,h)}intersectsPlane(e){let t,i=b.Dot(e.normal,this.direction);if(Math.abs(i)<999999997475243e-21)return null;{let r=b.Dot(e.normal,this.origin);return t=(-e.d-r)/i,t<0?t<-999999997475243e-21?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{let i=(this.origin.y-t)/this.direction.y;return i>0?null:new b(this.origin.x+this.direction.x*-i,t,this.origin.z+this.direction.z*-i)}case"x":{let i=(this.origin.x-t)/this.direction.x;return i>0?null:new b(t,this.origin.y+this.direction.y*-i,this.origin.z+this.direction.z*-i)}case"z":{let i=(this.origin.z-t)/this.direction.z;return i>0?null:new b(this.origin.x+this.direction.x*-i,this.origin.y+this.direction.y*-i,t)}default:return null}}intersectsMesh(e,t,i,r=!1,s,a=!1){let o=ee.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?n.TransformToRef(this,o,this._tmpRay):this._tmpRay=n.Transform(this,o),e.intersects(this._tmpRay,t,i,r,s,a)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;r<e.length;r++){let s=this.intersectsMesh(e[r],t);s.hit&&i.push(s)}return i.sort(this._comparePickingInfo),i}_comparePickingInfo(e,t){return e.distance<t.distance?-1:e.distance>t.distance?1:0}intersectionSegment(e,t,i){let r=this.origin,s=ee.Vector3[0],a=ee.Vector3[1],o=ee.Vector3[2],l=ee.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(n._Rayl,o),r.addToRef(o,a),e.subtractToRef(r,l);let c=b.Dot(s,s),f=b.Dot(s,o),d=b.Dot(o,o),u=b.Dot(s,l),h=b.Dot(o,l),m=c*d-f*f,g,p=m,_,v=m;m<n._Smallnum?(g=0,p=1,_=h,v=d):(g=f*h-d*u,_=c*h-f*u,g<0?(g=0,_=h,v=d):g>p&&(g=p,_=h+f,v=d)),_<0?(_=0,-u<0?g=0:-u>c?g=p:(g=-u,p=c)):_>v&&(_=v,-u+f<0?g=0:-u+f>c?g=p:(g=-u+f,p=c));let E=Math.abs(g)<n._Smallnum?0:g/p,S=Math.abs(_)<n._Smallnum?0:_/v,T=ee.Vector3[4];o.scaleToRef(S,T);let A=ee.Vector3[5];s.scaleToRef(E,A),A.addInPlace(l);let R=ee.Vector3[6];return A.subtractToRef(T,R),S>0&&S<=this.length&&R.lengthSquared()<i*i?A.length():-1}update(e,t,i,r,s,a,o,l=!1){if(l){n._RayDistant||(n._RayDistant=n.Zero()),n._RayDistant.unprojectRayToRef(e,t,i,r,Q.IdentityReadOnly,a,o);let c=ee.Matrix[0];s.invertToRef(c),n.TransformToRef(n._RayDistant,c,this)}else this.unprojectRayToRef(e,t,i,r,s,a,o);return this}static Zero(){return new n(b.Zero(),b.Zero())}static CreateNew(e,t,i,r,s,a,o){return n.Zero().update(e,t,i,r,s,a,o)}static CreateNewFromTo(e,t,i=Q.IdentityReadOnly){let r=new n(new b(0,0,0),new b(0,0,0));return n.CreateFromToToRef(e,t,r,i)}static CreateFromToToRef(e,t,i,r=Q.IdentityReadOnly){i.origin.copyFrom(e);let s=t.subtractToRef(e,i.direction),a=Math.sqrt(s.x*s.x+s.y*s.y+s.z*s.z);return i.length=a,i.direction.normalize(),n.TransformToRef(i,r,i)}static Transform(e,t){let i=new n(new b(0,0,0),new b(0,0,0));return n.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){b.TransformCoordinatesToRef(e.origin,t,i.origin),b.TransformNormalToRef(e.direction,t,i.direction),i.length=e.length,i.epsilon=e.epsilon;let r=i.direction,s=r.length();if(!(s===0||s===1)){let a=1/s;r.x*=a,r.y*=a,r.z*=a,i.length*=s}return i}unprojectRayToRef(e,t,i,r,s,a,o){let l=ee.Matrix[0];s.multiplyToRef(a,l),l.multiplyToRef(o,l),l.invert();let c=Oe.LastCreatedEngine,f=ee.Vector3[0];f.x=e/i*2-1,f.y=-(t/r*2-1),f.z=c!=null&&c.useReverseDepthBuffer?1:c!=null&&c.isNDCHalfZRange?0:-1;let d=ee.Vector3[1].copyFromFloats(f.x,f.y,1-1e-8),u=ee.Vector3[2],h=ee.Vector3[3];b.TransformCoordinatesToRef(f,l,u),b.TransformCoordinatesToRef(d,l,h),this.origin.copyFrom(u),h.subtractToRef(u,this.direction),this.direction.normalize()}};on._TmpVector3=yn(6,b.Zero);on._RayDistant=on.Zero();on._Smallnum=1e-8;on._Rayl=1e9});var bN=y(()=>{na();zl();RN();RN();c8(ai,Et);ai.prototype.createPickingRayToRef=function(n,e,t,i,r,s=!1,a=!1){return SE(this,n,e,t,i,r,s,a)};ai.prototype.createPickingRayInCameraSpace=function(n,e,t){return e8(this,n,e,t)};ai.prototype.createPickingRayInCameraSpaceToRef=function(n,e,t,i){return TN(this,n,e,t,i)};ai.prototype.pickWithBoundingInfo=function(n,e,t,i,r){return n8(this,n,e,t,i,r)};ai.prototype.pick=function(n,e,t,i,r,s,a=!1){return s8(this,n,e,t,i,r,s,a)};ai.prototype.pickWithRay=function(n,e,t,i){return a8(this,n,e,t,i)};ai.prototype.multiPick=function(n,e,t,i,r){return o8(this,n,e,t,i,r)};ai.prototype.multiPickWithRay=function(n,e,t){return l8(this,n,e,t)}});var f8,Jpe,MN=y(()=>{k();f8="kernelBlurVaryingDeclaration",Jpe="varying sampleCoord{X}: vec2f;";x.IncludesShadersStoreWGSL[f8]||(x.IncludesShadersStoreWGSL[f8]=Jpe)});var d8,ege,LM=y(()=>{k();d8="packingFunctions",ege=`fn pack(depth: f32)->vec4f
{const bit_shift: vec4f= vec4f(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const bit_mask: vec4f= vec4f(0.0,1.0/255.0,1.0/255.0,1.0/255.0);var res: vec4f=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}
fn unpack(color: vec4f)->f32
{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;x.IncludesShadersStoreWGSL[d8]||(x.IncludesShadersStoreWGSL[d8]=ege)});var u8,tge,h8=y(()=>{k();u8="kernelBlurFragment",tge=`#ifdef DOF
factor=sampleCoC(fragmentInputs.sampleCoord{X});
computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X}))*computedWeight;
#else
blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X})*computedWeight;
#endif
`;x.IncludesShadersStoreWGSL[u8]||(x.IncludesShadersStoreWGSL[u8]=tge)});var m8,ige,p8=y(()=>{k();m8="kernelBlurFragment2",ige=`#ifdef DOF
factor=sampleCoC(fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_DEP_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X}))*computedWeight;
#else
blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X})*computedWeight;
#endif
`;x.IncludesShadersStoreWGSL[m8]||(x.IncludesShadersStoreWGSL[m8]=ige)});var _8={};Be(_8,{kernelBlurPixelShaderWGSL:()=>rge});var yN,g8,rge,v8=y(()=>{k();MN();LM();h8();p8();yN="kernelBlurPixelShader",g8=`var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform delta: vec2f;varying sampleCenter: vec2f;
#ifdef DOF
var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d<f32>;fn sampleCoC(offset: vec2f)->f32 {var coc: f32=textureSample(circleOfConfusionSampler,circleOfConfusionSamplerSampler,offset).r;return coc; }
#endif
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
#ifdef PACKEDFLOAT
#include<packingFunctions>
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var computedWeight: f32=0.0;
#ifdef PACKEDFLOAT
var blend: f32=0.;
#else
var blend: vec4f= vec4f(0.);
#endif
#ifdef DOF
var sumOfWeights: f32=CENTER_WEIGHT;
var factor: f32=0.0;
#ifdef PACKEDFLOAT
blend+=unpack(textureSample(textureSampler,textureSamplerSampler,input.sampleCenter))*CENTER_WEIGHT;
#else
blend+=textureSample(textureSampler,textureSamplerSampler,input.sampleCenter)*CENTER_WEIGHT;
#endif
#endif
#include<kernelBlurFragment>[0..varyingCount]
#include<kernelBlurFragment2>[0..depCount]
#ifdef PACKEDFLOAT
fragmentOutputs.color=pack(blend);
#else
fragmentOutputs.color=blend;
#endif
#ifdef DOF
fragmentOutputs.color/=sumOfWeights;
#endif
}`;x.ShadersStoreWGSL[yN]||(x.ShadersStoreWGSL[yN]=g8);rge={name:yN,shader:g8}});var E8,nge,S8=y(()=>{k();E8="kernelBlurVertex",nge="vertexOutputs.sampleCoord{X}=vertexOutputs.sampleCenter+uniforms.delta*KERNEL_OFFSET{X};";x.IncludesShadersStoreWGSL[E8]||(x.IncludesShadersStoreWGSL[E8]=nge)});var A8={};Be(A8,{kernelBlurVertexShaderWGSL:()=>sge});var IN,T8,sge,x8=y(()=>{k();MN();S8();IN="kernelBlurVertexShader",T8=`attribute position: vec2f;uniform delta: vec2f;varying sampleCenter: vec2f;
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5);
#define CUSTOM_VERTEX_MAIN_BEGIN
vertexOutputs.sampleCenter=(vertexInputs.position*madd+madd);
#include<kernelBlurVertex>[0..varyingCount]
vertexOutputs.position= vec4f(vertexInputs.position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;x.ShadersStoreWGSL[IN]||(x.ShadersStoreWGSL[IN]=T8);sge={name:IN,shader:T8}});var R8,age,CN=y(()=>{k();R8="kernelBlurVaryingDeclaration",age="varying vec2 sampleCoord{X};";x.IncludesShadersStore[R8]||(x.IncludesShadersStore[R8]=age)});var b8,oge,DM=y(()=>{k();b8="packingFunctions",oge=`vec4 pack(float depth)
{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}
float unpack(vec4 color)
{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;x.IncludesShadersStore[b8]||(x.IncludesShadersStore[b8]=oge)});var M8,lge,y8=y(()=>{k();M8="kernelBlurFragment",lge=`#ifdef DOF
factor=sampleCoC(sampleCoord{X});
computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;
#else
blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;
#endif
`;x.IncludesShadersStore[M8]||(x.IncludesShadersStore[M8]=lge)});var I8,cge,C8=y(()=>{k();I8="kernelBlurFragment2",cge=`#ifdef DOF
factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_DEP_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;
#else
blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;
#endif
`;x.IncludesShadersStore[I8]||(x.IncludesShadersStore[I8]=cge)});var L8={};Be(L8,{kernelBlurPixelShader:()=>fge});var PN,P8,fge,D8=y(()=>{k();CN();DM();y8();C8();PN="kernelBlurPixelShader",P8=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;
#ifdef DOF
uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }
#endif
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
#ifdef PACKEDFLOAT
#include<packingFunctions>
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{float computedWeight=0.0;
#ifdef PACKEDFLOAT
float blend=0.;
#else
vec4 blend=vec4(0.);
#endif
#ifdef DOF
float sumOfWeights=CENTER_WEIGHT;
float factor=0.0;
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;
#else
blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;
#endif
#endif
#include<kernelBlurFragment>[0..varyingCount]
#include<kernelBlurFragment2>[0..depCount]
#ifdef PACKEDFLOAT
gl_FragColor=pack(blend);
#else
gl_FragColor=blend;
#endif
#ifdef DOF
gl_FragColor/=sumOfWeights;
#endif
}`;x.ShadersStore[PN]||(x.ShadersStore[PN]=P8);fge={name:PN,shader:P8}});var O8,dge,N8=y(()=>{k();O8="kernelBlurVertex",dge="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";x.IncludesShadersStore[O8]||(x.IncludesShadersStore[O8]=dge)});var F8={};Be(F8,{kernelBlurVertexShader:()=>uge});var LN,w8,uge,B8=y(()=>{k();CN();N8();LN="kernelBlurVertexShader",w8=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
sampleCenter=(position*madd+madd);
#include<kernelBlurVertex>[0..varyingCount]
gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;x.ShadersStore[LN]||(x.ShadersStore[LN]=w8);uge={name:LN,shader:w8}});var Os,DN=y(()=>{Ku();Yi();Os=class n extends sn{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(()=>(v8(),_8)),Promise.resolve().then(()=>(x8(),A8))]))):t.push(Promise.all([Promise.resolve().then(()=>(D8(),L8)),Promise.resolve().then(()=>(B8(),F8))]))}constructor(e,t=null,i,r,s){let a=!!(s!=null&&s.blockCompilation);super({...s,name:e,engine:t||Oe.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,uniforms:n.Uniforms,samplers:n.Samplers,vertexUrl:n.VertexUrl,blockCompilation:!0}),this._packedFloat=!1,this._staticDefines="",this.textureWidth=0,this.textureHeight=0,this._staticDefines=s?Array.isArray(s.defines)?s.defines.join(`
`):s.defines||"":"",this.options.blockCompilation=a,i!==void 0&&(this.direction=i),r!==void 0&&(this.kernel=r)}set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.options.blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this.options.blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}bind(e=!1){super.bind(e),this._drawWrapper.effect.setFloat2("delta",1/this.textureWidth*this.direction.x,1/this.textureHeight*this.direction.y)}_updateParameters(e,t){let i=this._kernel,r=(i-1)/2,s=[],a=[],o=0;for(let p=0;p<i;p++){let _=p/(i-1),v=this._gaussianWeight(_*2-1);s[p]=p-r,a[p]=v,o+=v}for(let p=0;p<a.length;p++)a[p]/=o;let l=[],c=[],f=[];for(let p=0;p<=r;p+=2){let _=Math.min(p+1,Math.floor(r));if(p===_)f.push({o:s[p],w:a[p]});else{let E=_===r,S=a[p]+a[_]*(E?.5:1),T=s[p]+1/(1+a[p]/a[_]);T===0?(f.push({o:s[p],w:a[p]}),f.push({o:s[p+1],w:a[p+1]})):(f.push({o:T,w:S}),f.push({o:-T,w:S}))}}for(let p=0;p<f.length;p++)c[p]=f[p].o,l[p]=f[p].w;s=c,a=l;let d=this.options.engine.getCaps().maxVaryingVectors-(this.options.shaderLanguage===1?1:0),u=Math.max(d,0)-1,h=Math.min(s.length,u),m="";m+=this._staticDefines,this._staticDefines.indexOf("DOF")!=-1&&(m+=`#define CENTER_WEIGHT ${this._glslFloat(a[h-1])}
`,h--);for(let p=0;p<h;p++)m+=`#define KERNEL_OFFSET${p} ${this._glslFloat(s[p])}
`,m+=`#define KERNEL_WEIGHT${p} ${this._glslFloat(a[p])}
`;let g=0;for(let p=u;p<s.length;p++)m+=`#define KERNEL_DEP_OFFSET${g} ${this._glslFloat(s[p])}
`,m+=`#define KERNEL_DEP_WEIGHT${g} ${this._glslFloat(a[p])}
`,g++;this.packedFloat&&(m+="#define PACKEDFLOAT 1"),this.options.blockCompilation=!1,this.updateEffect(m,null,null,{varyingCount:h,depCount:g},e,t)}_nearestBestKernel(e){let t=Math.round(e);for(let i of[t,t-1,t+1,t-2,t+2])if(i%2!==0&&Math.floor(i/2)%2===0&&i>0)return Math.max(i,3);return Math.max(t,3)}_gaussianWeight(e){let t=.3333333333333333,i=Math.sqrt(2*Math.PI)*t,r=-(e*e/(2*t*t));return 1/i*Math.exp(r)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}};Os.VertexUrl="kernelBlur";Os.FragmentUrl="kernelBlur";Os.Uniforms=["delta","direction"];Os.Samplers=["circleOfConfusionSampler"]});var mo,ON=y(()=>{jt();Oc();Kr();ir();Yt();Or();DN();mo=class n extends Ni{get direction(){return this._effectWrapper.direction}set direction(e){this._effectWrapper.direction=e}set kernel(e){this._effectWrapper.kernel=e}get kernel(){return this._effectWrapper.kernel}set packedFloat(e){this._effectWrapper.packedFloat=e}get packedFloat(){return this._effectWrapper.packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,r,s=null,a=_e.BILINEAR_SAMPLINGMODE,o,l,c=0,f="",d=!1,u=5){let h=typeof r=="number"?d:!!r.blockCompilation,m={uniforms:Os.Uniforms,samplers:Os.Samplers,size:typeof r=="number"?r:void 0,camera:s,samplingMode:a,engine:o,reusable:l,textureType:c,vertexUrl:Os.VertexUrl,indexParameters:{varyingCount:0,depCount:0},textureFormat:u,defines:f,...r,blockCompilation:!0};super(e,Os.FragmentUrl,{effectWrapper:typeof r=="number"||!r.effectWrapper?new Os(e,o,void 0,void 0,m):void 0,...m}),this._effectWrapper.options.blockCompilation=h,this.direction=t,this.onApplyObservable.add(()=>{this._effectWrapper.textureWidth=this._outputTexture?this._outputTexture.width:this.width,this._effectWrapper.textureHeight=this._outputTexture?this._outputTexture.height:this.height}),this.kernel=i}updateEffect(e=null,t=null,i=null,r,s,a){this._effectWrapper._updateParameters(s,a)}static _Parse(e,t,i,r){return at.Parse(()=>new n(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,r)}};P([mp()],mo.prototype,"direction",null);P([F()],mo.prototype,"kernel",null);P([F()],mo.prototype,"packedFloat",null);zt("BABYLON.BlurPostProcess",mo)});var U8,hge,V8=y(()=>{k();U8="bayerDitherFunctions",hge=`fn bayerDither2(_P: vec2f)->f32 {return ((2.0*_P.y+_P.x+1.0)%(4.0));}
fn bayerDither4(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0));
var P2: vec2f=floor(0.5*((_P)%(4.0)));
return 4.0*bayerDither2(P1)+bayerDither2(P2);}
fn bayerDither8(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0));
var P2: vec2f=floor(0.5 *((_P)%(4.0)));
var P4: vec2f=floor(0.25*((_P)%(8.0)));
return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}
`;x.IncludesShadersStoreWGSL[U8]||(x.IncludesShadersStoreWGSL[U8]=hge)});var G8,mge,k8=y(()=>{k();LM();V8();G8="shadowMapFragmentExtraDeclaration",mge=`#if SM_FLOAT==0
#include<packingFunctions>
#endif
#if SM_SOFTTRANSPARENTSHADOW==1
#include<bayerDitherFunctions>
uniform softTransparentShadowSM: vec2f;
#endif
varying vDepthMetricSM: f32;
#if SM_USEDISTANCE==1
uniform lightDataSM: vec3f;varying vPositionWSM: vec3f;
#endif
uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying zSM: f32;
#endif
`;x.IncludesShadersStoreWGSL[G8]||(x.IncludesShadersStoreWGSL[G8]=mge)});var z8,pge,W8=y(()=>{k();z8="shadowMapFragment",pge=`var depthSM: f32=fragmentInputs.vDepthMetricSM;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
#if SM_USEDISTANCE==1
depthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
depthSM=(-fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#else
depthSM=(fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#endif
#endif
depthSM=clamp(depthSM,0.0,1.0);
#ifdef USE_REVERSE_DEPTHBUFFER
fragmentOutputs.fragDepth=clamp(1.0-depthSM,0.0,1.0);
#else
fragmentOutputs.fragDepth=clamp(depthSM,0.0,1.0);
#endif
#elif SM_USEDISTANCE==1
depthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#endif
#if SM_ESM==1
depthSM=clamp(exp(-min(87.,uniforms.biasAndScaleSM.z*depthSM)),0.,1.);
#endif
#if SM_FLOAT==1
fragmentOutputs.color= vec4f(depthSM,1.0,1.0,1.0);
#else
fragmentOutputs.color=pack(depthSM);
#endif
`;x.IncludesShadersStoreWGSL[z8]||(x.IncludesShadersStoreWGSL[z8]=pge)});var X8={};Be(X8,{shadowMapPixelShaderWGSL:()=>gge});var NN,H8,gge,Y8=y(()=>{k();k8();qc();Qc();W8();NN="shadowMapPixelShader",H8=`#include<shadowMapFragmentExtraDeclaration>
#ifdef ALPHATEXTURE
varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d<f32>;
#endif
#include<clipPlaneFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#include<clipPlaneFragment>
#ifdef ALPHATEXTURE
var opacityMap: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUV);var alphaFromAlphaTexture: f32=opacityMap.a;
#if SM_SOFTTRANSPARENTSHADOW==1
if (uniforms.softTransparentShadowSM.y==1.0) {opacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;}
#endif
#ifdef ALPHATESTVALUE
if (alphaFromAlphaTexture<ALPHATESTVALUE) {discard;}
#endif
#endif
#if SM_SOFTTRANSPARENTSHADOW==1
#ifdef ALPHATEXTURE
if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x*alphaFromAlphaTexture) {discard;}
#else
if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x) {discard;}
#endif
#endif
#include<shadowMapFragment>
}`;x.ShadersStoreWGSL[NN]||(x.ShadersStoreWGSL[NN]=H8);gge={name:NN,shader:H8}});var K8,_ge,j8=y(()=>{k();K8="shadowMapVertexExtraDeclaration",_ge=`#if SM_NORMALBIAS==1
uniform lightDataSM: vec3f;
#endif
uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;varying vDepthMetricSM: f32;
#if SM_USEDISTANCE==1
varying vPositionWSM: vec3f;
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying zSM: f32;
#endif
`;x.IncludesShadersStoreWGSL[K8]||(x.IncludesShadersStoreWGSL[K8]=_ge)});var Z8,vge,q8=y(()=>{k();Z8="shadowMapVertexNormalBias",vge=`#if SM_NORMALBIAS==1
#if SM_DIRECTIONINLIGHTDATA==1
var worldLightDirSM: vec3f=normalize(-uniforms.lightDataSM.xyz);
#else
var directionToLightSM: vec3f=uniforms.lightDataSM.xyz-worldPos.xyz;var worldLightDirSM: vec3f=normalize(directionToLightSM);
#endif
var ndlSM: f32=dot(vNormalW,worldLightDirSM);var sinNLSM: f32=sqrt(1.0-ndlSM*ndlSM);var normalBiasSM: f32=uniforms.biasAndScaleSM.y*sinNLSM;worldPos=vec4f(worldPos.xyz-vNormalW*normalBiasSM,worldPos.w);
#endif
`;x.IncludesShadersStoreWGSL[Z8]||(x.IncludesShadersStoreWGSL[Z8]=vge)});var Q8,Ege,$8=y(()=>{k();Q8="shadowMapVertexMetric",Ege=`#if SM_USEDISTANCE==1
vertexOutputs.vPositionWSM=worldPos.xyz;
#endif
#if SM_DEPTHTEXTURE==1
#ifdef IS_NDC_HALF_ZRANGE
#define BIASFACTOR 0.5
#else
#define BIASFACTOR 1.0
#endif
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.position.z-=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR;
#else
vertexOutputs.position.z+=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR;
#endif
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
vertexOutputs.zSM=vertexOutputs.position.z;vertexOutputs.position.z=0.0;
#elif SM_USEDISTANCE==0
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetricSM=(-vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#else
vertexOutputs.vDepthMetricSM=(vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#endif
#endif
`;x.IncludesShadersStoreWGSL[Q8]||(x.IncludesShadersStoreWGSL[Q8]=Ege)});var e6={};Be(e6,{shadowMapVertexShaderWGSL:()=>Sge});var wN,J8,Sge,t6=y(()=>{k();Wc();Hc();yd();Id();ao();sh();pE();j8();Xc();Cd();Pd();Yc();Kc();jc();q8();$8();Zc();wN="shadowMapVertexShader",J8=`attribute position: vec3f;
#ifdef NORMAL
attribute normal: vec3f;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef INSTANCES
attribute world0: vec4f;attribute world1: vec4f;attribute world2: vec4f;attribute world3: vec4f;
#endif
#include<helperFunctions>
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
#ifdef ALPHATEXTURE
varying vUV: vec2f;uniform diffuseMatrix: mat4x4f;
#ifdef UV1
attribute uv: vec2f;
#endif
#ifdef UV2
attribute uv2: vec2f;
#endif
#endif
#include<shadowMapVertexExtraDeclaration>
#include<clipPlaneVertexDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=vertexInputs.position;
#ifdef UV1
var uvUpdated: vec2f=vertexInputs.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=vertexInputs.uv2;
#endif
#ifdef NORMAL
var normalUpdated: vec3f=vertexInputs.normal;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);
#ifdef NORMAL
var normWorldSM: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
var vNormalW: vec3f=normalUpdated/ vec3f(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normWorldSM=transposeMat3(inverseMat3(normWorldSM));
#endif
var vNormalW: vec3f=normalize(normWorldSM*normalUpdated);
#endif
#endif
#include<shadowMapVertexNormalBias>
vertexOutputs.position=scene.viewProjection*worldPos;
#include<shadowMapVertexMetric>
#ifdef ALPHATEXTURE
#ifdef UV1
vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef UV2
vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
#include<clipPlaneVertex>
}`;x.ShadersStoreWGSL[wN]||(x.ShadersStoreWGSL[wN]=J8);Sge={name:wN,shader:J8}});var r6={};Be(r6,{depthBoxBlurPixelShaderWGSL:()=>Tge});var FN,i6,Tge,n6=y(()=>{k();FN="depthBoxBlurPixelShader",i6=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform screenSize: vec2f;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var colorDepth: vec4f=vec4f(0.0);for (var x: i32=-OFFSET; x<=OFFSET; x++) {for (var y: i32=-OFFSET; y<=OFFSET; y++) {colorDepth+=textureSample(textureSampler,textureSamplerSampler,input.vUV+ vec2f(f32(x),f32(y))/uniforms.screenSize);}}
fragmentOutputs.color=(colorDepth/ f32((OFFSET*2+1)*(OFFSET*2+1)));}`;x.ShadersStoreWGSL[FN]||(x.ShadersStoreWGSL[FN]=i6);Tge={name:FN,shader:i6}});var a6={};Be(a6,{shadowMapFragmentSoftTransparentShadowWGSL:()=>Age});var BN,s6,Age,o6=y(()=>{k();BN="shadowMapFragmentSoftTransparentShadow",s6=`#if SM_SOFTTRANSPARENTSHADOW==1
if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x*alpha) {discard;}
#endif
`;x.IncludesShadersStoreWGSL[BN]||(x.IncludesShadersStoreWGSL[BN]=s6);Age={name:BN,shader:s6}});var l6,xge,c6=y(()=>{k();l6="bayerDitherFunctions",xge=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);}
float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0);
vec2 P2=floor(0.5*mod(_P,4.0));
return 4.0*bayerDither2(P1)+bayerDither2(P2);}
float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0);
vec2 P2=floor(0.5 *mod(_P,4.0));
vec2 P4=floor(0.25*mod(_P,8.0));
return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}
`;x.IncludesShadersStore[l6]||(x.IncludesShadersStore[l6]=xge)});var f6,Rge,d6=y(()=>{k();DM();c6();f6="shadowMapFragmentExtraDeclaration",Rge=`#if SM_FLOAT==0
#include<packingFunctions>
#endif
#if SM_SOFTTRANSPARENTSHADOW==1
#include<bayerDitherFunctions>
uniform vec2 softTransparentShadowSM;
#endif
varying float vDepthMetricSM;
#if SM_USEDISTANCE==1
uniform vec3 lightDataSM;varying vec3 vPositionWSM;
#endif
uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying float zSM;
#endif
`;x.IncludesShadersStore[f6]||(x.IncludesShadersStore[f6]=Rge)});var u6,bge,h6=y(()=>{k();u6="shadowMapFragment",bge=`float depthSM=vDepthMetricSM;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
#if SM_USEDISTANCE==1
depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#endif
depthSM=clamp(depthSM,0.0,1.0);
#ifdef USE_REVERSE_DEPTHBUFFER
gl_FragDepth=clamp(1.0-depthSM,0.0,1.0);
#else
gl_FragDepth=clamp(depthSM,0.0,1.0);
#endif
#elif SM_USEDISTANCE==1
depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#if SM_ESM==1
depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);
#endif
#if SM_FLOAT==1
gl_FragColor=vec4(depthSM,1.0,1.0,1.0);
#else
gl_FragColor=pack(depthSM);
#endif
return;`;x.IncludesShadersStore[u6]||(x.IncludesShadersStore[u6]=bge)});var p6={};Be(p6,{shadowMapPixelShader:()=>Mge});var UN,m6,Mge,g6=y(()=>{k();d6();af();of();h6();UN="shadowMapPixelShader",m6=`#include<shadowMapFragmentExtraDeclaration>
#ifdef ALPHATEXTURE
varying vec2 vUV;uniform sampler2D diffuseSampler;
#endif
#include<clipPlaneFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#include<clipPlaneFragment>
#ifdef ALPHATEXTURE
vec4 opacityMap=texture2D(diffuseSampler,vUV);float alphaFromAlphaTexture=opacityMap.a;
#if SM_SOFTTRANSPARENTSHADOW==1
if (softTransparentShadowSM.y==1.0) {opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;}
#endif
#ifdef ALPHATESTVALUE
if (alphaFromAlphaTexture<ALPHATESTVALUE)
discard;
#endif
#endif
#if SM_SOFTTRANSPARENTSHADOW==1
#ifdef ALPHATEXTURE
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x*alphaFromAlphaTexture) discard;
#else
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x) discard;
#endif
#endif
#include<shadowMapFragment>
}`;x.ShadersStore[UN]||(x.ShadersStore[UN]=m6);Mge={name:UN,shader:m6}});var _6,yge,VN=y(()=>{k();_6="sceneVertexDeclaration",yge=`uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;
`;x.IncludesShadersStore[_6]||(x.IncludesShadersStore[_6]=yge)});var v6,Ige,E6=y(()=>{k();v6="meshVertexDeclaration",Ige=`uniform mat4 world;uniform float visibility;
`;x.IncludesShadersStore[v6]||(x.IncludesShadersStore[v6]=Ige)});var S6,Cge,T6=y(()=>{k();VN();E6();S6="shadowMapVertexDeclaration",Cge=`#include<sceneVertexDeclaration>
#include<meshVertexDeclaration>
`;x.IncludesShadersStore[S6]||(x.IncludesShadersStore[S6]=Cge)});var A6,Pge,x6=y(()=>{k();lh();_E();A6="shadowMapUboDeclaration",Pge=`layout(std140,column_major) uniform;
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;x.IncludesShadersStore[A6]||(x.IncludesShadersStore[A6]=Pge)});var R6,Lge,b6=y(()=>{k();R6="shadowMapVertexExtraDeclaration",Lge=`#if SM_NORMALBIAS==1
uniform vec3 lightDataSM;
#endif
uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM;
#if SM_USEDISTANCE==1
varying vec3 vPositionWSM;
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying float zSM;
#endif
`;x.IncludesShadersStore[R6]||(x.IncludesShadersStore[R6]=Lge)});var M6,Dge,y6=y(()=>{k();M6="shadowMapVertexNormalBias",Dge=`#if SM_NORMALBIAS==1
#if SM_DIRECTIONINLIGHTDATA==1
vec3 worldLightDirSM=normalize(-lightDataSM.xyz);
#else
vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM);
#endif
float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM;
#endif
`;x.IncludesShadersStore[M6]||(x.IncludesShadersStore[M6]=Dge)});var I6,Oge,C6=y(()=>{k();I6="shadowMapVertexMetric",Oge=`#if SM_USEDISTANCE==1
vPositionWSM=worldPos.xyz;
#endif
#if SM_DEPTHTEXTURE==1
#ifdef IS_NDC_HALF_ZRANGE
#define BIASFACTOR 0.5
#else
#define BIASFACTOR 1.0
#endif
#ifdef USE_REVERSE_DEPTHBUFFER
gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;
#else
gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;
#endif
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
zSM=gl_Position.z;gl_Position.z=0.0;
#elif SM_USEDISTANCE==0
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#endif
`;x.IncludesShadersStore[I6]||(x.IncludesShadersStore[I6]=Oge)});var L6={};Be(L6,{shadowMapVertexShader:()=>Nge});var GN,P6,Nge,D6=y(()=>{k();$c();Jc();Ld();Dd();oo();T6();x6();b6();ef();Od();Nd();tf();rf();nf();y6();C6();sf();GN="shadowMapVertexShader",P6=`attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef INSTANCES
attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;
#endif
#include<helperFunctions>
#include<__decl__shadowMapVertex>
#ifdef ALPHATEXTURE
varying vec2 vUV;uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#include<shadowMapVertexExtraDeclaration>
#include<clipPlaneVertexDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#ifdef NORMAL
mat3 normWorldSM=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normWorldSM=transposeMat3(inverseMat3(normWorldSM));
#endif
vec3 vNormalW=normalize(normWorldSM*normalUpdated);
#endif
#endif
#include<shadowMapVertexNormalBias>
gl_Position=viewProjection*worldPos;
#include<shadowMapVertexMetric>
#ifdef ALPHATEXTURE
#ifdef UV1
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef UV2
vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#include<clipPlaneVertex>
}`;x.ShadersStore[GN]||(x.ShadersStore[GN]=P6);Nge={name:GN,shader:P6}});var N6={};Be(N6,{depthBoxBlurPixelShader:()=>wge});var kN,O6,wge,w6=y(()=>{k();kN="depthBoxBlurPixelShader",O6=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)
for (int y=-OFFSET; y<=OFFSET; y++)
colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;x.ShadersStore[kN]||(x.ShadersStore[kN]=O6);wge={name:kN,shader:O6}});var B6={};Be(B6,{shadowMapFragmentSoftTransparentShadow:()=>Fge});var zN,F6,Fge,U6=y(()=>{k();zN="shadowMapFragmentSoftTransparentShadow",F6=`#if SM_SOFTTRANSPARENTSHADOW==1
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x*alpha) discard;
#endif
`;x.IncludesShadersStore[zN]||(x.IncludesShadersStore[zN]=F6);Fge={name:zN,shader:F6}});var zi,OM=y(()=>{He();$t();qi();Ed();Kr();sd();Oc();ON();Si();Mn();Td();PR();Yu();Hl();os();Fv();zi=class n{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return this._depthScale!==void 0?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===n.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}else if(e===n.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}else if(e===n.FILTER_PCF||e===n.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===n.FILTER_PCF||e===n.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===n.FILTER_POISSONSAMPLING}set usePoissonSampling(e){let t=this._validateFilter(n.FILTER_POISSONSAMPLING);!e&&this.filter!==n.FILTER_POISSONSAMPLING||(this.filter=e?t:n.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===n.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){let t=this._validateFilter(n.FILTER_EXPONENTIALSHADOWMAP);!e&&this.filter!==n.FILTER_EXPONENTIALSHADOWMAP||(this.filter=e?t:n.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===n.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){let t=this._validateFilter(n.FILTER_BLUREXPONENTIALSHADOWMAP);!e&&this.filter!==n.FILTER_BLUREXPONENTIALSHADOWMAP||(this.filter=e?t:n.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===n.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){let t=this._validateFilter(n.FILTER_CLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==n.FILTER_CLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:n.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===n.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){let t=this._validateFilter(n.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==n.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:n.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===n.FILTER_PCF}set usePercentageCloserFiltering(e){let t=this._validateFilter(n.FILTER_PCF);!e&&this.filter!==n.FILTER_PCF||(this.filter=e?t:n.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===n.FILTER_PCSS}set useContactHardeningShadow(e){let t=this._validateFilter(n.FILTER_PCSS);!e&&this.filter!==n.FILTER_PCSS||(this.filter=e?t:n.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return n.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.indexOf(e)===-1&&this._shadowMap.renderList.push(e),t)for(let i of e.getChildMeshes())this._shadowMap.renderList.indexOf(i)===-1&&this._shadowMap.renderList.push(i);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;let i=this._shadowMap.renderList.indexOf(e);if(i!==-1&&this._shadowMap.renderList.splice(i,1),t)for(let r of e.getChildren())this.removeShadowCaster(r);return this}getLight(){return this._light}get shaderLanguage(){return this._shaderLanguage}_getCamera(){var e;return(e=this._camera)!=null?e:this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}get light(){return this._light}set light(e){this._light!==e&&(this.dispose(!1),this._light=e,this._createInstance())}get useFloat32TextureType(){return this._usefullFloatFirst}set useFloat32TextureType(e){this._usefullFloatFirst!==e&&(this.dispose(!1),this._usefullFloatFirst=e,this._createInstance())}get camera(){return this._camera}set camera(e){this._camera!==e&&(this.dispose(!1),this._camera=e,this._createInstance())}get useRedTextureFormat(){return this._useRedTextureType}set useRedTextureFormat(e){this._useRedTextureType!==e&&(this.dispose(!1),this._useRedTextureType=e,this._createInstance())}constructor(e,t,i,r,s,a=!1){this.onBeforeShadowMapRenderObservable=new re,this.onAfterShadowMapRenderObservable=new re,this.onBeforeShadowMapRenderMeshObservable=new re,this.onAfterShadowMapRenderMeshObservable=new re,this.doNotSerialize=!1,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=n.FILTER_NONE,this._filteringQuality=n.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this._shaderLanguage=0,this.forceBackFacesOnly=!1,this._lightDirection=b.Zero(),this._viewMatrix=Q.Zero(),this._projectionMatrix=Q.Zero(),this._transformMatrix=Q.Zero(),this._cachedPosition=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=Q.Identity(),this._shadersLoaded=!1,this._mapSize=e,this._light=t,this._usefullFloatFirst=!!i,this._scene=t.getScene(),this._camera=r!=null?r:null,this._useRedTextureType=!!s,this._forceGLSL=a,this._createInstance()}_createInstance(){this._initShaderSourceAsync(this._forceGLSL);let e=this._light._shadowGenerators;e||(e=this._light._shadowGenerators=new Map),e.set(this._camera,this),this.id=this._light.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`,{forceMono:!0})]),n._SceneComponentInitialization(this._scene);let t=this._scene.getEngine().getCaps();this._usefullFloatFirst?t.textureFloatRender&&t.textureFloatLinearFiltering?this._textureType=1:t.textureHalfFloatRender&&t.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:t.textureHalfFloatRender&&t.textureHalfFloatLinearFiltering?this._textureType=2:t.textureFloatRender&&t.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){var t;let e=this._scene.getEngine();(t=this._shadowMap)==null||t.dispose(),e._features.supportDepthStencilTexture?(this._shadowMap=new jr(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForShadowGenerator-${this._light.name}`)):this._shadowMap=new jr(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),this._shadowMap===null)return;this._shadowMap.wrapU=_e.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=_e.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(_e.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(r,s,a,o)=>this._renderForShadowMap(r,s,a,o),this._shadowMap.customIsReadyFunction=(r,s,a)=>{if(!a||!r.subMeshes)return!0;let o=!0;for(let l of r.subMeshes){let c=l.getRenderingMesh(),d=this._scene.getEngine(),u=l.getMaterial();if(!u||l.verticesCount===0||this.customAllowRendering&&!this.customAllowRendering(l))continue;let h=c._getInstancesRenderList(l._id,!!l.getReplacementMesh());if(h.mustReturn)continue;let m=d.getCaps().instancedArrays&&(h.visibleInstances[l._id]!==null&&h.visibleInstances[l._id]!==void 0||c.hasThinInstances),g=u.needAlphaBlendingForMesh(c);o=this.isReady(l,m,g)&&o}return o};let e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{var r;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._enableGPUDebugMarkers&&((r=e._debugPushGroup)==null||r.call(e,`Shadow map generation for pass id ${e.currentRenderPassId}`))}),this._shadowMap.onBeforeRenderObservable.add(r=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=r,this._filter===n.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),no.eyeAtCamera=!1,this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._sceneUBOs&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onAfterUnbindObservable.add(()=>{var s,a;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),no.eyeAtCamera=!0,this._scene.updateTransformMatrix(),this._filter===n.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){(s=e._debugPopGroup)==null||s.call(e);return}let r=this.getShadowMapForRendering();r&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,r.renderTarget,!0),e.unBindFramebuffer(r.renderTarget,!0)),e._enableGPUDebugMarkers&&((a=e._debugPopGroup)==null||a.call(e))});let t=new ht(0,0,0,0),i=new ht(1,1,1,1);this._shadowMap.onClearObservable.add(r=>{this._filter===n.FILTER_PCF?r.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?r.clear(t,!0,!0,!1):r.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(r=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=r.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let r=Ja.MIN_RENDERINGGROUPS;r<Ja.MAX_RENDERINGGROUPS;r++)this._shadowMap.setRenderingAutoClearDepthStencil(r,!1)}async _initShaderSourceAsync(e=!1){this._scene.getEngine().isWebGPU&&!e&&!n.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Promise.resolve().then(()=>(Y8(),X8)),Promise.resolve().then(()=>(t6(),e6)),Promise.resolve().then(()=>(n6(),r6)),Promise.resolve().then(()=>(o6(),a6))])):await Promise.all([Promise.resolve().then(()=>(g6(),p6)),Promise.resolve().then(()=>(D6(),L6)),Promise.resolve().then(()=>(w6(),N6)),Promise.resolve().then(()=>(U6(),B6))]),this._shadersLoaded=!0}_initializeBlurRTTAndPostProcesses(){let e=this._scene.getEngine(),t=this._mapSize/this.blurScale;(!this.useKernelBlur||this.blurScale!==1)&&(this._shadowMap2=new jr(this._light.name+"_shadowMap2",t,this._scene,!1,!0,this._textureType,void 0,void 0,!1),this._shadowMap2.wrapU=_e.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=_e.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(_e.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new mo(this._light.name+"KernelBlurX",new Fe(1,0),this.blurKernel,1,null,_e.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.width=t,this._kernelBlurXPostprocess.height=t,this._kernelBlurXPostprocess.externalTextureSamplerBinding=!0,this._kernelBlurXPostprocess.onApplyObservable.add(i=>{i.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new mo(this._light.name+"KernelBlurY",new Fe(0,1),this.blurKernel,1,null,_e.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===0&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new Ni(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,_e.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType,void 0,void 0,void 0,void 0,this._shaderLanguage),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",t,t),i.setTexture("textureSampler",this._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,r){let s;if(r.length)for(s=0;s<r.length;s++)this._renderSubMeshForShadowMap(r.data[s]);for(s=0;s<e.length;s++)this._renderSubMeshForShadowMap(e.data[s]);for(s=0;s<t.length;s++)this._renderSubMeshForShadowMap(t.data[s]);if(this._transparencyShadow)for(s=0;s<i.length;s++)this._renderSubMeshForShadowMap(i.data[s],!0);else for(s=0;s<i.length;s++)i.data[s].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}_bindCustomEffectForRenderSubMeshForShadowMap(e,t,i){t.setMatrix("viewProjection",this.getTransformMatrix())}_renderSubMeshForShadowMap(e,t=!1){var m,g;let i=e.getRenderingMesh(),r=e.getEffectiveMesh(),s=this._scene,a=s.getEngine(),o=e.getMaterial();if(r._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!o||e.verticesCount===0||e._renderId===s.getRenderId())return;let l=s.useRightHandedSystem,c=r._getWorldMatrixDeterminant()<0,f=o._getEffectiveOrientation(i);(c&&!l||!c&&l)&&(f=f===0?1:0);let d=f===0;a.setState(o.backFaceCulling,void 0,void 0,d,o.cullBackFaces);let u=i._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(u.mustReturn)return;let h=a.getCaps().instancedArrays&&(u.visibleInstances[e._id]!==null&&u.visibleInstances[e._id]!==void 0||i.hasThinInstances);if(!(this.customAllowRendering&&!this.customAllowRendering(e)))if(this.isReady(e,h,t)){e._renderId=s.getRenderId();let p=o.shadowDepthWrapper,_=(m=p==null?void 0:p.getEffect(e,this,a.currentRenderPassId))!=null?m:e._getDrawWrapper(),v=Ps.GetEffect(_);a.enableEffect(_),h||i._bind(e,v,o.fillMode),this.getTransformMatrix(),v.setFloat3("biasAndScaleSM",this.bias,this.normalBias,this.depthScale),this.getLight().getTypeID()===Jt.LIGHTTYPEID_DIRECTIONALLIGHT?v.setVector3("lightDataSM",this._cachedDirection):v.setVector3("lightDataSM",this._cachedPosition.subtractToRef(this._scene.floatingOriginOffset,ee.Vector3[0]));let E=this._getCamera();if(v.setFloat2("depthValuesSM",this.getLight().getDepthMinZ(E),this.getLight().getDepthMinZ(E)+this.getLight().getDepthMaxZ(E)),t&&this.enableSoftTransparentShadow&&v.setFloat2("softTransparentShadowSM",r.visibility*o.alpha,(g=this._opacityTexture)!=null&&g.getAlphaFromRGB?1:0),p)e._setMainDrawWrapperOverride(_),p.standalone?p.baseMaterial.bindForSubMesh(r.getWorldMatrix(),i,e):o.bindForSubMesh(r.getWorldMatrix(),i,e),e._setMainDrawWrapperOverride(null);else{this._opacityTexture&&(v.setTexture("diffuseSampler",this._opacityTexture),v.setMatrix("diffuseMatrix",this._opacityTexture.getTextureMatrix()||this._defaultTextureMatrix)),aa(i,v),as(i,v),i.morphTargetManager&&i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(v);let T=e.getMesh().bakedVertexAnimationManager;T&&T.isEnabled&&T.bind(v,h),ss(v,o,s)}!this._useUBO&&!p&&this._bindCustomEffectForRenderSubMeshForShadowMap(e,v,r),ud(v,this._scene.getSceneUniformBuffer()),this._scene.getSceneUniformBuffer().bindUniformBuffer();let S=r.getWorldMatrix();h&&(r.getMeshUniformBuffer().bindToEffect(v,"Mesh"),r.transferToEffect(S)),this.forceBackFacesOnly&&a.setState(!0,0,!1,!0,o.cullBackFaces),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(i),this.onBeforeShadowMapRenderObservable.notifyObservers(v),i._processRendering(r,e,v,o.fillMode,u,h,(T,A)=>{r!==i&&!T?(i.getMeshUniformBuffer().bindToEffect(v,"Mesh"),i.transferToEffect(A)):(r.getMeshUniformBuffer().bindToEffect(v,"Mesh"),r.transferToEffect(T?A:S))}),this.forceBackFacesOnly&&a.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(v),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===n.FILTER_NONE||this.filter===n.FILTER_PCSS?this._shadowMap.updateSamplingMode(_e.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(_e.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){let i={useInstances:!1,...t},r=this.getShadowMap();if(!r){e&&e(this);return}let s=r.renderList;if(!s){e&&e(this);return}let a=[];for(let c of s)a.push(...c.subMeshes);if(a.length===0){e&&e(this);return}let o=0,l=()=>{var c,f;if(!(!this._scene||!this._scene.getEngine())){for(;this.isReady(a[o],i.useInstances,(f=(c=a[o].getMaterial())==null?void 0:c.needAlphaBlendingForMesh(a[o].getMesh()))!=null?f:!1);)if(o++,o>=a.length){e&&e(this);return}setTimeout(l,16)}};l()}async forceCompilationAsync(e){return await new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(this._textureType!==0?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));let s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(D.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Jt.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var o;if(!this._shadersLoaded)return!1;let r=e.getMaterial(),s=r==null?void 0:r.shadowDepthWrapper;if(this._opacityTexture=null,!r)return!1;let a=[];if(this._prepareShadowDefines(e,t,a,i),s){if(!s.isReadyForSubMesh(e,a,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{let l=e._getDrawWrapper(void 0,!0),c=l.effect,f=l.defines,d=[D.PositionKind],u=e.getMesh(),h=!1,m=!1,g=!1,p=!1;this.normalBias&&u.isVerticesDataPresent(D.NormalKind)&&(d.push(D.NormalKind),a.push("#define NORMAL"),h=!0,u.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));let _=r.needAlphaTestingForMesh(u);if((_||r.needAlphaBlendingForMesh(u))&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=r.opacityTexture:this._opacityTexture=r.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;let A=(o=r.alphaCutOff)!=null?o:n.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),_&&a.push(`#define ALPHATESTVALUE ${A}${A%1===0?".":""}`),u.isVerticesDataPresent(D.UVKind)&&(d.push(D.UVKind),a.push("#define UV1"),m=!0),u.isVerticesDataPresent(D.UV2Kind)&&this._opacityTexture.coordinatesIndex===1&&(d.push(D.UV2Kind),a.push("#define UV2"),g=!0)}let v=new ds;if(u.useBones&&u.computeBonesUsingShaders&&u.skeleton){d.push(D.MatricesIndicesKind),d.push(D.MatricesWeightsKind),u.numBoneInfluencers>4&&(d.push(D.MatricesIndicesExtraKind),d.push(D.MatricesWeightsExtraKind));let A=u.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+u.numBoneInfluencers),u.numBoneInfluencers>0&&v.addCPUSkinningFallback(0,u),A.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(A.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");let E=u.morphTargetManager?Xl(u.morphTargetManager,a,d,u,!0,h,!1,m,g,p):0;if(Wl(r,this._scene,a),t&&(a.push("#define INSTANCES"),Qo(d),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(let A of this.customShaderOptions.defines)a.indexOf(A)===-1&&a.push(A);let S=u.bakedVertexAnimationManager;S&&S.isEnabled&&(a.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&d.push("bakedVertexAnimationSettingsInstanced"));let T=a.join(`
`);if(f!==T){f=T;let A="shadowMap",R=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureInfo","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],M=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],I=["Scene","Mesh"];if(ns(R),this.customShaderOptions){if(A=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(let L of this.customShaderOptions.attributes)d.indexOf(L)===-1&&d.push(L);if(this.customShaderOptions.uniforms)for(let L of this.customShaderOptions.uniforms)R.indexOf(L)===-1&&R.push(L);if(this.customShaderOptions.samplers)for(let L of this.customShaderOptions.samplers)M.indexOf(L)===-1&&M.push(L)}let C=this._scene.getEngine();c=C.createEffect(A,{attributes:d,uniformsNames:R,uniformBuffersNames:I,samplers:M,defines:T,fallbacks:v,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:E},shaderLanguage:this._shaderLanguage},C),l.setEffect(c,f)}if(!c.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(!this._blurPostProcesses||!this._blurPostProcesses.length)&&this._initializeBlurRTTAndPostProcesses(),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){let i=this._scene,r=this._light;!i.shadowsEnabled||!r.shadowEnabled||(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===n.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===n.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===n.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===n.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera(),a=this.getShadowMap();if(!a)return;if(!i.needCube()){let l=r.floatingOriginOffset,c=this.getTransformMatrix(),f=r.floatingOriginMode?QL(l,this._viewMatrix,this._projectionMatrix,ee.Matrix[0]):c;t.setMatrix("lightMatrix"+e,f)}let o=this.getShadowMapForRendering();this._filter===n.FILTER_PCF?(t.setDepthStencilTexture("shadowTexture"+e,o),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a.getSize().width,1/a.getSize().width,this.frustumEdgeFalloff,e)):this._filter===n.FILTER_PCSS?(t.setDepthStencilTexture("shadowTexture"+e,o),t.setTexture("depthTexture"+e,o),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/a.getSize().width,this._contactHardeningLightSizeUVRatio*a.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowTexture"+e,o),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/a.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e)}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){let e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),b.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),Math.abs(b.Dot(this._lightDirection,b.Up()))===1&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),Q.LookAtLHToRef(t,t.add(this._lightDirection),b.Up(),this._viewMatrix);let i=this.getShadowMap();if(i){let r=i.renderList;r&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,r)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){let e=this._shadowMap;if(!e)return;let t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(let i of t)this._shadowMap.renderList.push(i)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(e=!0){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){let t=this._light._shadowGenerators.entries();for(let i=t.next();i.done!==!0;i=t.next()){let[r,s]=i.value;s===this&&this._light._shadowGenerators.delete(r)}this._light._shadowGenerators.size===0&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}e&&(this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear())}serialize(){var i;let e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=(i=this._camera)==null?void 0:i.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let r=0;r<t.renderList.length;r++){let s=t.renderList[r];e.renderList.push(s.id)}return e}static Parse(e,t,i){let r=t.getLightById(e.lightId),s=e.cameraId!==void 0?t.getCameraById(e.cameraId):null,a=i?i(e.mapSize,r,s):new n(e.mapSize,r,void 0,s),o=a.getShadowMap();if(e.renderList.length&&o){let l=new Set(e.renderList),c=o.renderList;c||(c=o.renderList=[]);let f=t.meshes;for(let d of f)l.has(d.id)&&c.push(d)}return e.id!==void 0&&(a.id=e.id),a.forceBackFacesOnly=!!e.forceBackFacesOnly,e.darkness!==void 0&&a.setDarkness(e.darkness),e.transparencyShadow&&a.setTransparencyShadow(!0),e.frustumEdgeFalloff!==void 0&&(a.frustumEdgeFalloff=e.frustumEdgeFalloff),e.bias!==void 0&&(a.bias=e.bias),e.normalBias!==void 0&&(a.normalBias=e.normalBias),e.usePercentageCloserFiltering?a.usePercentageCloserFiltering=!0:e.useContactHardeningShadow?a.useContactHardeningShadow=!0:e.usePoissonSampling?a.usePoissonSampling=!0:e.useExponentialShadowMap?a.useExponentialShadowMap=!0:e.useBlurExponentialShadowMap?a.useBlurExponentialShadowMap=!0:e.useCloseExponentialShadowMap?a.useCloseExponentialShadowMap=!0:e.useBlurCloseExponentialShadowMap?a.useBlurCloseExponentialShadowMap=!0:e.useVarianceShadowMap?a.useExponentialShadowMap=!0:e.useBlurVarianceShadowMap&&(a.useBlurExponentialShadowMap=!0),e.contactHardeningLightSizeUVRatio!==void 0&&(a.contactHardeningLightSizeUVRatio=e.contactHardeningLightSizeUVRatio),e.filteringQuality!==void 0&&(a.filteringQuality=e.filteringQuality),e.depthScale&&(a.depthScale=e.depthScale),e.blurScale&&(a.blurScale=e.blurScale),e.blurBoxOffset&&(a.blurBoxOffset=e.blurBoxOffset),e.useKernelBlur&&(a.useKernelBlur=e.useKernelBlur),e.blurKernel&&(a.blurKernel=e.blurKernel),a}};zi.CLASSNAME="ShadowGenerator";zi.ForceGLSL=!1;zi.FILTER_NONE=0;zi.FILTER_EXPONENTIALSHADOWMAP=1;zi.FILTER_POISSONSAMPLING=2;zi.FILTER_BLUREXPONENTIALSHADOWMAP=3;zi.FILTER_CLOSEEXPONENTIALSHADOWMAP=4;zi.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP=5;zi.FILTER_PCF=6;zi.FILTER_PCSS=7;zi.QUALITY_HIGH=0;zi.QUALITY_MEDIUM=1;zi.QUALITY_LOW=2;zi.DEFAULT_ALPHA_CUTOFF=.5;zi._SceneComponentInitialization=n=>{throw $e("ShadowGeneratorSceneComponent")}});var G6={};Be(G6,{depthPixelShader:()=>Bge});var WN,V6,Bge,HN=y(()=>{k();af();DM();of();WN="depthPixelShader",V6=`#ifdef ALPHATEST
varying vec2 vUV;uniform sampler2D diffuseSampler;
#endif
#include<clipPlaneFragmentDeclaration>
varying float vDepthMetric;
#ifdef PACKED
#include<packingFunctions>
#endif
#ifdef STORE_CAMERASPACE_Z
varying vec4 vViewPos;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (texture2D(diffuseSampler,vUV).a<0.4)
discard;
#endif
#ifdef STORE_CAMERASPACE_Z
#ifdef PACKED
gl_FragColor=pack(vViewPos.z);
#else
gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);
#endif
#else
#ifdef NONLINEARDEPTH
#ifdef PACKED
gl_FragColor=pack(gl_FragCoord.z);
#else
gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);
#endif
#else
#ifdef PACKED
gl_FragColor=pack(vDepthMetric);
#else
gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);
#endif
#endif
#endif
}`;x.ShadersStore[WN]||(x.ShadersStore[WN]=V6);Bge={name:WN,shader:V6}});var k6,Uge,z6=y(()=>{k();k6="pointCloudVertexDeclaration",Uge=`#ifdef POINTSIZE
uniform float pointSize;
#endif
`;x.IncludesShadersStore[k6]||(x.IncludesShadersStore[k6]=Uge)});var H6={};Be(H6,{depthVertexShader:()=>Vge});var XN,W6,Vge,YN=y(()=>{k();$c();Jc();Ld();Dd();ef();bd();z6();Od();Nd();tf();rf();nf();sf();fN();XN="depthVertexShader",W6=`attribute vec3 position;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
#include<instancesDeclaration>
uniform mat4 viewProjection;uniform vec2 depthValues;
#if defined(ALPHATEST) || defined(NEED_UV)
varying vec2 vUV;uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#ifdef STORE_CAMERASPACE_Z
uniform mat4 view;varying vec4 vViewPos;
#endif
#include<pointCloudVertexDeclaration>
varying float vDepthMetric;
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#include<clipPlaneVertex>
gl_Position=viewProjection*worldPos;
#ifdef STORE_CAMERASPACE_Z
vViewPos=view*worldPos;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));
#else
vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));
#endif
#endif
#if defined(ALPHATEST) || defined(BASIC_RENDER)
#ifdef UV1
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef UV2
vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#include<pointCloudVertex>
}
`;x.ShadersStore[XN]||(x.ShadersStore[XN]=W6);Vge={name:XN,shader:W6}});var Y6={};Be(Y6,{depthVertexShaderWGSL:()=>Gge});var KN,X6,Gge,K6=y(()=>{k();Wc();Hc();yd();Id();Xc();Rd();Cd();Pd();Yc();Kc();jc();Zc();KN="depthVertexShader",X6=`attribute position: vec3f;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
#include<instancesDeclaration>
uniform viewProjection: mat4x4f;uniform depthValues: vec2f;
#if defined(ALPHATEST) || defined(NEED_UV)
varying vUV: vec2f;uniform diffuseMatrix: mat4x4f;
#ifdef UV1
attribute uv: vec2f;
#endif
#ifdef UV2
attribute uv2: vec2f;
#endif
#endif
#ifdef STORE_CAMERASPACE_Z
uniform view: mat4x4f;varying vViewPos: vec4f;
#endif
varying vDepthMetric: f32;
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=vertexInputs.position;
#ifdef UV1
var uvUpdated: vec2f=vertexInputs.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=vertexInputs.uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);
#include<clipPlaneVertex>
vertexOutputs.position=uniforms.viewProjection*worldPos;
#ifdef STORE_CAMERASPACE_Z
vertexOutputs.vViewPos=uniforms.view*worldPos;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetric=((-vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y));
#else
vertexOutputs.vDepthMetric=((vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y));
#endif
#endif
#if defined(ALPHATEST) || defined(BASIC_RENDER)
#ifdef UV1
vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef UV2
vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
}
`;x.ShadersStoreWGSL[KN]||(x.ShadersStoreWGSL[KN]=X6);Gge={name:KN,shader:X6}});var Z6={};Be(Z6,{depthPixelShaderWGSL:()=>kge});var jN,j6,kge,q6=y(()=>{k();qc();LM();Qc();jN="depthPixelShader",j6=`#ifdef ALPHATEST
varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d<f32>;
#endif
#include<clipPlaneFragmentDeclaration>
varying vDepthMetric: f32;
#ifdef PACKED
#include<packingFunctions>
#endif
#ifdef STORE_CAMERASPACE_Z
varying vViewPos: vec4f;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;}
#endif
#ifdef STORE_CAMERASPACE_Z
#ifdef PACKED
fragmentOutputs.color=pack(input.vViewPos.z);
#else
fragmentOutputs.color= vec4f(input.vViewPos.z,0.0,0.0,1.0);
#endif
#else
#ifdef NONLINEARDEPTH
#ifdef PACKED
fragmentOutputs.color=pack(input.position.z);
#else
fragmentOutputs.color= vec4f(input.position.z,0.0,0.0,0.0);
#endif
#else
#ifdef PACKED
fragmentOutputs.color=pack(input.vDepthMetric);
#else
fragmentOutputs.color= vec4f(input.vDepthMetric,0.0,0.0,1.0);
#endif
#endif
#endif
}`;x.ShadersStoreWGSL[jN]||(x.ShadersStoreWGSL[jN]=j6);kge={name:jN,shader:j6}});var fg,Q6=y(()=>{$t();qi();Kr();sd();zl();HN();YN();Mn();Hl();os();Td();fg=class n{get shaderLanguage(){return this._shaderLanguage}get alphaBlendedDepth(){return this._alphaBlendedDepth}set alphaBlendedDepth(e){this._alphaBlendedDepth!==e&&(this._alphaBlendedDepth=e,this._alphaBlendedDepthMaterialCache.clear())}setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}_ensureGaussianSplattingDepthMaterial(e,t){var s;let i=(s=e._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:s[t],r=this._alphaBlendedDepthMaterialCache.get(e.uniqueId);if(i===void 0||r!==this.alphaBlendedDepth){let a=e.material;if(!a)return null;let o=e.isCompound;i=a.makeDepthRenderingMaterial(this._scene,this._shaderLanguage,this.alphaBlendedDepth,o),this.setMaterialForRendering(e,i),this._alphaBlendedDepthMaterialCache.set(e.uniqueId,this.alphaBlendedDepth)}return i}constructor(e,t=1,i=null,r=!1,s=_e.TRILINEAR_SAMPLINGMODE,a=!1,o,l){this._shaderLanguage=0,this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this._alphaBlendedDepth=!1,this._alphaBlendedDepthMaterialCache=new Map,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._shadersLoaded=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=a,this.isPacked=t===0,this.isPacked?this.clearColor=new ht(1,1,1,1):this.clearColor=new ht(a?0:1,0,0,1),this._initShaderSourceAsync(),n._SceneComponentInitialization(this._scene);let c=e.getEngine();this._camera=i,s!==_e.NEAREST_SAMPLINGMODE&&(t===1&&!c._caps.textureFloatLinearFiltering&&(s=_e.NEAREST_SAMPLINGMODE),t===2&&!c._caps.textureHalfFloatLinearFiltering&&(s=_e.NEAREST_SAMPLINGMODE));let f=this.isPacked||!c._features.supportExtendedTextureFormats?5:6;this._depthMap=l!=null?l:new jr(o!=null?o:"DepthRenderer",{width:c.getRenderWidth(),height:c.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,f),this._depthMap.wrapU=_e.CLAMP_ADDRESSMODE,this._depthMap.wrapV=_e.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(u=>{u.clear(this.clearColor,!0,!0,!0)}),this._depthMap.customIsReadyFunction=(u,h,m)=>{if((m||h===0)&&u.subMeshes)for(let g=0;g<u.subMeshes.length;++g){let p=u.subMeshes[g],_=p.getMaterial(),v=p.getEffectiveMesh();if(!_||v.infiniteDistance||_.disableDepthWrite||p.verticesCount===0)continue;let E=p.getRenderingMesh(),S=E._getInstancesRenderList(p._id,!!p.getReplacementMesh()),T=c.getCaps().instancedArrays&&(S.visibleInstances[p._id]!==null&&S.visibleInstances[p._id]!==void 0||E.hasThinInstances);if(!this.isReady(p,T))return!1}return!0};let d=u=>{var M;let h=u.getRenderingMesh(),m=u.getEffectiveMesh(),g=this._scene,p=g.getEngine(),_=u.getMaterial();if(m._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!_||m.infiniteDistance||_.disableDepthWrite||u.verticesCount===0||u._renderId===g.getRenderId())return;let v=m._getWorldMatrixDeterminant()<0,E=_._getEffectiveOrientation(h);v&&(E=E===0?1:0);let S=E===0;p.setState(_.backFaceCulling,0,!1,S,this.reverseCulling?!_.cullBackFaces:_.cullBackFaces);let T=h._getInstancesRenderList(u._id,!!u.getReplacementMesh());if(T.mustReturn)return;let A=p.getCaps().instancedArrays&&(T.visibleInstances[u._id]!==null&&T.visibleInstances[u._id]!==void 0||h.hasThinInstances),R=this._camera||g.activeCamera;if(this.isReady(u,A)&&R){if(u._renderId=g.getRenderId(),m.getClassName()==="GaussianSplattingMesh"){let B=this._ensureGaussianSplattingDepthMaterial(m,p.currentRenderPassId);if(B&&!B.isReadyForSubMesh(m,u,A))return;this.alphaBlendedDepth&&_.needAlphaBlendingForMesh(m)?p.setAlphaMode(2):p.setAlphaMode(0),m.render(u,!1);return}let C=(M=m._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:M[p.currentRenderPassId],L=u._getDrawWrapper();!L&&C&&(L=C._getDrawWrapper());let w=R.mode===Et.ORTHOGRAPHIC_CAMERA;if(!L)return;let G=L.effect;p.enableEffect(L),A||h._bind(u,G,_.fillMode),C?C.bindForSubMesh(m.getWorldMatrix(),m,u):(G.setMatrix("viewProjection",g.getTransformMatrix()),G.setMatrix("world",m.getWorldMatrix()),this._storeCameraSpaceZ&&G.setMatrix("view",g.getViewMatrix()));let O,N;if(w?(O=!p.useReverseDepthBuffer&&p.isNDCHalfZRange?0:1,N=p.useReverseDepthBuffer&&p.isNDCHalfZRange?0:1):(O=p.useReverseDepthBuffer&&p.isNDCHalfZRange?R.minZ:p.isNDCHalfZRange?0:R.minZ,N=p.useReverseDepthBuffer&&p.isNDCHalfZRange?0:R.maxZ),G.setFloat2("depthValues",O,O+N),!C){if(_.needAlphaTestingForMesh(m)){let V=_.getAlphaTestTexture();V&&(G.setTexture("diffuseSampler",V),G.setMatrix("diffuseMatrix",V.getTextureMatrix()))}aa(h,G),ss(G,_,g),as(h,G),h.morphTargetManager&&h.morphTargetManager.isUsingTextureForTargets&&h.morphTargetManager._bind(G);let B=u.getMesh().bakedVertexAnimationManager;B&&B.isEnabled&&B.bind(G,A),_.pointsCloud&&G.setFloat("pointSize",_.pointSize)}this.alphaBlendedDepth&&_.needAlphaBlendingForMesh(m)?p.setAlphaMode(2):p.setAlphaMode(0),h._processRendering(m,u,G,_.fillMode,T,A,(B,V)=>G.setMatrix("world",V))}};this._depthMap.customRenderFunction=(u,h,m,g)=>{let p=this._scene.getEngine(),_=p.getAlphaMode(),v;if(g.length)for(v=0;v<g.length;v++)d(g.data[v]);for(v=0;v<u.length;v++)d(u.data[v]);for(v=0;v<h.length;v++)d(h.data[v]);if(this.forceDepthWriteTransparentMeshes)for(v=0;v<m.length;v++)d(m.data[v]);else for(v=0;v<m.length;v++)m.data[v].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1;this.alphaBlendedDepth&&p.setAlphaMode(_)}}async _initShaderSourceAsync(e=!1){this._scene.getEngine().isWebGPU&&!e&&!n.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Promise.resolve().then(()=>(K6(),Y6)),Promise.resolve().then(()=>(q6(),Z6))])):await Promise.all([Promise.resolve().then(()=>(YN(),H6)),Promise.resolve().then(()=>(HN(),G6))]),this._shadersLoaded=!0}isReady(e,t){var R,M;if(!this._shadersLoaded)return!1;let i=this._scene.getEngine(),r=e.getMesh(),s=r.getScene(),a=this._depthMap.renderPassId,o=(M=(R=r._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:R[a])!=null?M:null;if(r.getClassName()==="GaussianSplattingMesh"&&(o=this._ensureGaussianSplattingDepthMaterial(r,a)),o)return o.isReadyForSubMesh(r,e,t);let l=e.getMaterial();if(!l||l.disableDepthWrite)return!1;let c=[],f=[D.PositionKind],d=!1,u=!1,h=!1;l.needAlphaTestingForMesh(r)&&l.getAlphaTestTexture()&&(c.push("#define ALPHATEST"),r.isVerticesDataPresent(D.UVKind)&&(f.push(D.UVKind),c.push("#define UV1"),d=!0),r.isVerticesDataPresent(D.UV2Kind)&&(f.push(D.UV2Kind),c.push("#define UV2"),u=!0));let m=new ds;if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){f.push(D.MatricesIndicesKind),f.push(D.MatricesWeightsKind),r.numBoneInfluencers>4&&(f.push(D.MatricesIndicesExtraKind),f.push(D.MatricesWeightsExtraKind)),c.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),r.numBoneInfluencers>0&&m.addCPUSkinningFallback(0,r);let I=r.skeleton;I.isUsingTextureForMatrices?c.push("#define BONETEXTURE"):c.push("#define BonesPerMesh "+(I.bones.length+1))}else c.push("#define NUM_BONE_INFLUENCERS 0");let g=r.morphTargetManager?Xl(r.morphTargetManager,c,f,r,!0,!1,!1,d,u,h):0;l.pointsCloud&&c.push("#define POINTSIZE"),t&&(c.push("#define INSTANCES"),Qo(f),e.getRenderingMesh().hasThinInstances&&c.push("#define THIN_INSTANCES"));let p=r.bakedVertexAnimationManager;p&&p.isEnabled&&(c.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&f.push("bakedVertexAnimationSettingsInstanced")),this._storeNonLinearDepth&&c.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&c.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&c.push("#define PACKED"),Wl(l,s,c);let _=i.currentRenderPassId,E=this._depthMap.renderPassIds.includes(_)?_:this._depthMap.renderPassId,S=e._getDrawWrapper(E,!0),T=S.defines,A=c.join(`
`);if(T!==A){let I=["world","mBones","boneTextureInfo","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],C=["diffuseSampler","morphTargets","boneSampler","bakedVertexAnimationTexture"];ns(I),S.setEffect(i.createEffect("depth",{attributes:f,uniformsNames:I,uniformBuffersNames:[],samplers:C,defines:A,fallbacks:m,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:g},shaderLanguage:this._shaderLanguage},i),A)}return S.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){let e=[];for(let t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(let t of e)delete this._scene._depthRenderer[t]}}};fg.ForceGLSL=!1;fg._SceneComponentInitialization=n=>{throw $e("DepthRendererSceneComponent")}});var J6={};Be(J6,{minmaxReduxPixelShaderWGSL:()=>zge});var ZN,$6,zge,qN=y(()=>{k();ZN="minmaxReduxPixelShader",$6=`varying vUV: vec2f;var textureSampler: texture_2d<f32>;
#if defined(INITIAL)
uniform texSize: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*(uniforms.texSize-1.0));let f1=textureLoad(textureSampler,coord,0).r;let f2=textureLoad(textureSampler,coord+vec2i(1,0),0).r;let f3=textureLoad(textureSampler,coord+vec2i(1,1),0).r;let f4=textureLoad(textureSampler,coord+vec2i(0,1),0).r;
#ifdef DEPTH_REDUX
#ifdef VIEW_DEPTH
var minz=3.4e38;if (f1 != 0.0) { minz=f1; }
if (f2 != 0.0) { minz=min(minz,f2); }
if (f3 != 0.0) { minz=min(minz,f3); }
if (f4 != 0.0) { minz=min(minz,f4); }
let maxz=max(max(max(f1,f2),f3),f4);
#else
let minz=min(min(min(f1,f2),f3),f4);let maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);
#endif
#else
let minz=min(min(min(f1,f2),f3),f4);let maxz=max(max(max(f1,f2),f3),f4);
#endif
fragmentOutputs.color=vec4f(minz,maxz,0.,0.);}
#elif defined(MAIN)
uniform texSize: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*(uniforms.texSize-1.0));let f1=textureLoad(textureSampler,coord,0).rg;let f2=textureLoad(textureSampler,coord+vec2i(1,0),0).rg;let f3=textureLoad(textureSampler,coord+vec2i(1,1),0).rg;let f4=textureLoad(textureSampler,coord+vec2i(0,1),0).rg;let minz=min(min(min(f1.x,f2.x),f3.x),f4.x);let maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);fragmentOutputs.color=vec4(minz,maxz,0.,0.);}
#elif defined(ONEBEFORELAST)
uniform texSize: vec2i;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*vec2f(uniforms.texSize-1));let f1=textureLoad(textureSampler,coord % uniforms.texSize,0).rg;let f2=textureLoad(textureSampler,(coord+vec2i(1,0)) % uniforms.texSize,0).rg;let f3=textureLoad(textureSampler,(coord+vec2i(1,1)) % uniforms.texSize,0).rg;let f4=textureLoad(textureSampler,(coord+vec2i(0,1)) % uniforms.texSize,0).rg;let minz=min(min(min(f1.x,f2.x),f3.x),f4.x);let maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);fragmentOutputs.color=vec4(minz,maxz,0.,0.);}
#elif defined(LAST)
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(0.);if (true) {
discard;}}
#endif
`;x.ShadersStoreWGSL[ZN]||(x.ShadersStoreWGSL[ZN]=$6);zge={name:ZN,shader:$6}});var t9={};Be(t9,{minmaxReduxPixelShader:()=>Wge});var QN,e9,Wge,$N=y(()=>{k();QN="minmaxReduxPixelShader",e9=`varying vec2 vUV;uniform sampler2D textureSampler;
#if defined(INITIAL)
uniform vec2 texSize;void main(void)
{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(textureSampler,coord,0).r;float f2=texelFetch(textureSampler,coord+ivec2(1,0),0).r;float f3=texelFetch(textureSampler,coord+ivec2(1,1),0).r;float f4=texelFetch(textureSampler,coord+ivec2(0,1),0).r;
#ifdef DEPTH_REDUX
#ifdef VIEW_DEPTH
float minz=3.4e38;if (f1 != 0.0) { minz=f1; }
if (f2 != 0.0) { minz=min(minz,f2); }
if (f3 != 0.0) { minz=min(minz,f3); }
if (f4 != 0.0) { minz=min(minz,f4); }
float maxz=max(max(max(f1,f2),f3),f4);
#else
float minz=min(min(min(f1,f2),f3),f4);float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);
#endif
#else
float minz=min(min(min(f1,f2),f3),f4);float maxz=max(max(max(f1,f2),f3),f4);
#endif
glFragColor=vec4(minz,maxz,0.,0.);}
#elif defined(MAIN)
uniform vec2 texSize;void main(void)
{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}
#elif defined(ONEBEFORELAST)
uniform ivec2 texSize;void main(void)
{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}
#elif defined(LAST)
void main(void)
{glFragColor=vec4(0.);if (true) {
discard;}}
#endif
`;x.ShadersStore[QN]||(x.ShadersStore[QN]=e9);Wge={name:QN,shader:e9}});var i9,wd,Hge,Xge,il,NM,r9=y(()=>{Si();Ku();Yi();(function(n){n[n.NormalizedViewDepth=0]="NormalizedViewDepth",n[n.ViewDepth=1]="ViewDepth",n[n.ScreenDepth=2]="ScreenDepth"})(i9||(i9={}));wd=class n extends sn{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(()=>(qN(),J6)))):t.push(Promise.resolve().then(()=>($N(),t9)))}constructor(e,t=null,i="",r){super({...r,name:e,engine:t||Oe.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,uniforms:n.Uniforms,defines:i}),this.textureWidth=0,this.textureHeight=0}bind(e=!1){super.bind(e);let t=this.drawWrapper.effect;this.textureWidth===1||this.textureHeight===1?t.setInt2("texSize",this.textureWidth,this.textureHeight):t.setFloat2("texSize",this.textureWidth,this.textureHeight)}};wd.FragmentUrl="minmaxRedux";wd.Uniforms=["texSize"];Hge=new Float32Array(4),Xge=new Uint8Array(4),il={min:0,max:0},NM=class{get depthRedux(){return this._depthRedux}set depthRedux(e){this._depthRedux!==e&&(this._depthRedux=e,this._recreatePostProcesses())}get textureWidth(){return this._textureWidth}get textureHeight(){return this._textureHeight}constructor(e,t=!0){this.onAfterReductionPerformed=new re,this._textureWidth=0,this._textureHeight=0,this._scene=e,this._depthRedux=t,this.reductionSteps=[]}setTextureDimensions(e,t,i=0){return e===this._textureWidth&&t===this._textureHeight&&i===this._depthTextureType?!1:(this._textureWidth=e,this._textureHeight=t,this._depthTextureType=i,this._recreatePostProcesses(),!0)}readMinMax(e){let t=e.type===1||e.type===2,i=t?Hge:Xge;this._scene.getEngine()._readTexturePixels(e,1,1,-1,0,i,!1),il.min=i[0],il.max=i[1],t||(il.min=il.min/255,il.max=il.max/255),il.min>=il.max&&(il.min=0,il.max=1),this.onAfterReductionPerformed.notifyObservers(il)}dispose(e=!0){e&&(this.onAfterReductionPerformed.clear(),this._textureWidth=0,this._textureHeight=0);for(let t=0;t<this.reductionSteps.length;++t)this.reductionSteps[t].dispose();this.reductionSteps.length=0}_recreatePostProcesses(){this.dispose(!1);let e=this._scene,t=this.textureWidth,i=this.textureHeight,r=new wd("Initial reduction phase",e.getEngine(),"#define INITIAL"+(this._depthRedux?`
#define DEPTH_REDUX`:"")+(this._depthTextureType===1?`
#define VIEW_DEPTH`:""));r.textureWidth=t,r.textureHeight=i,this.reductionSteps.push(r);let s=1;for(;t>1||i>1;){t=Math.max(Math.round(t/2),1),i=Math.max(Math.round(i/2),1);let a=new wd("Reduction phase "+s,e.getEngine(),"#define "+(t==1&&i==1?"LAST":t==1||i==1?"ONEBEFORELAST":"MAIN"));a.textureWidth=t,a.textureHeight=i,this.reductionSteps.push(a),s++}}}});var wM,n9=y(()=>{Oc();IR();r9();$N();qN();wM=class{get onAfterReductionPerformed(){return this._thinMinMaxReducer.onAfterReductionPerformed}constructor(e){this._onAfterUnbindObserver=null,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new Dc(e.getScene()),this._thinMinMaxReducer=new NM(e.getScene()),this._reductionSteps=[],this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){if(e!==this._sourceTexture&&(this._thinMinMaxReducer.depthRedux=t,this.deactivate(),this._sourceTexture=e,this._forceFullscreenViewport=r,this._thinMinMaxReducer.setTextureDimensions(e.getRenderWidth(),e.getRenderHeight()))){this._disposePostProcesses();let s=this._thinMinMaxReducer.reductionSteps;for(let a=0;a<s.length;++a){let o=s[a],l=new Ni(o.name,wd.FragmentUrl,{effectWrapper:o,samplingMode:1,engine:this._camera.getScene().getEngine(),textureType:i,textureFormat:7,size:{width:o.textureWidth,height:o.textureHeight}});this._reductionSteps.push(l),l.autoClear=!1,l.forceFullscreenViewport=r,a===0&&(l.externalTextureSamplerBinding=!0,l.onApplyObservable.add(c=>{c.setTexture("textureSampler",this._sourceTexture)})),a===s.length-1&&this._reductionSteps[a-1].onAfterRenderObservable.add(()=>{this._thinMinMaxReducer.readMinMax(l.inputTexture.texture)})}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){this._onAfterUnbindObserver||!this._sourceTexture||(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(()=>{var t,i;let e=this._camera.getScene().getEngine();(t=e._debugPushGroup)==null||t.call(e,"min max reduction"),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport,0,0,!0,this._reductionSteps.length-1),e.unBindFramebuffer(this._reductionSteps[this._reductionSteps.length-1].inputTexture,!1),(i=e._debugPopGroup)==null||i.call(e)}),this._activated=!0)}deactivate(){!this._onAfterUnbindObserver||!this._sourceTexture||(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){e&&(this.onAfterReductionPerformed.clear(),this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=void 0,this._disposePostProcesses(),this._postProcessManager.dispose(),this._postProcessManager=void 0,this._thinMinMaxReducer.dispose(),this._thinMinMaxReducer=void 0,this._sourceTexture=null)}_disposePostProcesses(){for(let e=0;e<this._reductionSteps.length;++e)this._reductionSteps[e].dispose();this._reductionSteps.length=0}}});var FM,s9=y(()=>{Q6();n9();FM=class extends wM{get depthRenderer(){return this._depthRenderer}constructor(e){super(e)}setDepthRenderer(e=null,t=2,i=!0){let r=this._camera.getScene();this._depthRenderer&&(delete r._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null),e===null&&(r._depthRenderer||(r._depthRenderer={}),this._depthRendererId="minmax_"+this._camera.uniqueId,e=this._depthRenderer=new fg(r,t,this._camera,!1,1,!1,`DepthRenderer ${this._depthRendererId}`),e.enabled=!1,r._depthRenderer[this._depthRendererId]=e),super.setSourceTexture(e.getDepthMap(),!0,t,i)}setSourceTexture(e,t,i=2,r=!0){super.setSourceTexture(e,t,i,r)}activate(){this._depthRenderer&&(this._depthRenderer.enabled=!0),super.activate()}deactivate(){super.deactivate(),this._depthRenderer&&(this._depthRenderer.enabled=!1)}dispose(e=!0){super.dispose(e),this._depthRenderer&&e&&(this._depthRenderer.dispose(),this._depthRenderer=null)}}});var a9,Yge,Fr,dg,BM,rl,o9=y(()=>{He();sd();Mn();OM();Ip();s9();wt();Yi();Fv();a9=b.Up(),Yge=b.Zero(),Fr=new b,dg=new b,BM=new Q,rl=class n extends zi{_validateFilter(e){return e===zi.FILTER_NONE||e===zi.FILTER_PCF||e===zi.FILTER_PCSS?e:(te.Error('Unsupported filter "'+e+'"!'),zi.FILTER_NONE)}get numCascades(){return this._numCascades}set numCascades(e){e=Math.min(Math.max(e,n.MIN_CASCADES_COUNT),n.MAX_CASCADES_COUNT),e!==this._numCascades&&(this._numCascades=e,this.recreateShadowMap(),this._recreateSceneUBOs())}get freezeShadowCastersBoundingInfo(){return this._freezeShadowCastersBoundingInfo}set freezeShadowCastersBoundingInfo(e){this._freezeShadowCastersBoundingInfoObservable&&e&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),!this._freezeShadowCastersBoundingInfoObservable&&!e&&(this._freezeShadowCastersBoundingInfoObservable=this._scene.onBeforeRenderObservable.add(()=>this._computeShadowCastersBoundingInfo())),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){let e=this._shadowMap.renderList;for(let t=0;t<e.length;t++){let i=e[t];if(!i)continue;let r=i.getBoundingInfo(),s=r.boundingBox;this._scbiMin.minimizeInPlace(s.minimumWorld),this._scbiMax.maximizeInPlace(s.maximumWorld)}}this._shadowCastersBoundingInfo.reConstruct(this._scbiMin,this._scbiMax)}get shadowCastersBoundingInfo(){return this._shadowCastersBoundingInfo}set shadowCastersBoundingInfo(e){this._shadowCastersBoundingInfo=e}setMinMaxDistance(e,t){this._minDistance===e&&this._maxDistance===t||(e>t&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return n.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e<this._numCascades?this._cascadeMinExtents[e]:null}getCascadeMaxExtents(e){return e>=0&&e<this._numCascades?this._cascadeMaxExtents[e]:null}get shadowMaxZ(){return this._getCamera()?this._shadowMaxZ:0}set shadowMaxZ(e){let t=this._getCamera();if(!t){this._shadowMaxZ=e;return}this._shadowMaxZ===e||e<t.minZ||e>t.maxZ&&t.maxZ!==0||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){let t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e<this._numCascades?this._viewMatrices[e]:null}getCascadeProjectionMatrix(e){return e>=0&&e<this._numCascades?this._projectionMatrices[e]:null}getCascadeTransformMatrix(e){return e>=0&&e<this._numCascades?this._transformMatrices[e]:null}setDepthRenderer(e){this._depthRenderer=e,this._depthReducer&&this._depthReducer.setDepthRenderer(this._depthRenderer)}get autoCalcDepthBounds(){return this._autoCalcDepthBounds}set autoCalcDepthBounds(e){let t=this._getCamera();if(t){if(this._autoCalcDepthBounds=e,!e){this._depthReducer&&this._depthReducer.deactivate(),this.setMinMaxDistance(0,1);return}this._depthReducer||(this._depthReducer=new FM(t),this._depthReducer.onAfterReductionPerformed.add(i=>{let r=i.min,s=i.max;r>=s&&(r=0,s=1),(r!=this._minDistance||s!=this._maxDistance)&&this.setMinMaxDistance(r,s)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t,i;return(i=(t=(e=this._depthReducer)==null?void 0:e.depthRenderer)==null?void 0:t.getDepthMap().refreshRate)!=null?i:-1}set autoCalcDepthBoundsRefreshRate(e){var t;(t=this._depthReducer)!=null&&t.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){let e=this._getCamera();if(!e)return;let t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,s=this._minDistance,a=this._shadowMaxZ<i&&this._shadowMaxZ>=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,o=t+s*r,l=t+a*r,c=l-o,f=l/o;for(let d=0;d<this._cascades.length;++d){let u=(d+1)/this._numCascades,h=o*f**u,m=o+c*u,g=this._lambda*(h-m)+m;this._cascades[d].prevBreakDistance=d===0?s:this._cascades[d-1].breakDistance,this._cascades[d].breakDistance=(g-t)/r,this._viewSpaceFrustumsZ[d]=g,this._frustumLengths[d]=(this._cascades[d].breakDistance-this._cascades[d].prevBreakDistance)*r}this._breaksAreDirty=!1}_computeMatrices(){let e=this._scene;if(!this._getCamera())return;b.NormalizeToRef(this._light.getShadowDirection(0),this._lightDirection),Math.abs(b.Dot(this._lightDirection,b.Up()))===1&&(this._lightDirection.z=1e-13),this._cachedDirection.copyFrom(this._lightDirection);let i=e.getEngine().useReverseDepthBuffer;for(let r=0;r<this._numCascades;++r){this._computeFrustumInWorldSpace(r),this._computeCascadeFrustum(r),this._cascadeMaxExtents[r].subtractToRef(this._cascadeMinExtents[r],Fr),this._frustumCenter[r].addToRef(this._lightDirection.scale(this._cascadeMinExtents[r].z),this._shadowCameraPos[r]),Q.LookAtLHToRef(this._shadowCameraPos[r],this._frustumCenter[r],a9,this._viewMatrices[r]);let s=0,a=Fr.z,o=this._shadowCastersBoundingInfo;o.update(this._viewMatrices[r]);let l=o.boundingBox.minimumWorld.z,c=o.boundingBox.maximumWorld.z;l>a||(!this._depthClamp||this.filter===zi.FILTER_PCSS?(s=Math.min(s,l),this.filter!==zi.FILTER_PCSS&&(a=Math.min(a,c))):(a=Math.min(a,c),s=Math.max(s,l),a=Math.max(s+1,a))),Q.OrthoOffCenterLHToRef(this._cascadeMinExtents[r].x,this._cascadeMaxExtents[r].x,this._cascadeMinExtents[r].y,this._cascadeMaxExtents[r].y,i?a:s,i?s:a,this._projectionMatrices[r],e.getEngine().isNDCHalfZRange),this._cascadeMinExtents[r].z=s,this._cascadeMaxExtents[r].z=a,this._viewMatrices[r].multiplyToRef(this._projectionMatrices[r],this._transformMatrices[r]),b.TransformCoordinatesToRef(Yge,this._transformMatrices[r],Fr),Fr.scaleInPlace(this._mapSize/2),dg.copyFromFloats(Math.round(Fr.x),Math.round(Fr.y),Math.round(Fr.z)),dg.subtractInPlace(Fr).scaleInPlace(2/this._mapSize),Q.TranslationToRef(dg.x,dg.y,0,BM),this._projectionMatrices[r].multiplyToRef(BM,this._projectionMatrices[r]),this._viewMatrices[r].multiplyToRef(this._projectionMatrices[r],this._transformMatrices[r]),this._transformMatrices[r].copyToArray(this._transformMatricesAsArray,r*16)}}_computeFrustumInWorldSpace(e){let t=this._getCamera();if(!t)return;let i=this._cascades[e].prevBreakDistance,r=this._cascades[e].breakDistance,s=this._scene.getEngine().isNDCHalfZRange;t.getViewMatrix();let a=t.maxZ===0,o=t.maxZ;a&&(t.maxZ=this._shadowMaxZ,t.getProjectionMatrix(!0));let l=Q.Invert(t.getTransformationMatrix());a&&(t.maxZ=o,t.getProjectionMatrix(!0));let c=this._scene.getEngine().useReverseDepthBuffer?4:0;for(let f=0;f<n._FrustumCornersNdcSpace.length;++f)Fr.copyFrom(n._FrustumCornersNdcSpace[(f+c)%n._FrustumCornersNdcSpace.length]),s&&Fr.z===-1&&(Fr.z=0),b.TransformCoordinatesToRef(Fr,l,this._frustumCornersWorldSpace[e][f]);for(let f=0;f<n._FrustumCornersNdcSpace.length/2;++f)Fr.copyFrom(this._frustumCornersWorldSpace[e][f+4]).subtractInPlace(this._frustumCornersWorldSpace[e][f]),dg.copyFrom(Fr).scaleInPlace(i),Fr.scaleInPlace(r),Fr.addInPlace(this._frustumCornersWorldSpace[e][f]),this._frustumCornersWorldSpace[e][f+4].copyFrom(Fr),this._frustumCornersWorldSpace[e][f].addInPlace(dg)}_computeCascadeFrustum(e){if(this._cascadeMinExtents[e].copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cascadeMaxExtents[e].copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._frustumCenter[e].copyFromFloats(0,0,0),!!this._getCamera()){for(let i=0;i<this._frustumCornersWorldSpace[e].length;++i)this._frustumCenter[e].addInPlace(this._frustumCornersWorldSpace[e][i]);if(this._frustumCenter[e].scaleInPlace(1/this._frustumCornersWorldSpace[e].length),this.stabilizeCascades){let i=0;for(let r=0;r<this._frustumCornersWorldSpace[e].length;++r){let s=this._frustumCornersWorldSpace[e][r].subtractToRef(this._frustumCenter[e],Fr).length();i=Math.max(i,s)}i=Math.ceil(i*16)/16,this._cascadeMaxExtents[e].copyFromFloats(i,i,i),this._cascadeMinExtents[e].copyFromFloats(-i,-i,-i)}else{let i=this._frustumCenter[e];this._frustumCenter[e].addToRef(this._lightDirection,Fr),Q.LookAtLHToRef(i,Fr,a9,BM);for(let r=0;r<this._frustumCornersWorldSpace[e].length;++r)b.TransformCoordinatesToRef(this._frustumCornersWorldSpace[e][r],BM,Fr),this._cascadeMinExtents[e].minimizeInPlace(Fr),this._cascadeMaxExtents[e].maximizeInPlace(Fr)}}}_recreateSceneUBOs(){if(this._disposeSceneUBOs(),this._sceneUBOs)for(let e=0;e<this._numCascades;++e)this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light "${this._light.name}" cascade #${e})`,{forceMono:!0}))}static get IsSupported(){let e=Oe.LastCreatedEngine;return e?e._features.supportCSM:!1}constructor(e,t,i,r,s=!0){if(!n.IsSupported){te.Error("CascadedShadowMap is not supported by the current engine.");return}super(e,t,i,r,s),this.usePercentageCloserFiltering=!0}_initializeGenerator(){var e,t,i,r,s,a,o,l,c,f,d,u,h,m,g,p,_,v,E,S;this.penumbraDarkness=(e=this.penumbraDarkness)!=null?e:1,this._numCascades=(t=this._numCascades)!=null?t:n.DEFAULT_CASCADES_COUNT,this.stabilizeCascades=(i=this.stabilizeCascades)!=null?i:!1,this._freezeShadowCastersBoundingInfoObservable=(r=this._freezeShadowCastersBoundingInfoObservable)!=null?r:null,this.freezeShadowCastersBoundingInfo=(s=this.freezeShadowCastersBoundingInfo)!=null?s:!1,this._scbiMin=(a=this._scbiMin)!=null?a:new b(0,0,0),this._scbiMax=(o=this._scbiMax)!=null?o:new b(0,0,0),this._shadowCastersBoundingInfo=(l=this._shadowCastersBoundingInfo)!=null?l:new In(new b(0,0,0),new b(0,0,0)),this._breaksAreDirty=(c=this._breaksAreDirty)!=null?c:!0,this._minDistance=(f=this._minDistance)!=null?f:0,this._maxDistance=(d=this._maxDistance)!=null?d:1,this._currentLayer=(u=this._currentLayer)!=null?u:0,this._shadowMaxZ=(g=(m=this._shadowMaxZ)!=null?m:(h=this._getCamera())==null?void 0:h.maxZ)!=null?g:1e4,this._debug=(p=this._debug)!=null?p:!1,this._depthClamp=(_=this._depthClamp)!=null?_:!0,this._cascadeBlendPercentage=(v=this._cascadeBlendPercentage)!=null?v:.1,this._lambda=(E=this._lambda)!=null?E:.5,this._autoCalcDepthBounds=(S=this._autoCalcDepthBounds)!=null?S:!1,this._recreateSceneUBOs(),super._initializeGenerator()}_createTargetRenderTexture(){var i;let e=this._scene.getEngine();(i=this._shadowMap)==null||i.dispose();let t={width:this._mapSize,height:this._mapSize,layers:this.numCascades};this._shadowMap=new jr(this._light.name+"_CSMShadowMap",t,this._scene,!1,!0,this._textureType,!1,void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForCSMShadowGenerator-${this._light.name}`),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(super._initializeShadowMap(),this._shadowMap===null)return;this._transformMatricesAsArray=new Float32Array(this._numCascades*16),this._tempTransformMatricesAsArray=new Float32Array(this._numCascades*16),this._viewSpaceFrustumsZ=new Array(this._numCascades),this._frustumLengths=new Array(this._numCascades),this._lightSizeUVCorrection=new Array(this._numCascades*2),this._depthCorrection=new Array(this._numCascades),this._cascades=[],this._viewMatrices=[],this._projectionMatrices=[],this._transformMatrices=[],this._cascadeMinExtents=[],this._cascadeMaxExtents=[],this._frustumCenter=[],this._shadowCameraPos=[],this._frustumCornersWorldSpace=[];for(let t=0;t<this._numCascades;++t){this._cascades[t]={prevBreakDistance:0,breakDistance:0},this._viewMatrices[t]=Q.Zero(),this._projectionMatrices[t]=Q.Zero(),this._transformMatrices[t]=Q.Zero(),this._cascadeMinExtents[t]=new b,this._cascadeMaxExtents[t]=new b,this._frustumCenter[t]=new b,this._shadowCameraPos[t]=new b,this._frustumCornersWorldSpace[t]=new Array(n._FrustumCornersNdcSpace.length);for(let i=0;i<n._FrustumCornersNdcSpace.length;++i)this._frustumCornersWorldSpace[t][i]=new b}let e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.clear(),this._shadowMap.onBeforeRenderObservable.clear(),this._shadowMap.onBeforeRenderObservable.add(t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===zi.FILTER_PCF&&e.setColorWrite(!1),no.eyeAtCamera=!1,this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._enableGPUDebugMarkers&&((t=e._debugPushGroup)==null||t.call(e,`Cascaded shadow map generation for pass id ${e.currentRenderPassId}`)),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()}),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==zi.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);let i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;let s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),this.cascadeBlendPercentage===0&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera();if(!s)return;let a=this.getShadowMap();if(!a)return;let o=a.getSize().width,l=this._transformMatricesAsArray,c=r.floatingOriginMode?gz(this._scene.floatingOriginOffset,this._viewMatrices,this._projectionMatrices,this._numCascades,this._tempTransformMatricesAsArray):l;if(t.setMatrices("lightMatrix"+e,c),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,this.cascadeBlendPercentage===0?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===zi.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,a),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);else if(this._filter===zi.FILTER_PCSS){for(let f=0;f<this._numCascades;++f)this._lightSizeUVCorrection[f*2+0]=f===0?1:(this._cascadeMaxExtents[0].x-this._cascadeMinExtents[0].x)/(this._cascadeMaxExtents[f].x-this._cascadeMinExtents[f].x),this._lightSizeUVCorrection[f*2+1]=f===0?1:(this._cascadeMaxExtents[0].y-this._cascadeMinExtents[0].y)/(this._cascadeMaxExtents[f].y-this._cascadeMinExtents[f].y),this._depthCorrection[f]=f===0?1:(this._cascadeMaxExtents[f].z-this._cascadeMinExtents[f].z)/(this._cascadeMaxExtents[0].z-this._cascadeMinExtents[0].z);t.setDepthStencilTexture("shadowTexture"+e,a),t.setTexture("depthTexture"+e,a),t.setArray2("lightSizeUVCorrection"+e,this._lightSizeUVCorrection),t.setArray("depthCorrection"+e,this._depthCorrection),t.setFloat("penumbraDarkness"+e,this.penumbraDarkness),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/o,this._contactHardeningLightSizeUVRatio*o,this.frustumEdgeFalloff,e)}else t.setTexture("shadowTexture"+e,a),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e)}getTransformMatrix(){return this.getCascadeTransformMatrix(0)}dispose(){super.dispose(),this._freezeShadowCastersBoundingInfoObservable&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._depthReducer&&(this._depthReducer.dispose(),this._depthReducer=null)}serialize(){let e=super.serialize(),t=this.getShadowMap();if(!t)return e;if(e.numCascades=this._numCascades,e.debug=this._debug,e.stabilizeCascades=this.stabilizeCascades,e.lambda=this._lambda,e.cascadeBlendPercentage=this.cascadeBlendPercentage,e.depthClamp=this._depthClamp,e.autoCalcDepthBounds=this.autoCalcDepthBounds,e.shadowMaxZ=this._shadowMaxZ,e.penumbraDarkness=this.penumbraDarkness,e.freezeShadowCastersBoundingInfo=this._freezeShadowCastersBoundingInfo,e.minDistance=this.minDistance,e.maxDistance=this.maxDistance,e.renderList=[],t.renderList)for(let i=0;i<t.renderList.length;i++){let r=t.renderList[i];e.renderList.push(r.id)}return e}static Parse(e,t){let i=zi.Parse(e,t,(r,s,a)=>new n(r,s,void 0,a));return e.numCascades!==void 0&&(i.numCascades=e.numCascades),e.debug!==void 0&&(i.debug=e.debug),e.stabilizeCascades!==void 0&&(i.stabilizeCascades=e.stabilizeCascades),e.lambda!==void 0&&(i.lambda=e.lambda),e.cascadeBlendPercentage!==void 0&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),e.depthClamp!==void 0&&(i.depthClamp=e.depthClamp),e.autoCalcDepthBounds!==void 0&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),e.shadowMaxZ!==void 0&&(i.shadowMaxZ=e.shadowMaxZ),e.penumbraDarkness!==void 0&&(i.penumbraDarkness=e.penumbraDarkness),e.freezeShadowCastersBoundingInfo!==void 0&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),e.minDistance!==void 0&&e.maxDistance!==void 0&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}};rl._FrustumCornersNdcSpace=[new b(-1,1,-1),new b(1,1,-1),new b(1,-1,-1),new b(-1,-1,-1),new b(-1,1,1),new b(1,1,1),new b(1,-1,1),new b(-1,-1,1)];rl.CLASSNAME="CascadedShadowGenerator";rl.DEFAULT_CASCADES_COUNT=4;rl.MIN_CASCADES_COUNT=2;rl.MAX_CASCADES_COUNT=4;rl._SceneComponentInitialization=n=>{throw $e("ShadowGeneratorSceneComponent")}});function UM(n,e){Kge[n]=e}var Kge,JN=y(()=>{Kge={}});var ew,l9=y(()=>{OM();o9();Sp();JN();UM(tt.NAME_SHADOWGENERATOR,(n,e)=>{if(n.shadowGenerators!==void 0&&n.shadowGenerators!==null)for(let t=0,i=n.shadowGenerators.length;t<i;t++){let r=n.shadowGenerators[t];r.className===rl.CLASSNAME?rl.Parse(r,e):zi.Parse(r,e)}});ew=class{constructor(e){this.name=tt.NAME_SHADOWGENERATOR,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(tt.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR,this,this._gatherRenderTargets)}rebuild(){}serialize(e){e.shadowGenerators=[];let t=this.scene.lights;for(let i of t){if(i.doNotSerialize)continue;let r=i.getShadowGenerators();if(r){let s=r.values();for(let a=s.next();a.done!==!0;a=s.next()){let o=a.value;o.doNotSerialize||e.shadowGenerators.push(o.serialize())}}}}addFromContainer(e){}removeFromContainer(e,t){}dispose(){}_gatherRenderTargets(e){let t=this.scene;if(this.scene.shadowsEnabled)for(let i=0;i<t.lights.length;i++){let r=t.lights[i],s=r.getShadowGenerators();if(r.isEnabled()&&r.shadowEnabled&&s){let a=s.values();for(let o=a.next();o.done!==!0;o=a.next()){let c=o.value.getShadowMap();t.textures.indexOf(c)!==-1&&e.push(c)}}}}};zi._SceneComponentInitialization=n=>{let e=n._getComponent(tt.NAME_SHADOWGENERATOR);e||(e=new ew(n),n._addComponent(e))}});async function c9(n,e){let t=e.method||"GET";return await new Promise((i,r)=>{let s=new Ur;s.addEventListener("readystatechange",()=>{if(s.readyState==4)if(s.status==200){let a={};if(e.responseHeaders)for(let o of e.responseHeaders)a[o]=s.getResponseHeader(o)||"";i({response:s.response,headerValues:a})}else r(`Unable to fetch data from ${n}. Error code: ${s.status}`)}),s.open(t,n),s.send()})}var f9=y(()=>{Wu()});function jge(n){return!!n.createPlugin}function Zge(n){return!!n.name}function VM(){return Zl[".babylon"]}function qge(n){for(let e in Zl){let t=Zl[e];if(t.mimeType===n)return t}}function iw(n,e){let t=Zl[n];return t||(te.Warn("Unable to find a plugin to load "+n+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),e?VM():void 0)}function Qge(n){return!!Zl[n]}function $ge(n){for(let e in Zl){let t=Zl[e].plugin;if(t.canDirectLoad&&t.canDirectLoad(n))return Zl[e]}return VM()}function Jge(n){let e=n.indexOf("?");e!==-1&&(n=n.substring(0,e));let t=n.lastIndexOf(".");return n.substring(t,n.length).toLowerCase()}function e_e(n){return n.substring(0,5)==="data:"?n.substring(5):null}function rw(n,e,t){let r="Unable to load from "+(n.rawData?"binary data":n.url);return e?r+=`: ${e}`:t&&(r+=`: ${t}`),r}async function nw(n,e,t,i,r,s,a,o,l){var h;let c=e_e(n.url);if(n.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";let f=!c&&!a?Jge(n.url):"",d=a?iw(a,!0):c?$ge(n.url):iw(f,!1);if(!d&&f){if(n.url&&!n.url.startsWith("blob:")){let m=await c9(n.url,{method:"HEAD",responseHeaders:["Content-Type"]}),g=m.headerValues?m.headerValues["Content-Type"]:"";g&&(d=qge(g))}d||(d=VM())}if(!d)throw new Error(`No plugin or fallback for ${a!=null?a:n.url}`);if(((h=l==null?void 0:l[d.plugin.name])==null?void 0:h.enabled)===!1)throw new Error(`The '${d.plugin.name}' plugin is disabled via the loader options passed to the loading operation.`);if(n.rawData&&!d.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";return(m=>{if(jge(d.plugin)){let p=d.plugin.createPlugin(l!=null?l:{});return p instanceof Promise?(p.then(m).catch(_=>{r("Error instantiating plugin.",_)}),null):(m(p),p)}else return m(d.plugin),d.plugin})(m=>{var A;if(!m)throw`The loader plugin corresponding to the '${a}' file type has not been found. If using es6, please import the plugin you wish to use before.`;if(u9.notifyObservers(m),c&&(m.canDirectLoad&&m.canDirectLoad(n.url)||!Jf(n.url))){if(m.directLoad){let R=m.directLoad(e,c);R instanceof Promise?R.then(M=>{t(m,M)}).catch(M=>{r("Error in directLoad of _loadData: "+M,M)}):t(m,R)}else t(m,c);return}let g=d.isBinary,p=(R,M)=>{if(e.isDisposed){r("Scene has been disposed");return}t(m,R,M)},_=null,v=!1;(A=m.onDisposeObservable)==null||A.add(()=>{v=!0,_&&(_.abort(),_=null),s()});let E=()=>{if(v)return;let R=(M,I)=>{r(M==null?void 0:M.statusText,I)};if(!m.loadFile&&n.rawData)throw"Plugin does not support loading ArrayBufferView.";_=m.loadFile?m.loadFile(e,n.rawData||n.file||n.url,n.rootUrl,p,i,g,R,o):e._loadFile(n.file||n.url,p,i,!0,g,R)},S=e.getEngine(),T=S.enableOfflineSupport;if(T){let R=!1;for(let M of e.disableOfflineSupportExceptionRules)if(M.test(n.url)){R=!0;break}T=!R}T&&ye.OfflineProviderFactory?e.offlineProvider=ye.OfflineProviderFactory(n.url,E,S.disableManifestCheck):E()})}function sw(n,e){let t,i,r=null,s=null;if(!e)t=n,i=pe.GetFilename(n),n=pe.GetFolderPath(n);else if(Zge(e))t=`file:${e.name}`,i=e.name,r=e;else if(ArrayBuffer.isView(e))t="",i=Qf(),s=e;else if(e.startsWith("data:"))t=e,i="";else if(n){let a=e;if(a.substring(0,1)==="/")return pe.Error("Wrong sceneFilename parameter"),null;t=n+a,i=a}else t=e,i=pe.GetFilename(e),n=pe.GetFolderPath(e);return{url:t,rootUrl:n,name:i,file:r,rawData:s}}function Fd(n){if(typeof n.extensions=="string"){let e=n.extensions;Zl[e.toLowerCase()]={plugin:n,isBinary:!1}}else{let e=n.extensions,t=Object.keys(e);for(let i of t)Zl[i.toLowerCase()]={plugin:n,isBinary:e[i].isBinary,mimeType:e[i].mimeType}}}async function TE(n,e,t){let{meshNames:i,rootUrl:r="",onProgress:s,pluginExtension:a,name:o,pluginOptions:l}=t!=null?t:{};return await m9(i,r,n,e,s,a,o,l)}async function h9(n,e,t="",i=Oe.LastCreatedScene,r=null,s=null,a=null,o=null,l="",c={}){if(!i)return te.Error("No scene available to import mesh to"),null;let f=sw(e,t);if(!f)return null;let d={};i.addPendingData(d);let u=()=>{i.removePendingData(d)},h=(p,_)=>{let v=rw(f,p,_);a?a(i,v,new ra(v,$a.SceneLoaderError,_)):te.Error(v),u()},m=s?p=>{try{s(p)}catch(_){h("Error in onProgress callback: "+_,_)}}:void 0,g=(p,_,v,E,S,T,A,R)=>{if(i.importedMeshesFiles.push(f.url),r)try{r(p,_,v,E,S,T,A,R)}catch(M){h("Error in onSuccess callback: "+M,M)}i.removePendingData(d)};return await nw(f,i,(p,_,v)=>{if(p.rewriteRootURL&&(f.rootUrl=p.rewriteRootURL(f.rootUrl,v)),p.importMesh){let E=p,S=[],T=[],A=[];if(!E.importMesh(n,i,_,f.rootUrl,S,T,A,h))return;i.loadingPluginName=p.name,g(S,T,A,[],[],[],[],[])}else p.importMeshAsync(n,i,_,f.rootUrl,m,f.name).then(S=>{i.loadingPluginName=p.name,g(S.meshes,S.particleSystems,S.skeletons,S.animationGroups,S.transformNodes,S.geometries,S.lights,S.spriteManagers)}).catch(S=>{h(S.message,S)})},m,h,u,o,l,c)}async function m9(n,e,t,i,r,s,a,o){return await new Promise((l,c)=>{try{h9(n,e,t,i,(f,d,u,h,m,g,p,_)=>{l({meshes:f,particleSystems:d,skeletons:u,animationGroups:h,transformNodes:m,geometries:g,lights:p,spriteManagers:_})},r,(f,d,u)=>{c(u||new Error(d))},s,a,o).catch(c)}catch(f){c(f)}})}async function p9(n,e="",t=Oe.LastCreatedEngine,i=null,r=null,s=null,a=null,o="",l={}){if(!t){pe.Error("No engine available");return}await aw(n,e,new ai(t),i,r,s,a,o,l)}async function t_e(n,e,t,i,r,s,a){return await new Promise((o,l)=>{p9(n,e,t,c=>{o(c)},i,(c,f,d)=>{l(d||new Error(f))},r,s,a)})}async function aw(n,e="",t=Oe.LastCreatedScene,i=null,r=null,s=null,a=null,o="",l={}){if(!t)return te.Error("No scene available to append to"),null;let c=sw(n,e);if(!c)return null;let f={};t.addPendingData(f);let d=()=>{t.removePendingData(f)};an.ShowLoadingScreen&&!tw&&(tw=!0,t.getEngine().displayLoadingUI(),t.executeWhenReady(()=>{t.getEngine().hideLoadingUI(),tw=!1}));let u=(g,p)=>{let _=rw(c,g,p);s?s(t,_,new ra(_,$a.SceneLoaderError,p)):te.Error(_),d()},h=r?g=>{try{r(g)}catch(p){u("Error in onProgress callback",p)}}:void 0,m=()=>{if(i)try{i(t)}catch(g){u("Error in onSuccess callback",g)}t.removePendingData(f)};return await nw(c,t,(g,p)=>{if(g.load){if(!g.load(t,p,c.rootUrl,u))return;t.loadingPluginName=g.name,m()}else g.loadAsync(t,p,c.rootUrl,h,c.name).then(()=>{t.loadingPluginName=g.name,m()}).catch(v=>{u(v.message,v)})},h,u,d,a,o,l)}async function i_e(n,e,t,i,r,s,a){return await new Promise((o,l)=>{try{aw(n,e,t,c=>{o(c)},i,(c,f,d)=>{l(d||new Error(f))},r,s,a).catch(l)}catch(c){l(c)}})}async function ow(n,e="",t=Oe.LastCreatedScene,i=null,r=null,s=null,a=null,o="",l={}){if(!t)return te.Error("No scene available to load asset container to"),null;let c=sw(n,e);if(!c)return null;let f={};t.addPendingData(f);let d=()=>{t.removePendingData(f)},u=(g,p)=>{let _=rw(c,g,p);s?s(t,_,new ra(_,$a.SceneLoaderError,p)):te.Error(_),d()},h=r?g=>{try{r(g)}catch(p){u("Error in onProgress callback",p)}}:void 0,m=g=>{if(i)try{i(g)}catch(p){u("Error in onSuccess callback",p)}t.removePendingData(f)};return await nw(c,t,(g,p)=>{if(g.loadAssetContainer){let v=g.loadAssetContainer(t,p,c.rootUrl,u);if(!v)return;v.populateRootNodes(),t.loadingPluginName=g.name,m(v)}else g.loadAssetContainerAsync?g.loadAssetContainerAsync(t,p,c.rootUrl,h,c.name).then(v=>{v.populateRootNodes(),t.loadingPluginName=g.name,m(v)}).catch(v=>{u(v.message,v)}):u("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},h,u,d,a,o,l)}async function r_e(n,e,t,i,r,s,a){return await new Promise((o,l)=>{try{ow(n,e,t,c=>{o(c)},i,(c,f,d)=>{l(d||new Error(f))},r,s,a).catch(l)}catch(c){l(c)}})}async function g9(n,e="",t=Oe.LastCreatedScene,i=!0,r=0,s=null,a=null,o=null,l=null,c=null,f="",d={}){if(!t){te.Error("No scene available to load animations to");return}if(i){for(let p of t.animatables)p.reset();t.stopAllAnimations();let m=t.animationGroups.slice();for(let p of m)p.dispose();let g=t.getNodes();for(let p of g)p.animations&&(p.animations=[])}else switch(r){case 0:let m=t.animationGroups.slice();for(let g of m)g.dispose();break;case 1:for(let g of t.animationGroups)g.stop();break;case 2:for(let g of t.animationGroups)g.reset(),g.restart();break;case 3:break;default:te.Error("Unknown animation group loading mode value '"+r+"'");return}let u=t.animatables.length;await ow(n,e,t,m=>{m.mergeAnimationsTo(t,t.animatables.slice(u),s),m.dispose(),t.onAnimationFileImportedObservable.notifyObservers(t),a&&a(t)},o,l,c,f,d)}async function n_e(n,e,t,i,r,s,a,o,l,c){return await new Promise((f,d)=>{try{g9(n,e,t,i,r,s,u=>{f(u)},a,(u,h,m)=>{d(m||new Error(h))},o,l,c).catch(d)}catch(u){d(u)}})}var d9,u9,Zl,tw,dh,ug=y(()=>{Gi();Si();na();Yi();wt();ob();Cc();Tv();Sv();Yr();f9();(function(n){n[n.Clean=0]="Clean",n[n.Stop=1]="Stop",n[n.Sync=2]="Sync",n[n.NoSync=3]="NoSync"})(d9||(d9={}));u9=new re,Zl={},tw=!1;dh=class{static get ForceFullSceneLoadingForIncremental(){return an.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){an.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return an.ShowLoadingScreen}static set ShowLoadingScreen(e){an.ShowLoadingScreen=e}static get loggingLevel(){return an.loggingLevel}static set loggingLevel(e){an.loggingLevel=e}static get CleanBoneMatrixWeights(){return an.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){an.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return VM()}static GetPluginForExtension(e){var t;return(t=iw(e,!0))==null?void 0:t.plugin}static IsPluginForExtensionAvailable(e){return Qge(e)}static RegisterPlugin(e){Fd(e)}static ImportMesh(e,t,i,r,s,a,o,l,c,f){h9(e,t,i,r,s,a,o,l,c,f).catch(d=>o==null?void 0:o(Oe.LastCreatedScene,d==null?void 0:d.message,d))}static async ImportMeshAsync(e,t,i,r,s,a,o){return await m9(e,t,i,r,s,a,o)}static Load(e,t,i,r,s,a,o,l){p9(e,t,i,r,s,a,o,l).catch(c=>a==null?void 0:a(Oe.LastCreatedScene,c==null?void 0:c.message,c))}static async LoadAsync(e,t,i,r,s,a){return await t_e(e,t,i,r,s,a)}static Append(e,t,i,r,s,a,o,l){aw(e,t,i,r,s,a,o,l).catch(c=>a==null?void 0:a(i!=null?i:Oe.LastCreatedScene,c==null?void 0:c.message,c))}static async AppendAsync(e,t,i,r,s,a){return await i_e(e,t,i,r,s,a)}static LoadAssetContainer(e,t,i,r,s,a,o,l){ow(e,t,i,r,s,a,o,l).catch(c=>a==null?void 0:a(i!=null?i:Oe.LastCreatedScene,c==null?void 0:c.message,c))}static async LoadAssetContainerAsync(e,t,i,r,s,a){return await r_e(e,t,i,r,s,a)}static ImportAnimations(e,t,i,r,s,a,o,l,c,f,d){g9(e,t,i,r,s,a,o,l,c,f,d).catch(u=>c==null?void 0:c(i!=null?i:Oe.LastCreatedScene,u==null?void 0:u.message,u))}static async ImportAnimationsAsync(e,t,i,r,s,a,o,l,c,f,d){return await n_e(e,t,i,r,s,a,l,f,d)}};dh.NO_LOGGING=0;dh.MINIMAL_LOGGING=1;dh.SUMMARY_LOGGING=2;dh.DETAILED_LOGGING=3;dh.OnPluginActivatedObservable=u9});var GM,lw,cw,ql,AE=y(()=>{ki();cd();Pp();wt();Yi();yO();Ed();zl();Gi();td();GM=class{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.sounds=null,this.effectLayers=[],this.layers=[],this.reflectionProbes=[],this.spriteManagers=[]}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes);for(let t of this.skeletons)e=e.concat(t.bones);return e}},lw=class extends GM{},cw=class{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){let e=this.rootNodes;for(let r of e)r.dispose();e.length=0;let t=this.skeletons;for(let r of t)r.dispose();t.length=0;let i=this.animationGroups;for(let r of i)r.dispose();i.length=0}},ql=class extends GM{constructor(e){super(),this._wasAddedToScene=!1,e=e||Oe.LastCreatedScene,e&&(this.scene=e,this.proceduralTextures=[],e.onDisposeObservable.add(()=>{this._wasAddedToScene||this.dispose()}),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{for(let t of this.geometries)t._rebuild();for(let t of this.meshes)t._rebuild();for(let t of this.particleSystems)t.rebuild();for(let t of this.textures)t._rebuild();for(let t of this.spriteManagers)t.rebuild()}))}_topologicalSort(e){let t=new Map;for(let o of e)t.set(o.uniqueId,o);let i={dependsOn:new Map,dependedBy:new Map};for(let o of e){let l=o.uniqueId;i.dependsOn.set(l,new Set),i.dependedBy.set(l,new Set)}for(let o of e){let l=o.uniqueId,c=i.dependsOn.get(l);if(o instanceof zc){let d=o.sourceMesh;t.has(d.uniqueId)&&(c.add(d.uniqueId),i.dependedBy.get(d.uniqueId).add(l))}let f=i.dependedBy.get(l);for(let d of o.getDescendants()){let u=d.uniqueId;t.has(u)&&(f.add(u),i.dependsOn.get(u).add(l))}}let r=[],s=[];for(let o of e){let l=o.uniqueId;i.dependsOn.get(l).size===0&&(s.push(o),t.delete(l))}let a=s;for(;a.length>0;){let o=a.shift();r.push(o);let l=i.dependedBy.get(o.uniqueId);for(let c of Array.from(l.values())){let f=i.dependsOn.get(c);f.delete(o.uniqueId),f.size===0&&t.get(c)&&(a.push(t.get(c)),t.delete(c))}}return t.size>0&&(te.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(o=>{te.Error(o.name)})),r}_addNodeAndDescendantsToList(e,t,i,r){if(!(!i||r&&!r(i)||t.has(i.uniqueId))){e.push(i),t.add(i.uniqueId);for(let s of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,s,r)}}_isNodeInContainer(e){return e instanceof Ir&&this.meshes.indexOf(e)!==-1||e instanceof ii&&this.transformNodes.indexOf(e)!==-1||e instanceof Jt&&this.lights.indexOf(e)!==-1||e instanceof Et&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(let e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return te.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return te.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return te.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return te.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||pe.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");let r={},s={},a=new cw,o=[],l=[],c={doNotInstantiate:!0,...i},f=(g,p)=>{if(r[g.uniqueId]=p.uniqueId,s[p.uniqueId]=p,e&&(p.name=e(g.name)),p instanceof $){let _=p;if(_.morphTargetManager){let v=g.morphTargetManager;_.morphTargetManager=v.clone();for(let E=0;E<v.numTargets;E++){let S=v.getTarget(E),T=_.morphTargetManager.getTarget(E);r[S.uniqueId]=T.uniqueId,s[T.uniqueId]=T}}}},d=[],u=new Set;for(let g of this.transformNodes)g.parent===null&&this._addNodeAndDescendantsToList(d,u,g,c.predicate);for(let g of this.meshes)g.parent===null&&this._addNodeAndDescendantsToList(d,u,g,c.predicate);let h=this._topologicalSort(d),m=(g,p)=>{if(f(g,p),g.parent){let _=r[g.parent.uniqueId],v=s[_];v?p.parent=v:p.parent=g.parent}if(p.position&&g.position&&p.position.copyFrom(g.position),p.rotationQuaternion&&g.rotationQuaternion&&p.rotationQuaternion.copyFrom(g.rotationQuaternion),p.rotation&&g.rotation&&p.rotation.copyFrom(g.rotation),p.scaling&&g.scaling&&p.scaling.copyFrom(g.scaling),p.material){let _=p;if(_.material)if(t){let v=g.material;if(l.indexOf(v)===-1){let E=v.clone(e?e(v.name):"Clone of "+v.name);if(l.push(v),r[v.uniqueId]=E.uniqueId,s[E.uniqueId]=E,v.getClassName()==="MultiMaterial"){let S=v;for(let T of S.subMaterials)T&&(E=T.clone(e?e(T.name):"Clone of "+T.name),l.push(T),r[T.uniqueId]=E.uniqueId,s[E.uniqueId]=E);S.subMaterials=S.subMaterials.map(T=>T&&s[r[T.uniqueId]])}}_.getClassName()!=="InstancedMesh"&&(_.material=s[r[v.uniqueId]])}else _.material.getClassName()==="MultiMaterial"?this.scene.multiMaterials.indexOf(_.material)===-1&&this.scene.addMultiMaterial(_.material):this.scene.materials.indexOf(_.material)===-1&&this.scene.addMaterial(_.material)}p.parent===null&&a.rootNodes.push(p)};for(let g of h)if(g.getClassName()==="InstancedMesh"){let p=g,_=p.sourceMesh,v=r[_.uniqueId],S=(typeof v=="number"?s[v]:_).createInstance(p.name);m(p,S)}else{let p=!0;g.getClassName()==="TransformNode"||g.getClassName()==="Node"||g.skeleton||!g.getTotalVertices||g.getTotalVertices()===0?p=!1:c.doNotInstantiate&&(typeof c.doNotInstantiate=="function"?p=!c.doNotInstantiate(g):p=!c.doNotInstantiate);let _=p?g.createInstance(`instance of ${g.name}`):g.clone(`Clone of ${g.name}`,null,!0);if(!_)throw new Error(`Could not clone or instantiate node on Asset Container ${g.name}`);m(g,_)}for(let g of this.skeletons){if(c.predicate&&!c.predicate(g))continue;let p=g.clone(e?e(g.name):"Clone of "+g.name);for(let _ of this.meshes)if(_.skeleton===g&&!_.isAnInstance){let v=s[r[_.uniqueId]];if(!v||v.isAnInstance||(v.skeleton=p,o.indexOf(p)!==-1))continue;o.push(p);for(let E of p.bones)E._linkedTransformNode&&(E._linkedTransformNode=s[r[E._linkedTransformNode.uniqueId]])}a.skeletons.push(p)}for(let g of this.animationGroups){if(c.predicate&&!c.predicate(g))continue;let p=g.clone(e?e(g.name):"Clone of "+g.name,_=>s[r[_.uniqueId]]||_);a.animationGroups.push(p)}return a}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||pe.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(let e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){let t=[];for(let i of this.cameras)e&&!e(i)||(this.scene.addCamera(i),t.push(i));for(let i of this.lights)e&&!e(i)||(this.scene.addLight(i),t.push(i));for(let i of this.meshes)e&&!e(i)||(this.scene.addMesh(i),t.push(i));for(let i of this.skeletons)e&&!e(i)||this.scene.addSkeleton(i);for(let i of this.animations)e&&!e(i)||this.scene.addAnimation(i);for(let i of this.animationGroups)e&&!e(i)||this.scene.addAnimationGroup(i);for(let i of this.multiMaterials)e&&!e(i)||this.scene.addMultiMaterial(i);for(let i of this.materials)e&&!e(i)||this.scene.addMaterial(i);for(let i of this.morphTargetManagers)e&&!e(i)||this.scene.addMorphTargetManager(i);for(let i of this.geometries)e&&!e(i)||this.scene.addGeometry(i);for(let i of this.transformNodes)e&&!e(i)||(this.scene.addTransformNode(i),t.push(i));for(let i of this.actionManagers)e&&!e(i)||this.scene.addActionManager(i);for(let i of this.textures)e&&!e(i)||this.scene.addTexture(i);for(let i of this.reflectionProbes)e&&!e(i)||this.scene.addReflectionProbe(i);for(let i of this.spriteManagers)e&&!e(i)||(this.scene.spriteManagers||(this.scene.spriteManagers=[]),this.scene.spriteManagers.push(i));if(t.length){let i=new Set(this.scene.meshes);for(let r of this.scene.lights)i.add(r);for(let r of this.scene.cameras)i.add(r);for(let r of this.scene.transformNodes)i.add(r);for(let r of this.skeletons)for(let s of r.bones)i.add(s);for(let r of t)r.parent&&!i.has(r.parent)&&(r.setParent?r.setParent(null):r.parent=null)}}removeAllFromScene(){this._isValidHierarchy()||pe.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(let e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){for(let t of this.cameras)e&&!e(t)||this.scene.removeCamera(t);for(let t of this.lights)e&&!e(t)||this.scene.removeLight(t);for(let t of this.meshes)e&&!e(t)||this.scene.removeMesh(t,!0);for(let t of this.skeletons)e&&!e(t)||this.scene.removeSkeleton(t);for(let t of this.animations)e&&!e(t)||this.scene.removeAnimation(t);for(let t of this.animationGroups)e&&!e(t)||this.scene.removeAnimationGroup(t);for(let t of this.multiMaterials)e&&!e(t)||this.scene.removeMultiMaterial(t);for(let t of this.materials)e&&!e(t)||this.scene.removeMaterial(t);for(let t of this.morphTargetManagers)e&&!e(t)||this.scene.removeMorphTargetManager(t);for(let t of this.geometries)e&&!e(t)||this.scene.removeGeometry(t);for(let t of this.transformNodes)e&&!e(t)||this.scene.removeTransformNode(t);for(let t of this.actionManagers)e&&!e(t)||this.scene.removeActionManager(t);for(let t of this.textures)e&&!e(t)||this.scene.removeTexture(t);for(let t of this.reflectionProbes)e&&!e(t)||this.scene.removeReflectionProbe(t);for(let t of this.spriteManagers)if(!(e&&!e(t))&&this.scene.spriteManagers){let i=this.scene.spriteManagers.indexOf(t);i!==-1&&this.scene.spriteManagers.splice(i,1)}}dispose(){let e=this.cameras.slice(0);for(let g of e)g.dispose();this.cameras.length=0;let t=this.lights.slice(0);for(let g of t)g.dispose();this.lights.length=0;let i=this.meshes.slice(0);for(let g of i)g.dispose();this.meshes.length=0;let r=this.skeletons.slice(0);for(let g of r)g.dispose();this.skeletons.length=0;let s=this.animationGroups.slice(0);for(let g of s)g.dispose();this.animationGroups.length=0;let a=this.multiMaterials.slice(0);for(let g of a)g.dispose();this.multiMaterials.length=0;let o=this.materials.slice(0);for(let g of o)g.dispose();this.materials.length=0;let l=this.geometries.slice(0);for(let g of l)g.dispose();this.geometries.length=0;let c=this.transformNodes.slice(0);for(let g of c)g.dispose();this.transformNodes.length=0;let f=this.actionManagers.slice(0);for(let g of f)g.dispose();this.actionManagers.length=0;let d=this.textures.slice(0);for(let g of d)g.dispose();this.textures.length=0;let u=this.reflectionProbes.slice(0);for(let g of u)g.dispose();this.reflectionProbes.length=0;let h=this.morphTargetManagers.slice(0);for(let g of h)g.dispose();this.morphTargetManagers.length=0;let m=this.spriteManagers.slice(0);for(let g of m)g.dispose();this.spriteManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(let g of this.scene._serializableComponents)g.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(!(!e||!t))for(let r of e){let s=!0;if(i){for(let a of i)if(r===a){s=!1;break}}s&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,e===void 0&&(e=new lw);for(let t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||(t==="_environmentTexture"?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){let e=new $("assetContainerRootMesh",this.scene);for(let t of this.meshes)t.parent||e.addChild(t);return this.meshes.unshift(e),e}mergeAnimationsTo(e=Oe.LastCreatedScene,t,i=null){if(!e)return te.Error("No scene available to merge animations to"),[];let r=i||(l=>{let c,f=l.animations.length?l.animations[0].targetProperty:"",d=l.name.split(".").join("").split("_primitive")[0];switch(f){case"position":case"rotationQuaternion":c=e.getTransformNodeByName(l.name)||e.getTransformNodeByName(d);break;case"influence":c=e.getMorphTargetByName(l.name)||e.getMorphTargetByName(d);break;default:c=e.getNodeByName(l.name)||e.getNodeByName(d)}return c}),s=this.getNodes();for(let l of s){let c=r(l);if(c!==null){for(let f of l.animations){let d=c.animations.filter(u=>u.targetProperty===f.targetProperty);for(let u of d){let h=c.animations.indexOf(u,0);h>-1&&c.animations.splice(h,1)}}c.animations=c.animations.concat(l.animations)}}let a=[],o=this.animationGroups.slice();for(let l of o){a.push(l.clone(l.name,r));for(let c of l.animatables)c.stop()}for(let l of t){let c=r(l.target);c&&(e.beginAnimation(c,l.fromFrame,l.toFrame,l.loopAnimation,l.speedRatio,l.onAnimationEnd?l.onAnimationEnd:void 0,void 0,!0,void 0,l.onAnimationLoop?l.onAnimationLoop:void 0),e.stopAnimation(l.target))}return a}populateRootNodes(){this.rootNodes.length=0;for(let e of this.meshes)!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e);for(let e of this.transformNodes)!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e);for(let e of this.lights)!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e);for(let e of this.cameras)!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}addAllAssetsToContainer(e){if(!e)return;let t=[],i=new Set;for(t.push(e);t.length>0;){let r=t.pop();if(r instanceof $?(r.geometry&&this.geometries.indexOf(r.geometry)===-1&&this.geometries.push(r.geometry),this.meshes.push(r)):r instanceof zc?this.meshes.push(r):r instanceof ii?this.transformNodes.push(r):r instanceof Jt?this.lights.push(r):r instanceof Et&&this.cameras.push(r),r instanceof Ir){if(r.material&&this.materials.indexOf(r.material)===-1){this.materials.push(r.material);for(let s of r.material.getActiveTextures())this.textures.indexOf(s)===-1&&this.textures.push(s)}r.skeleton&&this.skeletons.indexOf(r.skeleton)===-1&&this.skeletons.push(r.skeleton),r.morphTargetManager&&this.morphTargetManagers.indexOf(r.morphTargetManager)===-1&&this.morphTargetManagers.push(r.morphTargetManager)}for(let s of r.getChildren())i.has(s)||t.push(s);i.add(r)}this.populateRootNodes()}_getByTags(e,t,i){if(t===void 0)return e;let r=[];for(let s in e){let a=e[s];ni&&ni.MatchesQuery(a,t)&&(!i||i(a))&&r.push(a)}return r}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialsByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}}});var uh,_9=y(()=>{Av();uh=class{constructor(e){this.byteOffset=0,this.buffer=e}async loadAsync(e){let t=await this.buffer.readAsync(this.byteOffset,e);this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._dataByteOffset=0}readUint32(){let e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){let t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return hk(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}});function fw(n,e,t,i){let r={externalResourceFunction:i};return t&&(r.uri=e==="file:"?t:e+t),ArrayBuffer.isView(n)?GLTFValidator.validateBytes(n,r):GLTFValidator.validateString(n,r)}function s_e(){let n=[];onmessage=e=>{let t=e.data;switch(t.id){case"init":{importScripts(t.url);break}case"validate":{fw(t.data,t.rootUrl,t.fileName,i=>new Promise((r,s)=>{let a=n.length;n.push({resolve:r,reject:s}),postMessage({id:"getExternalResource",index:a,uri:i})})).then(i=>{postMessage({id:"validate.resolve",value:i})},i=>{postMessage({id:"validate.reject",reason:i})});break}case"getExternalResource.resolve":{n[t.index].resolve(t.value);break}case"getExternalResource.reject":{n[t.index].reject(t.reason);break}}}}var hg,v9=y(()=>{Gi();hg=class n{static ValidateAsync(e,t,i,r){return typeof Worker=="function"?new Promise((s,a)=>{let o=`${fw}(${s_e})()`,l=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),c=new Worker(l),f=u=>{c.removeEventListener("error",f),c.removeEventListener("message",d),a(u)},d=u=>{let h=u.data;switch(h.id){case"getExternalResource":{r(h.uri).then(m=>{c.postMessage({id:"getExternalResource.resolve",index:h.index,value:m},[m.buffer])},m=>{c.postMessage({id:"getExternalResource.reject",index:h.index,reason:m})});break}case"validate.resolve":{c.removeEventListener("error",f),c.removeEventListener("message",d),n._LastResults=h.value,s(h.value),c.terminate();break}case"validate.reject":c.removeEventListener("error",f),c.removeEventListener("message",d),a(h.reason),c.terminate()}};if(c.addEventListener("error",f),c.addEventListener("message",d),c.postMessage({id:"init",url:pe.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){let u=e.slice();c.postMessage({id:"validate",data:u,rootUrl:t,fileName:i},[u.buffer])}else c.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})}):(this._LoadScriptPromise||(this._LoadScriptPromise=pe.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(()=>fw(e,t,i,r)))}};hg.Configuration={url:`${pe._DefaultCdnUrl}/gltf_validator.js`};hg._LastResults=null});var cf,xE,E9=y(()=>{cf="Z2xURg",xE={name:"gltf",extensions:{".gltf":{isBinary:!1,mimeType:"model/gltf+json"},".glb":{isBinary:!0,mimeType:"model/gltf-binary"}},canDirectLoad(n){return n.indexOf("asset")!==-1&&n.indexOf("version")!==-1||n.startsWith("data:base64,"+cf)||n.startsWith("data:;base64,"+cf)||n.startsWith("data:application/octet-stream;base64,"+cf)||n.startsWith("data:model/gltf-binary;base64,"+cf)}}});function S9(n,e,t){try{return Promise.resolve(new Uint8Array(n,e,t))}catch(i){return Promise.reject(i)}}function a_e(n,e,t){try{if(e<0||e>=n.byteLength)throw new RangeError("Offset is out of range.");if(e+t>n.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(n.buffer,n.byteOffset+e,t))}catch(i){return Promise.reject(i)}}var mg,hh,Ns,kM,o_e,dw,Bd,uw=y(()=>{Si();Gi();ug();AE();wt();_9();v9();E9();Cc();Tv();(function(n){n[n.AUTO=0]="AUTO",n[n.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"})(mg||(mg={}));(function(n){n[n.NONE=0]="NONE",n[n.FIRST=1]="FIRST",n[n.ALL=2]="ALL"})(hh||(hh={}));(function(n){n[n.LOADING=0]="LOADING",n[n.READY=1]="READY",n[n.COMPLETE=2]="COMPLETE"})(Ns||(Ns={}));kM=class{constructor(){this.alwaysComputeBoundingBox=!1,this.alwaysComputeSkeletonRootNode=!1,this.animationStartMode=hh.FIRST,this.compileMaterials=!1,this.compileShadowGenerators=!1,this.coordinateSystemMode=mg.AUTO,this.createInstances=!0,this.loadAllMaterials=!1,this.loadMorphTargets=!0,this.loadNodeAnimations=!0,this.loadOnlyMaterials=!1,this.loadSkins=!0,this.skipMaterials=!1,this.targetFps=60,this.transparencyAsCoverage=!1,this.useClipPlane=!1,this.useGltfTextureNames=!1,this.useRangeRequests=!1,this.useSRGBBuffers=!0,this.validate=!1,this.useOpenPBR=!1,this.dontUseTransmissionHelper=!1}},o_e=new kM,dw=class extends kM{constructor(){super(...arguments),this.extensionOptions={},this.preprocessUrlAsync=e=>Promise.resolve(e)}copyFrom(e){var t,i,r,s,a,o,l,c,f,d,u,h,m,g,p,_,v,E,S,T,A,R,M,I,C,L;e&&(this.alwaysComputeBoundingBox=(t=e.alwaysComputeBoundingBox)!=null?t:this.alwaysComputeBoundingBox,this.alwaysComputeSkeletonRootNode=(i=e.alwaysComputeSkeletonRootNode)!=null?i:this.alwaysComputeSkeletonRootNode,this.animationStartMode=(r=e.animationStartMode)!=null?r:this.animationStartMode,this.capturePerformanceCounters=(s=e.capturePerformanceCounters)!=null?s:this.capturePerformanceCounters,this.compileMaterials=(a=e.compileMaterials)!=null?a:this.compileMaterials,this.compileShadowGenerators=(o=e.compileShadowGenerators)!=null?o:this.compileShadowGenerators,this.coordinateSystemMode=(l=e.coordinateSystemMode)!=null?l:this.coordinateSystemMode,this.createInstances=(c=e.createInstances)!=null?c:this.createInstances,this.customRootNode=e.customRootNode,this.extensionOptions=(f=e.extensionOptions)!=null?f:this.extensionOptions,this.loadAllMaterials=(d=e.loadAllMaterials)!=null?d:this.loadAllMaterials,this.loadMorphTargets=(u=e.loadMorphTargets)!=null?u:this.loadMorphTargets,this.loadNodeAnimations=(h=e.loadNodeAnimations)!=null?h:this.loadNodeAnimations,this.loadOnlyMaterials=(m=e.loadOnlyMaterials)!=null?m:this.loadOnlyMaterials,this.loadSkins=(g=e.loadSkins)!=null?g:this.loadSkins,this.loggingEnabled=(p=e.loggingEnabled)!=null?p:this.loggingEnabled,this.onCameraLoaded=e.onCameraLoaded,this.onMaterialLoaded=e.onMaterialLoaded,this.onMeshLoaded=e.onMeshLoaded,this.onParsed=e.onParsed,this.onSkinLoaded=e.onSkinLoaded,this.onTextureLoaded=e.onTextureLoaded,this.onValidated=e.onValidated,this.preprocessUrlAsync=(_=e.preprocessUrlAsync)!=null?_:this.preprocessUrlAsync,this.skipMaterials=(v=e.skipMaterials)!=null?v:this.skipMaterials,this.targetFps=(E=e.targetFps)!=null?E:this.targetFps,this.transparencyAsCoverage=(S=e.transparencyAsCoverage)!=null?S:this.transparencyAsCoverage,this.useClipPlane=(T=e.useClipPlane)!=null?T:this.useClipPlane,this.useGltfTextureNames=(A=e.useGltfTextureNames)!=null?A:this.useGltfTextureNames,this.useOpenPBR=(R=e.useOpenPBR)!=null?R:this.useOpenPBR,this.useRangeRequests=(M=e.useRangeRequests)!=null?M:this.useRangeRequests,this.useSRGBBuffers=(I=e.useSRGBBuffers)!=null?I:this.useSRGBBuffers,this.validate=(C=e.validate)!=null?C:this.validate,this.dontUseTransmissionHelper=(L=e.dontUseTransmissionHelper)!=null?L:this.dontUseTransmissionHelper)}},Bd=class n extends dw{constructor(e){super(),this.onParsedObservable=new re,this.onMeshLoadedObservable=new re,this.onSkinLoadedObservable=new re,this.onTextureLoadedObservable=new re,this.onMaterialLoadedObservable=new re,this.onCameraLoadedObservable=new re,this.onCompleteObservable=new re,this.onErrorObservable=new re,this.onDisposeObservable=new re,this.onExtensionLoadedObservable=new re,this.onValidatedObservable=new re,this._loader=null,this._state=null,this._requests=new Array,this.name=xE.name,this.extensions=xE.extensions,this.onLoaderStateChangedObservable=new re,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled,this.copyFrom(Object.assign({...o_e},e))}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),e&&(this._onParsedObserver=this.onParsedObservable.add(e))}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),e&&(this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e))}set onSkinLoaded(e){this._onSkinLoadedObserver&&this.onSkinLoadedObservable.remove(this._onSkinLoadedObserver),e&&(this._onSkinLoadedObserver=this.onSkinLoadedObservable.add(t=>e(t.node,t.skinnedNode)))}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),e&&(this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e))}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),e&&(this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e))}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),e&&(this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e))}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(let e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,r,s,a,o,l){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,r,o,l),null;this._progressCallback=s;let c=t.name||pe.GetFilename(t);if(a){if(this.useRangeRequests){this.validate&&te.Warn("glTF validation is not supported when range requests are enabled");let f={abort:()=>{},onCompleteObservable:new re},d={readAsync:(u,h)=>new Promise((m,g)=>{this._loadFile(e,t,p=>{m(new Uint8Array(p))},!0,p=>{g(p)},p=>{p.setRequestHeader("Range",`bytes=${u}-${u+h-1}`)})}),byteLength:0};return this._unpackBinaryAsync(new uh(d)).then(u=>{f.onCompleteObservable.notifyObservers(f),r(u)},o?u=>o(void 0,u):void 0),f}return this._loadFile(e,t,f=>{this._validate(e,new Uint8Array(f,0,f.byteLength),i,c),this._unpackBinaryAsync(new uh({readAsync:(d,u)=>S9(f,d,u),byteLength:f.byteLength})).then(d=>{r(d)},o?d=>o(void 0,d):void 0)},!0,o)}else return this._loadFile(e,t,f=>{try{this._validate(e,f,i,c),r({json:this._parseJson(f)})}catch(d){o&&o()}},!1,o)}_loadBinary(e,t,i,r,s,a){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,a),this._unpackBinaryAsync(new uh({readAsync:(o,l)=>a_e(t,o,l),byteLength:t.byteLength})).then(o=>{r(o)},s?o=>s(void 0,o):void 0)}importMeshAsync(e,t,i,r,s,a){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${a||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,r,s,a)))}loadAsync(e,t,i,r,s){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,r,s)))}loadAssetContainerAsync(e,t,i,r,s){return Promise.resolve().then(()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t);let a=new ql(e),o=[];this.onMaterialLoadedObservable.add(d=>{o.push(d)});let l=[];this.onTextureLoadedObservable.add(d=>{l.push(d)});let c=[];this.onCameraLoadedObservable.add(d=>{c.push(d)});let f=[];return this.onMeshLoadedObservable.add(d=>{d.morphTargetManager&&f.push(d.morphTargetManager)}),this._loader.importMeshAsync(null,e,a,t,i,r,s).then(d=>(Array.prototype.push.apply(a.geometries,d.geometries),Array.prototype.push.apply(a.meshes,d.meshes),Array.prototype.push.apply(a.particleSystems,d.particleSystems),Array.prototype.push.apply(a.skeletons,d.skeletons),Array.prototype.push.apply(a.animationGroups,d.animationGroups),Array.prototype.push.apply(a.materials,o),Array.prototype.push.apply(a.textures,l),Array.prototype.push.apply(a.lights,d.lights),Array.prototype.push.apply(a.transformNodes,d.transformNodes),Array.prototype.push.apply(a.cameras,c),Array.prototype.push.apply(a.morphTargetManagers,f),a))})}canDirectLoad(e){return xE.canDirectLoad(e)}directLoad(e,t){if(t.startsWith("base64,"+cf)||t.startsWith(";base64,"+cf)||t.startsWith("application/octet-stream;base64,"+cf)||t.startsWith("model/gltf-binary;base64,"+cf)){let i=ed(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new uh({readAsync:(r,s)=>S9(i,r,s),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(e){return new n(e[xE.name])}get loaderState(){return this._state}whenCompleteAsync(){return new Promise((e,t)=>{this.onCompleteObservable.addOnce(()=>{e()}),this.onErrorObservable.addOnce(i=>{t(i)})})}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(Ns[this._state]))}_loadFile(e,t,i,r,s,a){let o=e._loadFile(t,i,l=>{this._onProgress(l,o)},!0,r,s,a);return o.onCompleteObservable.add(()=>{o._lengthComputable=!0,o._total=o._loaded}),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,r=0,s=0;for(let a of this._requests){if(a._lengthComputable===void 0||a._loaded===void 0||a._total===void 0)return;i=i&&a._lengthComputable,r+=a._loaded,s+=a._total}this._progressCallback({lengthComputable:i,loaded:r,total:i?s:0})}_validate(e,t,i="",r=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),hg.ValidateAsync(t,i,r,s=>this.preprocessUrlAsync(i+s).then(a=>e._loadFileAsync(a,void 0,!0,!0).then(o=>new Uint8Array(o,0,o.byteLength)))).then(s=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(s),this.onValidatedObservable.clear()},s=>{this._endPerformanceCounter("Validate JSON"),pe.Warn(`Failed to validate: ${s.message}`),this.onValidatedObservable.clear()}))}_getLoader(e){let t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);let i=n._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(t.minVersion!==void 0){let a=n._parseVersion(t.minVersion);if(!a)throw new Error("Invalid minimum version: "+t.minVersion);if(n._compareVersion(a,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}let s={1:n._CreateGLTF1Loader,2:n._CreateGLTF2Loader}[i.major];if(!s)throw new Error("Unsupported version: "+t.version);return s(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);let t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then(()=>{let t={Magic:1179937895},i=e.readUint32();if(i!==t.Magic)throw new ra("Unexpected magic: "+i,$a.GLTFLoaderUnexpectedMagicError);let r=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${r}`);let s=e.readUint32();!this.useRangeRequests&&s!==e.buffer.byteLength&&te.Warn(`Length in header does not match actual data length: ${s} != ${e.buffer.byteLength}`);let a;switch(r){case 1:{a=this._unpackBinaryV1Async(e,s);break}case 2:{a=this._unpackBinaryV2Async(e,s);break}default:throw new Error("Unsupported version: "+r)}return this._endPerformanceCounter("Unpack Binary"),a})}_unpackBinaryV1Async(e,t){let i={JSON:0},r=e.readUint32(),s=e.readUint32();if(s!==i.JSON)throw new Error(`Unexpected content format: ${s}`);let a=t-e.byteOffset,o={json:this._parseJson(e.readString(r)),bin:null};if(a!==0){let l=e.byteOffset;o.bin={readAsync:(c,f)=>e.buffer.readAsync(l+c,f),byteLength:a}}return Promise.resolve(o)}_unpackBinaryV2Async(e,t){let i={JSON:1313821514,BIN:5130562},r=e.readUint32();if(e.readUint32()!==i.JSON)throw new Error("First chunk format is not JSON");return e.byteOffset+r===t?e.loadAsync(r).then(()=>({json:this._parseJson(e.readString(r)),bin:null})):e.loadAsync(r+8).then(()=>{let a={json:this._parseJson(e.readString(r)),bin:null},o=()=>{let l=e.readUint32();switch(e.readUint32()){case i.JSON:throw new Error("Unexpected JSON chunk");case i.BIN:{let f=e.byteOffset;a.bin={readAsync:(d,u)=>e.buffer.readAsync(f+d,u),byteLength:l},e.skipBytes(l);break}default:{e.skipBytes(l);break}}return e.byteOffset!==t?e.loadAsync(8).then(o):Promise.resolve(a)};return o()})}static _parseVersion(e){if(e==="1.0"||e==="1.0.1")return{major:1,minor:0};let t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.major<t.major?-1:e.minor>t.minor?1:e.minor<t.minor?-1:0}_logOpen(e){this._log(e),this._logIndentLevel++}_logClose(){--this._logIndentLevel}_logEnabled(e){let t=n._logSpaces.substring(0,this._logIndentLevel*2);te.Log(`${t}${e}`)}_logDisabled(e){}_startPerformanceCounterEnabled(e){pe.StartPerformanceCounter(e)}_startPerformanceCounterDisabled(e){}_endPerformanceCounterEnabled(e){pe.EndPerformanceCounter(e)}_endPerformanceCounterDisabled(e){}};Bd.IncrementalLoading=!0;Bd.HomogeneousCoordinates=!1;Bd._logSpaces=" ";Fd(new Bd)});var zM,T9=y(()=>{zM=class{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}});var hs,A9=y(()=>{jt();Yt();Kl();kR();He();Gi();hs=class{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{let i=t.event;if(!i.metaKey){if(t.type===Yo.KEYDOWN)(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),e||i.preventDefault());else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1){let r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),e||i.preventDefault()}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){let e=this.camera;for(let t=0;t<this._keys.length;t++){let i=this._keys[t],r=e._computeLocalCameraSpeed();this.keysLeft.indexOf(i)!==-1?e._localDirection.copyFromFloats(-r,0,0):this.keysUp.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,0,r):this.keysRight.indexOf(i)!==-1?e._localDirection.copyFromFloats(r,0,0):this.keysDown.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,0,-r):this.keysUpward.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,r,0):this.keysDownward.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,-r,0):this.keysRotateLeft.indexOf(i)!==-1?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y-=this._getLocalRotation()):this.keysRotateRight.indexOf(i)!==-1?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y+=this._getLocalRotation()):this.keysRotateUp.indexOf(i)!==-1?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x-=this._getLocalRotation()):this.keysRotateDown.indexOf(i)!==-1&&(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x+=this._getLocalRotation()),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),b.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}getClassName(){return"FreeCameraKeyboardMoveInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}_getLocalRotation(){let e=this.camera._calculateHandednessMultiplier();return this.rotationSpeed*this._engine.getDeltaTime()/1e3*e}};P([F()],hs.prototype,"keysUp",void 0);P([F()],hs.prototype,"keysUpward",void 0);P([F()],hs.prototype,"keysDown",void 0);P([F()],hs.prototype,"keysDownward",void 0);P([F()],hs.prototype,"keysLeft",void 0);P([F()],hs.prototype,"keysRight",void 0);P([F()],hs.prototype,"rotationSpeed",void 0);P([F()],hs.prototype,"keysRotateLeft",void 0);P([F()],hs.prototype,"keysRotateRight",void 0);P([F()],hs.prototype,"keysRotateUp",void 0);P([F()],hs.prototype,"keysRotateDown",void 0);cs.FreeCameraKeyboardMoveInput=hs});var mh,x9=y(()=>{jt();Si();Yt();Kl();Xo();Gi();mh=class{constructor(e=!0){this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this._previousPosition=null,this.onPointerMovedObservable=new re,this._allowCameraRotation=!0,this._currentActiveButton=-1,this._activePointerId=-1}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement();this._pointerInput||(this._pointerInput=r=>{let s=r.event,a=s.pointerType==="touch";if(!this.touchEnabled&&a||r.type!==ot.POINTERMOVE&&this.buttons.indexOf(s.button)===-1)return;let o=s.target;if(r.type===ot.POINTERDOWN){if(a&&this._activePointerId!==-1||!a&&this._currentActiveButton!==-1)return;this._activePointerId=s.pointerId;try{o==null||o.setPointerCapture(s.pointerId)}catch(l){}this._currentActiveButton===-1&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},e||(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===ot.POINTERUP){if(a&&this._activePointerId!==s.pointerId||!a&&this._currentActiveButton!==s.button)return;try{o==null||o.releasePointerCapture(s.pointerId)}catch(l){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(r.type===ot.POINTERMOVE&&(this._activePointerId===s.pointerId||!a)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){let l=this.camera._calculateHandednessMultiplier(),c=(s.clientX-this._previousPosition.x)*l,f=(s.clientY-this._previousPosition.y)*l;this._allowCameraRotation&&(this.camera.cameraRotation.y+=c/this.angularSensibility,this.camera.cameraRotation.x+=f/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:c,offsetY:f}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}}),this._onMouseMove=r=>{if(!t.isPointerLock)return;let s=this.camera._calculateHandednessMultiplier();this.camera.cameraRotation.y+=r.movementX*s/this.angularSensibility,this.camera.cameraRotation.x+=r.movementY*s/this.angularSensibility,this._previousPosition=null,e||r.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ot.POINTERDOWN|ot.POINTERUP|ot.POINTERMOVE),i&&(this._contextMenuBind=r=>this.onContextMenu(r),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){let t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}};P([F()],mh.prototype,"buttons",void 0);P([F()],mh.prototype,"angularSensibility",void 0);cs.FreeCameraMouseInput=mh});var ph,R9=y(()=>{jt();Yt();Si();Xo();zR();Gi();ph=class{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new re,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==ot.POINTERWHEEL)return;let i=t.event,r=i.deltaMode===Ko.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,ot.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}};P([F()],ph.prototype,"wheelPrecisionX",void 0);P([F()],ph.prototype,"wheelPrecisionY",void 0);P([F()],ph.prototype,"wheelPrecisionZ",void 0)});var Ki,da,b9=y(()=>{jt();Yt();Kl();R9();He();(function(n){n[n.MoveRelative=0]="MoveRelative",n[n.RotateRelative=1]="RotateRelative",n[n.MoveScene=2]="MoveScene"})(Ki||(Ki={}));da=class extends ph{constructor(){super(...arguments),this._moveRelative=b.Zero(),this._rotateRelative=b.Zero(),this._moveScene=b.Zero(),this._wheelXAction=Ki.MoveRelative,this._wheelXActionCoordinate=0,this._wheelYAction=Ki.MoveRelative,this._wheelYActionCoordinate=2,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){e===null&&this._wheelXAction!==Ki.MoveRelative||(this._wheelXAction=Ki.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Ki.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){e===null&&this._wheelYAction!==Ki.MoveRelative||(this._wheelYAction=Ki.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Ki.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){e===null&&this._wheelZAction!==Ki.MoveRelative||(this._wheelZAction=Ki.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Ki.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){e===null&&this._wheelXAction!==Ki.RotateRelative||(this._wheelXAction=Ki.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Ki.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){e===null&&this._wheelYAction!==Ki.RotateRelative||(this._wheelYAction=Ki.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Ki.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){e===null&&this._wheelZAction!==Ki.RotateRelative||(this._wheelZAction=Ki.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Ki.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){e===null&&this._wheelXAction!==Ki.MoveScene||(this._wheelXAction=Ki.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Ki.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){e===null&&this._wheelYAction!==Ki.MoveScene||(this._wheelYAction=Ki.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Ki.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){e===null&&this._wheelZAction!==Ki.MoveScene||(this._wheelZAction=Ki.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Ki.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(this._wheelDeltaX===0&&this._wheelDeltaY===0&&this._wheelDeltaZ==0)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);let e=Q.Zero();this.camera.getViewMatrix().invertToRef(e);let t=b.Zero();b.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(e===0||t===null||i===null)return;let r=null;switch(t){case Ki.MoveRelative:r=this._moveRelative;break;case Ki.RotateRelative:r=this._rotateRelative;break;case Ki.MoveScene:r=this._moveScene;break}switch(i){case 0:r.set(e,0,0);break;case 1:r.set(0,e,0);break;case 2:r.set(0,0,e);break}}};P([F()],da.prototype,"wheelXMoveRelative",null);P([F()],da.prototype,"wheelYMoveRelative",null);P([F()],da.prototype,"wheelZMoveRelative",null);P([F()],da.prototype,"wheelXRotateRelative",null);P([F()],da.prototype,"wheelYRotateRelative",null);P([F()],da.prototype,"wheelZRotateRelative",null);P([F()],da.prototype,"wheelXMoveScene",null);P([F()],da.prototype,"wheelYMoveScene",null);P([F()],da.prototype,"wheelZMoveScene",null);cs.FreeCameraMouseWheelInput=da});var gh,M9=y(()=>{jt();Yt();Kl();Xo();He();Gi();gh=class{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=pe.IsSafari()}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments);let t=null;if(this._pointerInput===void 0&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{let r=i.event,s=r.pointerType==="mouse"||this._isSafari&&typeof r.pointerType=="undefined";if(!(!this.allowMouse&&s)){if(i.type===ot.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),this._pointerPressed.length!==1)return;t={x:r.clientX,y:r.clientY}}else if(i.type===ot.POINTERUP){e||r.preventDefault();let a=this._pointerPressed.indexOf(r.pointerId);if(a===-1||(this._pointerPressed.splice(a,1),a!=0))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===ot.POINTERMOVE){if(e||r.preventDefault(),!t||this._pointerPressed.indexOf(r.pointerId)!=0)return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ot.POINTERDOWN|ot.POINTERUP|ot.POINTERMOVE),this._onLostFocus){let r=this.camera.getEngine().getInputElement();r&&r.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){let t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(this._offsetX===null||this._offsetY===null||this._offsetX===0&&this._offsetY===0)return;let e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=this._offsetX*t/this.touchAngularSensibility,this.singleFingerRotate&&this._pointerPressed.length===1||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-(this._offsetY*t)/this.touchAngularSensibility;else{let r=e._computeLocalCameraSpeed(),s=ee.Vector3[0];s.copyFromFloats(0,0,this.touchMoveSensibility!==0?r*this._offsetY/this.touchMoveSensibility:0),Q.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),b.TransformCoordinatesToRef(s,e._cameraRotationMatrix,s),e.cameraDirection.addInPlace(s)}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}};P([F()],gh.prototype,"touchAngularSensibility",void 0);P([F()],gh.prototype,"touchMoveSensibility",void 0);cs.FreeCameraTouchInput=gh});var WM,y9=y(()=>{Kl();A9();x9();b9();M9();WM=class extends $p{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new hs),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new mh(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new da,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new gh),this}clear(){super.clear(),this._mouseInput=null}}});var ff,I9=y(()=>{jt();Yt();He();dO();y9();Gi();ir();Yr();ff=class extends oa{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysUpward(){let e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){let t=this.inputs.attached.keyboard;t&&(t.keysUpward=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysDownward(){let e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){let t=this.inputs.attached.keyboard;t&&(t.keysDownward=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get keysRotateLeft(){let e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){let e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){let e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){let e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new b(.5,1,.5),this.ellipsoidOffset=new b(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=b.Zero(),this._diffPosition=b.Zero(),this._newPosition=b.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(s,a,o=null)=>{this._newPosition.copyFrom(a),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>ye.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&o&&this.onCollide(o))},this.inputs=new WM(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=pe.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new b(0,0,0),this.cameraRotation=new Fe(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=b.TransformCoordinates(this.position,this.parent.getWorldMatrix()):t=this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let r=e;this.applyGravity&&(r=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=b.Zero(),this._transformedDirection=b.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}};P([nn()],ff.prototype,"ellipsoid",void 0);P([nn()],ff.prototype,"ellipsoidOffset",void 0);P([F()],ff.prototype,"checkCollisions",void 0);P([F()],ff.prototype,"applyGravity",void 0);zt("BABYLON.FreeCamera",ff)});var po,HM=y(()=>{He();Ol();Na();po=class n extends bi{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){e.updateFlag===this._localMatrix.updateFlag&&!this._needToCompose||(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,r=null,s=null,a=null,o=null){var l;super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._waitingTransformNodeUniqueId=null,this._skeleton=t,this._localMatrix=(l=r==null?void 0:r.clone())!=null?l:Q.Identity(),this._restMatrix=s!=null?s:this._localMatrix.clone(),this._bindMatrix=a!=null?a:this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new Q,this._absoluteBindMatrix=new Q,this._absoluteInverseBindMatrix=new Q,this._finalMatrix=new Q,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return this._index===null?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){let i=this.parent.children.indexOf(this);i!==-1&&this.parent.children.splice(i,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){var e;if(this._linkedTransformNode){let t=ee.Vector3[0],i=ee.Quaternion[0],r=ee.Vector3[1];this.getRestMatrix().decompose(t,i,r),this._linkedTransformNode.position.copyFrom(r),this._linkedTransformNode.rotationQuaternion=(e=this._linkedTransformNode.rotationQuaternion)!=null?e:je.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._skeleton.computeAbsoluteMatrices(),this._absoluteMatrix}getAbsoluteTransform(){return this.getAbsoluteMatrix()}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=b.Zero(),this._localRotation=je.Zero(),this._localPosition=b.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,Q.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let i=0;i<this.children.length;i++)this.children[i]._updateAbsoluteBindMatrices();this._scalingDeterminant=this._absoluteBindMatrix.determinant()<0?-1:1}markAsDirty(){return this._currentRenderId++,this._childUpdateId++,this._skeleton._markAsDirty(),this}_markAsDirtyAndCompose(){this.markAsDirty(),this._needToCompose=!0}_markAsDirtyAndDecompose(){this.markAsDirty(),this._needToDecompose=!0}_updatePosition(e,t=0,i,r=!0){let s=this.getLocalMatrix();if(t==0)r?(s.addAtIndex(12,e.x),s.addAtIndex(13,e.y),s.addAtIndex(14,e.z)):s.setTranslationFromFloats(e.x,e.y,e.z);else{let a=n._TmpMats[0],o=n._TmpVecs[0];this.parent?(a.copyFrom(this.parent.getAbsoluteMatrix()),i&&a.multiplyToRef(i.getWorldMatrix(),a)):Q.IdentityToRef(a),r&&a.setTranslationFromFloats(0,0,0),a.invert(),b.TransformCoordinatesToRef(e,a,o),r?(s.addAtIndex(12,o.x),s.addAtIndex(13,o.y),s.addAtIndex(14,o.z)):s.setTranslationFromFloats(o.x,o.y,o.z)}this._markAsDirtyAndDecompose()}translate(e,t=0,i){this._updatePosition(e,t,i,!0)}setPosition(e,t=0,i){this._updatePosition(e,t,i,!1)}setAbsolutePosition(e,t){this.setPosition(e,1,t)}scale(e,t,i,r=!1){let s=this.getLocalMatrix(),a=n._TmpMats[0];Q.ScalingToRef(e,t,i,a),a.multiplyToRef(s,s),a.invert();for(let o of this.children){let l=o.getLocalMatrix();l.multiplyToRef(a,l),l.multiplyAtIndex(12,e),l.multiplyAtIndex(13,t),l.multiplyAtIndex(14,i),o._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),r)for(let o of this.children)o.scale(e,t,i,r)}setScale(e){this._decompose(),this._localScaling.copyFrom(e),this._markAsDirtyAndCompose()}getScale(){return this._decompose(),this._localScaling}getScaleToRef(e){this._decompose(),e.copyFrom(this._localScaling)}setYawPitchRoll(e,t,i,r=0,s){if(r===0){let l=n._TmpQuat;je.RotationYawPitchRollToRef(e,t,i,l),this.setRotationQuaternion(l,r,s);return}let a=n._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(a,s))return;let o=n._TmpMats[1];Q.RotationYawPitchRollToRef(e,t,i,o),a.multiplyToRef(o,o),this._rotateWithMatrix(o,r,s)}rotate(e,t,i=0,r){let s=n._TmpMats[0];s.setTranslationFromFloats(0,0,0),Q.RotationAxisToRef(e,t,s),this._rotateWithMatrix(s,i,r)}setAxisAngle(e,t,i=0,r){if(i===0){let o=n._TmpQuat;je.RotationAxisToRef(e,t,o),this.setRotationQuaternion(o,i,r);return}let s=n._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(s,r))return;let a=n._TmpMats[1];Q.RotationAxisToRef(e,t,a),s.multiplyToRef(a,a),this._rotateWithMatrix(a,i,r)}setRotation(e,t=0,i){this.setYawPitchRoll(e.y,e.x,e.z,t,i)}setRotationQuaternion(e,t=0,i){if(t===0){this._decompose(),this._localRotation.copyFrom(e),this._markAsDirtyAndCompose();return}let r=n._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=n._TmpMats[1];Q.FromQuaternionToRef(e,s),r.multiplyToRef(s,s),this._rotateWithMatrix(s,t,i)}setRotationMatrix(e,t=0,i){if(t===0){let a=n._TmpQuat;je.FromRotationMatrixToRef(e,a),this.setRotationQuaternion(a,t,i);return}let r=n._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=n._TmpMats[1];s.copyFrom(e),r.multiplyToRef(e,s),this._rotateWithMatrix(s,t,i)}_rotateWithMatrix(e,t=0,i){let r=this.getLocalMatrix(),s=r.m[12],a=r.m[13],o=r.m[14],l=this.getParent(),c=n._TmpMats[3],f=n._TmpMats[4];l&&t==1?(i?(c.copyFrom(i.getWorldMatrix()),l.getAbsoluteMatrix().multiplyToRef(c,c)):c.copyFrom(l.getAbsoluteMatrix()),f.copyFrom(c),f.invert(),r.multiplyToRef(c,r),r.multiplyToRef(e,r),r.multiplyToRef(f,r)):t==1&&i?(c.copyFrom(i.getWorldMatrix()),f.copyFrom(c),f.invert(),r.multiplyToRef(c,r),r.multiplyToRef(e,r),r.multiplyToRef(f,r)):r.multiplyToRef(e,r),r.setTranslationFromFloats(s,a,o),this._markAsDirtyAndDecompose()}_getAbsoluteInverseMatrixUnscaledToRef(e,t){let i=n._TmpMats[2];return e.copyFrom(this.getAbsoluteMatrix()),t?(e.multiplyToRef(t.getWorldMatrix(),e),Q.ScalingToRef(t.scaling.x,t.scaling.y,t.scaling.z,i)):Q.IdentityToRef(i),e.invert(),isNaN(e.m[0])?!1:(i.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(i,e),!0)}getPosition(e=0,t=null){let i=b.Zero();return this.getPositionToRef(e,t,i),i}getPositionToRef(e=0,t,i){if(e==0){let r=this.getLocalMatrix();i.x=r.m[12],i.y=r.m[13],i.z=r.m[14]}else{let r=n._TmpMats[0].copyFrom(this.getAbsoluteMatrix());t&&r.multiplyToRef(t.getWorldMatrix(),r),i.x=r.m[12],i.y=r.m[13],i.z=r.m[14]}}getAbsolutePosition(e=null){let t=b.Zero();return this.getPositionToRef(1,e,t),t}getAbsolutePositionToRef(e,t){this.getPositionToRef(1,e,t)}computeAbsoluteMatrices(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteMatrix,this._absoluteMatrix);else{this._absoluteMatrix.copyFrom(this._localMatrix);let i=this._skeleton.getPoseMatrix();i&&this._absoluteMatrix.multiplyToRef(i,this._absoluteMatrix)}let e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].computeAbsoluteMatrices()}computeAbsoluteTransforms(){this.computeAbsoluteMatrices()}getDirection(e,t=null){let i=b.Zero();return this.getDirectionToRef(e,t,i),i}getDirectionToRef(e,t=null,i){let r=n._TmpMats[0].copyFrom(this.getAbsoluteMatrix());t&&r.multiplyToRef(t.getWorldMatrix(),r),b.TransformNormalToRef(e,r,i),i.normalize()}getRotation(e=0,t=null){let i=b.Zero();return this.getRotationToRef(e,t,i),i}getRotationToRef(e=0,t=null,i){let r=n._TmpQuat;this.getRotationQuaternionToRef(e,t,r),r.toEulerAnglesToRef(i)}getRotationQuaternion(e=0,t=null){let i=je.Identity();return this.getRotationQuaternionToRef(e,t,i),i}getRotationQuaternionToRef(e=0,t=null,i){if(e==0)this._decompose(),i.copyFrom(this._localRotation);else{let r=n._TmpMats[0],s=this.getAbsoluteMatrix();t?s.multiplyToRef(t.getWorldMatrix(),r):r.copyFrom(s),r.multiplyAtIndex(0,this._scalingDeterminant),r.multiplyAtIndex(1,this._scalingDeterminant),r.multiplyAtIndex(2,this._scalingDeterminant),r.decompose(void 0,i,void 0)}}getRotationMatrix(e=0,t){let i=Q.Identity();return this.getRotationMatrixToRef(e,t,i),i}getRotationMatrixToRef(e=0,t,i){if(e==0)this.getLocalMatrix().getRotationMatrixToRef(i);else{let r=n._TmpMats[0],s=this.getAbsoluteMatrix();t?s.multiplyToRef(t.getWorldMatrix(),r):r.copyFrom(s),r.multiplyAtIndex(0,this._scalingDeterminant),r.multiplyAtIndex(1,this._scalingDeterminant),r.multiplyAtIndex(2,this._scalingDeterminant),r.getRotationMatrixToRef(i)}}getAbsolutePositionFromLocal(e,t=null){let i=b.Zero();return this.getAbsolutePositionFromLocalToRef(e,t,i),i}getAbsolutePositionFromLocalToRef(e,t=null,i){let r=n._TmpMats[0].copyFrom(this.getAbsoluteMatrix());t&&r.multiplyToRef(t.getWorldMatrix(),r),b.TransformCoordinatesToRef(e,r,i)}getLocalPositionFromAbsolute(e,t=null){let i=b.Zero();return this.getLocalPositionFromAbsoluteToRef(e,t,i),i}getLocalPositionFromAbsoluteToRef(e,t=null,i){let r=n._TmpMats[0].copyFrom(this.getAbsoluteMatrix());t&&r.multiplyToRef(t.getWorldMatrix(),r),r.invert(),b.TransformCoordinatesToRef(e,r,i)}setCurrentPoseAsRest(){this.setRestMatrix(this.getLocalMatrix())}dispose(){this._linkedTransformNode=null;let e=this._skeleton.bones.indexOf(this);if(e!==-1&&this._skeleton.bones.splice(e,1),this._parentNode&&this._parentNode.children){let t=this._parentNode.children,i=t.indexOf(this);i!==-1&&t.splice(i,1)}super.dispose()}};po._TmpVecs=yn(2,b.Zero);po._TmpQuat=je.Identity();po._TmpMats=yn(5,Q.Identity)});var RE,C9=y(()=>{Kr();RE=class n extends _e{constructor(e,t,i,r,s,a=!0,o=!1,l=3,c=0,f,d,u,h){super(null,s,!a,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,f),this.format=r,this._engine&&(!this._engine._caps.textureFloatLinearFiltering&&c===1&&(l=1),!this._engine._caps.textureHalfFloatLinearFiltering&&c===2&&(l=1),this._texture=this._engine.createRawTexture(e,t,i,r,a,o,l,null,c,f!=null?f:0,d!=null?d:!1,h),this.wrapU=_e.CLAMP_ADDRESSMODE,this.wrapV=_e.CLAMP_ADDRESSMODE,this._waitingForData=!!u&&!e)}update(e){this.updateMipLevel(e,0)}updateMipLevel(e,t){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer,t),this._waitingForData=!1}clone(){if(!this._texture)return super.clone();let e=new n(null,this.getSize().width,this.getSize().height,this.format,this.getScene(),this._texture.generateMipMaps,this._invertY,this.samplingMode,this._texture.type,this._texture._creationFlags,this._useSRGBBuffer);return e._texture=this._texture,this._texture.incrementReferences(),e}isReady(){return super.isReady()&&!this._waitingForData}static CreateLuminanceTexture(e,t,i,r,s=!0,a=!1,o=3){return new n(e,t,i,1,r,s,a,o)}static CreateLuminanceAlphaTexture(e,t,i,r,s=!0,a=!1,o=3){return new n(e,t,i,2,r,s,a,o)}static CreateAlphaTexture(e,t,i,r,s=!0,a=!1,o=3){return new n(e,t,i,0,r,s,a,o)}static CreateRGBTexture(e,t,i,r,s=!0,a=!1,o=3,l=0,c=0,f=!1){return new n(e,t,i,4,r,s,a,o,l,c,f)}static CreateRGBATexture(e,t,i,r,s=!0,a=!1,o=3,l=0,c=0,f=!1,d=!1){return new n(e,t,i,5,r,s,a,o,l,c,f,d)}static CreateRGBAStorageTexture(e,t,i,r,s=!0,a=!1,o=3,l=0,c=!1){return new n(e,t,i,5,r,s,a,o,l,1,c)}static CreateRTexture(e,t,i,r,s=!0,a=!1,o=_e.TRILINEAR_SAMPLINGMODE,l=1){return new n(e,t,i,6,r,s,a,o,l)}static CreateRStorageTexture(e,t,i,r,s=!0,a=!1,o=_e.TRILINEAR_SAMPLINGMODE,l=1){return new n(e,t,i,6,r,s,a,o,l,1)}}});var XM,P9=y(()=>{HM();Si();He();C9();gd();rO();Yi();wt();bv();XM=class n{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=Q.Identity(),this._currentRenderId=-1,this._textureWidth=0,this._textureHeight=1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new re,this.metadata=null,this.bones=[],this._scene=i||Oe.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;let r=this._scene.getEngine().getCaps();this._canUseTextureForBones=r.textureFloat&&r.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return(!this._transformMatrices||this._isDirty)&&this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let i=!0;for(let r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].name===e)return t;return-1}findBoneFromLinkedTransformNode(e){for(let t of this.bones)if(t._linkedTransformNode===e)return t;return null}findBoneFromLinkedTransformNodeName(e){for(let t of this.bones)if(t._linkedTransformNode&&t._linkedTransformNode.name===e)return t;return null}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=new pd(e,t,i);for(let r=0,s=this.bones.length;r<s;r++)this.bones[r].animations[0]&&this.bones[r].animations[0].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,r=this.bones.length;i<r;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}getAnimationRanges(){let e=[],t;for(t in this._ranges)e.push(this._ranges[t]);return e}copyAnimationRange(e,t,i=!1){if(this._ranges[t]||!e.getAnimationRange(t))return!1;let r=!0,s=this._getHighestAnimationFrame()+1,a={},o=e.bones,l,c;for(c=0,l=o.length;c<l;c++)a[o[c].name]=o[c];this.bones.length!==o.length&&(te.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${o.length}`),r=!1);let f=i&&this.dimensionsAtRest&&e.dimensionsAtRest?this.dimensionsAtRest.divide(e.dimensionsAtRest):null;for(c=0,l=this.bones.length;c<l;c++){let u=this.bones[c].name,h=a[u];h?r=r&&this.bones[c].copyAnimationRange(h,t,s,i,f):(te.Warn("copyAnimationRange: not same rig, missing source bone "+u),r=!1)}let d=e.getAnimationRange(t);return d&&(this._ranges[t]=new pd(t,d.from+s,d.to+s)),r}returnToRest(){for(let e of this.bones)e._index!==-1&&e.returnToRest()}_getHighestAnimationFrame(){let e=0;for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].animations[0]){let r=this.bones[t].animations[0].getHighestFrame();e<r&&(e=r)}return e}beginAnimation(e,t,i,r){let s=this.getAnimationRange(e);return s?this._scene.beginAnimation(this,s.from,s.to,t,i,r):null}static MakeAnimationAdditive(e,t=0,i){let r=e.getAnimationRange(i);if(!r)return null;let s=e._scene.getAllAnimatablesByTarget(e),a=null;for(let l=0;l<s.length;l++){let c=s[l];if(c.fromFrame===(r==null?void 0:r.from)&&c.toFrame===(r==null?void 0:r.to)){a=c;break}}let o=e.getAnimatables();for(let l=0;l<o.length;l++){let f=o[l].animations;if(f)for(let d=0;d<f.length;d++)gt.MakeAnimationAdditive(f[d],t,i)}return a&&(a.isAdditive=!0),e}_markAsDirty(){this._isDirty=!0,this._absoluteTransformIsDirty=!0}_registerMeshWithPoseMatrix(e){this._meshesWithPoseMatrix.push(e)}_unregisterMeshWithPoseMatrix(e){let t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i<this.bones.length;i++){let r=this.bones[i];r._childUpdateId++;let s=r.getParent();if(s?r.getLocalMatrix().multiplyToRef(s.getFinalMatrix(),r.getFinalMatrix()):t?r.getLocalMatrix().multiplyToRef(t,r.getFinalMatrix()):r.getFinalMatrix().copyFrom(r.getLocalMatrix()),r._index!==-1){let a=r._index===null?i:r._index;r.getAbsoluteInverseBindMatrix().multiplyToArray(r.getFinalMatrix(),e,a*16)}}this._identity.copyToArray(e,this.bones.length*16)}_computeTextureSize(){let e=4*(this.bones.length+1),t=e,i=1;if(this.isUsingTextureForMatrices){let r=this.getScene().getEngine().getCaps().maxTextureSize&-4;r<t&&(t=r,i=Math.ceil(e/r))}return this._textureWidth=t,this._textureHeight=i,this._textureWidth*this._textureHeight*4}prepare(e=!1){var i;if(!e){let r=this.getScene().getRenderId();if(this._currentRenderId===r)return;this._currentRenderId=r}if(this._numBonesWithLinkedTransformNode>0){for(let r of this.bones)if(r._linkedTransformNode){let s=r._linkedTransformNode;r.position=s.position,s.rotationQuaternion?r.rotationQuaternion=s.rotationQuaternion:r.rotation=s.rotation,r.scaling=s.scaling}}let t=null;if(this.needInitialSkinMatrix)for(let r of this._meshesWithPoseMatrix){let s=r.getPoseMatrix(),a=this._isDirty;if(t===null&&(t=this._computeTextureSize()),(!r._bonesTransformMatrices||r._bonesTransformMatrices.length!==t)&&(r._bonesTransformMatrices=new Float32Array(t),a=!0),!!a){if(this._synchronizedWithMesh!==r){this._synchronizedWithMesh=r;for(let o of this.bones)o.getParent()||(o.getBindMatrix().multiplyToRef(s,ee.Matrix[1]),o._updateAbsoluteBindMatrices(ee.Matrix[1]));if(this.isUsingTextureForMatrices){let o=(i=r._transformMatrixTexture)==null?void 0:i.getSize(),l=o?o.width*o.height*4:0;(!r._transformMatrixTexture||l!==t)&&(r._transformMatrixTexture&&r._transformMatrixTexture.dispose(),r._transformMatrixTexture=RE.CreateRGBATexture(r._bonesTransformMatrices,this._textureWidth,this._textureHeight,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(r._bonesTransformMatrices,s),this.isUsingTextureForMatrices&&r._transformMatrixTexture&&r._transformMatrixTexture.update(r._bonesTransformMatrices)}}else{if(!this._isDirty)return;t===null&&(t=this._computeTextureSize()),(!this._transformMatrices||this._transformMatrices.length!==t)&&(this._transformMatrices=new Float32Array(t),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=RE.CreateRGBATexture(this._transformMatrices,this._textureWidth,this._textureHeight,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables}clone(e,t){let i=new n(e,t||e,this._scene);i.needInitialSkinMatrix=this.needInitialSkinMatrix,i.metadata=this.metadata;for(let r=0;r<this.bones.length;r++){let s=this.bones[r],a=null,o=s.getParent();if(o){let c=this.bones.indexOf(o);a=i.bones[c]}let l=new po(s.name,i,a,s.getBindMatrix().clone(),s.getRestMatrix().clone());l._index=s._index,s._linkedTransformNode&&l.linkTransformNode(s._linkedTransformNode),Ul.DeepCopy(s.animations,l.animations)}if(this._ranges){i._ranges={};for(let r in this._ranges){let s=this._ranges[r];s&&(i._ranges[r]=s.clone())}}return this._isDirty=!0,i.prepare(!0),i}enableBlending(e=.01){for(let t of this.bones)for(let i of t.animations)i.enableBlending=!0,i.blendingSpeed=e}dispose(){if(this._meshesWithPoseMatrix.length=0,this.metadata=null,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){let e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){var t,i;let e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix,this.metadata&&(e.metadata=this.metadata);for(let r=0;r<this.bones.length;r++){let s=this.bones[r],a=s.getParent(),o={parentBoneIndex:a?this.bones.indexOf(a):-1,index:s.getIndex(),name:s.name,id:s.id,uniqueId:s.uniqueId,matrix:s.getBindMatrix().asArray(),rest:s.getRestMatrix().asArray(),linkedTransformNodeId:(t=s.getTransformNode())==null?void 0:t.id,linkedTransformNodeUniqueId:(i=s.getTransformNode())==null?void 0:i.uniqueId};e.bones.push(o),s.length&&(o.length=s.length),s.metadata&&(o.metadata=s.metadata),s.animations&&s.animations.length>0&&(o.animation=s.animations[0].serialize()),e.ranges=[];for(let l in this._ranges){let c=this._ranges[l];if(!c)continue;let f={};f.name=l,f.from=c.from,f.to=c.to,e.ranges.push(f)}}return e}static Parse(e,t){let i=new n(e.name,e.id,t);e.dimensionsAtRest&&(i.dimensionsAtRest=b.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,e.metadata&&(i.metadata=e.metadata);let r;for(r=0;r<e.bones.length;r++){let s=e.bones[r],a=e.bones[r].index,o=null;s.parentBoneIndex>-1&&(o=i.bones[s.parentBoneIndex]);let l=s.rest?Q.FromArray(s.rest):null,c=new po(s.name,i,o,Q.FromArray(s.matrix),l,null,a);s.id!==void 0&&s.id!==null&&(c.id=s.id),s.length&&(c.length=s.length),s.metadata&&(c.metadata=s.metadata),s.animation&&c.animations.push(gt.Parse(s.animation)),s.linkedTransformNodeId!==void 0&&s.linkedTransformNodeId!==null&&(i._hasWaitingData=!0,c._waitingTransformNodeId=s.linkedTransformNodeId),s.linkedTransformNodeUniqueId!==void 0&&s.linkedTransformNodeUniqueId!==null&&(i._hasWaitingData=!0,c._waitingTransformNodeUniqueId=s.linkedTransformNodeUniqueId)}if(e.ranges)for(r=0;r<e.ranges.length;r++){let s=e.ranges[r];i.createAnimationRange(s.name,s.from,s.to)}return i}computeAbsoluteMatrices(e=!1){(this._absoluteTransformIsDirty||e)&&(this.bones[0].computeAbsoluteMatrices(),this._absoluteTransformIsDirty=!1)}computeAbsoluteTransforms(e=!1){this.computeAbsoluteMatrices(e)}getPoseMatrix(){let e=null;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){let e=[],t=new Array(this.bones.length);for(let i=0;i<this.bones.length;i++)this._sortBones(i,e,t);this.bones=e}_sortBones(e,t,i){if(i[e])return;i[e]=!0;let r=this.bones[e];if(!r)return;r._index===void 0&&(r._index=e);let s=r.getParent();s&&this._sortBones(this.bones.indexOf(s),t,i),t.push(r)}setCurrentPoseAsRest(){for(let e of this.bones)e.setCurrentPoseAsRest()}}});var Ud,hw=y(()=>{jt();Si();Yi();qi();Yt();Or();ir();Ud=class n{get influence(){return this._influence}set influence(e){if(this._influence===e)return;let t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(t===0||e===0)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null,r=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uv2s=null,this._colors=null,this._uniqueId=0,this.onInfluenceChanged=new re,this._onDataLayoutChanged=new re,this.morphTargetManager=null,this._animationPropertiesOverride=null,this.id=e,this.morphTargetManager=r,this._scene=i||Oe.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}get hasUV2s(){return!!this._uv2s}get hasColors(){return!!this._colors}get vertexCount(){return this._positions?this._positions.length/3:this._normals?this._normals.length/3:this._tangents?this._tangents.length/3:this._uvs?this._uvs.length/2:this._uv2s?this._uv2s.length/2:this._colors?this._colors.length/4:0}setPositions(e){let t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){let t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){let t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){let t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}setUV2s(e){let t=this.hasUV2s;this._uv2s=e,t!==this.hasUV2s&&this._onDataLayoutChanged.notifyObservers(void 0)}getUV2s(){return this._uv2s}setColors(e){let t=this.hasColors;this._colors=e,t!==this.hasColors&&this._onDataLayoutChanged.notifyObservers(void 0)}getColors(){return this._colors}clone(){let e=at.Clone(()=>new n(this.name,this.influence,this._scene,this.morphTargetManager),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e._uv2s=this._uv2s,e._colors=this._colors,e}serialize(){let e={};return e.name=this.name,e.influence=this.influence,this.id!=null&&(e.id=this.id),e.uniqueId=this.uniqueId,e.positions=Array.prototype.slice.call(this.getPositions()),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),this.hasUV2s&&(e.uv2s=Array.prototype.slice.call(this.getUV2s())),this.hasColors&&(e.colors=Array.prototype.slice.call(this.getColors())),at.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t,i=null){let r=new n(e.name,e.influence,t,i);if(r.setPositions(e.positions),e.id!=null&&(r.id=e.id),e.normals&&r.setNormals(e.normals),e.tangents&&r.setTangents(e.tangents),e.uvs&&r.setUVs(e.uvs),e.uv2s&&r.setUV2s(e.uv2s),e.colors&&r.setColors(e.colors),e.animations){for(let s=0;s<e.animations.length;s++){let a=e.animations[s],o=Vn("BABYLON.Animation");o&&r.animations.push(o.Parse(a))}e.autoAnimate&&t&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1)}return r}static FromMesh(e,t,i){t||(t=e.name);let r=new n(t,i,e.getScene(),e.morphTargetManager);return r.setPositions(e.getVerticesData(D.PositionKind)),e.isVerticesDataPresent(D.NormalKind)&&r.setNormals(e.getVerticesData(D.NormalKind)),e.isVerticesDataPresent(D.TangentKind)&&r.setTangents(e.getVerticesData(D.TangentKind)),e.isVerticesDataPresent(D.UVKind)&&r.setUVs(e.getVerticesData(D.UVKind)),e.isVerticesDataPresent(D.UV2Kind)&&r.setUV2s(e.getVerticesData(D.UV2Kind)),e.isVerticesDataPresent(D.ColorKind)&&r.setColors(e.getVerticesData(D.ColorKind)),r}};P([F()],Ud.prototype,"id",void 0);P([F()],Ud.prototype,"morphTargetManager",void 0)});var YM,L9=y(()=>{Kr();YM=class n extends _e{get depth(){return this._depth}constructor(e,t,i,r,s,a,o=!0,l=!1,c=_e.TRILINEAR_SAMPLINGMODE,f=0,d,u){super(null,a,!o,l),this.format=s,this._texture=a.getEngine().createRawTexture2DArray(e,t,i,r,s,o,l,c,null,f,d!=null?d:0,u),this._depth=r,this.is2DArray=!0}update(e){this.updateMipLevel(e,0)}updateMipLevel(e,t){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,t)}static CreateRGBATexture(e,t,i,r,s,a=!0,o=!1,l=3,c=0){return new n(e,t,i,r,5,s,a,o,l,c)}}});var _h,D9=y(()=>{Wo();wt();Yi();hw();L9();_h=class n{set areUpdatesFrozen(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(this._forceUpdateWhenUnfrozen),this._forceUpdateWhenUnfrozen=!1))}get areUpdatesFrozen(){return this._blockCounter>0}constructor(e=null,t){if(this.meshName=t,this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Qi(16),this._supportsPositions=!1,this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._supportsUV2s=!1,this._supportsColors=!1,this._vertexCount=0,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._mustSynchronize=!0,this._forceUpdateWhenUnfrozen=!1,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._parentContainer=null,this.optimizeInfluencers=!0,this.enablePositionMorphing=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this.enableUV2Morphing=!0,this.enableColorMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,this.metadata=null,this._influencesAreDirty=!1,this._needUpdateInfluences=!1,e||(e=Oe.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();let i=this._scene.getEngine().getCaps();this._canUseTextureForTargets=i.canUseGLVertexID&&i.textureFloat&&i.maxVertexTextureImageUnits>0&&i.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return n.ConstantTargetCountForTextureMode>0&&this.isUsingTextureForTargets?n.ConstantTargetCountForTextureMode:this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._mustSynchronize=!0,this._syncActiveTargets())}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsPositions(){return this._supportsPositions&&this.enablePositionMorphing}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get supportsUV2s(){return this._supportsUV2s&&this.enableUV2Morphing}get supportsColors(){return this._supportsColors&&this.enableColorMorphing}get hasPositions(){return this._supportsPositions}get hasNormals(){return this._supportsNormals}get hasTangents(){return this._supportsTangents}get hasUVs(){return this._supportsUVs}get hasUV2s(){return this._supportsUV2s}get hasColors(){return this._supportsColors}get numTargets(){return this._targets.length}get numInfluencers(){return this._influencesAreDirty&&this._syncActiveTargets(),this._activeTargets.length}get influences(){return this._influencesAreDirty&&this._syncActiveTargets(),this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets!==e&&(this._useTextureToStoreTargets=e,this._mustSynchronize=!0,this._syncActiveTargets())}get isUsingTextureForTargets(){var e;return n.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!((e=this._scene)!=null&&e.getEngine().getCaps().disableMorphTargetTexture)}getActiveTarget(e){return this._influencesAreDirty&&this._syncActiveTargets(),this._activeTargets.data[e]}getTarget(e){return this._targets[e]}getTargetByName(e){for(let t of this._targets)if(t.name===e)return t;return null}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add(t=>{this.areUpdatesFrozen&&t&&(this._forceUpdateWhenUnfrozen=!0),this._influencesAreDirty=!0,this._needUpdateInfluences=this._needUpdateInfluences||t})),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add(()=>{this._mustSynchronize=!0,this._syncActiveTargets()})),this._mustSynchronize=!0,this._syncActiveTargets()}removeTarget(e){let t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._mustSynchronize=!0,this._syncActiveTargets()),this._scene&&this._scene.stopAnimation(e)}_bind(e){this._influencesAreDirty&&this._syncActiveTargets(),e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setFloat("morphTargetCount",this.numInfluencers)}clone(){let e=new n(this._scene);e.areUpdatesFrozen=!0;for(let t of this._targets)e.addTarget(t.clone());return e.areUpdatesFrozen=!1,e.enablePositionMorphing=this.enablePositionMorphing,e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e.enableUV2Morphing=this.enableUV2Morphing,e.enableColorMorphing=this.enableColorMorphing,e.metadata=this.metadata,e}serialize(){let e={};e.id=this.uniqueId,e.meshName=this.meshName,e.targets=[];for(let t of this._targets)e.targets.push(t.serialize());return this.metadata&&(e.metadata=this.metadata),e}_syncActiveTargets(e=!1){if(this.areUpdatesFrozen)return;e=e||this._needUpdateInfluences,this._needUpdateInfluences=!1,this._influencesAreDirty=!1;let t=!!this._targetStoreTexture,i=this.isUsingTextureForTargets;(this._mustSynchronize||t!==i)&&(this._mustSynchronize=!1,this.synchronize());let r=0;this._activeTargets.reset(),(!this._morphTargetTextureIndices||this._morphTargetTextureIndices.length!==this._targets.length)&&(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let s=-1;for(let a of this._targets)if(s++,!(a.influence===0&&this.optimizeInfluencers)){if(this._activeTargets.length>=n.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(a),this._morphTargetTextureIndices[r]=s,this._tempInfluences[r++]=a.influence}this._morphTargetTextureIndices.length!==r&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,r)),(!this._influences||this._influences.length!==r)&&(this._influences=new Float32Array(r));for(let a=0;a<r;a++)this._influences[a]=this._tempInfluences[a];if(e&&this._scene)for(let a of this._scene.meshes)a.morphTargetManager===this&&(i?a._markSubMeshesAsAttributesDirty():a._syncGeometryWithMorphTargetManager())}synchronize(){var t;if(!this._scene||this.areUpdatesFrozen)return;let e=this._scene.getEngine();this._supportsPositions=!0,this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._supportsUV2s=!0,this._supportsColors=!0,this._vertexCount=0,(t=this._targetStoreTexture)==null||t.dispose(),this._targetStoreTexture=null,this.isUsingTextureForTargets&&this._targets.length>e.getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1);for(let i of this._targets){this._supportsPositions=this._supportsPositions&&i.hasPositions,this._supportsNormals=this._supportsNormals&&i.hasNormals,this._supportsTangents=this._supportsTangents&&i.hasTangents,this._supportsUVs=this._supportsUVs&&i.hasUVs,this._supportsUV2s=this._supportsUV2s&&i.hasUV2s,this._supportsColors=this._supportsColors&&i.hasColors;let r=i.vertexCount;if(this._vertexCount===0)this._vertexCount=r;else if(this._vertexCount!==r){te.Error(`Incompatible target. Targets must all have the same vertices count. Current vertex count: ${this._vertexCount}, vertex count for target "${i.name}": ${r}`);return}}if(this.isUsingTextureForTargets){this._textureVertexStride=0,this._supportsPositions&&this._textureVertexStride++,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._supportsUV2s&&this._textureVertexStride++,this._supportsColors&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;let i=e.getCaps().maxTextureSize;this._textureWidth>i&&(this._textureHeight=Math.ceil(this._textureWidth/i),this._textureWidth=i);let r=this._targets.length,s=new Float32Array(r*this._textureWidth*this._textureHeight*4),a;for(let o=0;o<r;o++){let l=this._targets[o],c=l.getPositions(),f=l.getNormals(),d=l.getUVs(),u=l.getTangents(),h=l.getUV2s(),m=l.getColors();a=o*this._textureWidth*this._textureHeight*4;for(let g=0;g<this._vertexCount;g++)this._supportsPositions&&c&&(s[a]=c[g*3],s[a+1]=c[g*3+1],s[a+2]=c[g*3+2],a+=4),this._supportsNormals&&f&&(s[a]=f[g*3],s[a+1]=f[g*3+1],s[a+2]=f[g*3+2],a+=4),this._supportsUVs&&d&&(s[a]=d[g*2],s[a+1]=d[g*2+1],a+=4),this._supportsTangents&&u&&(s[a]=u[g*3],s[a+1]=u[g*3+1],s[a+2]=u[g*3+2],a+=4),this._supportsUV2s&&h&&(s[a]=h[g*2],s[a+1]=h[g*2+1],a+=4),this._supportsColors&&m&&(s[a]=m[g*4],s[a+1]=m[g*4+1],s[a+2]=m[g*4+2],s[a+3]=m[g*4+3],a+=4)}this._targetStoreTexture=YM.CreateRGBATexture(s,this._textureWidth,this._textureHeight,r,this._scene,!1,!1,1,1),this._targetStoreTexture.name=`Morph texture_${this.uniqueId}`}for(let i of this._scene.meshes)i.morphTargetManager===this&&i._syncGeometryWithMorphTargetManager()}dispose(){if(this._targetStoreTexture&&this._targetStoreTexture.dispose(),this._targetStoreTexture=null,this.metadata=null,this._scene){if(this._scene.removeMorphTargetManager(this),this._parentContainer){let e=this._parentContainer.morphTargetManagers.indexOf(this);e>-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(let e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){let i=new n(t);for(let r of e.targets)i.addTarget(Ud.Parse(r,t,i));return e.metadata&&(i.metadata=e.metadata),i}};_h.EnableTextureStorage=!0;_h.MaxActiveMorphTargetsInVertexAttributeMode=8;_h.ConstantTargetCountForTextureMode=0});function KM(n,e,t){bE(n)&&te.Warn(`Extension with the name '${n}' already exists`),mw.set(n,{isGLTFExtension:e,factory:t})}function bE(n){return mw.delete(n)}var mw,O9,pw=y(()=>{wt();mw=new Map,O9=mw});var z,gw=y(()=>{z=class{};z.AUTOSAMPLERSUFFIX="Sampler";z.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS";z.ALPHA_DISABLE=0;z.ALPHA_ADD=1;z.ALPHA_COMBINE=2;z.ALPHA_SUBTRACT=3;z.ALPHA_MULTIPLY=4;z.ALPHA_MAXIMIZED=5;z.ALPHA_ONEONE=6;z.ALPHA_PREMULTIPLIED=7;z.ALPHA_PREMULTIPLIED_PORTERDUFF=8;z.ALPHA_INTERPOLATE=9;z.ALPHA_SCREENMODE=10;z.ALPHA_ONEONE_ONEONE=11;z.ALPHA_ALPHATOCOLOR=12;z.ALPHA_REVERSEONEMINUS=13;z.ALPHA_SRC_DSTONEMINUSSRCALPHA=14;z.ALPHA_ONEONE_ONEZERO=15;z.ALPHA_EXCLUSION=16;z.ALPHA_LAYER_ACCUMULATE=17;z.ALPHA_MIN=18;z.ALPHA_MAX=19;z.ALPHA_DUAL_SRC0_ADD_SRC1xDST=20;z.ALPHA_EQUATION_ADD=0;z.ALPHA_EQUATION_SUBSTRACT=1;z.ALPHA_EQUATION_REVERSE_SUBTRACT=2;z.ALPHA_EQUATION_MAX=3;z.ALPHA_EQUATION_MIN=4;z.ALPHA_EQUATION_DARKEN=5;z.DELAYLOADSTATE_NONE=0;z.DELAYLOADSTATE_LOADED=1;z.DELAYLOADSTATE_LOADING=2;z.DELAYLOADSTATE_NOTLOADED=4;z.NEVER=512;z.ALWAYS=519;z.LESS=513;z.EQUAL=514;z.LEQUAL=515;z.GREATER=516;z.GEQUAL=518;z.NOTEQUAL=517;z.KEEP=7680;z.ZERO=0;z.REPLACE=7681;z.INCR=7682;z.DECR=7683;z.INVERT=5386;z.INCR_WRAP=34055;z.DECR_WRAP=34056;z.TEXTURE_CLAMP_ADDRESSMODE=0;z.TEXTURE_WRAP_ADDRESSMODE=1;z.TEXTURE_MIRROR_ADDRESSMODE=2;z.TEXTURE_CREATIONFLAG_STORAGE=1;z.TEXTUREFORMAT_ALPHA=0;z.TEXTUREFORMAT_LUMINANCE=1;z.TEXTUREFORMAT_LUMINANCE_ALPHA=2;z.TEXTUREFORMAT_RGB=4;z.TEXTUREFORMAT_RGBA=5;z.TEXTUREFORMAT_RED=6;z.TEXTUREFORMAT_R=6;z.TEXTUREFORMAT_R16_UNORM=33322;z.TEXTUREFORMAT_RG16_UNORM=33324;z.TEXTUREFORMAT_RGB16_UNORM=32852;z.TEXTUREFORMAT_RGBA16_UNORM=32859;z.TEXTUREFORMAT_R16_SNORM=36760;z.TEXTUREFORMAT_RG16_SNORM=36761;z.TEXTUREFORMAT_RGB16_SNORM=36762;z.TEXTUREFORMAT_RGBA16_SNORM=36763;z.TEXTUREFORMAT_RG=7;z.TEXTUREFORMAT_RED_INTEGER=8;z.TEXTUREFORMAT_R_INTEGER=8;z.TEXTUREFORMAT_RG_INTEGER=9;z.TEXTUREFORMAT_RGB_INTEGER=10;z.TEXTUREFORMAT_RGBA_INTEGER=11;z.TEXTUREFORMAT_BGRA=12;z.TEXTUREFORMAT_DEPTH24_STENCIL8=13;z.TEXTUREFORMAT_DEPTH32_FLOAT=14;z.TEXTUREFORMAT_DEPTH16=15;z.TEXTUREFORMAT_DEPTH24=16;z.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17;z.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18;z.TEXTUREFORMAT_STENCIL8=19;z.TEXTUREFORMAT_UNDEFINED=4294967295;z.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492;z.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493;z.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495;z.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494;z.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779;z.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919;z.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778;z.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918;z.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777;z.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776;z.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917;z.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x4=37809;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x5=37810;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x5=37811;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x6=37812;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x5=37813;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x6=37814;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x8=37815;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x5=37816;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x6=37817;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x8=37818;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x10=37819;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x10=37820;z.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x12=37821;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR=37841;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR=37842;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR=37843;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR=37844;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR=37845;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR=37846;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR=37847;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR=37848;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR=37849;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR=37850;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR=37851;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR=37852;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR=37853;z.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196;z.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493;z.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494;z.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495;z.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496;z.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497;z.TEXTURETYPE_UNSIGNED_BYTE=0;z.TEXTURETYPE_UNSIGNED_INT=0;z.TEXTURETYPE_FLOAT=1;z.TEXTURETYPE_HALF_FLOAT=2;z.TEXTURETYPE_BYTE=3;z.TEXTURETYPE_SHORT=4;z.TEXTURETYPE_UNSIGNED_SHORT=5;z.TEXTURETYPE_INT=6;z.TEXTURETYPE_UNSIGNED_INTEGER=7;z.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;z.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;z.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;z.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;z.TEXTURETYPE_UNSIGNED_INT_24_8=12;z.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;z.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;z.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;z.TEXTURETYPE_UNDEFINED=16;z.TEXTURE_2D=3553;z.TEXTURE_2D_ARRAY=35866;z.TEXTURE_CUBE_MAP=34067;z.TEXTURE_CUBE_MAP_ARRAY=3735928559;z.TEXTURE_3D=32879;z.TEXTURE_NEAREST_SAMPLINGMODE=1;z.TEXTURE_NEAREST_NEAREST=1;z.TEXTURE_BILINEAR_SAMPLINGMODE=2;z.TEXTURE_LINEAR_LINEAR=2;z.TEXTURE_TRILINEAR_SAMPLINGMODE=3;z.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;z.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;z.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;z.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;z.TEXTURE_NEAREST_LINEAR=7;z.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;z.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;z.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;z.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;z.TEXTURE_LINEAR_NEAREST=12;z.TEXTURE_EXPLICIT_MODE=0;z.TEXTURE_SPHERICAL_MODE=1;z.TEXTURE_PLANAR_MODE=2;z.TEXTURE_CUBIC_MODE=3;z.TEXTURE_PROJECTION_MODE=4;z.TEXTURE_SKYBOX_MODE=5;z.TEXTURE_INVCUBIC_MODE=6;z.TEXTURE_EQUIRECTANGULAR_MODE=7;z.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;z.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;z.TEXTURE_FILTERING_QUALITY_OFFLINE=4096;z.TEXTURE_FILTERING_QUALITY_HIGH=64;z.TEXTURE_FILTERING_QUALITY_MEDIUM=16;z.TEXTURE_FILTERING_QUALITY_LOW=8;z.SCALEMODE_FLOOR=1;z.SCALEMODE_NEAREST=2;z.SCALEMODE_CEILING=3;z.MATERIAL_TextureDirtyFlag=1;z.MATERIAL_LightDirtyFlag=2;z.MATERIAL_FresnelDirtyFlag=4;z.MATERIAL_AttributesDirtyFlag=8;z.MATERIAL_MiscDirtyFlag=16;z.MATERIAL_PrePassDirtyFlag=32;z.MATERIAL_ImageProcessingDirtyFlag=64;z.MATERIAL_AllDirtyFlag=127;z.MATERIAL_TriangleFillMode=0;z.MATERIAL_WireFrameFillMode=1;z.MATERIAL_PointFillMode=2;z.MATERIAL_PointListDrawMode=3;z.MATERIAL_LineListDrawMode=4;z.MATERIAL_LineLoopDrawMode=5;z.MATERIAL_LineStripDrawMode=6;z.MATERIAL_TriangleStripDrawMode=7;z.MATERIAL_TriangleFanDrawMode=8;z.MATERIAL_ClockWiseSideOrientation=0;z.MATERIAL_CounterClockWiseSideOrientation=1;z.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR=0;z.MATERIAL_DIFFUSE_MODEL_BURLEY=1;z.MATERIAL_DIFFUSE_MODEL_LAMBERT=2;z.MATERIAL_DIFFUSE_MODEL_LEGACY=3;z.MATERIAL_DIELECTRIC_SPECULAR_MODEL_GLTF=0;z.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR=1;z.MATERIAL_CONDUCTOR_SPECULAR_MODEL_GLTF=0;z.MATERIAL_CONDUCTOR_SPECULAR_MODEL_OPENPBR=1;z.ACTION_NothingTrigger=0;z.ACTION_OnPickTrigger=1;z.ACTION_OnLeftPickTrigger=2;z.ACTION_OnRightPickTrigger=3;z.ACTION_OnCenterPickTrigger=4;z.ACTION_OnPickDownTrigger=5;z.ACTION_OnDoublePickTrigger=6;z.ACTION_OnPickUpTrigger=7;z.ACTION_OnPickOutTrigger=16;z.ACTION_OnLongPressTrigger=8;z.ACTION_OnPointerOverTrigger=9;z.ACTION_OnPointerOutTrigger=10;z.ACTION_OnEveryFrameTrigger=11;z.ACTION_OnIntersectionEnterTrigger=12;z.ACTION_OnIntersectionExitTrigger=13;z.ACTION_OnKeyDownTrigger=14;z.ACTION_OnKeyUpTrigger=15;z.PARTICLES_BILLBOARDMODE_Y=2;z.PARTICLES_BILLBOARDMODE_ALL=7;z.PARTICLES_BILLBOARDMODE_STRETCHED=8;z.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9;z.MESHES_CULLINGSTRATEGY_STANDARD=0;z.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;z.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;z.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;z.SCENELOADER_NO_LOGGING=0;z.SCENELOADER_MINIMAL_LOGGING=1;z.SCENELOADER_SUMMARY_LOGGING=2;z.SCENELOADER_DETAILED_LOGGING=3;z.PREPASS_IRRADIANCE_LEGACY_TEXTURE_TYPE=0;z.PREPASS_POSITION_TEXTURE_TYPE=1;z.PREPASS_VELOCITY_TEXTURE_TYPE=2;z.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3;z.PREPASS_COLOR_TEXTURE_TYPE=4;z.PREPASS_DEPTH_TEXTURE_TYPE=5;z.PREPASS_NORMAL_TEXTURE_TYPE=6;z.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7;z.PREPASS_WORLD_NORMAL_TEXTURE_TYPE=8;z.PREPASS_LOCAL_POSITION_TEXTURE_TYPE=9;z.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE=10;z.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE=11;z.PREPASS_ALBEDO_TEXTURE_TYPE=12;z.PREPASS_NORMALIZED_VIEW_DEPTH_TEXTURE_TYPE=13;z.PREPASS_IRRADIANCE_TEXTURE_TYPE=14;z.BUFFER_CREATIONFLAG_READ=1;z.BUFFER_CREATIONFLAG_WRITE=2;z.BUFFER_CREATIONFLAG_READWRITE=3;z.BUFFER_CREATIONFLAG_UNIFORM=4;z.BUFFER_CREATIONFLAG_VERTEX=8;z.BUFFER_CREATIONFLAG_INDEX=16;z.BUFFER_CREATIONFLAG_STORAGE=32;z.BUFFER_CREATIONFLAG_INDIRECT=64;z.RENDERPASS_MAIN=0;z.INPUT_ALT_KEY=18;z.INPUT_CTRL_KEY=17;z.INPUT_META_KEY1=91;z.INPUT_META_KEY2=92;z.INPUT_META_KEY3=93;z.INPUT_SHIFT_KEY=16;z.SNAPSHOTRENDERING_STANDARD=0;z.SNAPSHOTRENDERING_FAST=1;z.PERSPECTIVE_CAMERA=0;z.ORTHOGRAPHIC_CAMERA=1;z.FOVMODE_VERTICAL_FIXED=0;z.FOVMODE_HORIZONTAL_FIXED=1;z.RIG_MODE_NONE=0;z.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;z.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;z.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;z.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;z.RIG_MODE_STEREOSCOPIC_INTERLACED=14;z.RIG_MODE_VR=20;z.RIG_MODE_CUSTOM=22;z.MAX_SUPPORTED_UV_SETS=6;z.GL_ALPHA_EQUATION_ADD=32774;z.GL_ALPHA_EQUATION_MIN=32775;z.GL_ALPHA_EQUATION_MAX=32776;z.GL_ALPHA_EQUATION_SUBTRACT=32778;z.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779;z.GL_ALPHA_FUNCTION_SRC=768;z.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769;z.GL_ALPHA_FUNCTION_SRC_ALPHA=770;z.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771;z.GL_ALPHA_FUNCTION_DST_ALPHA=772;z.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773;z.GL_ALPHA_FUNCTION_DST_COLOR=774;z.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775;z.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776;z.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769;z.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770;z.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771;z.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772;z.GL_ALPHA_FUNCTION_SRC1_COLOR=35065;z.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_COLOR=35066;z.GL_ALPHA_FUNCTION_SRC1_ALPHA=34185;z.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_ALPHA=35067;z.SnippetUrl="https://snippet.babylonjs.com";z.FOGMODE_NONE=0;z.FOGMODE_EXP=1;z.FOGMODE_EXP2=2;z.FOGMODE_LINEAR=3;z.BYTE=5120;z.UNSIGNED_BYTE=5121;z.SHORT=5122;z.UNSIGNED_SHORT=5123;z.INT=5124;z.UNSIGNED_INT=5125;z.FLOAT=5126;z.PositionKind="position";z.NormalKind="normal";z.TangentKind="tangent";z.UVKind="uv";z.UV2Kind="uv2";z.UV3Kind="uv3";z.UV4Kind="uv4";z.UV5Kind="uv5";z.UV6Kind="uv6";z.ColorKind="color";z.ColorInstanceKind="instanceColor";z.MatricesIndicesKind="matricesIndices";z.MatricesWeightsKind="matricesWeights";z.MatricesIndicesExtraKind="matricesIndicesExtra";z.MatricesWeightsExtraKind="matricesWeightsExtra";z.ANIMATIONTYPE_FLOAT=0;z.ANIMATIONTYPE_VECTOR3=1;z.ANIMATIONTYPE_QUATERNION=2;z.ANIMATIONTYPE_MATRIX=3;z.ANIMATIONTYPE_COLOR3=4;z.ANIMATIONTYPE_COLOR4=7;z.ANIMATIONTYPE_VECTOR2=5;z.ANIMATIONTYPE_SIZE=6;z.ShadowMinZ=0;z.ShadowMaxZ=1e4;z.OUTLINELAYER_SAMPLING_TRIDIRECTIONAL=0;z.OUTLINELAYER_SAMPLING_OCTADIRECTIONAL=1});var Jrt,N9=y(()=>{Jrt=[{regex:new RegExp("^/nodes/\\d+/extensions/")}]});function Vd(n,e,t,i){let r=lt(n,e);return i?r[t][i]:r[t]}function lt(n,e,t){var i,r,s;return(s=(r=n._data)==null?void 0:r[(i=t==null?void 0:t.fillMode)!=null?i:z.MATERIAL_TriangleFillMode])==null?void 0:s.babylonMaterial}function Tn(n,e){return{offset:{componentsCount:2,type:"Vector2",get:(t,i,r)=>{let s=Vd(t,r,n,e);return new Fe(s==null?void 0:s.uOffset,s==null?void 0:s.vOffset)},getTarget:lt,set:(t,i,r,s)=>{let a=Vd(i,s,n,e);a.uOffset=t.x,a.vOffset=t.y},getPropertyName:[()=>`${n}${e?"."+e:""}.uOffset`,()=>`${n}${e?"."+e:""}.vOffset`]},rotation:{type:"number",get:(t,i,r)=>{var s;return(s=Vd(t,r,n,e))==null?void 0:s.wAng},getTarget:lt,set:(t,i,r,s)=>Vd(i,s,n,e).wAng=t,getPropertyName:[()=>`${n}${e?"."+e:""}.wAng`]},scale:{componentsCount:2,type:"Vector2",get:(t,i,r)=>{let s=Vd(t,r,n,e);return new Fe(s==null?void 0:s.uScale,s==null?void 0:s.vScale)},getTarget:lt,set:(t,i,r,s)=>{let a=Vd(i,s,n,e);a.uScale=t.x,a.vScale=t.y},getPropertyName:[()=>`${n}${e?"."+e:""}.uScale`,()=>`${n}${e?"."+e:""}.vScale`]}}}function ME(n){let e=n.split("/").map(i=>i.replace(/{}/g,"__array__")),t=w9;for(let i of e)i&&(t=t[i]);if(t&&t.type&&t.get)return t}function yE(n,e){let t=n.split("/").map(r=>r.replace(/{}/g,"__array__")),i=w9;for(let r of t)r&&(i=i[r]);i&&i.type&&i.get&&(i.interpolation=e)}var l_e,c_e,f_e,d_e,u_e,h_e,w9,_w=y(()=>{He();gw();$t();uO();N9();l_e={length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonTransformNode),getPropertyName:[()=>"length"]},__array__:{__target__:!0,translation:{type:"Vector3",get:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.position},set:(n,e)=>{var t;return(t=e._babylonTransformNode)==null?void 0:t.position.copyFrom(n)},getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"position"]},rotation:{type:"Quaternion",get:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.rotationQuaternion},set:(n,e)=>{var t,i;return(i=(t=e._babylonTransformNode)==null?void 0:t.rotationQuaternion)==null?void 0:i.copyFrom(n)},getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"rotationQuaternion"]},scale:{type:"Vector3",get:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.scaling},set:(n,e)=>{var t;return(t=e._babylonTransformNode)==null?void 0:t.scaling.copyFrom(n)},getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"scaling"]},weights:{length:{type:"number",get:n=>n._numMorphTargets,getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"influence"]},__array__:{__target__:!0,type:"number",get:(n,e)=>{var t,i;return e!==void 0?(i=(t=n._primitiveBabylonMeshes)==null?void 0:t[0].morphTargetManager)==null?void 0:i.getTarget(e).influence:void 0},getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"influence"]},type:"number[]",get:(n,e)=>[0],getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"influence"]},matrix:{type:"Matrix",get:n=>{var e,t,i;return Q.Compose((e=n._babylonTransformNode)==null?void 0:e.scaling,(t=n._babylonTransformNode)==null?void 0:t.rotationQuaternion,(i=n._babylonTransformNode)==null?void 0:i.position)},getTarget:n=>n._babylonTransformNode,isReadOnly:!0},globalMatrix:{type:"Matrix",get:n=>{var r,s,a,o,l,c,f;let e=Q.Identity(),t=n.parent;for(;t&&t.parent;)t=t.parent;let i=((r=n._babylonTransformNode)==null?void 0:r.position._isDirty)||((a=(s=n._babylonTransformNode)==null?void 0:s.rotationQuaternion)==null?void 0:a._isDirty)||((o=n._babylonTransformNode)==null?void 0:o.scaling._isDirty);if(t){let d=(l=t._babylonTransformNode)==null?void 0:l.computeWorldMatrix(!0).invert();d&&((f=(c=n._babylonTransformNode)==null?void 0:c.computeWorldMatrix(i))==null||f.multiplyToRef(d,e))}else n._babylonTransformNode&&e.copyFrom(n._babylonTransformNode.computeWorldMatrix(i));return e},getTarget:n=>n._babylonTransformNode,isReadOnly:!0},extensions:{EXT_lights_ies:{multiplier:{type:"number",get:n=>{var e,t;return(t=(e=n._babylonTransformNode)==null?void 0:e.getChildren(i=>i instanceof Zr,!0)[0])==null?void 0:t.intensity},getTarget:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.getChildren(t=>t instanceof Zr,!0)[0]},set:(n,e)=>{if(e._babylonTransformNode){let t=e._babylonTransformNode.getChildren(i=>i instanceof Zr,!0)[0];t&&(t.intensity=n)}}},color:{type:"Color3",get:n=>{var e,t;return(t=(e=n._babylonTransformNode)==null?void 0:e.getChildren(i=>i instanceof Zr,!0)[0])==null?void 0:t.diffuse},getTarget:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.getChildren(t=>t instanceof Zr,!0)[0]},set:(n,e)=>{if(e._babylonTransformNode){let t=e._babylonTransformNode.getChildren(i=>i instanceof Zr,!0)[0];t&&(t.diffuse=n)}}}},KHR_node_visibility:{visible:{type:"boolean",get:n=>n._primitiveBabylonMeshes?n._primitiveBabylonMeshes[0].isVisible:!1,getTarget:()=>{},set:(n,e)=>{e._primitiveBabylonMeshes&&e._primitiveBabylonMeshes.forEach(t=>t.isVisible=n)}}}}}},c_e={length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonAnimationGroup),getPropertyName:[()=>"length"]},__array__:{}},f_e={length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>{var t;return(t=e.primitives[0]._instanceData)==null?void 0:t.babylonSourceMesh}),getPropertyName:[()=>"length"]},__array__:{}},d_e={__array__:{__target__:!0,orthographic:{xmag:{componentsCount:2,type:"Vector2",get:n=>{var e,t,i,r;return new Fe((t=(e=n._babylonCamera)==null?void 0:e.orthoLeft)!=null?t:0,(r=(i=n._babylonCamera)==null?void 0:i.orthoRight)!=null?r:0)},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.orthoLeft=n.x,e._babylonCamera.orthoRight=n.y)},getTarget:n=>n,getPropertyName:[()=>"orthoLeft",()=>"orthoRight"]},ymag:{componentsCount:2,type:"Vector2",get:n=>{var e,t,i,r;return new Fe((t=(e=n._babylonCamera)==null?void 0:e.orthoBottom)!=null?t:0,(r=(i=n._babylonCamera)==null?void 0:i.orthoTop)!=null?r:0)},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.orthoBottom=n.x,e._babylonCamera.orthoTop=n.y)},getTarget:n=>n,getPropertyName:[()=>"orthoBottom",()=>"orthoTop"]},zfar:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.maxZ},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.maxZ=n)},getTarget:n=>n,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.minZ},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.minZ=n)},getTarget:n=>n,getPropertyName:[()=>"minZ"]}},perspective:{aspectRatio:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.getEngine().getAspectRatio(n._babylonCamera)},getTarget:n=>n,getPropertyName:[()=>"aspectRatio"],isReadOnly:!0},yfov:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.fov},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.fov=n)},getTarget:n=>n,getPropertyName:[()=>"fov"]},zfar:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.maxZ},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.maxZ=n)},getTarget:n=>n,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.minZ},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.minZ=n)},getTarget:n=>n,getPropertyName:[()=>"minZ"]}}}},u_e={__array__:{__target__:!0,emissiveFactor:{type:"Color3",get:(n,e,t)=>lt(n,e,t).emissiveColor,set:(n,e,t,i)=>lt(e,t,i).emissiveColor.copyFrom(n),getTarget:(n,e,t)=>lt(n,e,t),getPropertyName:[()=>"emissiveColor"]},emissiveTexture:{extensions:{KHR_texture_transform:Tn("emissiveTexture")}},normalTexture:{scale:{type:"number",get:(n,e,t)=>{var i;return(i=Vd(n,t,"bumpTexture"))==null?void 0:i.level},set:(n,e,t,i)=>{let r=Vd(e,i,"bumpTexture");r&&(r.level=n)},getTarget:(n,e,t)=>lt(n,e,t),getPropertyName:[()=>"level"]},extensions:{KHR_texture_transform:Tn("bumpTexture")}},occlusionTexture:{strength:{type:"number",get:(n,e,t)=>lt(n,e,t).ambientTextureStrength,set:(n,e,t,i)=>{let r=lt(e,t,i);r&&(r.ambientTextureStrength=n)},getTarget:(n,e,t)=>lt(n,e,t),getPropertyName:[()=>"ambientTextureStrength"]},extensions:{KHR_texture_transform:Tn("ambientTexture")}},pbrMetallicRoughness:{baseColorFactor:{type:"Color4",get:(n,e,t)=>{let i=lt(n,e,t);return ht.FromColor3(i.albedoColor,i.alpha)},set:(n,e,t,i)=>{let r=lt(e,t,i);r.albedoColor.set(n.r,n.g,n.b),r.alpha=n.a},getTarget:(n,e,t)=>lt(n,e,t),getPropertyName:[()=>"albedoColor",()=>"alpha"]},baseColorTexture:{extensions:{KHR_texture_transform:Tn("albedoTexture")}},metallicFactor:{type:"number",get:(n,e,t)=>lt(n,e,t).metallic,set:(n,e,t,i)=>{let r=lt(e,t,i);r&&(r.metallic=n)},getTarget:(n,e,t)=>lt(n,e,t),getPropertyName:[()=>"metallic"]},roughnessFactor:{type:"number",get:(n,e,t)=>lt(n,e,t).roughness,set:(n,e,t,i)=>{let r=lt(e,t,i);r&&(r.roughness=n)},getTarget:(n,e,t)=>lt(n,e,t),getPropertyName:[()=>"roughness"]},metallicRoughnessTexture:{extensions:{KHR_texture_transform:Tn("metallicTexture")}}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:{type:"number",get:(n,e,t)=>lt(n,e,t).anisotropy.intensity,set:(n,e,t,i)=>{lt(e,t,i).anisotropy.intensity=n},getTarget:(n,e,t)=>lt(n,e,t),getPropertyName:[()=>"anisotropy.intensity"]},anisotropyRotation:{type:"number",get:(n,e,t)=>lt(n,e,t).anisotropy.angle,set:(n,e,t,i)=>{lt(e,t,i).anisotropy.angle=n},getTarget:(n,e,t)=>lt(n,e,t),getPropertyName:[()=>"anisotropy.angle"]},anisotropyTexture:{extensions:{KHR_texture_transform:Tn("anisotropy","texture")}}},KHR_materials_clearcoat:{clearcoatFactor:{type:"number",get:(n,e,t)=>lt(n,e,t).clearCoat.intensity,set:(n,e,t,i)=>{lt(e,t,i).clearCoat.intensity=n},getTarget:(n,e,t)=>lt(n,e,t),getPropertyName:[()=>"clearCoat.intensity"]},clearcoatRoughnessFactor:{type:"number",get:(n,e,t)=>lt(n,e,t).clearCoat.roughness,set:(n,e,t,i)=>{lt(e,t,i).clearCoat.roughness=n},getTarget:(n,e,t)=>lt(n,e,t),getPropertyName:[()=>"clearCoat.roughness"]},clearcoatTexture:{extensions:{KHR_texture_transform:Tn("clearCoat","texture")}},clearcoatNormalTexture:{scale:{type:"number",get:(n,e,t)=>{var i;return(i=lt(n,e,t).clearCoat.bumpTexture)==null?void 0:i.level},getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).clearCoat.bumpTexture.level=n},extensions:{KHR_texture_transform:Tn("clearCoat","bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:Tn("clearCoat","textureRoughness")}}},KHR_materials_dispersion:{dispersion:{type:"number",get:(n,e,t)=>lt(n,e,t).subSurface.dispersion,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).subSurface.dispersion=n}},KHR_materials_emissive_strength:{emissiveStrength:{type:"number",get:(n,e,t)=>lt(n,e,t).emissiveIntensity,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).emissiveIntensity=n}},KHR_materials_ior:{ior:{type:"number",get:(n,e,t)=>lt(n,e,t).indexOfRefraction,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).indexOfRefraction=n}},KHR_materials_iridescence:{iridescenceFactor:{type:"number",get:(n,e,t)=>lt(n,e,t).iridescence.intensity,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).iridescence.intensity=n},iridescenceIor:{type:"number",get:(n,e,t)=>lt(n,e,t).iridescence.indexOfRefraction,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).iridescence.indexOfRefraction=n},iridescenceTexture:{extensions:{KHR_texture_transform:Tn("iridescence","texture")}},iridescenceThicknessMaximum:{type:"number",get:(n,e,t)=>lt(n,e,t).iridescence.maximumThickness,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).iridescence.maximumThickness=n},iridescenceThicknessMinimum:{type:"number",get:(n,e,t)=>lt(n,e,t).iridescence.minimumThickness,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).iridescence.minimumThickness=n},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:Tn("iridescence","thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:{type:"Color3",get:(n,e,t)=>lt(n,e,t).sheen.color,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).sheen.color.copyFrom(n)},sheenColorTexture:{extensions:{KHR_texture_transform:Tn("sheen","texture")}},sheenRoughnessFactor:{type:"number",get:(n,e,t)=>lt(n,e,t).sheen.intensity,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).sheen.intensity=n},sheenRoughnessTexture:{extensions:{KHR_texture_transform:Tn("sheen","thicknessTexture")}}},KHR_materials_specular:{specularFactor:{type:"number",get:(n,e,t)=>lt(n,e,t).metallicF0Factor,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).metallicF0Factor=n,getPropertyName:[()=>"metallicF0Factor"]},specularColorFactor:{type:"Color3",get:(n,e,t)=>lt(n,e,t).metallicReflectanceColor,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).metallicReflectanceColor.copyFrom(n),getPropertyName:[()=>"metallicReflectanceColor"]},specularTexture:{extensions:{KHR_texture_transform:Tn("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:Tn("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:{type:"number",get:(n,e,t)=>lt(n,e,t).subSurface.refractionIntensity,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).subSurface.refractionIntensity=n,getPropertyName:[()=>"subSurface.refractionIntensity"]},transmissionTexture:{extensions:{KHR_texture_transform:Tn("subSurface","refractionIntensityTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:{type:"number",get:(n,e,t)=>lt(n,e,t).subSurface.translucencyIntensity,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).subSurface.translucencyIntensity=n},diffuseTransmissionTexture:{extensions:{KHR_texture_transform:Tn("subSurface","translucencyIntensityTexture")}},diffuseTransmissionColorFactor:{type:"Color3",get:(n,e,t)=>lt(n,e,t).subSurface.translucencyColor,getTarget:lt,set:(n,e,t,i)=>{var r;return n&&((r=lt(e,t,i).subSurface.translucencyColor)==null?void 0:r.copyFrom(n))}},diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:Tn("subSurface","translucencyColorTexture")}}},KHR_materials_volume:{attenuationColor:{type:"Color3",get:(n,e,t)=>lt(n,e,t).subSurface.tintColor,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).subSurface.tintColor.copyFrom(n)},attenuationDistance:{type:"number",get:(n,e,t)=>lt(n,e,t).subSurface.tintColorAtDistance,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).subSurface.tintColorAtDistance=n},thicknessFactor:{type:"number",get:(n,e,t)=>lt(n,e,t).subSurface.maximumThickness,getTarget:lt,set:(n,e,t,i)=>lt(e,t,i).subSurface.maximumThickness=n},thicknessTexture:{extensions:{KHR_texture_transform:Tn("subSurface","thicknessTexture")}}}}}},h_e={KHR_lights_punctual:{lights:{length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonLight),getPropertyName:[n=>"length"]},__array__:{__target__:!0,color:{type:"Color3",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.diffuse},set:(n,e)=>{var t;return(t=e._babylonLight)==null?void 0:t.diffuse.copyFrom(n)},getTarget:n=>n._babylonLight,getPropertyName:[n=>"diffuse"]},intensity:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.intensity},set:(n,e)=>e._babylonLight?e._babylonLight.intensity=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"intensity"]},range:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.range},set:(n,e)=>e._babylonLight?e._babylonLight.range=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"range"]},spot:{innerConeAngle:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.innerAngle},set:(n,e)=>e._babylonLight?e._babylonLight.innerAngle=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"innerConeAngle"]},outerConeAngle:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.angle},set:(n,e)=>e._babylonLight?e._babylonLight.angle=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"outerConeAngle"]}}}}},EXT_lights_area:{lights:{length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonLight),getPropertyName:[n=>"length"]},__array__:{__target__:!0,color:{type:"Color3",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.diffuse},set:(n,e)=>{var t;return(t=e._babylonLight)==null?void 0:t.diffuse.copyFrom(n)},getTarget:n=>n._babylonLight,getPropertyName:[n=>"diffuse"]},intensity:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.intensity},set:(n,e)=>e._babylonLight?e._babylonLight.intensity=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"intensity"]},size:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.height},set:(n,e)=>e._babylonLight?e._babylonLight.height=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"size"]},rect:{aspect:{type:"number",get:n=>{var e,t;return((e=n._babylonLight)==null?void 0:e.width)/((t=n._babylonLight)==null?void 0:t.height)},set:(n,e)=>e._babylonLight?e._babylonLight.width=n*e._babylonLight.height:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"aspect"]}}}}},EXT_lights_ies:{lights:{length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonLight),getPropertyName:[n=>"length"]}}},EXT_lights_image_based:{lights:{length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonTexture),getPropertyName:[n=>"length"]},__array__:{__target__:!0,intensity:{type:"number",get:n=>{var e;return(e=n._babylonTexture)==null?void 0:e.level},set:(n,e)=>{e._babylonTexture&&(e._babylonTexture.level=n)},getTarget:n=>n._babylonTexture},rotation:{type:"Quaternion",get:n=>{var e;return n._babylonTexture&&je.FromRotationMatrix((e=n._babylonTexture)==null?void 0:e.getReflectionTextureMatrix())},set:(n,e)=>{var t;e._babylonTexture&&((t=e._babylonTexture.getScene())!=null&&t.useRightHandedSystem||(n=je.Inverse(n)),Q.FromQuaternionToRef(n,e._babylonTexture.getReflectionTextureMatrix()))},getTarget:n=>n._babylonTexture}}}}};w9={cameras:d_e,nodes:l_e,materials:u_e,extensions:h_e,animations:c_e,meshes:f_e}});function vw(...n){let e=t=>!!t&&typeof t=="object";return n.reduce((t,i)=>{let r=Object.keys(i);for(let s of r){let a=t[s],o=i[s];Array.isArray(a)&&Array.isArray(o)?t[s]=a.concat(...o):e(a)&&e(o)?t[s]=vw(a,o):t[s]=o}return t},{})}var F9=y(()=>{});var IE,B9=y(()=>{IE=class{constructor(e){this._factory=e}get value(){return this._factory&&(this._value=this._factory(),this._factory=void 0),this._value}}});var jM,U9=y(()=>{He();gd();jM=class{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,r){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._yoyoDirection=1,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._coreRuntimeAnimation=null,this._animation=t,this._target=e,this._scene=i,this._host=r,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===gt.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=Q.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minFrame!==0){let a={frame:0,value:this._keys[0].value};this._keys.splice(0,0,a)}if(this._target instanceof Array){let a=0;for(let o of this._target)this._preparePath(o,a),this._getOriginalValues(a),a++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];let s=t.getEvents();if(s&&s.length>0)for(let a of s)this._events.push(a._clone());this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){let i=this._animation.targetPropertyPath;if(i.length>1){let r=e;for(let s=0;s<i.length-1;s++){let a=i[s];if(r=r[a],r===void 0)throw new Error(`Invalid property (${a}) in property path (${i.join(".")})`)}this._targetPath=i[i.length-1],this._activeTargets[t]=r}else this._targetPath=i[0],this._activeTargets[t]=e;if(this._activeTargets[t][this._targetPath]===void 0)throw new Error(`Invalid property (${this._targetPath}) in property path (${i.join(".")})`)}get animation(){return this._animation}reset(e=!1){if(e)if(this._target instanceof Array){let t=0;for(let i of this._target)this._originalValue[t]!==void 0&&this._setValue(i,this._activeTargets[t],this._originalValue[t],-1,t),t++}else this._originalValue[0]!==void 0&&this._setValue(this._target,this._directTarget,this._originalValue[0],-1,0);this._offsetsCache={},this._highLimitsCache={},this._currentFrame=0,this._blendingFactor=0;for(let t=0;t<this._events.length;t++)this._events[t].isDone=!1}isStopped(){return this._stopped}dispose(){let e=this._animation.runtimeAnimations.indexOf(this);e>-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;i<this._target.length;i++){let r=this._target[i];this._setValue(r,this._activeTargets[i],e,t,i)}return}this._setValue(this._target,this._directTarget,e,t,0)}_getOriginalValues(e=0){let t,i=this._activeTargets[e];if(gt.InheritOriginalValueFromActiveAnimations){let r=this._scene._activeAnimatables;for(let s=0;s<r.length;s++){let a=r[s]._runtimeAnimations;for(let o=0;o<a.length;o++){let l=a[o];if(l!==this&&l._targetPath===this._targetPath){for(let c=0;c<l._activeTargets.length;c++)if(l._activeTargets[c]===i&&l._originalValue[c]!==void 0){l._originalValue[c]&&l._originalValue[c].clone?this._originalValue[e]=l._originalValue[c].clone():this._originalValue[e]=l._originalValue[c];return}}}}}i.getLocalMatrix&&this._targetPath==="_matrix"?t=i.getLocalMatrix():t=i[this._targetPath],t&&t.clone?this._originalValue[e]=t.clone():this._originalValue[e]=t}_registerTargetForLateAnimationBinding(e,t){let i=e.target;this._scene._registeredForLateAnimationBindings.pushNoDuplicate(i),i._lateAnimationHolders||(i._lateAnimationHolders={}),i._lateAnimationHolders[e.targetPath]||(i._lateAnimationHolders[e.targetPath]={totalWeight:0,totalAdditiveWeight:0,animations:[],additiveAnimations:[],originalValue:t}),e.isAdditive?(i._lateAnimationHolders[e.targetPath].additiveAnimations.push(e),i._lateAnimationHolders[e.targetPath].totalAdditiveWeight+=e.weight):(i._lateAnimationHolders[e.targetPath].animations.push(e),i._lateAnimationHolders[e.targetPath].totalWeight+=e.weight)}_setValue(e,t,i,r,s){if(this._currentActiveTarget=t,this._weight=r,this._enableBlending&&this._blendingFactor<=1){if(!this._originalBlendValue){let o=t[this._targetPath];o.clone?this._originalBlendValue=o.clone():this._originalBlendValue=o}this._originalBlendValue.m?gt.AllowMatrixDecomposeForInterpolation?this._currentValue?Q.DecomposeLerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=Q.DecomposeLerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue?Q.LerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=Q.Lerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue=gt._UniversalLerp(this._originalBlendValue,i,this._blendingFactor);let a=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.blendingSpeed:this._animation.blendingSpeed;this._blendingFactor+=a}else this._currentValue?this._currentValue.copyFrom?this._currentValue.copyFrom(i):this._currentValue=i:i!=null&&i.clone?this._currentValue=i.clone():this._currentValue=i;r!==-1?this._registerTargetForLateAnimationBinding(this,this._originalValue[s]):this._animationState.loopMode===gt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT?this._currentValue.addToRef?this._currentValue.addToRef(this._originalValue[s],t[this._targetPath]):t[this._targetPath]=this._originalValue[s]+this._currentValue:t[this._targetPath]=this._currentValue,e.markAsDirty&&e.markAsDirty(this._animation.targetProperty)}_getCorrectLoopMode(){return this._target&&this._target.animationPropertiesOverride?this._target.animationPropertiesOverride.loopMode:this._animation.loopMode}goToFrame(e,t=-1){let i=this._animation.getKeys();e<i[0].frame?e=i[0].frame:e>i[i.length-1].frame&&(e=i[i.length-1].frame);let r=this._events;if(r.length)for(let a=0;a<r.length;a++)r[a].onlyOnce||(r[a].isDone=r[a].frame<e);this._currentFrame=e;let s=this._animation._interpolate(e,this._animationState);this.setValue(s,t)}_prepareForSpeedRatioChange(e){let t=this._previousElapsedTime*(this._animation.framePerSecond*e)/1e3;this._absoluteFrameOffset=this._previousAbsoluteFrame-t}animate(e,t,i,r,s,a=-1){let o=this._animation,l=o.targetPropertyPath;if(!l||l.length<1)return this._stopped=!0,!1;let c=!0,f,d=this._events,u;if(this._coreRuntimeAnimation)u=i-t,f=this._coreRuntimeAnimation.currentFrame,this._currentFrame=f,this._animationState.repeatCount=this._coreRuntimeAnimation._animationState.repeatCount,this._animationState.highLimitValue=this._coreRuntimeAnimation._animationState.highLimitValue,this._animationState.offsetValue=this._coreRuntimeAnimation._animationState.offsetValue;else{(t<this._minFrame||t>this._maxFrame)&&(t=this._minFrame),(i<this._minFrame||i>this._maxFrame)&&(i=this._maxFrame),u=i-t;let m,g=e*(o.framePerSecond*s)/1e3+this._absoluteFrameOffset,p=0,_=!1,v=r&&this._animationState.loopMode===gt.ANIMATIONLOOPMODE_YOYO;if(v){let E=(g-t)/u,S=Math.sin(E*Math.PI);g=Math.abs(S)*u+t;let A=S>=0?1:-1;this._yoyoDirection!==A&&(_=!0),this._yoyoDirection=A}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=g,!r&&i>=t&&(g>=u&&s>0||g<=0&&s<0))c=!1,p=o.evaluate(i);else if(!r&&t>=i&&(g<=u&&s<0||g>=0&&s>0))c=!1,p=o.evaluate(t);else if(this._animationState.loopMode!==gt.ANIMATIONLOOPMODE_CYCLE){let E=i.toString()+t.toString();if(!this._offsetsCache[E]){this._animationState.repeatCount=0,this._animationState.loopMode=gt.ANIMATIONLOOPMODE_CYCLE;let S=o._interpolate(t,this._animationState),T=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case gt.ANIMATIONTYPE_FLOAT:this._offsetsCache[E]=T-S;break;case gt.ANIMATIONTYPE_QUATERNION:this._offsetsCache[E]=T.subtract(S);break;case gt.ANIMATIONTYPE_VECTOR3:this._offsetsCache[E]=T.subtract(S);break;case gt.ANIMATIONTYPE_VECTOR2:this._offsetsCache[E]=T.subtract(S);break;case gt.ANIMATIONTYPE_SIZE:this._offsetsCache[E]=T.subtract(S);break;case gt.ANIMATIONTYPE_COLOR3:this._offsetsCache[E]=T.subtract(S);break;default:break}this._highLimitsCache[E]=T}p=this._highLimitsCache[E],m=this._offsetsCache[E]}if(m===void 0)switch(o.dataType){case gt.ANIMATIONTYPE_FLOAT:m=0;break;case gt.ANIMATIONTYPE_QUATERNION:m=nO;break;case gt.ANIMATIONTYPE_VECTOR3:m=sO;break;case gt.ANIMATIONTYPE_VECTOR2:m=aO;break;case gt.ANIMATIONTYPE_SIZE:m=oO;break;case gt.ANIMATIONTYPE_COLOR3:m=lO;break;case gt.ANIMATIONTYPE_COLOR4:m=cO;break}if(this._host&&this._host.syncRoot){let E=this._host.syncRoot,S=(E.masterFrame-E.fromFrame)/(E.toFrame-E.fromFrame);f=t+u*S}else g>0&&t>i||g<0&&t<i?f=c&&u!==0?i+g%u:t:f=c&&u!==0?t+g%u:i;if(!v&&(s>0&&this.currentFrame>f||s<0&&this.currentFrame<f)||v&&_){this._onLoop();for(let E=0;E<d.length;E++)d[E].onlyOnce||(d[E].isDone=!1);this._animationState.key=s>0?0:o.getKeys().length-1}this._currentFrame=f,this._animationState.repeatCount=u===0?0:g/u>>0,this._animationState.highLimitValue=p,this._animationState.offsetValue=m}let h=o._interpolate(f,this._animationState);if(this.setValue(h,a),d.length){for(let m=0;m<d.length;m++)if(u>=0&&f>=d[m].frame&&d[m].frame>=t||u<0&&f<=d[m].frame&&d[m].frame<=t){let g=d[m];g.isDone||(g.onlyOnce&&(d.splice(m,1),m--),g.isDone=!0,g.action(f))}}return c||(this._stopped=!0),c}}});function m_e(n){if(n.totalWeight===0&&n.totalAdditiveWeight===0)return n.originalValue;let e=1,t=ee.Vector3[0],i=ee.Vector3[1],r=ee.Quaternion[0],s=0,a=n.animations[0],o=n.originalValue,l,c=!1;if(n.totalWeight<1)l=1-n.totalWeight,o.decompose(i,r,t);else{if(s=1,e=n.totalWeight,l=a.weight/e,l==1)if(n.totalAdditiveWeight)c=!0;else return a.currentValue;a.currentValue.decompose(i,r,t)}if(!c){i.scaleInPlace(l),t.scaleInPlace(l),r.scaleInPlace(l);for(let d=s;d<n.animations.length;d++){let u=n.animations[d];if(u.weight===0)continue;l=u.weight/e;let h=ee.Vector3[2],m=ee.Vector3[3],g=ee.Quaternion[1];u.currentValue.decompose(m,g,h),m.scaleAndAddToRef(l,i),g.scaleAndAddToRef(je.Dot(r,g)>0?l:-l,r),h.scaleAndAddToRef(l,t)}r.normalize()}for(let d=0;d<n.additiveAnimations.length;d++){let u=n.additiveAnimations[d];if(u.weight===0)continue;let h=ee.Vector3[2],m=ee.Vector3[3],g=ee.Quaternion[1];u.currentValue.decompose(m,g,h),m.multiplyToRef(i,m),b.LerpToRef(i,m,u.weight,i),r.multiplyToRef(g,g),je.SlerpToRef(r,g,u.weight,r),h.scaleAndAddToRef(u.weight,t)}let f=a?a._animationState.workValue:ee.Matrix[0].clone();return Q.ComposeToRef(i,r,t,f),f}function p_e(n,e){if(n.totalWeight===0&&n.totalAdditiveWeight===0)return e;let t=n.animations[0],i=n.originalValue,r=e;if(n.totalWeight===0&&n.totalAdditiveWeight>0)r.copyFrom(i);else if(n.animations.length===1){if(je.SlerpToRef(i,t.currentValue,Math.min(1,n.totalWeight),r),n.totalAdditiveWeight===0)return r}else if(n.animations.length>1){let s=1,a,o;if(n.totalWeight<1){let c=1-n.totalWeight;a=[],o=[],a.push(i),o.push(c)}else{if(n.animations.length===2&&(je.SlerpToRef(n.animations[0].currentValue,n.animations[1].currentValue,n.animations[1].weight/n.totalWeight,e),n.totalAdditiveWeight===0))return e;a=[],o=[],s=n.totalWeight}for(let c=0;c<n.animations.length;c++){let f=n.animations[c];a.push(f.currentValue),o.push(f.weight/s)}let l=0;for(let c=0;c<a.length;){if(!c){je.SlerpToRef(a[c],a[c+1],o[c+1]/(o[c]+o[c+1]),e),r=e,l=o[c]+o[c+1],c+=2;continue}l+=o[c],je.SlerpToRef(r,a[c],o[c]/l,r),c++}}for(let s=0;s<n.additiveAnimations.length;s++){let a=n.additiveAnimations[s];a.weight!==0&&(r.multiplyToRef(a.currentValue,ee.Quaternion[0]),je.SlerpToRef(r,ee.Quaternion[0],a.weight,r))}return r}function g_e(n){if(n._registeredForLateAnimationBindings.length){for(let e=0;e<n._registeredForLateAnimationBindings.length;e++){let t=n._registeredForLateAnimationBindings.data[e];for(let i in t._lateAnimationHolders){let r=t._lateAnimationHolders[i],s=r.animations[0],a=r.originalValue;if(a==null)continue;let o=gt.AllowMatrixDecomposeForInterpolation&&a.m,l=t[i];if(o)l=m_e(r);else if(a.w!==void 0)l=p_e(r,l||je.Identity());else{let f=0,d=1,u=s&&s._animationState.loopMode===gt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT;if(r.totalWeight<1)u?l=a.clone?a.clone():a:s&&a.scale?l=a.scale(1-r.totalWeight):s?l=a*(1-r.totalWeight):a.clone?l=a.clone():l=a;else if(s){d=r.totalWeight;let h=s.weight/d;h!==1?s.currentValue.scale?l=s.currentValue.scale(h):l=s.currentValue*h:l=s.currentValue,u&&(l.addToRef?l.addToRef(a,l):l+=a),f=1}for(let h=f;h<r.animations.length;h++){let m=r.animations[h],g=m.weight/d;if(g)m.currentValue.scaleAndAddToRef?m.currentValue.scaleAndAddToRef(g,l):l+=m.currentValue*g;else continue}for(let h=0;h<r.additiveAnimations.length;h++){let m=r.additiveAnimations[h],g=m.weight;if(g)m.currentValue.scaleAndAddToRef?m.currentValue.scaleAndAddToRef(g,l):l+=m.currentValue*g;else continue}}t[i]=l}t._lateAnimationHolders={}}n._registeredForLateAnimationBindings.reset()}}function V9(n,e){e&&(e.prototype.copyAnimationRange=function(t,i,r,s=!1,a=null){this.animations.length===0&&(this.animations.push(new gt(this.name,"_matrix",t.animations[0].framePerSecond,gt.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));let o=t.animations[0].getRange(i);if(!o)return!1;let l=o.from,c=o.to,f=t.animations[0].getKeys(),d=t.length,u=t.getParent(),h=this.getParent(),m=s&&u&&d&&this.length&&d!==this.length,g=m&&h&&u?h.length/u.length:1,p=s&&!h&&a&&(a.x!==1||a.y!==1||a.z!==1),_=this.animations[0].getKeys(),v,E,S;for(let T=0,A=f.length;T<A;T++)v=f[T],v.frame>=l&&v.frame<=c&&(s?(S=v.value.clone(),m?(E=S.getTranslation(),S.setTranslation(E.scaleInPlace(g))):p&&a?(E=S.getTranslation(),S.setTranslation(E.multiplyInPlace(a))):S=v.value):S=v.value,_.push({frame:v.frame+r,value:S}));return this.animations[0].createRange(i,l+r,c+r),!0}),n&&(n.prototype._animate=function(t){if(!this.animationsEnabled)return;let i=br.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=i}this.deltaTime=t!==void 0?t:this.useConstantAnimationDeltaTime?16:(i-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=i;let r=this._activeAnimatables;if(r.length===0)return;this._animationTime+=this.deltaTime;let s=this._animationTime;for(let a=0;a<r.length;a++){let o=r[a];!o._animate(s)&&o.disposeOnEnd&&a--}g_e(this)},n.prototype.sortActiveAnimatables=function(){this._activeAnimatables.sort((t,i)=>t.playOrder-i.playOrder)},n.prototype.beginWeightedAnimation=function(t,i,r,s=1,a,o=1,l,c,f,d,u=!1){let h=this.beginAnimation(t,i,r,a,o,l,c,!1,f,d,u);return h.weight=s,h},n.prototype.beginAnimation=function(t,i,r,s,a=1,o,l,c=!0,f,d,u=!1){if(a<0){let m=i;i=r,r=m,a=-a}i>r&&(a=-a),c&&this.stopAnimation(t,void 0,f),l||(l=new CE(this,t,i,r,s,a,o,void 0,d,u));let h=f?f(t):!0;if(t.animations&&h&&l.appendAnimations(t,t.animations),t.getAnimatables){let m=t.getAnimatables();for(let g=0;g<m.length;g++)this.beginAnimation(m[g],i,r,s,a,o,l,c,f,d)}return l.reset(),l},n.prototype.beginHierarchyAnimation=function(t,i,r,s,a,o=1,l,c,f=!0,d,u,h=!1){let m=t.getDescendants(i),g=[];g.push(this.beginAnimation(t,r,s,a,o,l,c,f,d,void 0,h));for(let p of m)g.push(this.beginAnimation(p,r,s,a,o,l,c,f,d,void 0,h));return g},n.prototype.beginDirectAnimation=function(t,i,r,s,a,o=1,l,c,f=!1){if(o<0){let u=r;r=s,s=u,o=-o}return r>s&&(o=-o),new CE(this,t,r,s,a,o,l,i,c,f)},n.prototype.beginDirectHierarchyAnimation=function(t,i,r,s,a,o,l,c,f,d=!1){let u=t.getDescendants(i),h=[];h.push(this.beginDirectAnimation(t,r,s,a,o,l,c,f,d));for(let m of u)h.push(this.beginDirectAnimation(m,r,s,a,o,l,c,f,d));return h},n.prototype.getAnimatableByTarget=function(t){for(let i=0;i<this._activeAnimatables.length;i++)if(this._activeAnimatables[i].target===t)return this._activeAnimatables[i];return null},n.prototype.getAllAnimatablesByTarget=function(t){let i=[];for(let r=0;r<this._activeAnimatables.length;r++)this._activeAnimatables[r].target===t&&i.push(this._activeAnimatables[r]);return i},n.prototype.stopAnimation=function(t,i,r){let s=this.getAllAnimatablesByTarget(t);for(let a of s)a.stop(i,r)},n.prototype.stopAllAnimations=function(){if(this._activeAnimatables){for(let t=0;t<this._activeAnimatables.length;t++)this._activeAnimatables[t].stop(void 0,void 0,!0);this._activeAnimatables.length=0}for(let t of this.animationGroups)t.stop()})}var CE,Ew=y(()=>{Si();U9();gd();Ac();He();CE=class n{get syncRoot(){return this._syncRoot}get masterFrame(){return this._runtimeAnimations.length===0?0:this._runtimeAnimations[0].currentFrame}get weight(){return this._weight}set weight(e){if(e===-1){this._weight=-1;return}this._weight=Math.min(Math.max(e,0),1)}get speedRatio(){return this._speedRatio}set speedRatio(e){for(let t=0;t<this._runtimeAnimations.length;t++)this._runtimeAnimations[t]._prepareForSpeedRatioChange(e);this._speedRatio=e,this._goToFrame!==null&&this.goToFrame(this._goToFrame)}get elapsedTime(){return this._localDelayOffset===null?0:this._scene._animationTime-this._localDelayOffset}constructor(e,t,i=0,r=100,s=!1,a=1,o,l,c,f=!1,d=0){this.target=t,this.fromFrame=i,this.toFrame=r,this.loopAnimation=s,this.onAnimationEnd=o,this.onAnimationLoop=c,this.isAdditive=f,this.playOrder=d,this._localDelayOffset=null,this._pausedDelay=null,this._manualJumpDelay=null,this._runtimeAnimations=new Array,this._paused=!1,this._speedRatio=1,this._weight=-1,this._previousWeight=-1,this._syncRoot=null,this._frameToSyncFromJump=null,this._goToFrame=null,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new re,this.onAnimationLoopObservable=new re,this._scene=e,l&&this.appendAnimations(t,l),this._speedRatio=a,e._activeAnimatables.push(this)}syncWith(e){if(this._syncRoot=e,e){let t=this._scene._activeAnimatables.indexOf(this);t>-1&&(this._scene._activeAnimatables.splice(t,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i<t.length;i++){let r=t[i],s=new jM(e,r,this._scene,this);s._onLoop=()=>{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i].animation;return null}getRuntimeAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i];return null}reset(){let e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].reset(!0);this._localDelayOffset=null,this._pausedDelay=null}enableBlending(e){let t=this._runtimeAnimations;for(let i=0;i<t.length;i++)t[i].animation.enableBlending=!0,t[i].animation.blendingSpeed=e}disableBlending(){let e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].animation.enableBlending=!1}goToFrame(e,t=!1){var r;let i=this._runtimeAnimations;if(i[0]){let s=i[0].animation.framePerSecond;this._frameToSyncFromJump=(r=this._frameToSyncFromJump)!=null?r:i[0].currentFrame;let a=this.speedRatio===0?0:(e-this._frameToSyncFromJump)/s*1e3/this.speedRatio;this._manualJumpDelay=-a}for(let s=0;s<i.length;s++)i[s].goToFrame(e,t?this._weight:-1);this._goToFrame=e}get paused(){return this._paused}pause(){this._paused||(this._paused=!0)}restart(){this._paused=!1}_raiseOnAnimationEnd(){this.onAnimationEnd&&this.onAnimationEnd(),this.onAnimationEndObservable.notifyObservers(this)}stop(e,t,i=!1,r=!1){if(e||t){let s=this._scene._activeAnimatables.indexOf(this);if(s>-1){let a=this._runtimeAnimations;for(let o=a.length-1;o>=0;o--){let l=a[o];e&&l.animation.name!=e||t&&!t(l.target)||(l.dispose(),a.splice(o,1))}a.length==0&&(i||this._scene._activeAnimatables.splice(s,1),r||this._raiseOnAnimationEnd())}}else{let s=this._scene._activeAnimatables.indexOf(this);if(s>-1){i||this._scene._activeAnimatables.splice(s,1);let a=this._runtimeAnimations;for(let o=0;o<a.length;o++)a[o].dispose();this._runtimeAnimations.length=0,r||this._raiseOnAnimationEnd()}}}async waitAsync(){return await new Promise(e=>{this.onAnimationEndObservable.add(()=>{e(this)},void 0,void 0,this,!0)})}_animate(e){if(this._paused)return this.animationStarted=!1,this._pausedDelay===null&&(this._pausedDelay=e),!0;if(this._localDelayOffset===null?(this._localDelayOffset=e,this._pausedDelay=null):this._pausedDelay!==null&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),this._manualJumpDelay!==null&&(this._localDelayOffset+=this.speedRatio<0?-this._manualJumpDelay:this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,!n.ProcessPausedAnimatables&&this._weight===0&&this._previousWeight===0)return!0;this._previousWeight=this._weight;let t=!1,i=this._runtimeAnimations,r;for(r=0;r<i.length;r++){let a=i[r].animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this._speedRatio,this._weight);t=t||a}if(this.animationStarted=t,!t){if(this.disposeOnEnd)for(r=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(r,1),r=0;r<i.length;r++)i[r].dispose();this._raiseOnAnimationEnd(),this.disposeOnEnd&&(this.onAnimationEnd=null,this.onAnimationLoop=null,this.onAnimationLoopObservable.clear(),this.onAnimationEndObservable.clear())}return t}};CE.ProcessPausedAnimatables=!1});var G9=y(()=>{HM();Ew();na();Ew();V9(ai,po)});var k9={};Be(k9,{AnimationGroup:()=>Sw,TargetedAnimation:()=>ZM});var ZM,Sw,z9=y(()=>{gd();Si();Yi();td();G9();jR();ZM=class{getClassName(){return"TargetedAnimation"}constructor(e){this.parent=e,this.uniqueId=Uc.UniqueId}serialize(){let e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e.targetUniqueId=this.target.uniqueId,e}},Sw=class n{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(!this.mask&&!e){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let t=0;t<this._animatables.length;++t){let i=this._animatables[t];!this.mask||this.mask.disabled||this.mask.retainsTarget(i.target.name)?(this._numActiveAnimatables++,i.paused&&i.restart()):i.paused||i.pause()}}removeUnmaskedAnimations(){if(!(!this.mask||this.mask.disabled)){for(let e=0;e<this._animatables.length;++e){let t=this._animatables[e];this.mask.retainsTarget(t.target.name)||(t.stop(),this._animatables.splice(e,1),--e)}for(let e=0;e<this._targetedAnimations.length;e++){let t=this._targetedAnimations[e];this.mask.retainsTarget(t.target.name)||(this._targetedAnimations.splice(e,1),--e)}}}get from(){return this._from}set from(e){if(this._from!==e){this._from=e;for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.fromFrame=this._from}}}get to(){return this._to}set to(e){if(this._to!==e){this._to=e;for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.toFrame=this._to}}}get isStarted(){return this._isStarted}get isPlaying(){return this._isStarted&&!this._isPaused}get speedRatio(){return this._speedRatio}set speedRatio(e){if(this._speedRatio!==e){this._speedRatio=e;for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.speedRatio=this._speedRatio}}}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){if(this._loopAnimation!==e){this._loopAnimation=e;for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.loopAnimation=this._loopAnimation}}}get isAdditive(){return this._isAdditive}set isAdditive(e){if(this._isAdditive!==e){this._isAdditive=e;for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.isAdditive=this._isAdditive}}}get weight(){return this._weight}set weight(e){this._weight!==e&&(this._weight=e,this.setWeightForAllAnimatables(this._weight))}get targetedAnimations(){return this._targetedAnimations}get animatables(){return this._animatables}get children(){return this._targetedAnimations}get playOrder(){return this._playOrder}set playOrder(e){if(this._playOrder!==e&&(this._playOrder=e,this._animatables.length>0)){for(let t=0;t<this._animatables.length;t++)this._animatables[t].playOrder=this._playOrder;this._scene.sortActiveAnimatables()}}get enableBlending(){return this._enableBlending}set enableBlending(e){if(this._enableBlending!==e&&(this._enableBlending=e,e!==null))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.enableBlending=e}get blendingSpeed(){return this._blendingSpeed}set blendingSpeed(e){if(this._blendingSpeed!==e&&(this._blendingSpeed=e,e!==null))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.blendingSpeed=e}getLength(e,t){e=e!=null?e:this._from,t=t!=null?t:this._to;let i=this.targetedAnimations[0].animation.framePerSecond*this._speedRatio;return(t-e)/i}static MergeAnimationGroups(e,t=!0,i=!1,r){if(e.length===0)return null;r=r!=null?r:e[0].weight;let s=Number.MAX_VALUE,a=-Number.MAX_VALUE;if(i)for(let l of e)l.from<s&&(s=l.from),l.to>a&&(a=l.to);let o=new n(e[0].name+"_merged",e[0]._scene,r);for(let l of e){i&&l.normalize(s,a);for(let c of l.targetedAnimations)o.addTargetedAnimation(c.animation,c.target);t&&l.dispose()}return o}getScene(){return this._scene}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._shouldStart=!0,this._parentContainer=null,this.onAnimationEndObservable=new re,this.onAnimationLoopObservable=new re,this.onAnimationGroupLoopObservable=new re,this.onAnimationGroupEndObservable=new re,this.onAnimationGroupPauseObservable=new re,this.onAnimationGroupPlayObservable=new re,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||Oe.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){let i=new ZM(this);i.animation=e,i.target=t;let r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to<r[r.length-1].frame&&(this._to=r[r.length-1].frame),this._enableBlending!==null&&(e.enableBlending=this._enableBlending),this._blendingSpeed!==null&&(e.blendingSpeed=this._blendingSpeed),this._targetedAnimations.push(i),this._shouldStart=!0,i}removeTargetedAnimation(e){for(let t=this._targetedAnimations.length-1;t>-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){e==null&&(e=this._from),t==null&&(t=this._to);for(let i=0;i<this._targetedAnimations.length;i++){let s=this._targetedAnimations[i].animation.getKeys(),a=s[0],o=s[s.length-1];if(a.frame>e){let l={frame:e,value:a.value,inTangent:a.inTangent,outTangent:a.outTangent,interpolation:a.interpolation};s.splice(0,0,l)}if(o.frame<t){let l={frame:t,value:o.value,inTangent:o.inTangent,outTangent:o.outTangent,interpolation:o.interpolation};s.push(l)}}return this._from=e,this._to=t,this}_processLoop(e,t,i){e.onAnimationLoop=()=>{this.onAnimationLoopObservable.notifyObservers(t),!this._animationLoopFlags[i]&&(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,s){if(this._isStarted||this._targetedAnimations.length===0)return this;this._loopAnimation=e,this._shouldStart=!1,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let a=0;a<this._targetedAnimations.length;a++){let o=this._targetedAnimations[a],l=this._scene.beginDirectAnimation(o.target,[o.animation],i!==void 0?i:this._from,r!==void 0?r:this._to,e,t,void 0,void 0,s!==void 0?s:this._isAdditive);l.weight=this._weight,l.playOrder=this._playOrder,l.onAnimationEnd=()=>{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(l)},this._processLoop(l,o,a),this._animatables.push(l)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e<this._animatables.length;e++)this._animatables[e].pause();return this.onAnimationGroupPauseObservable.notifyObservers(this),this}play(e){return this.isStarted&&this._animatables.length&&!this._shouldStart?(e!==void 0&&(this.loopAnimation=e),this.restart()):(this.stop(),this.start(e,this._speedRatio)),this}reset(){if(!this._isStarted)return this.play(),this.goToFrame(0),this.stop(!0),this;for(let e=0;e<this._animatables.length;e++)this._animatables[e].reset();return this}restart(){if(!this._isStarted)return this;for(let e=0;e<this._animatables.length;e++)this._animatables[e].restart();return this.syncWithMask(),this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}stop(e=!1){if(!this._isStarted)return this;let t=this._animatables.slice();for(let r=0;r<t.length;r++)t[r].stop(void 0,void 0,!0,e);let i=0;for(let r=0;r<this._scene._activeAnimatables.length;r++){let s=this._scene._activeAnimatables[r];s._runtimeAnimations.length>0?this._scene._activeAnimatables[i++]=s:e&&this._checkAnimationGroupEnded(s,e)}return this._scene._activeAnimatables.length=i,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.weight=e}return this}syncAllAnimationsWith(e){for(let t=0;t<this._animatables.length;t++)this._animatables[t].syncWith(e);return this}goToFrame(e,t=!1){if(!this._isStarted)return this;for(let i=0;i<this._animatables.length;i++)this._animatables[i].goToFrame(e,t);return this}getCurrentFrame(){var e;return((e=this.animatables[0])==null?void 0:e.masterFrame)||0}dispose(){if(this.isStarted&&this.stop(),this._targetedAnimations.length=0,this._animatables.length=0,this._scene.removeAnimationGroup(this),this._parentContainer){let e=this._parentContainer.animationGroups.indexOf(this);e>-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e,t=!1){let i=this._animatables.indexOf(e);i>-1&&this._animatables.splice(i,1),this._animatables.length===this._targetedAnimations.length-this._numActiveAnimatables&&(this._isStarted=!1,t||this.onAnimationGroupEndObservable.notifyObservers(this),this._animatables.length=0)}clone(e,t,i=!1,r=!1){let s=new n(e||this.name,this._scene,this._weight,this._playOrder);s._from=this.from,s._to=this.to,s._speedRatio=this.speedRatio,s._loopAnimation=this.loopAnimation,s._isAdditive=this.isAdditive,s._enableBlending=this.enableBlending,s._blendingSpeed=this.blendingSpeed,s.metadata=this.metadata,s.mask=this.mask;for(let a of this._targetedAnimations)s.addTargetedAnimation(i?a.animation.clone(r):a.animation,t?t(a.target):a.target);return s}serialize(){let e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;t<this.targetedAnimations.length;t++){let i=this.targetedAnimations[t];e.targetedAnimations[t]=i.serialize()}return ni&&ni.HasTags(this)&&(e.tags=ni.GetTags(this)),this.metadata&&(e.metadata=this.metadata),e}static Parse(e,t,i){let r=new n(e.name,t,e.weight,e.playOrder);for(let s=0;s<e.targetedAnimations.length;s++){let a=e.targetedAnimations[s],o=gt.Parse(a.animation),l=i?i(a):a.animation.property==="influence"?t.getMorphTargetById(a.targetId):t.getNodeById(a.targetId);l&&r.addTargetedAnimation(o,l)}return ni&&ni.AddTagsTo(r,e.tags),e.from!==null&&e.to!==null&&r.normalize(e.from,e.to),e.speedRatio!==void 0&&(r._speedRatio=e.speedRatio),e.loopAnimation!==void 0&&(r._loopAnimation=e.loopAnimation),e.isAdditive!==void 0&&(r._isAdditive=e.isAdditive),e.weight!==void 0&&(r._weight=e.weight),e.playOrder!==void 0&&(r._playOrder=e.playOrder),e.enableBlending!==void 0&&(r._enableBlending=e.enableBlending),e.blendingSpeed!==void 0&&(r._blendingSpeed=e.blendingSpeed),e.metadata!==void 0&&(r.metadata=e.metadata),r}static MakeAnimationAdditive(e,t,i,r=!1,s){let a;typeof t=="object"?a=t:a={referenceFrame:t,range:i,cloneOriginalAnimationGroup:r,clonedAnimationName:s};let o=e;a.cloneOriginalAnimationGroup&&(o=e.clone(a.clonedAnimationGroupName||o.name));let l=o.targetedAnimations;for(let c=0;c<l.length;c++){let f=l[c];f.animation=gt.MakeAnimationAdditive(f.animation,a)}if(o.isAdditive=!0,a.clipKeys){let c=Number.MAX_VALUE,f=-Number.MAX_VALUE,d=o.targetedAnimations;for(let u=0;u<d.length;u++){let g=d[u].animation.getKeys();c>g[0].frame&&(c=g[0].frame),f<g[g.length-1].frame&&(f=g[g.length-1].frame)}o._from=c,o._to=f}return o}static ClipKeys(e,t,i,r,s){let a=e.clone(r||e.name);return n.ClipKeysInPlace(a,t,i,s)}static ClipKeysInPlace(e,t,i,r){return n.ClipInPlace(e,t,i,r,!1)}static ClipFrames(e,t,i,r,s){let a=e.clone(r||e.name);return n.ClipFramesInPlace(a,t,i,s)}static ClipFramesInPlace(e,t,i,r){return n.ClipInPlace(e,t,i,r,!0)}static ClipInPlace(e,t,i,r,s=!1){let a=Number.MAX_VALUE,o=-Number.MAX_VALUE,l=e.targetedAnimations;for(let c=0;c<l.length;c++){let f=l[c],d=r?f.animation:f.animation.clone();s&&(d.createKeyForFrame(t),d.createKeyForFrame(i));let u=d.getKeys(),h=[],m=Number.MAX_VALUE;for(let g=0;g<u.length;g++){let p=u[g];if(!s&&g>=t&&g<=i||s&&p.frame>=t&&p.frame<=i){let _={frame:p.frame,value:p.value.clone?p.value.clone():p.value,inTangent:p.inTangent,outTangent:p.outTangent,interpolation:p.interpolation,lockedTangent:p.lockedTangent};m===Number.MAX_VALUE&&(m=_.frame),_.frame-=m,h.push(_)}}if(h.length===0){l.splice(c,1),c--;continue}a>h[0].frame&&(a=h[0].frame),o<h[h.length-1].frame&&(o=h[h.length-1].frame),d.setKeys(h,!0),f.animation=d}return e._from=a,e._to=o,e}getClassName(){return"AnimationGroup"}toString(e){let t="Name: "+this.name;return t+=", type: "+this.getClassName(),e&&(t+=", from: "+this._from,t+=", to: "+this._to,t+=", isStarted: "+this._isStarted,t+=", speedRatio: "+this._speedRatio,t+=", targetedAnimations length: "+this._targetedAnimations.length,t+=", animatables length: "+this._animatables.length),t}}});var X9={};Be(X9,{AnimationPropertyInfo:()=>PE,TransformNodeAnimationPropertyInfo:()=>pg,WeightAnimationPropertyInfo:()=>qM,getQuaternion:()=>W9,getVector3:()=>Tw,getWeights:()=>H9});function Tw(n,e,t,i){return b.FromArray(e,t).scaleInPlace(i)}function W9(n,e,t,i){return je.FromArray(e,t).scaleInPlace(i)}function H9(n,e,t,i){let r=new Array(n._numMorphTargets);for(let s=0;s<r.length;s++)r[s]=e[t++]*i;return r}var PE,pg,qM,Y9=y(()=>{gd();He();_w();PE=class{constructor(e,t,i,r){this.type=e,this.name=t,this.getValue=i,this.getStride=r}_buildAnimation(e,t,i){let r=new gt(e,this.name,t,this.type);return r.setKeys(i,!0),r}},pg=class extends PE{buildAnimations(e,t,i,r){let s=[];return s.push({babylonAnimatable:e._babylonTransformNode,babylonAnimation:this._buildAnimation(t,i,r)}),s}},qM=class extends PE{buildAnimations(e,t,i,r){let s=[];if(e._numMorphTargets)for(let a=0;a<e._numMorphTargets;a++){let o=new gt(`${t}_${a}`,this.name,i,this.type);if(o.setKeys(r.map(l=>({frame:l.frame,inTangent:l.inTangent?l.inTangent[a]:void 0,value:l.value[a],outTangent:l.outTangent?l.outTangent[a]:void 0,interpolation:l.interpolation})),!0),e._primitiveBabylonMeshes){for(let l of e._primitiveBabylonMeshes)if(l.morphTargetManager){let c=l.morphTargetManager.getTarget(a),f=o.clone();c.animations.push(f),s.push({babylonAnimatable:c,babylonAnimation:f})}}}return s}};yE("/nodes/{}/translation",[new pg(gt.ANIMATIONTYPE_VECTOR3,"position",Tw,()=>3)]);yE("/nodes/{}/rotation",[new pg(gt.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",W9,()=>4)]);yE("/nodes/{}/scale",[new pg(gt.ANIMATIONTYPE_VECTOR3,"scaling",Tw,()=>3)]);yE("/nodes/{}/weights",[new qM(gt.ANIMATIONTYPE_FLOAT,"influence",H9,n=>n._numMorphTargets)])});var __e,v_e,E_e,S_e,Aw,QM,xw,K9,$M=y(()=>{Kr();cD();__e="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSe"+"EoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==",v_e="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAF9UlEQVR4nGWVy64eVxGF16X27u7/HMcyuZGYAINwmTBigngBXoc34El4B0ZMGDJjFCExQUIKiRKZYBITHdvn/L1rF4P+c+yEUqmH9WmtrrWLkdB4C1/91h/9yn947D8+8CfdlBeGGAMtqwNd6K7VWAJrw9qwLtw2nDaernh6wKuHPD3S1Vs6vaPT97W9r/Wx1seKUWj7Uzz6vX79T//wF/Gbx/7rw/jsFB/39nlrX7q99LKrp5bJZXAtrqW1uJIncbNOXafBU+o0tZW28got0AJ3KACsE4OfYvmzfvDMb/+4//Td9snD9rfr9vHWnyz9361/1fpNLLde0mt5pTZ7a9pCm32SrqQTfZI3aqNXHAwvcAB4BPwnk/oMEcqX8eaz1t9cHjxs7133f5z6p2v/Ylme9eWmLbexjlhnrPBirz3WxWv30rw0L/Yi96PpDrcDcPMEfq+qvQCfsFF1blcv2js3vb2xLNd9O/XT1p8u/Vlfnvd+25bResXC6BFLj2WJpUdv7uEe0exGByPoOAC//BH+cgNqUjfkU4mOEetde+O2vf+y8br71Nva+9q/XpYXvZ97z9ardUXrra3RerQWrUU4myLk4AzYiADwJ+NRQ41i7MSNEBIcM5YR1+f21rnlXcPWtbVYW1/a7dL21mZvbK211lv01lpEtIi0MxTmFGzMAABAN6gF1CTPxI1gkXa5Z5xGPNrbfo6xB/bQubW9nXvkHtXDPfqIJd2bI+1mpZjmNK17QFuxDzhBJued8Fy0KLvcp7fpNzJuM3JE7daIWGKMqAylW0bLiHQ0e1ppTXEK8Qrwkzv8fUIua6oG553wQpRIme7lbfpBxm3GnoEMZ+wZlYGMlu6pNh1pT3nqALCEugCeAB2ohKqYk9hZd4JFS5ThDm/lB9N305nGtKfnNKZiqk23qZhySZOcYhHFewXfI54UMCBDOYlU3TMkSaYWaCtdwXu5yprOKUxrqk9FyUWXNKXiBfCNgucGboGAUBwUJzFYO3G+MCwFtdAn6K6UZZSyXCXBAUVdGCoS5IVxAcQNujAHKCiLLHJqDtWZh1GHV0Et8EYNqOABTUhglKJoyKBBgSwCBC6Ajz7Azz+GiJbwhFTkZCXnEM6EJcuHDmmlztCkBE2IkMGAAhQoSCBBvgYA0G6xN4DgLE5IU5iqZA1hJ8zDqCY2qktJHfEnZSpIk6bE++kEXwHUEBMCmBBBFzE5UzNZuyBRshlSSF0aEg6MaDHIgyFCPAqvA/YdIjTgQ3WBLNZkpWoQPnRIUljdGiIkHd9jumgeO0ESEI97cNTPJj6Z4ISOZh1JUSVLwiAs7pRp02aTypRUhwIzjvhfPCKF1wH/BTqwA5pQlnYyipgs6dDBQVncZatZaZUlsUxZYVq0jyfm8kNeBzz/Gu0ETrjABAURAoTJOVVJpDAoM3ZOc5olfmMK42CYMrRTAr6tIK6QiSA84VtIIEosslSTNYUkUxyS5aEDQ6tMmQ7YDMOmjziYx8E56oPEl8DdDgM2/BLeIJVw9CRSTClZg97ZrDl0BF6m49V0GTIZQL4CvNuxFj47w4ASmqUkAalYU+DBoIbK8hAG506aZTLonWFG0IMa1AAHXlegW9wFGuAJG97hhFkqiuCxUZyqSSWR5GCZHKxB7nSwDcZADHiACQ4eJ/Oot9+BvsaLQD2Hby9RUEEs1cUlcdKpmWKSQ2VyqAY56J0RiEEPOqHxXYv2W4yJuANWxBkBOKEGFcwyjlhMYdLJSjLJpA8FAxqMwXZRQA0wgdQ94Hcf4nqDFnQhBDcY5YJUIqSSpnxpRqone6ol+2Af7Il2MJJxnN/8lgIA8yWQUKItaBMRsGEdDIrQoYNTnGSyBqdZQSY16IEYaANOOKn/A+htXH+OdgLOiB1BBOEGCz5ejmO6JpGEeexVJTmohJNORqIlnVDyO4CvvsT2AGm0BVEHo0IMHeEooeQipzDFY5eSNcigLgwoGYlIKHF/ky9Z+xD/WrCfoQUuRCGAKBhlwIBRQvmSuykkMYHkqx7EAPK+/wdqEbWmfB0bfwAAAABJRU5ErkJggg==",E_e="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAABGSklEQVR42u3cx4tb6brvcf0DmmpUoxrUoAY1KCgwFAZjME1jjGmMTWNs2tjY2MY2DjjinHPOOeec3dXOOeecU2VlaSksSc/9aq1X0pJKqmD3Dn3upvnCSe197v38nlfS2fscW1x+kbCMloAsFY/skEY5KbVySb7JXfkoT+WtvJGX8ol/67s8lDr+o065KW65Jl7+q/zyF3/nWTpJx+gQ/7H94pPd/Oe38yduEZds4E9dK/Wykj95GX/OYvkq8/kz58h7mcmfP41/hMnyTCbIIxkn9/nv5raMlOsyTK7IELkgg6RKBshp6ScnpI8ckd5yQHrJHvmd/3578I/QjX+E32SNdOEfobMskV9lAf+vmiOdZIZ0lKnSQSZKe/7kSv7kdjKchkoFf2q59Ke+UsafWCY9pZQ/rZQ/rUS6Umcp5k8q5k8p5k8p4k8p4k8o4u928Hc7+Dsd/F1mpWLn7zArVhWpHOlsRvYC/Yf++t8A/j8fQCxrADvTA/j6vwH8/zGAaOzX/w3g/+cBaJEuEkqMMQbg/t8A2jiA8n/+AHzB7qLFx8K2zBhAA5Q16QE8+98A/q8PwOXvLYHYePEllsO666cGcPR/A/jnDaDRN0C80Ynija8QV2K3GsBlywDe5h3AVYAvAv0X4IUH4P7fAP7bB9DgGyau0BRx6yvFGd8j9YlTUp24LF+g/gDKGwbwAqwnwD1o5QD2/VcPYMT/BmD9q94/Thq0GeKMrpbG2B6pi5+S78kBJAoNoDFrAFU/PICP/+UD6PL/xwDqAlOlNjBH6sMQ6XulJnZavsWvyGcG8D7BABJvsgZwxxiAK2sAZ9ID8P/gAF78QwbQ/v/eAGqDc6Tav1BqtA1SE90v1fpp+Rq7Ip/id+UdA3jNAJ4nPsnjRGYAN0C9whe8C+kB+BmAP2sAu/jPNx1AjRrAlzwDeNqKARz/3wD+7r+qtSXy1QdLcJN8Dx+Qb9Ez8kW/Ih9id+Vt/Jm8sgzgfqL5ARwxBuBjAN70ADbznSE5gDWMJzWARekBvGsygLFy738D+Hf+9T20Sj77VsuXwFb5oh2SL5Gz8lG/Ku8ZwJvYM3kZfyPP4h/lUeIbA6iV24lGuZ5IDcALjQ8aP4+zOYCD/Pt70wNwqQE0WAbwLWcAr/MM4FbOAP78Bw+g6L97AN/CG+Sjb6N89O+Qj9oR+Rg+J++jV+Wtfk9eMYAXsTfyhAE8jH+TuwzgVqLBGMDlhFvOJ7zyZyI5AB8D8EHjyxrAtjYN4EnWAEYYA7j8XzCAXwoMoOJvHsB/aARfwtvkvS/ZHnkfOCbvtCp5G74mb6L35KX+TJ4xgMexj/IgOYB4rdyMN8i1hFMuGQPwyDlGcJoRHE+YAzgA/l7jn1VwqwE0WgZQLUuNAXxmAB+MAcyQVxClBvCQAdxtxQD25x1A1x8ewB9tGEAljO3+7wzgU2SPvPPvlje+A/LGf0LeBP+S16Fr8jJyT55Hn8kT/Y080j/K/dhXuROvYQD1cjWeHIBL/lIDOEXH6TAdoD0JcwBbGcAmBrCeL4Br+AWQO4DZ/MQ0B/C8mQGczxnA4YIDaM0LUNmqAfz2LxmA/b9xAB8iB+VN4IC88h2Rl/5T8jJwXl5o1+V56L48jTyTx9HX8kD/IHf1r3IrViPXY/VyJd4oF+IuqYq75SzYJ0E/ZgzAI/tpD6/DDgaylZdiE9efHMBqYwDfGcBXBvBJ5uUMYJIxgAeWAVyzDODcv2gAA35oAEV5BpAZwT9sAO+iR+VV4Ii88B2X576z8tx/QZ4Fb8gT7b48Dj+Vh5HXcj/6Qe7oX+SmXi3XYnVyOdbAAJwMwCVnGMHJuEeOAn/IGICbAbiMAWzhC+NGvjOs49fD6kSNrFADWGgM4L0awEs1gMeWAdxUA7jUxgGs+Le8AP+nBvAmelJeBE/IM99peeqrkif+S/I4cFMeMYAHoadyP/xK7kTey63oF7muf5creq1c4hU4H2uUczGXnGYEJxjBETpE+4DfbQzAqQZQzwBqZVWiWlbwS2JJ4ossTHxUA3ijBvDMGMB4YwB3ZFTeAZz6FwzA+gL0+jcN4L/sl8BL/Yw8004Df04e+87LI98Veei/JQ+CD+Se9lTuhF7JrfB7uRH5JNei3+SyXiMX9Hqp0hvkbMwppxjBcTrCEA7SXtrF67Ad/C1c/wauf60awHJjAJ8ZwAeZm3gnsxJvZHrihUxNpAZwvxUDOKQGsJsBbP+bB/A7df/JAfzD/mcBz3WuXvtTHvmr5IHvotz3XZN7DOBu4IHcCT6VW9oruRF6J9fCn+RK5KtcjFbL+Wid/MkITuuNcpIRHKPDjGA/8HtoJ98RtvFrYTNfGDeAv5bnf2XiOwP4KosTn2SBMYC3DOCVMYApiacyKfFIxifuy5hEcgA3YLrKAC7KYPlLBjKA/nKSARzLM4DNagCr/4UD6PRvGsB/YARPda5eOy8PAhfknu+y3PVdlzu+O3LL/0BuBp7Kde2lXNPeyZXQR7kU/irnI9+lKlojZxnBKV6B44zgCB3iI2E/7aEd4G8Ff1O8Tjbw03FNvFpW8jNyGc//Yp7/BYn3lgE8ZwBPZKIxgHsM4LaMSlyXEYkrMjTBABJVDOCsMYC+lgH0VAPo/hMDqGhxAJ1bOYCyf+4AHuuX+Ky/yMVfAv6q3PLdlJsM4Ib/oVxnANeCL+WK9lYuaR/kQuiLVIW/yblItZyO1spJRnCMl+AwQzhAe2kXXxB38B1hC18WN4K/HvzV8e8M4KssjX+WRfGPMp/nfw7P/8zES5mWHsADGZe4ywBuGQMYbgzggjmAxBnpn2AAiaPSJ5EcwD4GsAuubWoA6/83gB/964F+Re6Grsjt4FW56b8uN3y35LrvrlzzPZQr/qdyOfBSLgbfyHntvVRpn+Rc6KucCX+Xk5EaOR6plSOM4FC0XvYzhD20U6+TbeBvidXKBn42rot9l1Vc/4r4FwbwiQF8kHnxtzI7/lpmxl8wgGcyOfE4awAjE9cYwGXLAE4zgBMM4AgDOCi9E3ulZ4IBJBhAYpN0S6QGsByyxX/bAEqyBtDxJwbwX/xL4J5+TW6Hr8nN4HW57r8B/G254rsnl32P5BIDuOB/IecDb6Qq+F7OaR/ljPZFToW+yXFGcJQRHGYEB3gN9tJufiHsoK18UdzET8YN4K+JfZOVsa+yPPZJlsQ+yML4OwbwhgG8khnx5zI1/lQmxx/JhPh9BnBHRiduqgFcYgDnGcCfWQP4Iz2AndkDSKySLgkGkGAAifnyS2K2GsCUv2UAxQUH8A//HwbdiV2Xm2HwtRtyNXAL/DtyyXdfLjCA876n8hcDqAq8lnOBd3Im+EFO8QqcYATHGMFhRnAwXC37GcIe2sl3g+18SdwC/kZ+Mq7Xv8lq/SsD+CzLYh9lcey9LIi9lbmx1zIr/lKmx58xgCcyKf6QAdyTsfHbMjp+Q0bGrxoDGMIABiXOqQEcVwM4wAD2qAFsVQNYl38ACQaQYAAJBpBgAIm2DKDrDwzg7/gp+G8ewc3YTbkevilXtZs897flov8u+PfBfyRVDOCc74Wc9b+S04G3cpJX4ETwoxzTPssR7ascYgT7+U6whyHs4svhDtoa/S6b+Lm4Afi1+hdZpX+WFfpHWap/kEWxdzI/9kbmxF7JzNgLmR57KlPijxnAAxkfv8sAbjEAvgDGr8iw+EUZEv9LBsX5CZjgJ6AxgMMMgF8AxgB2SA9jABuNAXRt7QASDCDBABIMIMEAEgwgwQAShQbQ+n9VUNP/WcA/4HvA9RhXH7nFl7xbciFwR84zgCrfA/mTAZzzPZEzvudy2v9STvrfyHFegaO8AkcYwSFGsJ+XYC/fCXbTDoawLfJNtvBTcSOtj36RNdFPshL85eAv0d/JQv2tzNNfyWzwZ8aeybTYE5kceyQTY/dlfOyOjInflFHxawzgMgO4wACqGMBZGRDnJ2D8mPSNH8oZwBY1gLUMYCUDWMYAFlkGML1tA0gwgAQDSDCARKEBFP7nA/6RA7jCAC5FbssFDfwg+P57wD8A/pGcZgAnGcAJ30s57n8tR/1v5XDgvRxiBPsZwV4+DvYwhJ38OthOW8JfZBNtiHyWtZFPsir6UVZEP8jS6DtZBP4C/bXM1V/KLP25zNCfylT9MQN4IBNid2Vc7LaMid2QUTGe/xif/3E+/+N/MoDTagD8AkgOIM4A4rulZ5wBxJMD2JBnAPPyDGAs+KPyDKBf4QEkGECCASQYQIIBJP5d/7OAf+MILvH/8Rcid+Sv0B35kwGcC9zn4h/IKQZwkgEc9z2TY3wMHPG9kkO8AgcZwX5GsJcR7GEEO/liuJ0hbAl9ks20IfxR1tHqyAdZGXkvyyPvZEn0rSyMvpZ50ZcyR+f69WcyHfwp+kOZpN+XCfodGcsQR/N9ZGTsCgO4KENjf8ngGJ//DKB//DgD4BdAnC+A8X0MgF8A8e3mAOIb5Lf4GukaTw5gqWUAsywDmNDGAXQrPIAEA0gwgAQDSDCABANIMIBEqZE9UaIqVhVZcqSzJf5LBnCep7cqeoefd3flrHaPz/r7PPcPuPpH4D+RowzgMK/AIV6BA3wX2M8I9vJ9YDcfBzv5TrCdIWzVPshm2hj6IOtpTei9rAy/kxW0NPJWFkVeywLw50ZfyOzoM5kRfSLT9EcyWX8gE/W7Ml6/LWP1GzKaXyQjYjz/sQsMoIoBnJWBsZPSP8bnf+wwA+ALYHwvA+ALYHwbA9icPYA4A4gvlF/jc+WXeGoAk/+GAfzSigGUtXEAagS5/bsHUMUAzkXv8tv+Lt/w78lJBnCcARxlAEd8j4F/KgcZwH5egX2MYA8j2M0IdjCC7bQ1+E4200btnayntbQq9FZW0rLwG1kSfiULIy9lXuSFzIk8k1ngT48+lqnRBzI5es+4/nH6TRmjX5dR+hUZoV+SYfp5GRLj+Y/x/BsD4PM/xvMf2y+9Y3z+x3YwgK0MgF8AcX4CxlczgBUMYEn2AOLTpGOcAcStAxje4gBK/5MDSGfL9K/86xwDOM0ATjGAEwzgePC+HAk8kMP+R+A/lgO8Avt5BfYygj2MYBcj2MEItvOdYEvgjWymjcE3sp7Wam9kNa2k5aFXsoQWhV/K/PBzmRt+JrMjT2RG5LFMizyUKdH7Mol/3PHRWzI2al7/SP2yDNe5fr1KhujnZJDOAHSe/9gRywB2mwOI8fzH+AIY4ydgfBUDWK4GsEANYGb2AOIMIM4A4gwgzgDihb4E9rAMoMvfMIDiHxxAzghy+7v+Os0ATgJxnAEcYwBHGMAhBnDQ/xD4R1z9Y+CfyG5GsJMR7GAE22gLvww2M4SNgVeyntYGX8lqWqm9kuXaS1lKi7UXsiD0XOaFnsmc8BOZGX4s08MPZWrkvkyO3JWJfPkcF+X6o9dkVJTrj15kAOcZwJ8yWD8jA/WT5gB0nn/9gPyh8/zHdjGA7WoAfAGMrZXfYiula4wBxBYbA/glPqd1A4gzgDgDiDOAOAOIM4A4A4gzgDgDiDOAeGoAnZoZQL7vAcXNvgI/PYC21NxfJ+N35Difw0cZwJHQPb7h35cDDGA/HwN7eQX2MIBdDGAHbWcEW2kLQ9jECDb4X8h6Wht4IatpZfCFLKelwefgP5eF2jOZrz2VOaHHMiv0SGaEHsi08H2Zwj/WJPAnRG7KuMh1GRO5ygAuMYALMizK9UfN6x+on5D++lHpqx9iAFy/vkd66Tulp87nf2yzGsAaYwBdYvwCiPEFMMZPwNgc6RSbwQCmMoBJDGA8AxhjGcCQtg0gzgDiDCDOAOK5A/iZL4L/xhEU6hgDOMIADnORB/kiuF+7L/sYwR5GsJtXYCevwA5GsI22MILNfCfYxAg20Hpa638uq2ll4LksDzyTpbQ4+EwWBp+A/0Tmao9ltvZIZoI/PQQ+/xiTwuCHwQ9fl7Hgj45clpGRCzI8wvVHuf7oGRkU5fqjxxkAz79+kOvfxwB2MwCef53Pf32TdNfXSzedz39jAEvVAPgFEJttDKBjjAHEGECMAcSSAxj59wwgzgDiDCBeYfZPHsARBnCIL2IHGcB+cPbyMbCHAeziy+AOXoHtvgdc/SPwH4H/WDbSBoawjtbQKlrpfyLLaWngiSymhYHHMj/4WOYGH4H/QGYyqun8uVO1uzI5dFsmhm7K+BD44WsyOnxFRoUvygjwh0W4/shZGRzh+qMnGMBR6Rfl+qP7jee/t87zr/P861sYAJ//Op//Op//Ol8AdT7/db4A6skB8AUwxi+AGD8BYxNpnDmA2EhpFxtGDCDGAGL9pTzGAGIMINaaAXTMGUBqBAwgXqZiAPF/0AAOxW/LAQawL3JH9jCA3SDtDN7jW/592ea/L1sZwRZGsMn3EPhHXP0jWUtrGMIqWknLaan/sSzmI2MhzQ88lLm8ILMZ0kyaEbwr07Q7MkW7JZO0mzJBuy7jQtdkTAj80CUZGT4vw8NVMjR8jgGclkERrj/C9Ue4/uhBcwBRnv/oDukZ3coAeP51nn+dz3+dz3+dz3+dz3+dL4A6XwB1BqAzAJ0B6AxAZwD6aKnUrQMY2HQAMQYQYwCx/AMoNgaQ7xXIMwCjYktFmbIG4PjPDmA/A9jH7/A9DGBX+I7sAGo7I9gWuMu3/Ht80bvP1d8H/z5X/wD8B7KaVjKIFbSMlvLvL6aFjGU+zeXvmc3fO4s/Y0bwjkwL3pYpwQz+eO2qjNWuyOgkfuiCjAhVybAQ+OEzMjh8UgaGjzOAI9Ivckj6RsCPcP2RXQyA649y/dGN0j3K8x9drQawjAEsYgDzGQBfAHW+AOp8AdT5AqjzBTA9gBHSTmcA+mCp0AeC38wAYgwgxgBi/BSMtXUApc0PIO5IZzOym/0nRrAnfkv26LdkV/S27OCzeXvojmxlBFuA2wTgBv9dvujdBf8eV3+fq78vK733ZQUt499eQotoIc3nv2Yu/7WzaZb/jswI3JZpgVsyJXBTJgevy8TgNRkfTOJfljHaRRmlga/9JcNDf8rQ0BkZEjolg0I8/eGj0j98WPqFuf7wPgawhwFw/ZFt8ntkMwPYwADWMgCe/yjPf5TP/yjPf5TnPzqb+AKo8/mvT1IDGEujmg5AZwA6A9AZgJ4aQPecAfxqDiDGAGIMIMYAYgwg1poBlLRtAAWzFe5nB7ArflN2MoAd/B7fFr4lW/iM3qzd5rf9HdkQuAP+Hb7o3eHq73L1Zsu9d2UpLaFF/PsLaL7vjsyl2b7b4N+SGTTNfxP8GzI5AH4giX9FxgUvyZhgEv+8jNSqZLj2pwzTzsoQ7bQMDnH9oWMyIMT1h7j+8H4GAH6Y6w9vZwBbGABf/iJcf4Rv/xGuP8LzH+H5j/L8R3n+ozz/0enEAKIMIDo+ZwBDCw9AZwA6A9AZgN6KAcQYQIwBxMpVDCBWavT3DqCFEfzMQHYwgO36TdnK7/EtDGBT6JZs4LN6A0/2Oq53DVe8yn8b+Ns8+be5+js8+Xdksfe2LKQFNM93C/xb4N+Smb6bMoOm+a/LFJrsvyYT/VdkQuCyjAuAH7ggo4PgB6tkRPCcgT80ia+dlEEaT792RPqD3y8Efmiv/BHazQC4/jCf/WGuP8z1h9dJtzDPf2QFA1jKAHj+Izz/EZ7/yExjAB2jU2iiOYAoXwCjDCA63DIAfgHo/ahP4QHoDEBnADoD0Ns4gFiJqlhVZCl3AI5/3QBaalv8hmzRb8jm6A3ZyO/yDXxDX89n9VpaHbwpq3i+V3LNy2kZwEtoMS303pT5NI/m0GzvDfCvy3Sa5rsmU2iy74qJ778k4/wXZWwSPwB+APzAORkePCNDg6dlSNDEH5jE18DXDkhfbZ/00bj+0E7pFeL6Q1x/aKP0CK1nAFx/mOsPc/3hJbRQOofnMQCe/wjPf4TP/wif/5EJDIDP/yif/9GR5gCifAGM8gsgah1A79YNQGcAOgPQGYDOAHQGoLd2AHlGoLIZ2bP7dw1gS/y6bNKvy4YoRa7LOn6br9FuyGpaGbwhK3jCl/tv8C3/BvA3ePJv8OTfAP+6zKU5NItmeq/JdJrmuwr+FfAvy0TfJZnguwj+BRnrPy+j/VUyyv+niR8AP3BKhgROyOAg+MEjMiB4iAFk8P/QdklvbYf00rh+jevXuP4Q1x/i+kMMIMSXvxDPf5jnP8zzH55FPP9hnv/IJHMAEZ7/CAOIjGAAw7IHEGUAUQYQZQDRnj8+AL1cxQD0UiO7/pMDyJvN7O8cwMb4NdmgX5P10WuyNnJN1vDbfBW/0VfybX0FX9yW8fm9hBbznC/kqhfQPJpLswGf5b0qM7xXwL8iU2mK95JMoonAj/ddkHG+8zLW95eM9iXxz8kI/1kZ7j8tw/wnTfzAMRkUAD8AfvCg9Avul75B8IMZ/J4a169x/RrXr62RbtpK+U1bzgC4/hDXH+L6Qzz/YZ7/8DTi+Q/z/Id5/iNjaJQxgHYRBhBhABF+Akb6Nx1AlAFEGUCUAUQZQJQBRFszgArLAMoyAzAqtlRklncAjtYPoFA/MoAN8auyLnZV1uhXZXXkqqwMX5UVoauynJ9qS/nGvoQWBa7yE+8qP/Gugn9F5tBsmgn4DO9lmQb4VJrivQj+BZlI473nZZz3L/CrwP9TRvnA952R4T6F7z8ug/3g+4/IwCR+4ID0C4Af2CN9ArsYAPjBbdIzCH4Q/CDXr/HNX1sFPp/9Gp/9Gtevcf2hucTzH+L5D3H9ockMgOsP8/yH+fwP8/yHef7DfP5HBmcGEOlLfP5HGECEAUR6GAMoif6WPYAoA4gygCgDiLZ1ACVNB2DkSGfT/6YBtKXUANbGr8ia2BVZpV+RlZErsiJ8RZaFrshSfqcvpkV8c18QuAL+ZX7iXQb/ksyimTQd9GmgTwV8Mk0CfQKN91aBXyVjvH/KaO85GeU9A/5p8E/KMN8JGeoD33fUxPcfkgF+8P3g+8H3gx/YIb0D26RXYIv0DGyS3wMbGMBa6R5cLd2CyetfxgC4fo3r17h+jevXZhLPf4jrD/H8h8YTz39otGUAQ4jnP8zzH2YAYQYQTg6gV2YAEQYQYQARBhApMIAoA4gygCgDiFaYNRlAaQsDyDMC3d60f+UIkq2OX5KVMdIvyfLoJVkaviRLQpdkkXZJFtJ8frbN49v7XJrNF7lZPO0zeNqn0zTQpwA+mSZy7RNAHw/6ONDH0GjgR3lPywjvKRnuBd97HPxj4B+RQb7DMtAHvu+A9Pftk74+he8H3w++H3y/wg+sk+4B8APgB3n6g1x/kG/+wQUMgOvXuH6N69f48qdx/RrPv8bzr/H8h3j+Q3z+h3j+Qzz/IQYQSg6A5z/M858cQJgBhHn+wwwg3M0ygM5SHGEAEQYQYQARBhApMIAoA4iWqcCP/k0DaJItu58dwMr4RVkRuyjL9IuyNHpRFkcuyqLQRVmgXZD5NDd4Qebw7X02zeSL3Ayaxuf6VD7Xp4A+CfSJNAH48aCP9Z4F/wz4p2Uk8COAH+49YeJ7j8pgL/jeQzLQe1AGePcb+P3A7+sD3we+D3wf+D7w/eD7wfevMfEDK2ipdA0sli4B8INcf5DrD3L9Qa5f4/o1rl/j+dd4/rXRxPVrXL/G86/x/Id4/kNcf4gBhBhAiOc/xC8A6wDCDCDchRhAOM8AIgwgwgAiDCDSzACiJapiS3/zAFpboQEsj1+QZbELskS/IIujF2Rh5IIsCJ+XeaHzMlc7L7P5zT6LZgb+kun+v/h9XwV+Fd/y/5RJNBH0JPw44MeCPoZGeU7JSM9JGeE5IcM9x2WY55gM8RwB/7DCP2Die/dKPy/43l3Sx7tD/vBuk97eLQxgEwPYIL/71ksP3xoGsEq6+cH38/T7efoDPP2B+TRHfg3wzT/A9QenEtcf5PqDPP9Bnn+N69e4fo3r14aYA9AYgMYANJ7/0B9qADz/IQYQ4gtgiAGEcgYQZgBhBhBmAOE8AzBiAJEyVakaQYEBpHOks/07RpCvpfHzsjh2Xhbp52VB9LzMj/wl88J/yZzQXzJbq5KZNCNYJdP57T6Vn3BT+CY/mS90k2iC7yz4Z8A/beCP5tpHAT8S+BHADwd+GPBDPIdlsOeQDPIclIGe/TLAs0/6e/ZIP89u6evZKX08Fnwv+F7wvQrfB76P6/cpfP8iAt/P0++fbeD/EuCbf4DrD0wirj/I9Qd5/oMMIMgAguYAKjSef43nX+tnDkBjABrPv8YAtB6WAfD8hxhAiAGEGEAoZwBhBhBmAGEGEC4wALJHSlTFZs0NIJ29af/KASyOV8nCWJUs0KtkXrRK5kaqZE64SmaF/gT/T5mhnZNpwXMyld/uUwJnZZL/DD/xzoB/mp95SfhTXP1J8E+Afxz84+Cb8EMN/EPgHwT/gMLfq/B3gb8D/O3yh2er9PaA7wHfo/C94HvB9ybxl9MS6eoD38fT75tn4P/q5+n38/T7uX4/1+/n+gPjCPwA+AGe/wDPf5DnP8j1B7n+INcfTA6A51/rrQbwuzkAjQFoXL/GALScAYQ6SVGIAYQYQChnAEYMIFymKjAAoyJLjjwjsLciW3Y/M4CF8T9lfuxPmaefkznRczI7ck5mhc/JjNA5ma6dlWk0JXhGJgdOyySayG/48f5T/L4/yU+8k+CfAP84X/aOAX+Uqz+i8A8p/AMyyL1fBrr3yQD3Hunv3i393Dulrxt8N/hu8N0WfM866eEB32Pid/OC7+Vz3wu+18Tv7OPp9/H0+7h+H9fvM/E7+nn6/Tz9fj77/Ul8rj/A9Qd4/gNcf2CAGgDXH2QAQQYQtA6A67cOQGMAGvga15/GVwMIMYAQAwhVmOUOgOzhElWxWZMBqBGobEb27FozgNZUaADz4udkbuyszNHPyqzoWZkZOSMzwmdkeui0TNVOyxSaHDwlEwOnZELgJPgnZZz/BPjHZYzPhB/Jl7sRfLkbzlM/DHQT/4AMBn4Q8AOBN/F3gb9D4W8Dfwv4m6WXe6P0dIPvBt9t4nf3gO8B3wO+hy99ngUMAHwv+F7wveB7k/g8/T6efh9Pv4/r93H9fq7fD76f6/dz/X6uPzDQGEB5gOsPMIDAH2oAPP9BBhDk+oMMIJgaQBL/18wANAagga+1V+UMIMQAQmWqUqMmAzAqyslhlh5AnhHkzWYW/cnmxk/L7NhpmaWflpnR0zI9clqmhU/J1NAp8E/KJJoYPCkTgidkfOA4+MD7j8lofseP4ufcSOBH8OVuOOjDeOqHAj+Ep34w8IPcexX+bvB3Sj8X+K7t0se1Vf5wge/aJL1cG8BfD/5aA7+HG3w3+G7w3SZ+V89CBsDnvofPfQ9Pv4en38vT7+Xp93L9Xp5+L9fv4/p9XL+P6/cNJ67fz/X7uX4/A/Bz/f4kPtcfAD/A9QcYQKCHZQDgB7n+IAMIMoBgMwPQGIBWoWIAWs4AQiWqYksFBkC2dPbsmhtAS7U0gNnxUzIzdkpm6KdkevSkTIuclCnhkzI5dEIm0UTtuIwPAh88JmMDx8A/KqP9R0x8fseP4Fv9MK8F3pMfvh/wfV3bwN8C/mbwN5r4LvBd4LtW00rp7loB/jLw+cx3g+8G3w2+ey4pfM90At8DvoenP4nvHUtcv5fr944w8X1cv4/r94Hv4/n39zMH4Of6/QzA35N+NwcQYAABrj/AAAI5AwgygCADCDKAYAq/wACMSo3sWolZ1giKcnKks4UKDCBvNrPITzYzflJmxIDXT8jU6AmZEjkuk8PHZSJNCB2T8doxGacdlbHBIzImALz/sIz0Aw/+cN9B8A/w+34/+PvA38uXvT3g7wZ/F/g71NVvM67exN9kwV8H/ppsfBf4riW0SLq6ePZdFnw3+G7w3eC7JzMAnn4PT7+Hp98DvmcUA+D6vVy/F3wv1+8dpAbA9fsYgK8PMQBfL2MApckB+MH3c/1+BuBXAwgwgAADCDCAAAMIWAYQrFQxgGCFWXMDMCpWFWWXOwAje/7yDaClWhrA9PhxmRY7LlN14PVjMil6TCZGjsqE8FEZHzoiYzXgtcMyOnhIRgUOgX9QRvgPgL9fhtFQ7z4Zwu/5wcAP4mfdQOAHAG/ibwN/a/rq/wC+N/C9uPqeXL2Jv0rhL8+DP4/Ad4Hvmkngu5L4Uwh89wQC383T7+Hp94Dv4fo9XL8HfA/X7wXfy/V7wfdy/d4kfm9zAD7wfVy/jwH4UgMA3w++H3w/+H4T3xhAgAEEGEAA/EA7I3MA5aoyVamRPZhvALkjcKSzpbMXHkE6W3bhH2xq/JhMiR0F/6hM0o/IxOgRGR85IuPCh2Vs6BD4h2Q0jQoelJGBA+Dvl+H+JP4+GerbA/4eGezdDf4ufubtUPjbwd8K/hbwN6ur36Dw10lPJ/hOrt650qi7M4m/FPjFOfhzmuK7wHeB7wLfNd7A7+AG3831u8F3D6OhBn47D9fvAd/D9XuS+H3MAXjB9/L8exmAt4eBX+oD38f1+xiAjwH4LAPwg+/voMoZQIABBMpVZWbWAaQrttSKARSquRE0V6EBTIkfkUkx4MGfoB+W8dFDMi5ySMaGwQ8dBP+AjNT2y4gg8IF9Msy/V4b6gQd/sA94r4I38LeDv5Vv+lsU/qb01fd2rpdewPd0rgF/lcJfAf4y6eYE3wm+c6F0dYLvBN8JvhN8Zwb/l1x8F/gunn4X+C7wXcNNfDfX7wbfzfW7+zOAfuYAPOB7uH4PA/AofC/X7+X6vQzAywC8DMCrBuBjAD4G4GMAPvB97c0B+BmAH3wjBuAvN0sNIFBqZA+UWMoZQDpHOluwFQPIyta0UBubFD8kE2OHwD8k42ls9KCMiRyQ0eH9Miq038TX9snw4F4ZFthj4vt3g79TBvl2yEBvEh94zzYD3sTfDP5G8JNXn4RfR2vAXw3+SoW/XOHz5DsXKfz5FvxZJr4TfCf4TvCd4Dsn5sEfaeK7ePpd4Lu4flcSf4AxgHI3+G6u380A3En8nuYAPAzAwwA84HvA9yh8L/he8L2dVJYB+CpV4PsqzFID8JepwDcqMUsNIF2RJUfTERjZm9aaAbQm6wAmxA/K+NhBGacfkLH6fhkT3S+jI+CH98nI0F7w98hwGhbcLUMDu8DfKYP9OxT+dhng3QY+8NSX3/R9+U3fB3gTf526+tW0SuGbV9+dq+/WyNU3gt+4QLo2gt84l8BvBL9xBmXjd0riO8F3gu8E3wm+cyQDMPErXUMVPtfvAt/F9bu4fhf4riR+b3MAbvDd4LvBd3P9bssAPAzAwwA8DMCj8I0YgJcBeCtVDMCrBuArV5WpwPdZBmBUbKnILDUAS7Z0drNgc9my+5ExjI/vl3Gx/Sa+vk9GR/fKqAjwYeBDwGvAa8AHd8qQwA4T379dBvq2gb9F+nuT+En4TdLHvUHhrwd/bfrqewL/u+XquzcuUfgLFf48hT87G78R/EbwG8FvBL9xPPGlr3EMAxht4jt5+p3gO8F3gu9M4g+04PdVAwDfBb6L63cxABcDcCUHAL4bfDf47s5GxW4G4FYD8IDv6aBiAB7wPe0yAzAqV5Wp1AB8Jari7FIDMHJkZUuVGkCz2ZqOoLnyDWBcfJ+Mie2V0Trw+h4ZGd0jIyK7ZXh4twwL7QIfeA34IPAB4P1bZYB/iwzwJfE3Sz/vJunr2Wjg/+FeD/468NfwZS9z9b9z9T0M+KUKf5HCn6/w5yj8mQp/msKfrPAnZOM3gt8IfiP4jeA3JvGHGPjtnOA7uX4n+E7wneA7uX5nHnwX1+9iAC4G4GIALvBdCt/dScUA3OC726vMATiMwPeUq8pUpeYAjEpUxZl8RTk5skoPwG8vnHUALdXSKMbE98jo2B4TX98tI6K7ZHhkpwwL75ChoR3gb5fB2jYZFNwqAwNbDPz+/s3S37cJ/I3gc/Ue4N3rjKvvDXwvftr1VPC/c/U9LFffTV29ic/VN4DfMEs6N4DfMJ3AbwC/AfwG8BvAbwC/gWe/AfwGK/5wE78R/EauvxH8RvAbuf5G8BtT+L3NATgZgJMBOMF38s3facW3DMDFAFzguzoaFbkYgEvhG4HvrlCVqywDILtRicoyAG9RTg6z1ADS2ZuWdxC2pgXa0Oj4bhkV2wX+Lhmh75Th0R0yLAJ+eLsMCW0Df6sM0rbIwCD4AeD9wPuA922Qvt714K+TPzzAu9cY8L34Td/Tlbn6Hs7k1S82rr6b5eq7NiTxZyv8GRb8KQp/Yn78BvAbwG8Av2Eogd8AfgP4DeA3JPG5fmMAfxD4jeA3gt8IfiPX32gOoCQ5ACcDcILvBN8JvvMXMzWANL5RpYoBuCpU5WbJARiVGtndJZmSA0hXlJMjMwKypbNn8jWXLZO/DaUGMDK+U0bEdshwHXgaGgU+Anx4qwwObTHxtc0yILhJ+gc2Sj//BgO/j2+d9PGuBX8N+Fy9e6XC5+pdyw34HnzD7+40r76b5eq7GlefxJ9pwZ+ajV8Pfj349eDXg18Pfj349SMYQC7+oAx+A/gN4Ddw/Q3gN4DfAH6DBb+R628EvxH8RvAbOxsVN6YGAL6zo1GRkwE426vAd7bLPwBXmarUyO6yDMBdbKkou+QALNnS2c28LWXLHkFL5Q5hRBz82Hbwt8lQGhIFPgJ8GPjQZvA3yQBto/QPbpB+AfD9wPuA966h1dLbs8rAT8L3BP531zKFvxj8RQp/PvjzFL559Sa+efW/1oNfD349T359Cn+cBX9UBr8e/Hrw68GvB7+ez/168OvBrwe/Hvx68Ot5+uutAwDfiAE0cP0NDKCBATQwgAaF3/iLigE0gt/YQQV+Y6UZA3AYge8sV5VlDcCeGkC6YktFZukROLKypbNnRtBcyQG0pkKDGB7fJsNiW8HfIkNocBT8CPBh4EPAaxtM/OB66RtYK338wPtWg78KfK6eerqXg78MfOBdSwz47vyu7+Y0r/63JDxf9LpannwDvz6Jn4SfbMEf3zJ+Hfh14Ncl8Qem8Sss+OVJ/Hrw68Gv5/rrwa8Hv57rrwe/Hvx6E98YQAMDaAC/AfyGjkZFDeA3tDczBtDOyNFYoSo3Sw7AqNTIblSSKd8A0jmysqVKDqCljBHYWq65YQyLb5GhsST+ZhlMg6KbZGBkowwIAx8CXlsP/joTPwC8H3jfSuntTeKvMPB/dy8Ffwn4XL0rib8AfPPqM/iz0k++iT/Vgm9evYFfB34d+HWjCfw68OvAr+Pbfl0Ofh34deDXgV8Hfh34deDXgV8Hfh34deDXgV8Hfp0VXw2gHvx68Ot/UTGAevDrO5gZA6hUtTNyNFSo1AAay1SlRnajkkzOYktFORUYgMvefOkh2JqvpXEMjW+WIbFN4G+SQfpGGRjdIAMi4IeBDwGvrZW+wTXgrwIfeOrlWyG9vFy9Z5nCXww+8K6FGXznXPCB5+ediW/Cd1ZP/q/qyU/j14034DvWjcnBH94Uvxb8WvBrwa8Fvxb8WvBrwa8FvzaDX2bFp5I6BlAHfh34dVx/HfhG4NeBX9fRqKguOYD2qkoV+PUVqnJzAA1llkqN7A0lmRqLcyrKLjkAS7Z09kzNjsFWOHcrGhLfKINjG8HfIANpQHS99I+sk35h4EPAa6ulTxD8QBIfeN9yWiY9vcB7uHp3Eh94F/Cu+eDPU/jANwLPb/sMvgn/q3ryDfy6JP64PPhcfS34teDXgl8Lfm0r8WvBrwW/FnwjBlDLAGrBrwW/FvzazkbFteDXgl/bySyFbwR+XaWqnZGjzjIAozJVqZHdqMTMGEFxTkXZNTrS2bKyZ3I2l83M9YMNjm+QQbEk/noZoK+T/tG14K8BH3htFa2UP4LgB8D3A+9bCv4S8IH3LGIAKfx5BLxzDqXwZ4BvXn02/kQyrz4bf5R0qOXqa5viV6bwa/jCVwN+Dfg14NeAXwN+TW8Cv6aniqe/Bvwa8GvArwG/BvyaLioGUAN+zS9mxgA6GhXVgl/bXlWpAr9WDcCoXFWmKjWyG5WYGUMotlTUtAZHOltW9kyNzWUzc7ay3AEMiq+XgbF14K+V/voa6RdZLX3DwIeAT+JrK6R3kKsPgO8H37dYfvcC71kI/gLw51vwgXfOAn9mDr4J/6u6+mz8McTV1xbArwG/Bvyaga3A79UCftcc/NQAOqnAr+mgAr+mUtXOyFFboSpXlVkqNbIblWRGUFdsqahp9Y50tqzsmRqay2bW2MpyBzEwvlYGxNaAv1r6RVdJ38hK6RMGPrQC/OXSW1smvYLAB5YwAPB94HsXMID50t1twndzcfUuhe8EvnE6mVffFN+E76SuvmNtHvyaYWn4yppB2fjV4Ff3JfCrwa/ubVRWDX41+NU8/dXgV4NfDX71b0Yl1eBXg1/d2ai4Gvxq8Ks7qbj+auCN2qsqzZL4RhWqclWZqtTIblRilhxBbXFORU2rc6SzZWXPVN9ctkwNrcw6iAHx1dI/tkr66SulbxT8CPDh5QxgGfhLpZcGfHAxA1gkv/u5eh9X7wXfA77bhP/NlYSfmQcf+IZJ4JtX3zy+Cd++ZmhT/Grwq1vA/w7+d/C/g/8d/O/dVOB/B/87+N87q8D//osK/O8djYq+d1BZ8KvbGTmqK1TllspUpUZ2o5LMCGqKcyrKCfjaTLas7NnVFcqWXX0rS42hfxz8GPgMoE8U/AhXHwY/lMH/PbAQfK7eB7x3HvhzTXy3wnfNAB945zTwgW/k6hX+L03wzSe/o4LvYLn6LPxq8KtN/HZW/O/gfwf/e2+jsu/N4H8D/xv437qowP8G/rdfVJ1UOfhGlSrwjSpU5aoyS6VG9u8lZtWpii0V5clhjkBlS2dvWm2hbE2ra2XJIfSLgx9bIX10rj4KfGQpA1givUJcvcbVB8EPgO8H3we+d4508wDvngX+TBPfZeJ3dqbwufoG4BsUfL159Xnxa3Lwq/Pgfwf/ewH8b+B/A/8b+N/A/9ZNVQj/1yb4xd+AN2qvqlS1M3J8q1CVWypTlRrZjUrMjCEU51SUJ4c5ApUtnT1/+YZRY8tfbSvrG18ufWLL5A8d+OgSBrBYeoUXSc8Q8NoCBjBfegSA989lAOB7wfeA755pwHd1cfVJeOcU8Ln6xjz49T+I/z0P/jfwvyXh8+HTV/C/gv+1qwr8r+B/Bd4I/K+dVB2Nir52UIH/tVLVzsjxtcJSuarMUqmR3agkM4JvxTkV5clhxhBsWdmbL2sYtsLVtKI+cfBj4OvgR8GPgB8GPwS+Bn4Q/MAcBjBbuvmA985kAFy9W+G7FL5T4Tcq/AYFX6/g+YnXUcF3sDz57S3wlQY8fc/B/wb+tzz4X8H/Cv7X7ioTvzSF/wX8L51V4H/5RQX+l45GRV86qNqrKlXtjBxfKlTllspUpUZ2oxJzAOmKcyrKyZGV7Zs1e8ulB2FrueZG8kcc+NhiBrBIekUXSs8I8OH5DGCe9NC4+iD4AfD9VnwTvosLeNdk8E34XxuT8OPz49e1Al/Bp/G/5cH/miwP/hfwv4D/JQnfEr4awGfgjdqrKlXtjByfKyyVq8oslRrZjUrMERgV51SUJ0dWtmRfU9lb3zdb68s3jj/i4MfA18GPgh8BP6zwNfCDs8AH3jeDAXD1HvDdOfhOhd+Yg1//I/hJ+Bz8r+Cn4RX+F/C/dFdZ8D8nA/9zZxX4n4H/lKyTqqNR0SfwP7VXVaraGTmMKlTlqjJLpUZ2o5KcinMqyu5zMkdWNmtf7G3IZva1jaVG0Tu+UHrFFkhPHfjoPAYwV3qEgddmE/gB8P3g+8D3gu8B353En0TAOycQ8I3jwAe+YQz4wNeb8B3rTPgOtcNaid83g/81g1+ewv9i4pel8D+D/xn8JPynZOB/6qwC36gA/sdk7VWVqnZGjo8VqnJLZZZKjexGJZaK81TUtE+OrGzp7K3rcypb0760oV5x8GPzGQD4UfAj4IcUfhD8wHQGME26+oD3TgGfq3crfJcFv7EAfp3CrzXh2xs/8fLgW66+Cf6XJHwO/meF/wn8T3nwPwJvBP7HTqqORia8Bf9DpaqdkeNDhaVyVZmlUiO7UUlOxTkV5cmR6SPoWdnbGIiffrDkWHrGwY+Br4MfBT4yiwHMlG4aVx8EPwC+H3wf+J48+E4LfoPCr28O34QviG/A5+L/bvYZ/CT8p2Q5+B+7qEz8kjS+GsCHjirgjdqrcvDfJ6tQlVsqs1RqZDcqyak4p6I8ObKypfqQzN7GbE372IZ6xufK77E50kMHPwp+GPwQ+Br4QfAD4PvB94LvmcgAgHeNJ+CdY8EHvnE0+MA3jGwVfuonXrP4Xyz4nxX+pxz8j0n4HPwPvxoVf/hFlYP/Pll7VaWldkZp/HfllsoslRrZjUpyKs6pqECOrGxZ2TO9b022lvvQTL/HwY/NZgDgR8EPgx8CXwM/OIUBTOb6uXov+B7w3QrfBb5T4Tem8EcQ8HXDaKiJX6vwa3Lx++XB750f/1MKv5vZxxz8D8ny4L/vpAL/fQ7+u2SVqnZGjncVlhT+2zJLpensRiWWivNUlCdHVrYm2Qv3Ll+2Hys1jh5x8GPg6+BHpzOAaQxgqnTVwA+C7wffB743D77Tgt+Qiw987eBm8NWXva8W/C8WfAM+B/9jBr/0Q1cFb8F/D/77X1QW/Hd87r/roLLgv03WzsjxtsJSuSXg36QqNbIbleRUnFNRgRxZ2bKy/0A2s7c/WI/4TOkemyHddPAj4IfBD4GvgR8A3w++D3wP+G6F77LgN1rw63PxB6XxK1vE75WD3yOD/9GC/yEH/31nAz4L/10nVUcV8G+TtVdl4xe9YQBvKlTllpriO16Db1Riqbhpr4oK5MjKlpW9cK8LZWu5N83UPT6DAYCvgx8BPwx+CHxtEgMA3w++F3wP8O4x4APvGsUARmbwGyz4dQq/NolvwjfF75Mf/3MO/kcL/gcL/vsuKgv+u19UCv9tR5UF/02ySlW7dAb861TlZq/Kcio1shuV5FSc3ctkRXlyZGVrkr2N2bJ79QN1j4MfA1+fygDADyv8IPgB4P3jGAD4HvDdFnwn8I3DwR9m4tfnwa9J4vc3/gkdA/975vO+IufLnoH/KQ/+Bwv++xz8d78apfHfdlJZ8N90UPAK/3WqdkaOVxWWyi0p+JfJSo3sRiU5FWf3IllRgRxZ2bKy/0C2H8s6mm5x8GPg6+BHwA+Dr02QzsHxDAB8H/heC77Lgt8IfMPQDH5dK/C/tYD/sRX473Lw31rw33RUWfBftzfRX6VqZ5SGf5ms3FKZJfBfmNmNSnIqzu55sqI8OZpky8r+A9l+vm5x8GPg65MZAPgh8DXwg+AHxjIA8L2jGYCJ38kFvtOKD3z94Ax+rcKvSeL3y4Pfuxn87k3x31vw31nw3/6q4BX+mxz81x1M+FftLfD0sp2RiW7Bf5GqzJIF/3mykpyKm/asqECOrGxNsv9Atp/vtzj4MfCjE6VLBPwQ+Br4QfD94PvA94DvVvgu8J3gN4LfkMIfZNQEv7pvC/i/N8VPX70FPw3f2YA3U/hvLPivkwH/qoOCV72sVJn4RS8YwIsKlQX/eVlOpUYG/rOSPBVn97SoQKA/yc6Wlf0Hs/18v8XB17n86AQGAH4IfA38IPh+8L3ge8B358FvAL/egl+bB//7D+C/z4P/Ngf/jQU/Cf8qmQX/ZSqF/6JdujT+82TllkB/lqo0nf2ZGsBTa4A/ya0of48dWdmaZG97j5LZfr6u8UkMAPwo+JFxDAB8DfwA+H7wveB7FL4LfCf4jUMYgMKvB77Ogl+Twu+Tg9+rbfjvCuC/seC/7qTgTfzilx0s8PSiUqXwn7dT6Kpn5ZYs+E9L09mfJCvJSYE/tlaUv0eOJtmaZM/fw+aytb0Heeoa5+nXwY+CHwE/NIYBgB8A3w++F3y3wneB7wS/EfyGHPxaC361Bf/bT+C/teC/seAb8Bb8lxb8F6kU/vN26Uz0VBb8p2VmT5KVpjPwH5fkSaE/slaUv4eOrGzJHlizt637qWx/T13iE9QAwA+DHwJfG8UAwPeNYADgu4cxgBz8BuDrga+z4NdY8L9b8L/+BP4bC/7rXxS8wn9pwX9hwX9eqVL4z9pZ4OlpudmTcoVu6XFpOvtjNYBH1izoD1MVmT3IzdEk2/3c7M13r1C27O7+YF3i4OtcfxT8MPgh8IPgB8D3ge8B3w2+C3wn+I0mfvsUfh34tRb86gx+hRX/S/Zv/Dbhv87Bf2nBf5HEVwN4bsF/VmnAmyXR6UmFQrfgP7YG/CMzu5FCf5gK7Ae5WcDv5+bI7h7gWQF5t43dSWX7e+oSB1/n+o0BgK+BHwTfD74PfI/Cd4HvBL8R/IYB6vot+DU5+N9y8D9n45dZ8d8p/LcK/00O/qs8+C8s+M8t+M8s+E+TpeAV/mNrCv5RWRrewH9YaoI/yA3w+7lZwO9Zuutoks3aHYcFs4Vu58tmdusn6xwHXwc/yvUbAwA/CL4ffC/4HhO/gwt8J/iNwBsD6M8AwK818c3rB/+7Bf+riV+ehd8tD34XKW0J/6XCf2HBf67wn7XPwD+tNOGfJFPwj1Mp+EflCl0FuNED4I0U+H1rFvR7qZLQBQI4N1uq26ksoLda2c1kth/vRk6d4+Dr4EfBD3P9xgDA9w9lAOC7W8Cv7aOu34L/LQ/+pzz47wvgv6ZXzeA/z4P/VPWkXboMfIVCt+A/VD0oM+CN7oNvZIG/V2Ji381XEjpfgN+2dAvsJllBW9ENawrv+k90TfVrfDQDAD8Kfhh8jetXA+igBtBeDaDSGAD49eDX5eBXg/89B//LT+K/VPgv8uA/U/hpeAv+Ywv+Iwv+w3ILuup+aToD/55Cv5vKAn7HmsK+rbplzZHpJth5y0Wl663omj2D15quttCvcfD1kQwA/PBwBgB+AHwf+F7w3eC7uH4n+I3gN4BfD35dH2MAFTU5+N/A/6rwP1vwP7YevyQf/nMTv/hZDv4TC/5jhf+oItNDBf+g3IKeSuHfA/5uqQWd7qSyoN9W3Spq2s1UjuxugJ3qeqpCsM10NZUF70obulwgcwDgR8APga/x9AfA9/H0exS+C3yniV+ZD7+6lxpAHvxP/wL8p+0t8JVp+KJHyVLwFRb48hz4MgPdcdcsjX8npzR4blZw1Y0iA9voeiabtWupCuGqrjRXHsRLbehiTr/ER6YH0DEEvgZ+AHwf+B4LfiP4DX0t1w9+TR78rz3Mf+Wugd89g/8h81Ov9F0L+C8U/vOOaXgD/2kO/uNKC7zCT8I/qMjA3y+3oKvuZvAdd0ot4KpbJdngN61Zwem6NQV/LVMa/WqqFoAvW7qUr2YwL7Sh86pf4uDrXH9kmGUAgxgA+J4BDAB8Zz9jAO2MAYBfB34t+DW9jAGUfwf/2++W6+9uefpbif8yH37HbPwn7S3wOfhp+AoLvMpAT2Wip7LfLrWgW/Bv5nSjOA84XUtlgb9qZruSpxaBVRctXbDWDGZz/ZWnKmMA4OvgR8APgR/k+v1cv5cBuLl+NYB2jbn4vbPxv6Wuv7vl6c/+Z/XMp/9n8Ntn8NPw9MCCnwVfboEvy4J3JOFvlWbQb1pLgdP1VLngqqsqcHOzXVZdStVaZEvnrbWAWtWK/sypkzEA8CNDGAD4QfD94HvBd4Pv4vqd4DeAXw9+XW/L9YP/PQf/cw7+hxz8t23Af9rBAq/wHxXAv1+RA2/Bv6O6bcI7blnwrfA3SnLQ6VqqXHBrgF9WXTKzWbuYqjXIlv6yVGVvPeq5FjprqVN8WHoAHYwBgO/n6feC7wbfBX4j+A1/WAYAfg346QGA/7W7un6F/zEXv0vr8J+1At+AV/j3LaXhyzPoBnyZgZ7KfrM0B52ul+RBVzUBp8uqS47sLlrAL1hrBXRVgf5M1QbYZGdyOp2nTnHwda4/An6I61cDqPRYrl8NoKI+P37m+rsZA8jCf9/F8rmf/YWvJI3fqQl+cSvwi9LwFRl4K74Bb8G/aZaGv24pC1x1pbgp+iVrJrjRhUwG+HlrhS66APS5fP0AbqpTOZ20ZA4A/Ahf/DTwg1y/D3yPun4n+I3J6we/rpcxgHJjAOB/72G5/m6W6++qBtCl6Ze+tuI/UvgPKxU83W9n4hvwFvw75TnwZVnwjhvgJ8uCT2VFV13Og35RdaEoC91+3iyN/pelghddAPus6oyl1uCebKYTOR1XdYwPSQ+gfXIAAfB94HvAd4HvBL+ht3n9xgDAr8mDb1x/U/yCn/vN4T9uI/4dVRZ8WRa843oSvjQHna6WZMNfVl0qLoBuwT9v6S8zW1VOzWGfzYN9Ok+tQc6Hm69jOXWMg69z/WHwtQF5B1BhDAD8OoWvrr/sW3fL9Vs+9z90UQNoBf7zVuLfV6XhKzLwufg3y7Lg0/i58FdKsuEvWcqHfj5VNrq9yswEV51L1VZs1UlrbUC24h7N6UiesgcAfgB8H/hu8F1cfyP4DeDX98xcfzXX/727GkDy+n+zXH8e/Dd5vvQ1we/QFP9BK/Bv061yC3xZFryBf63Ucu0p+JKca0/BFxdAp79UVY7sssBVZx0/iK06oTpubz3ykQIdtnQop45x8HXwwwMyA/BmBlCRGkDy+mvBr+lhuX7wv/xmDCD99BsDsPwrePN97reE/7AZ/DsVGfi8+GUZ/GtmTeFLsuEvpuCLm0FPZYIbncuURj+j+mHsnFoL3RxyqoOWDqg6pAfQnwGAH+jLAMB3c/1O8BvN6y+v+90cQPr6u6UHkPzf0W96/Zl/Tj/7S19T/OKW8IEvysW/pcqCL8uCd1wtbQp/qSTn2i2dL86Gr7L0Z1ETdPtZswy6pULgzWKrjqqO2NsOnQ852f4CdYgPZAADjAFUJgfg5/q94LvAd4Lf2DMzgOT1V4OfGoBx/V3VALpYrj/zr+BN47/M81v/ieVzPx/+vVbgp+HLMvAp/CbwqrzwxXmuXcGfS5VBtwNuP52LrmoNeF7snA7b2wZdCHmfpb2W9qgBtI9y/WHwNa7f3yd7AA3g1yevv4cxgLLq1PX/Zrn+LvmffuP6O2U//Xnx27eMf7vCAt8MPvCOK0n80jzwJU3RDfjiZtDpbFEWujUTPKd86C2BH1YdspaD3dJFF0LO125Vh/gAYwCVagDt/OB7wHeB7+T6G35Xz39yAMnr75YeQPL/KldmAJ0LX39z3/gftbd84au04LdrHf61six4A/9yDr4BX1IAvrh5+DNFTeFBt2eBq447mqK3CZwOqg7YC2Pnu+jmkJPtsrTTUodYcgDgh7n+YJ/sAfD8lxsDAL+2u3n9xgCS19/V+L/MVfDpV9ef/fRn8ItbgV+UDz/r6pviO5L4TeBLCsAXq8/23GtX8KeLmqCnykZXNXflrQKn/al+EDsf9I4Cbaf2sf7mAEJqAL7eDAB8F9ffCH59D3MAyeuvBv/7b5br75K+fuN/T/+d+b+2ZV5/HvxnzXzps+LfycG/mcIvz8a/WpYF77hU2hTeip8Fr2py7Sl4OlXUBN7eBF111NE69ILgqn2qtmDvbAF7u6Vtqq2qzADAD/5hDKDCbQ6gPDWA5PXXdDMHkLz+r10tA8jz9L9Ofe7n/LN7hb70tQX/Whvwz6vywhdnw5/OgT9ZlIVuP54pG52OOLLRm7vyguCqPfafu+xcaCv2ljy1j4Ef7WsZAPhurt8JfmOP7AEkr/+bwv+s8Ft7/blP/8NWPPst4St4Az8vfEkB+OIW4IvywtuboKsKoee78rzglnbb8193a7C3toC9WbXJUmYA4Ae5fusAGpLPP/i13SzPf3IAXTLX/yEH/3Whpz/P5376d34ufkUG/3oO/pV8+KUt46fhi5uHP1GUDX9M1QRddcjxc+i7VbtUhcCbe8Zbi71RtcFS+xj4Ua4/OYAAA/AmBwC+s0fOANT1pwfQ2RhA9vV3Utdv+RdzNvnWn/Ol767l6W8rPvCOC6V54EsKwNPp4mbg6XhRBv6o6ohZNrqqNeh7WkKnHal+4Lpbi51qvaXKrAGA7+X6XakBgF8Hfs1vlgF0ST//qf/TbCXvLNf/Kv/T3+LnfnP4V/9m/ILwRRn4I5aaoKvaim4Fz0JXWdHbct2twV5naa1qjU3+HwuefjlXE4+yAAAAAElFTkSuQmCC",S_e=0,Aw=(n,e,t,i)=>{if(!n[t]){let r=n.useDelayedTextureLoading;n.useDelayedTextureLoading=!1;let s=n._blockEntityCollection;n._blockEntityCollection=!1;let a=_e.CreateFromBase64String(e,i+S_e++,n,!0,!1,_e.BILINEAR_SAMPLINGMODE);n._blockEntityCollection=s;let o=n.getEngine().getLoadedTexturesCache(),l=o.indexOf(a.getInternalTexture());l!==-1&&o.splice(l,1),a.isRGBD=!0,a.wrapU=_e.CLAMP_ADDRESSMODE,a.wrapV=_e.CLAMP_ADDRESSMODE,n[t]=a,n.useDelayedTextureLoading=r,Ap.ExpandRGBDTexture(a);let c=n.getEngine().onContextRestoredObservable.add(()=>{a.isRGBD=!0;let f=n.onBeforeRenderObservable.add(()=>{a.isReady()&&(n.onBeforeRenderObservable.remove(f),Ap.ExpandRGBDTexture(a))})});n.onDisposeObservable.add(()=>{n.getEngine().onContextRestoredObservable.remove(c)})}return n[t]},QM=n=>Aw(n,__e,"environmentBRDFTexture","EnvironmentBRDFTexture"),xw=n=>Aw(n,v_e,"environmentFuzzBRDFTexture","EnvironmentFuzzBRDFTexture"),K9=n=>Aw(n,E_e,"openPBREnvironmentBRDFTexture","OpenPBREnvironmentBRDFTexture")});function j9(n){return class extends n{constructor(){super(...arguments),this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1}}}var Z9=y(()=>{});var Rw=y(()=>{ea();wt();Is();Pt.prototype.restoreSingleAttachment=function(){let n=this._gl;this.bindAttachments([n.BACK])};Pt.prototype.restoreSingleAttachmentForRenderTarget=function(){let n=this._gl;this.bindAttachments([n.COLOR_ATTACHMENT0])};Pt.prototype.buildTextureLayout=function(n,e=!1){let t=this._gl,i=[];if(e)i.push(t.BACK);else for(let r=0;r<n.length;r++)n[r]?i.push(t["COLOR_ATTACHMENT"+r]):i.push(t.NONE);return i};Pt.prototype.bindAttachments=function(n){this._gl.drawBuffers(n)};Pt.prototype.unBindMultiColorAttachmentFramebuffer=function(n,e=!1,t){this._currentRenderTarget=null,n.disableAutomaticMSAAResolve||this.resolveMultiFramebuffer(n),e||this.generateMipMapsMultiFramebuffer(n),t&&(n._MSAAFramebuffer&&this._bindUnboundFramebuffer(n._framebuffer),t()),this._bindUnboundFramebuffer(null)};Pt.prototype.createMultipleRenderTarget=function(n,e,t=!0){var q,K,J,Y,j,ue,Ee,Ue;let i=!1,r=!0,s=!1,a=!1,o,l=1,c=1,f=0,d=3,u=!1,h=5,m=3553,g=[],p=[],_=[],v=[],E=[],S=[],T=[],A=[],R=[],M=!1,I=this._createHardwareRenderTargetWrapper(!0,!1,n);e!==void 0&&(i=e.generateMipMaps===void 0?!1:e.generateMipMaps,r=e.generateDepthBuffer===void 0?!0:e.generateDepthBuffer,s=e.generateStencilBuffer===void 0?!1:e.generateStencilBuffer,a=e.generateDepthTexture===void 0?!1:e.generateDepthTexture,l=(q=e.textureCount)!=null?q:1,c=(K=e.samples)!=null?K:c,g=e.types||g,p=e.samplingModes||p,_=e.useSRGBBuffers||_,v=e.formats||v,E=e.targetTypes||E,S=e.faceIndex||S,T=e.layerIndex||T,A=e.layerCounts||A,R=e.labels||R,M=(J=e.dontCreateTextures)!=null?J:!1,this.webGLVersion>1&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===16||e.depthTextureFormat===14||e.depthTextureFormat===18)&&(o=e.depthTextureFormat)),o===void 0&&(o=s?13:14);let C=this._gl,L=this._currentFramebuffer,w=C.createFramebuffer();this._bindUnboundFramebuffer(w);let G=(Y=n.width)!=null?Y:n,O=(j=n.height)!=null?j:n,N=[],B=[],V=this.webGLVersion>1&&(o===13||o===17||o===18);I.label=(ue=e==null?void 0:e.label)!=null?ue:"MultiRenderTargetWrapper",I._framebuffer=w,I._generateDepthBuffer=a||r,I._generateStencilBuffer=a?V:s,I._depthStencilBuffer=this._setupFramebufferDepthAttachments(I._generateStencilBuffer,I._generateDepthBuffer,G,O,1,o),I._attachments=B;for(let se=0;se<l;se++){let ve=p[se]||d,ne=g[se]||f,me=_[se]||u,Le=v[se]||h,de=E[se]||m,be=(Ee=A[se])!=null?Ee:1;(ne===1&&!this._caps.textureFloatLinearFiltering||ne===2&&!this._caps.textureHalfFloatLinearFiltering)&&(ve=1);let we=this._getSamplingParameters(ve,i);ne===1&&!this._caps.textureFloat&&(ne=0,te.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),me=me&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU);let dt=this.webGLVersion>1,Ve=C[dt?"COLOR_ATTACHMENT"+se:"COLOR_ATTACHMENT"+se+"_WEBGL"];if(B.push(Ve),de===-1||M)continue;let Ze=new Xi(this,6);N[se]=Ze,C.activeTexture(C["TEXTURE"+se]),C.bindTexture(de,Ze._hardwareTexture.underlyingResource),C.texParameteri(de,C.TEXTURE_MAG_FILTER,we.mag),C.texParameteri(de,C.TEXTURE_MIN_FILTER,we.min),C.texParameteri(de,C.TEXTURE_WRAP_S,C.CLAMP_TO_EDGE),C.texParameteri(de,C.TEXTURE_WRAP_T,C.CLAMP_TO_EDGE);let Kt=this._getRGBABufferInternalSizedFormat(ne,Le,me),Bt=this._getInternalFormat(Le),wi=this._getWebGLTextureType(ne);if(dt&&(de===35866||de===32879))de===35866?Ze.is2DArray=!0:Ze.is3D=!0,Ze.baseDepth=Ze.depth=be,C.texImage3D(de,0,Kt,G,O,be,0,Bt,wi,null);else if(de===34067){for(let ae=0;ae<6;ae++)C.texImage2D(C.TEXTURE_CUBE_MAP_POSITIVE_X+ae,0,Kt,G,O,0,Bt,wi,null);Ze.isCube=!0}else C.texImage2D(C.TEXTURE_2D,0,Kt,G,O,0,Bt,wi,null);i&&C.generateMipmap(de),this._bindTextureDirectly(de,null),Ze.baseWidth=G,Ze.baseHeight=O,Ze.width=G,Ze.height=O,Ze.isReady=!0,Ze.samples=1,Ze.generateMipMaps=i,Ze.samplingMode=ve,Ze.type=ne,Ze._useSRGBBuffer=me,Ze.format=Le,Ze.label=(Ue=R[se])!=null?Ue:I.label+"-Texture"+se,this._internalTexturesCache.push(Ze)}if(a&&this._caps.depthTextureExtension&&!M){let se=new Xi(this,14),ve=5,ne=C.DEPTH_COMPONENT16,me=C.DEPTH_COMPONENT,Le=C.UNSIGNED_SHORT,de=C.DEPTH_ATTACHMENT;this.webGLVersion<2?ne=C.DEPTH_COMPONENT:o===14?(ve=1,Le=C.FLOAT,ne=C.DEPTH_COMPONENT32F):o===18?(ve=0,Le=C.FLOAT_32_UNSIGNED_INT_24_8_REV,ne=C.DEPTH32F_STENCIL8,me=C.DEPTH_STENCIL,de=C.DEPTH_STENCIL_ATTACHMENT):o===16?(ve=0,Le=C.UNSIGNED_INT,ne=C.DEPTH_COMPONENT24,de=C.DEPTH_ATTACHMENT):(o===13||o===17)&&(ve=12,Le=C.UNSIGNED_INT_24_8,ne=C.DEPTH24_STENCIL8,me=C.DEPTH_STENCIL,de=C.DEPTH_STENCIL_ATTACHMENT),this._bindTextureDirectly(C.TEXTURE_2D,se,!0),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_MAG_FILTER,C.NEAREST),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_MIN_FILTER,C.NEAREST),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_WRAP_S,C.CLAMP_TO_EDGE),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_WRAP_T,C.CLAMP_TO_EDGE),C.texImage2D(C.TEXTURE_2D,0,ne,G,O,0,me,Le,null),C.framebufferTexture2D(C.FRAMEBUFFER,de,C.TEXTURE_2D,se._hardwareTexture.underlyingResource,0),this._bindTextureDirectly(C.TEXTURE_2D,null),I._depthStencilTexture=se,I._depthStencilTextureWithStencil=V,se.baseWidth=G,se.baseHeight=O,se.width=G,se.height=O,se.isReady=!0,se.samples=1,se.generateMipMaps=i,se.samplingMode=1,se.format=o,se.type=ve,se.label=I.label+"-DepthStencil",N[l]=se,this._internalTexturesCache.push(se)}if(I.setTextures(N),t&&C.drawBuffers(B),this._bindUnboundFramebuffer(L),I.setLayerAndFaceIndices(T,S),this.resetTextureCache(),!M)this.updateMultipleRenderTargetTextureSampleCount(I,c,t);else if(c>1){let se=C.createFramebuffer();if(!se)throw new Error("Unable to create multi sampled framebuffer");I._samples=c,I._MSAAFramebuffer=se,l>0&&t&&(this._bindUnboundFramebuffer(se),C.drawBuffers(B),this._bindUnboundFramebuffer(L))}return I};Pt.prototype.updateMultipleRenderTargetTextureSampleCount=function(n,e,t=!0){if(this.webGLVersion<2||!n)return 1;if(n.samples===e)return e;let i=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),n._depthStencilBuffer&&(i.deleteRenderbuffer(n._depthStencilBuffer),n._depthStencilBuffer=null),n._MSAAFramebuffer&&(i.deleteFramebuffer(n._MSAAFramebuffer),n._MSAAFramebuffer=null);let r=n._attachments.length;for(let a=0;a<r;a++){let l=n.textures[a]._hardwareTexture;l==null||l.releaseMSAARenderBuffers()}if(e>1&&typeof i.renderbufferStorageMultisample=="function"){let a=i.createFramebuffer();if(!a)throw new Error("Unable to create multi sampled framebuffer");n._MSAAFramebuffer=a,this._bindUnboundFramebuffer(a);let o=[];for(let l=0;l<r;l++){let c=n.textures[l],f=c._hardwareTexture,d=i[this.webGLVersion>1?"COLOR_ATTACHMENT"+l:"COLOR_ATTACHMENT"+l+"_WEBGL"],u=this._createRenderBuffer(c.width,c.height,e,-1,this._getRGBABufferInternalSizedFormat(c.type,c.format,c._useSRGBBuffer),d);if(!u)throw new Error("Unable to create multi sampled framebuffer");f.addMSAARenderBuffer(u),c.samples=e,o.push(d)}t&&i.drawBuffers(o)}else this._bindUnboundFramebuffer(n._framebuffer);let s=n._depthStencilTexture?n._depthStencilTexture.format:void 0;return n._depthStencilBuffer=this._setupFramebufferDepthAttachments(n._generateStencilBuffer,n._generateDepthBuffer,n.width,n.height,e,s),this._bindUnboundFramebuffer(null),n._samples=e,e};Pt.prototype.generateMipMapsMultiFramebuffer=function(n){let e=n,t=this._gl;if(e.isMulti)for(let i=0;i<e._attachments.length;i++){let r=e.textures[i];r!=null&&r.generateMipMaps&&!(r!=null&&r.isCube)&&!(r!=null&&r.is3D)&&(this._bindTextureDirectly(t.TEXTURE_2D,r,!0),t.generateMipmap(t.TEXTURE_2D),this._bindTextureDirectly(t.TEXTURE_2D,null))}};Pt.prototype.resolveMultiFramebuffer=function(n){let e=n,t=this._gl;if(!e._MSAAFramebuffer||!e.isMulti)return;let i=e.resolveMSAAColors?t.COLOR_BUFFER_BIT:0;i|=e._generateDepthBuffer&&e.resolveMSAADepth?t.DEPTH_BUFFER_BIT:0,i|=e._generateStencilBuffer&&e.resolveMSAAStencil?t.STENCIL_BUFFER_BIT:0;let r=e._attachments,s=r.length;t.bindFramebuffer(t.READ_FRAMEBUFFER,e._MSAAFramebuffer),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer);for(let a=0;a<s;a++){let o=e.textures[a];for(let l=0;l<s;l++)r[l]=t.NONE;r[a]=t[this.webGLVersion>1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"],t.readBuffer(r[a]),t.drawBuffers(r),t.blitFramebuffer(0,0,o.width,o.height,0,0,o.width,o.height,i,t.NEAREST)}for(let a=0;a<s;a++)r[a]=t[this.webGLVersion>1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"];t.drawBuffers(r),t.bindFramebuffer(this._gl.FRAMEBUFFER,e._MSAAFramebuffer)}});var JM,q9=y(()=>{Kr();sd();Rw();JM=class extends jr{get isSupported(){var e,t;return(t=(e=this._engine)==null?void 0:e.getCaps().drawBuffersExtension)!=null?t:!1}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t<this._textures.length;t++)this._textures[t].wrapU=e}set wrapV(e){if(this._textures)for(let t=0;t<this._textures.length;t++)this._textures[t].wrapV=e}constructor(e,t,i,r,s,a){let o=s&&s.generateMipMaps?s.generateMipMaps:!1,l=s&&s.generateDepthTexture?s.generateDepthTexture:!1,c=s&&s.depthTextureFormat?s.depthTextureFormat:15,f=!s||s.doNotChangeAspectRatio===void 0?!0:s.doNotChangeAspectRatio,d=s&&s.drawOnlyOnFirstAttachmentByDefault?s.drawOnlyOnFirstAttachmentByDefault:!1;if(super(e,t,r,o,f,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0),!this.isSupported){this.dispose();return}this._textureNames=a;let u=[],h=[],m=[],g=[],p=[],_=[],v=[],E=[];this._initTypes(i,u,h,m,g,p,_,v,E,s);let S=!s||s.generateDepthBuffer===void 0?!0:s.generateDepthBuffer,T=!s||s.generateStencilBuffer===void 0?!1:s.generateStencilBuffer,A=s&&s.samples?s.samples:1;this._multiRenderTargetOptions={samplingModes:h,generateMipMaps:o,generateDepthBuffer:S,generateStencilBuffer:T,generateDepthTexture:l,depthTextureFormat:c,types:u,textureCount:i,useSRGBBuffers:m,samples:A,formats:g,targetTypes:p,faceIndex:_,layerIndex:v,layerCounts:E,labels:a,label:e},this._count=i,this._drawOnlyOnFirstAttachmentByDefault=d,i>0&&(this._createInternalTextures(),this._createTextures(a))}_initTypes(e,t,i,r,s,a,o,l,c,f){for(let d=0;d<e;d++)f&&f.types&&f.types[d]!==void 0?t.push(f.types[d]):t.push(f&&f.defaultType?f.defaultType:0),f&&f.samplingModes&&f.samplingModes[d]!==void 0?i.push(f.samplingModes[d]):i.push(_e.BILINEAR_SAMPLINGMODE),f&&f.useSRGBBuffers&&f.useSRGBBuffers[d]!==void 0?r.push(f.useSRGBBuffers[d]):r.push(!1),f&&f.formats&&f.formats[d]!==void 0?s.push(f.formats[d]):s.push(5),f&&f.targetTypes&&f.targetTypes[d]!==void 0?a.push(f.targetTypes[d]):a.push(3553),f&&f.faceIndex&&f.faceIndex[d]!==void 0?o.push(f.faceIndex[d]):o.push(0),f&&f.layerIndex&&f.layerIndex[d]!==void 0?l.push(f.layerIndex[d]):l.push(0),f&&f.layerCounts&&f.layerCounts[d]!==void 0?c.push(f.layerCounts[d]):c.push(1)}_createInternaTextureIndexMapping(){let e={},t=[];if(!this._renderTarget)return t;let i=this._renderTarget.textures;for(let r=0;r<i.length;r++){let s=i[r];if(!s)continue;let a=e[s.uniqueId];a!==void 0?t[r]=a:e[s.uniqueId]=r}return t}_rebuild(e=!1,t=!1,i){if(this._count<1||e)return;let r=this._createInternaTextureIndexMapping();this.releaseInternalTextures(),this._createInternalTextures(),t&&(this._releaseTextures(),this._createTextures(i));let s=this._renderTarget.textures;for(let a=0;a<s.length;a++){let o=this._textures[a];r[a]!==void 0&&this._renderTarget.setTexture(s[r[a]],a),o._texture=s[a],o._texture&&(o._noMipmap=!o._texture.useMipMaps,o._useSRGBBuffer=o._texture._useSRGBBuffer)}this.samples!==1&&this._renderTarget.setSamples(this.samples,!this._drawOnlyOnFirstAttachmentByDefault,!0)}_createInternalTextures(){this._renderTarget=this._getEngine().createMultipleRenderTarget(this._size,this._multiRenderTargetOptions,!this._drawOnlyOnFirstAttachmentByDefault),this._texture=this._renderTarget.texture}_releaseTextures(){if(this._textures)for(let e=0;e<this._textures.length;e++)this._textures[e]._texture=null,this._textures[e].dispose()}_createTextures(e){let t=this._renderTarget.textures;this._textures=[];for(let i=0;i<t.length;i++){let r=new _e(null,this.getScene());e!=null&&e[i]&&(r.name=e[i]),r._texture=t[i],r._texture&&(r._noMipmap=!r._texture.useMipMaps,r._useSRGBBuffer=r._texture._useSRGBBuffer),this._textures.push(r)}}setInternalTexture(e,t,i=!0){var r,s;if(this.renderTarget&&(t===0&&(this._texture=e),this.renderTarget.setTexture(e,t,i),this.textures[t]||(this.textures[t]=new _e(null,this.getScene()),this.textures[t].name=(s=(r=this._textureNames)==null?void 0:r[t])!=null?s:this.textures[t].name),this.textures[t]._texture=e,this.textures[t]._noMipmap=!e.useMipMaps,this.textures[t]._useSRGBBuffer=e._useSRGBBuffer,this._count=this.renderTarget.textures?this.renderTarget.textures.length:0,this._multiRenderTargetOptions.types&&(this._multiRenderTargetOptions.types[t]=e.type),this._multiRenderTargetOptions.samplingModes&&(this._multiRenderTargetOptions.samplingModes[t]=e.samplingMode),this._multiRenderTargetOptions.useSRGBBuffers&&(this._multiRenderTargetOptions.useSRGBBuffers[t]=e._useSRGBBuffer),this._multiRenderTargetOptions.targetTypes&&this._multiRenderTargetOptions.targetTypes[t]!==-1)){let a;e.is2DArray?a=35866:e.isCube?a=34067:e.is3D?a=32879:a=3553,this._multiRenderTargetOptions.targetTypes[t]=a}}setLayerAndFaceIndex(e,t=-1,i=-1){!this.textures[e]||!this.renderTarget||(this._multiRenderTargetOptions.layerIndex&&(this._multiRenderTargetOptions.layerIndex[e]=t),this._multiRenderTargetOptions.faceIndex&&(this._multiRenderTargetOptions.faceIndex[e]=i),this.renderTarget.setLayerAndFaceIndex(e,t,i))}setLayerAndFaceIndices(e,t){this.renderTarget&&(this._multiRenderTargetOptions.layerIndex=e,this._multiRenderTargetOptions.faceIndex=t,this.renderTarget.setLayerAndFaceIndices(e,t))}get samples(){return this._samples}set samples(e){this._renderTarget?this._samples=this._renderTarget.setSamples(e):this._samples=e}resize(e){this._processSizeParameter(e),this._rebuild(!1,void 0,this._textureNames)}updateCount(e,t,i){this._multiRenderTargetOptions.textureCount=e,this._count=e;let r=[],s=[],a=[],o=[],l=[],c=[],f=[],d=[];this._textureNames=i,this._initTypes(e,r,s,a,o,l,c,f,d,t),this._multiRenderTargetOptions.types=r,this._multiRenderTargetOptions.samplingModes=s,this._multiRenderTargetOptions.useSRGBBuffers=a,this._multiRenderTargetOptions.formats=o,this._multiRenderTargetOptions.targetTypes=l,this._multiRenderTargetOptions.faceIndex=c,this._multiRenderTargetOptions.layerIndex=f,this._multiRenderTargetOptions.layerCounts=d,this._multiRenderTargetOptions.labels=i,this._rebuild(!1,!0,i)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindMultiColorAttachmentFramebuffer(this._renderTarget,this.isCube,()=>{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var t,i;let e=(t=this._renderTarget)==null?void 0:t.textures;if(e){for(let r=e.length-1;r>=0;r--)this._textures[r]._texture=null;(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null}}}});var Q9,T_e,$9=y(()=>{k();Q9="mrtFragmentDeclaration",T_e=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
layout(location=0) out vec4 glFragData[{X}];
#endif
`;x.IncludesShadersStore[Q9]||(x.IncludesShadersStore[Q9]=T_e)});var J9,A_e,ey=y(()=>{k();J9="pbrFragmentReflectionDeclaration",A_e=`#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
#define sampleReflection(s,c) textureCube(s,c)
uniform samplerCube reflectionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)
#else
uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;
#endif
#ifdef USEIRRADIANCEMAP
uniform samplerCube irradianceSampler;
#endif
#else
#define sampleReflection(s,c) texture2D(s,c)
uniform sampler2D reflectionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)
#else
uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh;
#endif
#ifdef USEIRRADIANCEMAP
uniform sampler2D irradianceSampler;
#endif
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#endif
#endif
`;x.IncludesShadersStore[J9]||(x.IncludesShadersStore[J9]=A_e)});var e7,x_e,bw=y(()=>{k();e7="sceneFragmentDeclaration",x_e=`uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;uniform mat4 inverseProjection;
`;x.IncludesShadersStore[e7]||(x.IncludesShadersStore[e7]=x_e)});var t7,R_e,gg=y(()=>{k();t7="pbrBRDFFunctions",R_e=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25
#define BRDF_DIFFUSE_MODEL_EON 0
#define BRDF_DIFFUSE_MODEL_BURLEY 1
#define BRDF_DIFFUSE_MODEL_LAMBERT 2
#define BRDF_DIFFUSE_MODEL_LEGACY 3
#define DIELECTRIC_SPECULAR_MODEL_GLTF 0
#define DIELECTRIC_SPECULAR_MODEL_OPENPBR 1
#define CONDUCTOR_SPECULAR_MODEL_GLTF 0
#define CONDUCTOR_SPECULAR_MODEL_OPENPBR 1
#if !defined(PBR_VERTEX_SHADER) && !defined(OPENPBR_VERTEX_SHADER)
#ifdef MS_BRDF_ENERGY_CONSERVATION
vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}
#endif
#if CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR
#define F82_COS_THETA_MAX 0.142857143
#define F82_ONE_MINUS_CTM_POW5 0.462664366
#define F82_ONE_MINUS_CTM_POW6 0.396569457
#define F82_B_DENOMINATOR_RECIP 17.6512785
#define BRDF_Z_SCALE 16.0
vec3 getF82Specular(float NdotV,vec3 F0,vec3 edgeTint,float roughness) {vec3 white_minus_F0=vec3(1.0)-F0;vec3 b=(F0+white_minus_F0*F82_ONE_MINUS_CTM_POW5)*(vec3(1.0)-edgeTint)*F82_B_DENOMINATOR_RECIP;float cos_theta=max(roughness,NdotV);float one_minus_cos_theta=1.0-cos_theta;vec3 offset_from_F0=(white_minus_F0-b*cos_theta*one_minus_cos_theta)*pow(one_minus_cos_theta,5.0);return clamp(F0+offset_from_F0,0.0,1.0);}
vec3 getF82B(vec3 F0,vec3 edgeTint) {return (F0+(vec3(1.0)-F0)*F82_ONE_MINUS_CTM_POW5)*(vec3(1.0)-edgeTint)*F82_B_DENOMINATOR_RECIP;}
vec3 getF82DirectionalAlbedo(vec3 F0,vec3 F90,vec3 b,vec3 environmentBrdf) {return (F90-F0)*environmentBrdf.x+F0*environmentBrdf.y-b*environmentBrdf.z;}
vec3 getF82AverageFresnel(vec3 F0,vec3 b) {return F0+(vec3(1.0)-F0)/21.0-b/126.0;}
#endif
#ifdef FUZZENVIRONMENTBRDF
vec3 getFuzzBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(perceptualRoughness,NdotV);vec4 brdfLookup=texture2D(environmentFuzzBrdfSampler,UV);const vec2 RiRange=vec2(0.0,0.75);const vec2 ARange =vec2(0.005,0.88);const vec2 BRange =vec2(-0.18,0.002);brdfLookup.r=mix(ARange.x, ARange.y, brdfLookup.r);brdfLookup.g=mix(BRange.x, BRange.y, brdfLookup.g);brdfLookup.b=mix(RiRange.x,RiRange.y,brdfLookup.b);return brdfLookup.rgb;}
#endif
#ifdef ENVIRONMENTBRDF
vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);
#ifdef ENVIRONMENTBRDF_RGBD
brdfLookup.rgb=fromRGBD(brdfLookup.rgba);
#endif
return brdfLookup.rgb;}
vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {
#ifdef BRDF_V_HEIGHT_CORRELATED
vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;
#else
vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;
#endif
return reflectance;}
vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {
#ifdef BRDF_V_HEIGHT_CORRELATED
vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);
#else
vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;
#endif
return reflectance;}
#endif
/* NOT USED
#if defined(SHEEN) && defined(SHEEN_SOFTER)
float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)
{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}
#endif
*/
#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)
vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)
{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF)
/**
* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.
* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table
*/
vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}
#endif
vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)
{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}
float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)
{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}
#ifdef CLEARCOAT
vec3 getR0RemappedForClearCoat(vec3 f0) {
#ifdef CLEARCOAT_DEFAULTIOR
#ifdef MOBILE
return saturate(f0*(f0*0.526868+0.529324)-0.0482256);
#else
return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);
#endif
#else
vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t);
#endif
}
#endif
#ifdef IRIDESCENCE
const mat3 XYZ_TO_REC709=mat3(
3.2404542,-0.9692660, 0.0556434,
-1.5371385, 1.8760108,-0.2040259,
-0.4985314, 0.0415560, 1.0572252
);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}
vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));}
float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));}
vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;}
vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}
float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR<outsideIOR) phi12=PI;float phi21=PI-phi12;vec3 baseIOR=getIORTfromAirToSurfaceR0(clamp(baseF0,0.0,0.9999));
vec3 R1=getR0fromIORs(baseIOR,iridescenceIOR);float maxR1=max(R1.r,max(R1.g,R1.b));if (maxR1<1e-6) {return max(vec3(R12),vec3(0.0));}
vec3 R23=fresnelSchlickGGX(cosTheta2,R1,vec3(1.));vec3 phi23=vec3(0.0);if (baseIOR[0]<iridescenceIOR) phi23[0]=PI;if (baseIOR[1]<iridescenceIOR) phi23[1]=PI;if (baseIOR[2]<iridescenceIOR) phi23[2]=PI;float opd=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;vec3 phi=vec3(phi21)+phi23;vec3 R123=clamp(R12*R23,1e-5,0.9999);vec3 r123=sqrt(R123);vec3 Rs=square(T121)*R23/(vec3(1.0)-R123);vec3 C0=R12+Rs;I=C0;vec3 Cm=Rs-T121;for (int m=1; m<=2; ++m)
{Cm*=r123;vec3 Sm=2.0*evalSensitivity(float(m)*opd,float(m)*phi);I+=Cm*Sm;}
return max(I,vec3(0.0));}
#endif
float normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)
{float a2=square(alphaG);float d=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);}
#ifdef SHEEN
float normalDistributionFunction_CharlieSheen(float NdotH,float alphaG)
{float invR=1./alphaG;float cos2h=NdotH*NdotH;float sin2h=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);}
#endif
#ifdef ANISOTROPIC
float normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {float a2=alphaTB.x*alphaTB.y;vec3 v=vec3(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);float v2=dot(v,v);float w2=a2/v2;return a2*w2*w2*RECIPROCAL_PI;}
#endif
#ifdef BRDF_V_HEIGHT_CORRELATED
float smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) {
#ifdef MOBILE
float GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);float GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL);
#else
float a2=alphaG*alphaG;float GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);float GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL);
#endif
}
#else
float smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG)
{
#ifdef MOBILE
return 1.0/(dot+alphaG+(1.0-alphaG)*dot ));
#else
float alphaSquared=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));
#endif
}
float smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG)
{float visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;}
#endif
#ifdef ANISOTROPIC
float smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {float lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));float lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));float v=0.5/(lambdaV+lambdaL);return v;}
#endif
#ifdef CLEARCOAT
float visibility_Kelemen(float VdotH) {return 0.25/(VdotH*VdotH); }
#endif
#ifdef SHEEN
float visibility_Ashikhmin(float NdotL,float NdotV)
{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));}
/* NOT USED
#ifdef SHEEN_SOFTER
float l(float x,float alphaG)
{float oneMinusAlphaSq=(1.0-alphaG)*(1.0-alphaG);float a=mix(21.5473,25.3245,oneMinusAlphaSq);float b=mix(3.82987,3.32435,oneMinusAlphaSq);float c=mix(0.19823,0.16801,oneMinusAlphaSq);float d=mix(-1.97760,-1.27393,oneMinusAlphaSq);float e=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;}
float lambdaSheen(float cosTheta,float alphaG)
{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));}
float visibility_CharlieSheen(float NdotL,float NdotV,float alphaG)
{float G=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);}
#endif
*/
#endif
float diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {float diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));float diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));float diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;float fresnel =
(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *
(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;}
const float constant1_FON=0.5-2.0/(3.0*PI);const float constant2_FON=2.0/3.0-28.0/(15.0*PI);float E_FON_approx(float mu,float roughness)
{float sigma=roughness;
float mucomp=1.0-mu;float mucomp2=mucomp*mucomp;const mat2 Gcoeffs=mat2(0.0571085289,-0.332181442,
0.491881867,0.0714429953);float GoverPi=dot(Gcoeffs*vec2(mucomp,mucomp2),vec2(1.0,mucomp2));return (1.0+sigma*GoverPi)/(1.0+constant1_FON*sigma);}
vec3 diffuseBRDF_EON(vec3 albedo,float roughness,float NdotL,float NdotV,float LdotV)
{vec3 rho=albedo;float sigma=roughness;
float mu_i=NdotL;
float mu_o=NdotV;
float s=LdotV-mu_i*mu_o;
float sovertF=s>0.0 ? s/max(mu_i,mu_o) : s;
float AF=1.0/(1.0+constant1_FON*sigma);
vec3 f_ss=(rho*RECIPROCAL_PI)*AF*(1.0+sigma*sovertF);
float EFo=E_FON_approx(mu_o,sigma);
float EFi=E_FON_approx(mu_i,sigma);
float avgEF=AF*(1.0+constant2_FON*sigma);
vec3 rho_ms=(rho*rho)*avgEF/(vec3(1.0)-rho*(1.0-avgEF));const float eps=1.0e-7;vec3 f_ms=(rho_ms*RECIPROCAL_PI)*max(eps,1.0-EFo)
* max(eps,1.0-EFi)
/ max(eps,1.0-avgEF);return (f_ss+f_ms);}
#ifdef SS_TRANSLUCENCY
vec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {vec3 S=1./maxEps(diffusionDistance);vec3 temp=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);}
float computeWrappedDiffuseNdotL(float NdotL,float w) {float t=1.0+w;float invt2=1.0/square(t);return saturate((NdotL+w)*invt2);}
#endif
#endif
`;x.IncludesShadersStore[t7]||(x.IncludesShadersStore[t7]=R_e)});var i7,b_e,Mw=y(()=>{k();i7="openpbrDielectricReflectance",b_e=`struct ReflectanceParams
{float F0;float F90;vec3 coloredF0;vec3 coloredF90;};
#define pbr_inline
ReflectanceParams dielectricReflectance(
in float insideIOR,in float outsideIOR,in vec3 specularColor,in float specularWeight
)
{ReflectanceParams outParams;float dielectricF0=pow((insideIOR-outsideIOR)/(insideIOR+outsideIOR),2.0);float dielectricF0_NoSpec=pow((1.0-outsideIOR)/(1.0+outsideIOR),2.0);float f90Scale=clamp(2.0*abs(insideIOR-outsideIOR),0.0,1.0);float f90Scale_NoSpec=clamp(2.0*abs(1.0-outsideIOR),0.0,1.0);
#if (DIELECTRIC_SPECULAR_MODEL==DIELECTRIC_SPECULAR_MODEL_OPENPBR)
vec3 dielectricColorF90=specularColor.rgb*vec3(f90Scale);vec3 dielectricColorF90_NoSpec=specularColor.rgb*vec3(f90Scale_NoSpec);
#else
vec3 dielectricColorF90=vec3(f90Scale);vec3 dielectricColorF90_NoSpec=vec3(f90Scale_NoSpec);
#endif
#if DIELECTRIC_SPECULAR_MODEL==DIELECTRIC_SPECULAR_MODEL_GLTF
float maxF0=max(specularColor.r,max(specularColor.g,specularColor.b));outParams.F0=mix(dielectricF0_NoSpec,dielectricF0,specularWeight)*maxF0;
#else
outParams.F0=mix(dielectricF0_NoSpec,dielectricF0,specularWeight);
#endif
outParams.F90=mix(f90Scale_NoSpec,f90Scale,specularWeight);outParams.coloredF0=mix(vec3(dielectricF0_NoSpec),vec3(dielectricF0),specularWeight)*specularColor.rgb;outParams.coloredF90=mix(dielectricColorF90_NoSpec,dielectricColorF90,specularWeight);return outParams;}
`;x.IncludesShadersStore[i7]||(x.IncludesShadersStore[i7]=b_e)});var r7,M_e,ty=y(()=>{k();r7="pbrIBLFunctions",M_e=`#if defined(REFLECTION) || defined(SS_REFRACTION)
float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;}
float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;}
#endif
#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)
float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);}
#endif
#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)
float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);}
#endif
#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)
#define UNPACK_LOD(x) (1.0-x)*255.0
float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);}
#endif
`;x.IncludesShadersStore[r7]||(x.IncludesShadersStore[r7]=M_e)});var n7,y_e,yw=y(()=>{k();n7="openpbrGeometryInfo",y_e=`struct geometryInfoOutParams
{float NdotV;float NdotVUnclamped;vec3 environmentBrdf;float horizonOcclusion;};struct geometryInfoAnisoOutParams
{float NdotV;float NdotVUnclamped;vec3 environmentBrdf;float horizonOcclusion;float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;mat3 TBN;};
#define pbr_inline
geometryInfoOutParams geometryInfo(
in vec3 normalW,in vec3 viewDirectionW,in float roughness,in vec3 geometricNormalW
)
{geometryInfoOutParams outParams;outParams.NdotVUnclamped=dot(normalW,viewDirectionW);outParams.NdotV=absEps(outParams.NdotVUnclamped);
#if defined(ENVIRONMENTBRDF)
outParams.environmentBrdf=getBRDFLookup(outParams.NdotV,roughness);
#else
outParams.environmentBrdf=vec3(0.0);
#endif
outParams.horizonOcclusion=1.0;
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
#ifdef HORIZONOCCLUSION
#if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL)
#ifdef REFLECTIONMAP_3D
outParams.horizonOcclusion=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);
#endif
#endif
#endif
#endif
return outParams;}
#define pbr_inline
geometryInfoAnisoOutParams geometryInfoAniso(
in vec3 normalW,in vec3 viewDirectionW,in float roughness,in vec3 geometricNormalW
,in vec3 vAnisotropy,in mat3 TBN
)
{geometryInfoOutParams geoInfo=geometryInfo(normalW,viewDirectionW,roughness,geometricNormalW);geometryInfoAnisoOutParams outParams;outParams.NdotV=geoInfo.NdotV;outParams.NdotVUnclamped=geoInfo.NdotVUnclamped;outParams.environmentBrdf=geoInfo.environmentBrdf;outParams.horizonOcclusion=geoInfo.horizonOcclusion;outParams.anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));outParams.anisotropicTangent=normalize(anisoTBN*anisotropyDirection);outParams.anisotropicBitangent=normalize(cross(anisoTBN[2],outParams.anisotropicTangent));outParams.TBN=TBN;return outParams;}`;x.IncludesShadersStore[n7]||(x.IncludesShadersStore[n7]=y_e)});var s7,I_e,Iw=y(()=>{k();s7="openpbrIblFunctions",I_e=`#ifdef REFLECTION
vec3 sampleIrradiance(
in vec3 surfaceNormal
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,in vec3 vEnvironmentIrradianceSH
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,in mat4 iblMatrix
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
,in samplerCube irradianceSampler
#else
,in sampler2D irradianceSampler
#endif
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
,in vec3 reflectionDominantDirection
#endif
#endif
#ifdef REALTIME_FILTERING
,in vec2 vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,in sampler2D icdfSampler
#endif
#endif
,in vec2 vReflectionInfos
,in vec3 viewDirectionW
,in float diffuseRoughness
,in vec3 surfaceAlbedo
) {vec3 environmentIrradiance=vec3(0.,0.,0.);
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
vec3 irradianceVector=(iblMatrix*vec4(surfaceNormal,0)).xyz;vec3 irradianceView=(iblMatrix*vec4(viewDirectionW,0)).xyz;
#if !defined(USE_IRRADIANCE_DOMINANT_DIRECTION) && !defined(REALTIME_FILTERING)
#if BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LAMBERT && BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LEGACY
{float NdotV=max(dot(surfaceNormal,viewDirectionW),0.0);irradianceVector=mix(irradianceVector,irradianceView,(0.5*(1.0-NdotV))*diffuseRoughness);}
#endif
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;irradianceView.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;irradianceView.y*=-1.0;
#endif
#endif
#ifdef USESPHERICALFROMREFLECTIONMAP
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
environmentIrradiance=vEnvironmentIrradianceSH;
#else
#if defined(REALTIME_FILTERING)
environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo,diffuseRoughness,surfaceAlbedo,irradianceView
#ifdef IBL_CDF_FILTERING
,icdfSampler
#endif
);
#else
environmentIrradiance=computeEnvironmentIrradiance(irradianceVector);
#endif
#endif
#elif defined(USEIRRADIANCEMAP)
#ifdef REFLECTIONMAP_3D
vec4 environmentIrradianceFromTexture=sampleReflection(irradianceSampler,irradianceVector);
#else
vec4 environmentIrradianceFromTexture=sampleReflection(irradianceSampler,reflectionCoords);
#endif
environmentIrradiance=environmentIrradianceFromTexture.rgb;
#ifdef RGBDREFLECTION
environmentIrradiance.rgb=fromRGBD(environmentIrradianceFromTexture);
#endif
#ifdef GAMMAREFLECTION
environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);
#endif
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
vec3 Ls=normalize(reflectionDominantDirection);float NoL=dot(irradianceVector,Ls);float NoV=dot(irradianceVector,irradianceView);vec3 diffuseRoughnessTerm=vec3(1.0);
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
float LoV=dot (Ls,irradianceView);float mag=length(reflectionDominantDirection)*2.0;vec3 clampedAlbedo=clamp(surfaceAlbedo,vec3(0.1),vec3(1.0));diffuseRoughnessTerm=diffuseBRDF_EON(clampedAlbedo,diffuseRoughness,NoL,NoV,LoV)*PI;diffuseRoughnessTerm=diffuseRoughnessTerm/clampedAlbedo;diffuseRoughnessTerm=mix(vec3(1.0),diffuseRoughnessTerm,sqrt(clamp(mag*NoV,0.0,1.0)));
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
vec3 H=(irradianceView+Ls)*0.5;float VoH=dot(irradianceView,H);diffuseRoughnessTerm=vec3(diffuseBRDF_Burley(NoL,NoV,VoH,diffuseRoughness)*PI);
#endif
environmentIrradiance=environmentIrradiance.rgb*diffuseRoughnessTerm;
#endif
#endif
environmentIrradiance*=vReflectionInfos.x;return environmentIrradiance;}
#define pbr_inline
#ifdef REFLECTIONMAP_3D
vec3 createReflectionCoords(
#else
vec2 createReflectionCoords(
#endif
in vec3 vPositionW
,in vec3 normalW
)
{vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords=reflectionVector;
#else
vec2 reflectionCoords=reflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
reflectionCoords/=reflectionVector.z;
#endif
reflectionCoords.y=1.0-reflectionCoords.y;
#endif
return reflectionCoords;}
#define pbr_inline
#define inline
vec3 sampleRadiance(
in float alphaG
,in vec3 vReflectionMicrosurfaceInfos
,in vec2 vReflectionInfos
,in geometryInfoOutParams geoInfo
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSampler
,const vec3 reflectionCoords
#else
,in sampler2D reflectionSampler
,const vec2 reflectionCoords
#endif
#ifdef REALTIME_FILTERING
,in vec2 vReflectionFilteringInfo
#endif
)
{vec4 environmentRadiance=vec4(0.,0.,0.,0.);
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,geoInfo.NdotVUnclamped);
#elif defined(LINEARSPECULARREFLECTION)
float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);
#else
float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);
#endif
reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;
#ifdef REALTIME_FILTERING
environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0);
#else
environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);
#endif
#ifdef RGBDREFLECTION
environmentRadiance.rgb=fromRGBD(environmentRadiance);
#endif
#ifdef GAMMAREFLECTION
environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);
#endif
environmentRadiance.rgb*=vec3(vReflectionInfos.x);return environmentRadiance.rgb;}
#if defined(ANISOTROPIC)
#define pbr_inline
#define inline
vec3 sampleRadianceAnisotropic(
in float alphaG
,in vec3 vReflectionMicrosurfaceInfos
,in vec2 vReflectionInfos
,in geometryInfoAnisoOutParams geoInfo
,const vec3 normalW
,const vec3 viewDirectionW
,const vec3 positionW
,const vec3 noise
,bool isRefraction
,float ior
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSampler
#else
,in sampler2D reflectionSampler
#endif
#ifdef REALTIME_FILTERING
,in vec2 vReflectionFilteringInfo
#endif
)
{vec4 environmentRadiance=vec4(0.,0.,0.,0.);float alphaT=alphaG*sqrt(2.0/(1.0+(1.0-geoInfo.anisotropy)*(1.0-geoInfo.anisotropy)));float alphaB=(1.0-geoInfo.anisotropy)*alphaT;alphaG=alphaB;
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,geoInfo.NdotVUnclamped);
#elif defined(LINEARSPECULARREFLECTION)
float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);
#else
float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);
#endif
reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;
#ifdef REALTIME_FILTERING
vec3 view=(reflectionMatrix*vec4(viewDirectionW,0.0)).xyz;vec3 tangent=(reflectionMatrix*vec4(geoInfo.anisotropicTangent,0.0)).xyz;vec3 bitangent=(reflectionMatrix*vec4(geoInfo.anisotropicBitangent,0.0)).xyz;vec3 normal=(reflectionMatrix*vec4(normalW,0.0)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
view.z*=-1.0;tangent.z*=-1.0;bitangent.z*=-1.0;normal.z*=-1.0;
#endif
environmentRadiance =
vec4(radianceAnisotropic(alphaT,alphaB,reflectionSampler,
view,tangent,
bitangent,normal,
vReflectionFilteringInfo,noise.xy,isRefraction,ior),
1.0);
#else
const int samples=16;vec4 radianceSample=vec4(0.0);vec3 reflectionCoords=vec3(0.0);float sample_weight=0.0;float total_weight=0.0;float step=1.0/float(max(samples-1,1));for (int i=0; i<samples; ++i) {float t=mix(-1.0,1.0,float(i)*step);t+=step*2.0*noise.x;sample_weight=max(1.0-abs(t),0.001);sample_weight*=sample_weight;t*=min(4.0*alphaT*geoInfo.anisotropy,1.0);vec3 bentNormal;if (t<0.0) {float blend=t+1.0;bentNormal=normalize(mix(-geoInfo.anisotropicTangent,normalW,blend));} else if (t>0.0) {float blend=t;bentNormal=normalize(mix(normalW,geoInfo.anisotropicTangent,blend));} else {bentNormal=normalW;}
if (isRefraction) {reflectionCoords=double_refract(-viewDirectionW,bentNormal,ior);} else {reflectionCoords=reflect(-viewDirectionW,bentNormal);}
reflectionCoords=vec3(reflectionMatrix*vec4(reflectionCoords,0));
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionCoords.z*=-1.0;
#endif
radianceSample=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);
#ifdef RGBDREFLECTION
environmentRadiance.rgb+=sample_weight*fromRGBD(radianceSample);
#elif defined(GAMMAREFLECTION)
environmentRadiance.rgb+=sample_weight*toLinearSpace(radianceSample.rgb);
#else
environmentRadiance.rgb+=sample_weight*radianceSample.rgb;
#endif
total_weight+=sample_weight;}
environmentRadiance=vec4(environmentRadiance.xyz/float(total_weight),1.0);
#endif
environmentRadiance.rgb*=vec3(vReflectionInfos.x);return environmentRadiance.rgb;}
#endif
#endif
#if defined(ENVIRONMENTBRDF)
#define pbr_inline
float computeDielectricIblFresnel(in ReflectanceParams reflectance,in vec3 environmentBrdf)
{float dielectricIblFresnel=getReflectanceFromBRDFLookup(vec3(reflectance.F0),vec3(reflectance.F90),environmentBrdf).r;float dielectricECF=1.0+reflectance.F0*(1.0/environmentBrdf.y-1.0);return clamp(dielectricIblFresnel*dielectricECF,0.0,1.0);}
#define pbr_inline
vec3 computeConductorIblFresnel(in ReflectanceParams reflectance,in vec3 environmentBrdf)
{
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR) && defined(ENVIRONMENTBRDF)
vec3 openPBRBrdf=vec3(environmentBrdf.xy,environmentBrdf.z/BRDF_Z_SCALE);vec3 b =getF82B(reflectance.coloredF0,reflectance.coloredF90);vec3 E_F82=getF82DirectionalAlbedo(reflectance.coloredF0,vec3(1.0),b,openPBRBrdf);vec3 F_avg=getF82AverageFresnel(reflectance.coloredF0,b);vec3 ECF =vec3(1.0)+F_avg*(vec3(1.0)/openPBRBrdf.y-vec3(1.0));return clamp(E_F82*ECF,vec3(0.0),vec3(1.0));
#else
return getReflectanceFromBRDFLookup(reflectance.coloredF0,reflectance.coloredF90,environmentBrdf);
#endif
}
#endif
`;x.IncludesShadersStore[s7]||(x.IncludesShadersStore[s7]=I_e)});var a7,C_e,Cw=y(()=>{k();a7="openpbrSubsurfaceLayerData",C_e=`float subsurface_weight=vSubsurfaceWeight;vec3 subsurface_color=vSubsurfaceColor.rgb;float subsurface_radius=vSubsurfaceRadius;vec3 subsurface_radius_scale=vSubsurfaceRadiusScale;float subsurface_scatter_anisotropy=clamp(vSubsurfaceScatterAnisotropy,-0.9999,0.9999);
#ifdef SUBSURFACE_WEIGHT
vec4 subsurfaceWeightFromTexture=texture2D(subsurfaceWeightSampler,vSubsurfaceWeightUV+uvOffset);
#endif
#ifdef SUBSURFACE_COLOR
vec4 subsurfaceColorFromTexture=texture2D(subsurfaceColorSampler,vSubsurfaceColorUV+uvOffset);
#endif
#ifdef SUBSURFACE_RADIUS_SCALE
vec4 subsurfaceRadiusScaleFromTexture=texture2D(subsurfaceRadiusScaleSampler,vSubsurfaceRadiusScaleUV+uvOffset);
#endif
#ifdef SUBSURFACE_WEIGHT
subsurface_weight*=subsurfaceWeightFromTexture.r;
#endif
#ifdef SUBSURFACE_COLOR
#ifdef SUBSURFACE_COLOR_GAMMA
subsurface_color*=toLinearSpace(subsurfaceColorFromTexture.rgb);
#else
subsurface_color*=subsurfaceColorFromTexture.rgb;
#endif
subsurface_color*=vSubsurfaceColorInfos.y;
#endif
#ifdef SUBSURFACE_RADIUS_SCALE
subsurface_radius_scale*=subsurfaceRadiusScaleFromTexture.rgb;
#endif
`;x.IncludesShadersStore[a7]||(x.IncludesShadersStore[a7]=C_e)});var o7,P_e,Pw=y(()=>{k();o7="openpbrTransmissionLayerData",P_e=`float transmission_weight=vTransmissionWeight;vec3 transmission_color=vTransmissionColor.rgb;float transmission_depth=vTransmissionDepth;vec3 transmission_scatter=vTransmissionScatter.rgb;float transmission_scatter_anisotropy=clamp(vTransmissionScatterAnisotropy,-0.9999,0.9999);float transmission_dispersion_scale=vTransmissionDispersionScale;float transmission_dispersion_abbe_number=vTransmissionDispersionAbbeNumber;
#ifdef TRANSMISSION_WEIGHT
vec4 transmissionWeightFromTexture=texture2D(transmissionWeightSampler,vTransmissionWeightUV+uvOffset);
#endif
#ifdef TRANSMISSION_COLOR
vec4 transmissionColorFromTexture=texture2D(transmissionColorSampler,vTransmissionColorUV+uvOffset);
#endif
#ifdef TRANSMISSION_DEPTH
vec4 transmissionDepthFromTexture=texture2D(transmissionDepthSampler,vTransmissionDepthUV+uvOffset);
#endif
#ifdef TRANSMISSION_SCATTER
vec4 transmissionScatterFromTexture=texture2D(transmissionScatterSampler,vTransmissionScatterUV+uvOffset);
#endif
#ifdef TRANSMISSION_DISPERSION_SCALE
vec4 transmissionDispersionScaleFromTexture=texture2D(transmissionDispersionScaleSampler,vTransmissionDispersionScaleUV+uvOffset);
#endif
#ifdef TRANSMISSION_WEIGHT
transmission_weight*=transmissionWeightFromTexture.r;
#endif
#ifdef TRANSMISSION_COLOR
#ifdef TRANSMISSION_COLOR_GAMMA
transmission_color*=toLinearSpace(transmissionColorFromTexture.rgb);
#else
transmission_color*=transmissionColorFromTexture.rgb;
#endif
transmission_color*=vTransmissionColorInfos.y;
#endif
#ifdef TRANSMISSION_DEPTH
transmission_depth*=transmissionDepthFromTexture.r;
#endif
#ifdef TRANSMISSION_SCATTER
transmission_scatter*=transmissionScatterFromTexture.rgb;
#endif
#ifdef TRANSMISSION_DISPERSION_SCALE
transmission_dispersion_scale*=transmissionDispersionScaleFromTexture.r;
#endif
`;x.IncludesShadersStore[o7]||(x.IncludesShadersStore[o7]=P_e)});var c7={};Be(c7,{geometryPixelShader:()=>L_e});var Lw,l7,L_e,Dw=y(()=>{k();af();$9();xM();RM();oo();ey();bw();lh();gg();Mw();ty();vE();yw();Iw();fh();of();bM();Cw();Pw();Lw="geometryPixelShader",l7=`#extension GL_EXT_draw_buffers : require
#if defined(BUMP) || !defined(NORMAL)
#extension GL_OES_standard_derivatives : enable
#endif
precision highp float;
#ifdef BUMP
varying mat4 vWorldView;varying vec3 vNormalW;
#else
varying vec3 vNormalV;
#endif
varying vec4 vViewPos;
#if defined(POSITION) || defined(BUMP) || defined(IRRADIANCE)
varying vec3 vPositionW;
#endif
#if defined(VELOCITY) || defined(VELOCITY_LINEAR)
varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;
#endif
#ifdef NEED_UV
varying vec2 vUV;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;
#endif
#if defined(REFLECTIVITY)
#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)
uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV;
#else
#ifdef METALLIC_TEXTURE
uniform sampler2D metallicSampler;varying vec2 vMetallicUV;
#endif
#ifdef ROUGHNESS_TEXTURE
uniform sampler2D roughnessSampler;varying vec2 vRoughnessUV;
#endif
#endif
#ifdef ALBEDOTEXTURE
varying vec2 vAlbedoUV;uniform sampler2D albedoSampler;
#endif
#ifdef REFLECTIVITYCOLOR
uniform vec3 reflectivityColor;
#endif
#ifdef ALBEDOCOLOR
uniform vec3 albedoColor;
#endif
#ifdef METALLIC
uniform float metallic;
#endif
#if defined(ROUGHNESS) || defined(GLOSSINESS)
uniform float glossiness;
#endif
#endif
#if defined(ALPHATEST) && defined(NEED_UV)
uniform sampler2D diffuseSampler;
#endif
#include<clipPlaneFragmentDeclaration>
#include<mrtFragmentDeclaration>[SCENE_MRT_COUNT]
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#include<helperFunctions>
#ifdef IRRADIANCE
#include<pbrFragmentReflectionDeclaration>
#ifdef REFLECTION
#ifdef USEIRRADIANCEMAP
#include<__decl__sceneFragment>
uniform mat4 reflectionMatrix;uniform vec2 vReflectionInfos;uniform vec3 vReflectionDominantDirection;
#include<pbrBRDFFunctions>
#include<openpbrDielectricReflectance>
#include<pbrIBLFunctions>
#include<reflectionFunction>
#include<openpbrGeometryInfo>
#include<openpbrIblFunctions>
#elif defined(USESPHERICALFROMREFLECTIONMAP)
varying vec3 vEnvironmentIrradiance;
#endif
#ifdef IBL_SHADOW_TEXTURE
uniform sampler2D iblShadowSampler;uniform vec2 shadowTextureSize;
#endif
#ifdef IRRADIANCE_SCATTER_MASK
uniform float vSubsurfaceWeight;
#include<samplerFragmentDeclaration>(_DEFINENAME_,SUBSURFACE_WEIGHT,_VARYINGNAME_,SubsurfaceWeight,_SAMPLERNAME_,subsurfaceWeight)
uniform float vSubsurfaceScatterAnisotropy;uniform float vTransmissionWeight;
#include<samplerFragmentDeclaration>(_DEFINENAME_,TRANSMISSION_WEIGHT,_VARYINGNAME_,TransmissionWeight,_SAMPLERNAME_,transmissionWeight)
uniform float vTransmissionScatterAnisotropy;
#endif
#endif
#endif
void main() {
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (texture2D(diffuseSampler,vUV).a<0.4)
discard;
#endif
vec3 normalOutput;
#ifdef BUMP
vec3 normalW=normalize(vNormalW);
#include<bumpFragment>
#ifdef NORMAL_WORLDSPACE
normalOutput=normalW;
#else
normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));
#endif
#elif defined(HAS_NORMAL_ATTRIBUTE)
normalOutput=normalize(vNormalV);
#elif defined(POSITION)
normalOutput=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));
#endif
#ifdef ENCODE_NORMAL
normalOutput=normalOutput*0.5+0.5;
#endif
#ifdef DEPTH
gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);
#endif
#ifdef NORMAL
gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);
#endif
#ifdef SCREENSPACE_DEPTH
gl_FragData[SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,1.0);
#endif
#ifdef POSITION
gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);
#endif
#ifdef VELOCITY
vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);
#endif
#ifdef VELOCITY_LINEAR
vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w) -
(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,1.0);
#endif
#ifdef REFLECTIVITY
vec4 reflectivity=vec4(0.0,0.0,0.0,1.0);
#ifdef METALLICWORKFLOW
float metal=1.0;float roughness=1.0;
#ifdef ORMTEXTURE
metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g;
#else
#ifdef METALLIC_TEXTURE
metal*=texture2D(metallicSampler,vMetallicUV).r;
#endif
#ifdef ROUGHNESS_TEXTURE
roughness*=texture2D(roughnessSampler,vRoughnessUV).r;
#endif
#endif
#ifdef METALLIC
metal*=metallic;
#endif
#ifdef ROUGHNESS
roughness*=(1.0-glossiness);
#endif
reflectivity.a-=roughness;vec3 color=vec3(1.0);
#ifdef ALBEDOTEXTURE
color=texture2D(albedoSampler,vAlbedoUV).rgb;
#ifdef GAMMAALBEDO
color=toLinearSpace(color);
#endif
#endif
#ifdef ALBEDOCOLOR
color*=albedoColor.xyz;
#endif
reflectivity.rgb=mix(vec3(0.04),color,metal);
#else
#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)
reflectivity=texture2D(reflectivitySampler,vReflectivityUV);
#ifdef GAMMAREFLECTIVITYTEXTURE
reflectivity.rgb=toLinearSpace(reflectivity.rgb);
#endif
#else
#ifdef REFLECTIVITYCOLOR
reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0;
#endif
#endif
#ifdef GLOSSINESSS
reflectivity.a*=glossiness;
#endif
#endif
gl_FragData[REFLECTIVITY_INDEX]=reflectivity;
#endif
#ifdef IRRADIANCE
vec3 irradiance=vec3(0.0);float irradiance_alpha=1.0;
#ifdef REFLECTION
#ifdef IRRADIANCE_SCATTER_MASK
vec3 vSubsurfaceColor=vec3(1.0);float vSubsurfaceRadius=0.0;vec3 vSubsurfaceRadiusScale=vec3(1.0);
#include<openpbrSubsurfaceLayerData>
float vTransmissionDepth=1.0;vec3 vTransmissionColor=vec3(1.0);vec3 vTransmissionScatter=vec3(0.0);float vTransmissionDispersionScale=0.0;float vTransmissionDispersionAbbeNumber=0.0;
#include<openpbrTransmissionLayerData>
#endif
#ifdef IBL_SHADOW_TEXTURE
#ifdef COLORED_IBL_SHADOWS
vec3 iblShadowValue=texture(iblShadowSampler,gl_FragCoord.xy/shadowTextureSize).rgb;
#else
vec3 iblShadowValue=vec3(texture(iblShadowSampler,gl_FragCoord.xy/shadowTextureSize).r);
#endif
#endif
#if defined(USEIRRADIANCEMAP)
#ifdef IRRADIANCE_SCATTER_MASK
float bendAmount=subsurface_weight*-min(subsurface_scatter_anisotropy,0.0);bendAmount=mix(bendAmount,-min(transmission_scatter_anisotropy,0.0),transmission_weight);vec3 viewVector=normalize(vEyePosition.xyz-vPositionW.xyz);vec3 bentNormal=mix(normalOutput,viewVector,bendAmount*dot(normalOutput,viewVector));
#else
vec3 bentNormal=normalOutput;
#endif
irradiance=sampleIrradiance(
bentNormal
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,vEnvironmentIrradiance
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,reflectionMatrix
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
,vReflectionDominantDirection
#endif
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
#endif
#endif
,vReflectionInfos
,vViewPos.xyz
,1.0
,vec3(1.0)
);
#elif defined(USESPHERICALFROMREFLECTIONMAP)
irradiance=vEnvironmentIrradiance;
#endif
#ifdef IBL_SHADOW_TEXTURE
irradiance*=iblShadowValue;
#endif
#ifndef BUMP
vec2 uvOffset=vec2(0.0);
#endif
#ifdef IRRADIANCE_SCATTER_MASK
irradiance_alpha=min(subsurface_weight+transmission_weight,1.0);
#endif
#endif
gl_FragData[IRRADIANCE_INDEX]=vec4(irradiance,irradiance_alpha);
#endif
}
`;x.ShadersStore[Lw]||(x.ShadersStore[Lw]=l7);L_e={name:Lw,shader:l7}});var f7,D_e,d7=y(()=>{k();f7="geometryVertexDeclaration",D_e="uniform mat4 viewProjection;uniform mat4 view;";x.IncludesShadersStore[f7]||(x.IncludesShadersStore[f7]=D_e)});var u7,O_e,h7=y(()=>{k();lh();u7="geometryUboDeclaration",O_e=`#include<sceneUboDeclaration>
`;x.IncludesShadersStore[u7]||(x.IncludesShadersStore[u7]=O_e)});var m7,N_e,_g=y(()=>{k();m7="harmonicsFunctions",N_e=`#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00
+ vSphericalL1_1*(normal.y)
+ vSphericalL10*(normal.z)
+ vSphericalL11*(normal.x)
+ vSphericalL2_2*(normal.y*normal.x)
+ vSphericalL2_1*(normal.y*normal.z)
+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)
+ vSphericalL21*(normal.z*normal.x)
+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}
#else
vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;}
#endif
#endif
`;x.IncludesShadersStore[m7]||(x.IncludesShadersStore[m7]=N_e)});var g7={};Be(g7,{geometryVertexShader:()=>w_e});var Ow,p7,w_e,Nw=y(()=>{k();$c();Jc();Ld();Dd();bd();d7();h7();ef();_g();Od();Nd();tf();rf();nf();sf();uM();Ow="geometryVertexShader",p7=`precision highp float;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<instancesDeclaration>
#include<__decl__geometryVertex>
#include<clipPlaneVertexDeclaration>
#ifdef IRRADIANCE
#ifdef REFLECTION
uniform mat4 reflectionMatrix;uniform vec2 vReflectionInfos;uniform vec3 vReflectionColor;
#ifdef USESPHERICALFROMREFLECTIONMAP
varying vec3 vEnvironmentIrradiance;
#ifdef SPHERICAL_HARMONICS
uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;
#else
uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;
#endif
#include<harmonicsFunctions>
#endif
#endif
#endif
attribute vec3 position;
#ifdef HAS_NORMAL_ATTRIBUTE
attribute vec3 normal;
#endif
#ifdef NEED_UV
varying vec2 vUV;
#ifdef ALPHATEST
uniform mat4 diffuseMatrix;
#endif
#ifdef BUMP
uniform mat4 bumpMatrix;varying vec2 vBumpUV;
#endif
#ifdef REFLECTIVITY
uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV;
#endif
#ifdef METALLIC_TEXTURE
varying vec2 vMetallicUV;uniform mat4 metallicMatrix;
#endif
#ifdef ROUGHNESS_TEXTURE
varying vec2 vRoughnessUV;uniform mat4 roughnessMatrix;
#endif
#ifdef SUBSURFACE_WEIGHT
varying vec2 vSubsurfaceWeightUV;uniform mat4 subsurfaceWeightMatrix;
#endif
#ifdef TRANSMISSION_WEIGHT
varying vec2 vTransmissionWeightUV;uniform mat4 transmissionWeightMatrix;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#ifdef BUMP
varying mat4 vWorldView;
#endif
#ifdef BUMP
varying vec3 vNormalW;
#else
varying vec3 vNormalV;
#endif
varying vec4 vViewPos;
#if defined(POSITION) || defined(BUMP) || defined(IRRADIANCE)
varying vec3 vPositionW;
#endif
#if defined(VELOCITY) || defined(VELOCITY_LINEAR)
uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#ifdef HAS_NORMAL_ATTRIBUTE
vec3 normalUpdated=normal;
#else
vec3 normalUpdated=vec3(0.0,0.0,0.0);
#endif
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));
#ifdef BUMP
vWorldView=view*finalWorld;mat3 normalWorld=mat3(finalWorld);vNormalW=normalize(normalWorld*normalUpdated);
#else
#ifdef NORMAL_WORLDSPACE
vNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));
#else
vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));
#endif
#endif
vViewPos=view*worldPos;
#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);
#if NUM_BONE_INFLUENCERS>0
mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
#endif
vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);
#else
vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#endif
#if defined(POSITION) || defined(BUMP) || defined(IRRADIANCE)
vPositionW=worldPos.xyz/worldPos.w;
#endif
gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);
#include<clipPlaneVertex>
#ifdef NEED_UV
#ifdef UV1
#if defined(ALPHATEST) && defined(ALPHATEST_UV1)
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#else
vUV=uvUpdated;
#endif
#ifdef BUMP_UV1
vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef REFLECTIVITY_UV1
vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));
#else
#ifdef METALLIC_UV1
vMetallicUV=vec2(metallicMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef ROUGHNESS_UV1
vRoughnessUV=vec2(roughnessMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#endif
#ifdef ALBEDO_UV1
vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef SUBSURFACE_COLOR_UV1
vSubsurfaceColorUV=vec2(subsurfaceColorMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef SUBSURFACE_WEIGHT_UV1
vSubsurfaceWeightUV=vec2(subsurfaceWeightMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#endif
#ifdef UV2
#if defined(ALPHATEST) && defined(ALPHATEST_UV2)
vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0));
#else
vUV=uv2Updated;
#endif
#ifdef BUMP_UV2
vBumpUV=vec2(bumpMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#ifdef REFLECTIVITY_UV2
vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2Updated,1.0,0.0));
#else
#ifdef METALLIC_UV2
vMetallicUV=vec2(metallicMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#ifdef ROUGHNESS_UV2
vRoughnessUV=vec2(roughnessMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#ifdef ALBEDO_UV2
vAlbedoUV=vec2(albedoMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#ifdef SUBSURFACE_COLOR_UV2
vSubsurfaceColorUV=vec2(subsurfaceColorMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#ifdef SUBSURFACE_WEIGHT_UV2
vSubsurfaceWeightUV=vec2(subsurfaceWeightMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#endif
#include<bumpVertex>
#ifdef IRRADIANCE
#ifdef REFLECTION
#ifdef USESPHERICALFROMREFLECTIONMAP
vec3 reflectionVector=vec3(reflectionMatrix*vec4(normalUpdated,0.0)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector)*vReflectionInfos.x;
#endif
#endif
#endif
}
`;x.ShadersStore[Ow]||(x.ShadersStore[Ow]=p7);w_e={name:Ow,shader:p7}});var _7,F_e,vg=y(()=>{k();_7="harmonicsFunctions",F_e=`#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
fn computeEnvironmentIrradiance(normal: vec3f)->vec3f {return uniforms.vSphericalL00
+ uniforms.vSphericalL1_1*(normal.y)
+ uniforms.vSphericalL10*(normal.z)
+ uniforms.vSphericalL11*(normal.x)
+ uniforms.vSphericalL2_2*(normal.y*normal.x)
+ uniforms.vSphericalL2_1*(normal.y*normal.z)
+ uniforms.vSphericalL20*((3.0*normal.z*normal.z)-1.0)
+ uniforms.vSphericalL21*(normal.z*normal.x)
+ uniforms.vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}
#else
fn computeEnvironmentIrradiance(normal: vec3f)->vec3f {var Nx: f32=normal.x;var Ny: f32=normal.y;var Nz: f32=normal.z;var C1: vec3f=uniforms.vSphericalZZ.rgb;var Cx: vec3f=uniforms.vSphericalX.rgb;var Cy: vec3f=uniforms.vSphericalY.rgb;var Cz: vec3f=uniforms.vSphericalZ.rgb;var Cxx_zz: vec3f=uniforms.vSphericalXX_ZZ.rgb;var Cyy_zz: vec3f=uniforms.vSphericalYY_ZZ.rgb;var Cxy: vec3f=uniforms.vSphericalXY.rgb;var Cyz: vec3f=uniforms.vSphericalYZ.rgb;var Czx: vec3f=uniforms.vSphericalZX.rgb;var a1: vec3f=Cyy_zz*Ny+Cy;var a2: vec3f=Cyz*Nz+a1;var b1: vec3f=Czx*Nz+Cx;var b2: vec3f=Cxy*Ny+b1;var b3: vec3f=Cxx_zz*Nx+b2;var t1: vec3f=Cz *Nz+C1;var t2: vec3f=a2 *Ny+t1;var t3: vec3f=b3 *Nx+t2;return t3;}
#endif
#endif
`;x.IncludesShadersStoreWGSL[_7]||(x.IncludesShadersStoreWGSL[_7]=F_e)});var E7={};Be(E7,{geometryVertexShaderWGSL:()=>B_e});var ww,v7,B_e,S7=y(()=>{k();Wc();Hc();yd();Id();Rd();sh();Xc();vg();Cd();Pd();Yc();Kc();jc();Zc();zb();ww="geometryVertexShader",v7=`#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<instancesDeclaration>
#include<sceneUboDeclaration>
#include<clipPlaneVertexDeclaration>
#ifdef IRRADIANCE
#ifdef REFLECTION
uniform reflectionMatrix: mat4x4f;uniform vReflectionInfos: vec2f;uniform vReflectionColor: vec3f;
#ifdef USESPHERICALFROMREFLECTIONMAP
varying vEnvironmentIrradiance: vec3f;
#ifdef SPHERICAL_HARMONICS
uniform vSphericalL00: vec3f;uniform vSphericalL1_1: vec3f;uniform vSphericalL10: vec3f;uniform vSphericalL11: vec3f;uniform vSphericalL2_2: vec3f;uniform vSphericalL2_1: vec3f;uniform vSphericalL20: vec3f;uniform vSphericalL21: vec3f;uniform vSphericalL22: vec3f;
#else
uniform vSphericalX: vec3f;uniform vSphericalY: vec3f;uniform vSphericalZ: vec3f;uniform vSphericalXX_ZZ: vec3f;uniform vSphericalYY_ZZ: vec3f;uniform vSphericalZZ: vec3f;uniform vSphericalXY: vec3f;uniform vSphericalYZ: vec3f;uniform vSphericalZX: vec3f;
#endif
#include<harmonicsFunctions>
#endif
#endif
#endif
attribute position : vec3<f32>;
#ifdef HAS_NORMAL_ATTRIBUTE
attribute normal: vec3f;
#endif
#ifdef NEED_UV
varying vUV: vec2f;
#ifdef ALPHATEST
uniform diffuseMatrix: mat4x4f;
#endif
#ifdef BUMP
uniform bumpMatrix: mat4x4f;varying vBumpUV: vec2f;
#endif
#ifdef REFLECTIVITY
uniform reflectivityMatrix: mat4x4f;uniform albedoMatrix: mat4x4f;varying vReflectivityUV: vec2f;varying vAlbedoUV: vec2f;
#endif
#ifdef METALLIC_TEXTURE
varying vMetallicUV: vec2f;uniform metallicMatrix: mat4x4f;
#endif
#ifdef ROUGHNESS_TEXTURE
varying vRoughnessUV: vec2f;uniform roughnessMatrix: mat4x4f;
#endif
#ifdef SUBSURFACE_WEIGHT
varying vSubsurfaceWeightUV: vec2f;uniform subsurfaceWeightMatrix: mat4x4f;
#endif
#ifdef TRANSMISSION_WEIGHT
varying vTransmissionWeightUV: vec2f;uniform transmissionWeightMatrix: mat4x4f;
#endif
#ifdef UV1
attribute uv: vec2f;
#endif
#ifdef UV2
attribute uv2: vec2f;
#endif
#endif
#ifdef BUMP
varying vWorldView0: vec4f;varying vWorldView1: vec4f;varying vWorldView2: vec4f;varying vWorldView3: vec4f;
#endif
#ifdef BUMP
varying vNormalW: vec3f;
#else
varying vNormalV: vec3f;
#endif
varying vViewPos: vec4f;
#if defined(POSITION) || defined(BUMP) || defined(IRRADIANCE)
varying vPositionW: vec3f;
#endif
#if defined(VELOCITY) || defined(VELOCITY_LINEAR)
uniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=vertexInputs.position;
#ifdef HAS_NORMAL_ATTRIBUTE
var normalUpdated: vec3f=vertexInputs.normal;
#else
var normalUpdated: vec3f=vec3f(0.0,0.0,0.0);
#endif
#ifdef UV1
var uvUpdated: vec2f=vertexInputs.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=vertexInputs.uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f= vec4f(finalWorld* vec4f(positionUpdated,1.0));
#ifdef BUMP
let vWorldView=scene.view*finalWorld;vertexOutputs.vWorldView0=vWorldView[0];vertexOutputs.vWorldView1=vWorldView[1];vertexOutputs.vWorldView2=vWorldView[2];vertexOutputs.vWorldView3=vWorldView[3];let normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated);
#else
#ifdef NORMAL_WORLDSPACE
vertexOutputs.vNormalV=normalize((finalWorld* vec4f(normalUpdated,0.0)).xyz);
#else
vertexOutputs.vNormalV=normalize(((scene.view*finalWorld)* vec4f(normalUpdated,0.0)).xyz);
#endif
#endif
vertexOutputs.vViewPos=scene.view*worldPos;
#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)
vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0);
#if NUM_BONE_INFLUENCERS>0
var previousInfluence: mat4x4f;previousInfluence=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];
#endif
vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0);
#else
vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0);
#endif
#endif
#if defined(POSITION) || defined(BUMP) || defined(IRRADIANCE)
vertexOutputs.vPositionW=worldPos.xyz/worldPos.w;
#endif
vertexOutputs.position=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0);
#include<clipPlaneVertex>
#ifdef NEED_UV
#ifdef UV1
#if defined(ALPHATEST) && defined(ALPHATEST_UV1)
vertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#else
vertexOutputs.vUV=uvUpdated;
#endif
#ifdef BUMP_UV1
vertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef REFLECTIVITY_UV1
vertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#else
#ifdef METALLIC_UV1
vertexOutputs.vMetallicUV=(uniforms.metallicMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef ROUGHNESS_UV1
vertexOutputs.vRoughnessUV=(uniforms.roughnessMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#endif
#ifdef ALBEDO_UV1
vertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef SUBSURFACE_WEIGHT_UV1
vertexOutputs.vSubsurfaceWeightUV=(uniforms.subsurfaceWeightMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef TRANSMISSION_WEIGHT_UV1
vertexOutputs.vTransmissionWeightUV=(uniforms.transmissionWeightMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#endif
#ifdef UV2
#if defined(ALPHATEST) && defined(ALPHATEST_UV2)
vertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#else
vertexOutputs.vUV=uv2Updated;
#endif
#ifdef BUMP_UV2
vertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#ifdef REFLECTIVITY_UV2
vertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#else
#ifdef METALLIC_UV2
vertexOutputs.vMetallicUV=(uniforms.metallicMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#ifdef ROUGHNESS_UV2
vertexOutputs.vRoughnessUV=(uniforms.roughnessMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
#ifdef ALBEDO_UV2
vertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#ifdef SUBSURFACE_WEIGHT_UV2
vertexOutputs.vSubsurfaceWeightUV=(uniforms.subsurfaceWeightMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#ifdef TRANSMISSION_WEIGHT_UV2
vertexOutputs.vTransmissionWeightUV=(uniforms.transmissionWeightMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
#endif
#include<bumpVertex>
#ifdef IRRADIANCE
#ifdef REFLECTION
#ifdef USESPHERICALFROMREFLECTIONMAP
var reflectionVector: vec3f=(uniforms.reflectionMatrix*vec4f(normalUpdated,0.0)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0f;
#endif
vertexOutputs.vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector)*uniforms.vReflectionInfos.x;
#endif
#endif
#endif
}
`;x.ShadersStoreWGSL[ww]||(x.ShadersStoreWGSL[ww]=v7);B_e={name:ww,shader:v7}});var T7,U_e,iy=y(()=>{k();T7="pbrFragmentReflectionDeclaration",U_e=`#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
var reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube<f32>;
#ifdef LODBASEDMICROSFURACE
#else
var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_cube<f32>;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_cube<f32>;
#endif
#ifdef USEIRRADIANCEMAP
var irradianceSamplerSampler: sampler;var irradianceSampler: texture_cube<f32>;
#endif
#else
var reflectionSamplerSampler: sampler;var reflectionSampler: texture_2d<f32>;
#ifdef LODBASEDMICROSFURACE
#else
var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_2d<f32>;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_2d<f32>;
#endif
#ifdef USEIRRADIANCEMAP
var irradianceSamplerSampler: sampler;var irradianceSampler: texture_2d<f32>;
#endif
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vPositionUVW: vec3f;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vDirectionW: vec3f;
#endif
#endif
#endif
`;x.IncludesShadersStoreWGSL[T7]||(x.IncludesShadersStoreWGSL[T7]=U_e)});var A7,V_e,Eg=y(()=>{k();A7="pbrBRDFFunctions",V_e=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25
#define BRDF_DIFFUSE_MODEL_EON 0
#define BRDF_DIFFUSE_MODEL_BURLEY 1
#define BRDF_DIFFUSE_MODEL_LAMBERT 2
#define BRDF_DIFFUSE_MODEL_LEGACY 3
#define DIELECTRIC_SPECULAR_MODEL_GLTF 0
#define DIELECTRIC_SPECULAR_MODEL_OPENPBR 1
#define CONDUCTOR_SPECULAR_MODEL_GLTF 0
#define CONDUCTOR_SPECULAR_MODEL_OPENPBR 1
#if !defined(PBR_VERTEX_SHADER) && !defined(OPENPBR_VERTEX_SHADER)
#ifdef MS_BRDF_ENERGY_CONSERVATION
fn getEnergyConservationFactor(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}
#endif
#if CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR
const F82_COS_THETA_MAX: f32 =0.142857143;const F82_ONE_MINUS_CTM_POW5: f32 =0.462664366;const F82_ONE_MINUS_CTM_POW6: f32 =0.396569457;const F82_B_DENOMINATOR_RECIP: f32 =17.6512785;const BRDF_Z_SCALE: f32 =16.0;fn getF82Specular(NdotV: f32,F0: vec3f,edgeTint: vec3f,roughness: f32)->vec3f {let white_minus_F0: vec3f=vec3f(1.0f)-F0;let b_numerator: vec3f=(F0+white_minus_F0*F82_ONE_MINUS_CTM_POW5)*(vec3f(1.0)-edgeTint);let b: vec3f=b_numerator*F82_B_DENOMINATOR_RECIP;let cos_theta: f32=max(roughness,NdotV);let one_minus_cos_theta: f32=1.0-cos_theta;let offset_from_F0: vec3f=(white_minus_F0-b*cos_theta*one_minus_cos_theta)*pow(one_minus_cos_theta,5.0f);return clamp(F0+offset_from_F0,vec3f(0.0f),vec3f(1.0f));}
fn getF82B(F0: vec3f,edgeTint: vec3f)->vec3f {return (F0+(vec3f(1.0)-F0)*F82_ONE_MINUS_CTM_POW5)*(vec3f(1.0)-edgeTint)*F82_B_DENOMINATOR_RECIP;}
fn getF82DirectionalAlbedo(F0: vec3f,F90: vec3f,b: vec3f,environmentBrdf: vec3f)->vec3f {return (F90-F0)*environmentBrdf.x+F0*environmentBrdf.y-b*environmentBrdf.z;}
fn getF82AverageFresnel(F0: vec3f,b: vec3f)->vec3f {return F0+(vec3f(1.0)-F0)/21.0-b/126.0;}
#endif
#ifdef FUZZENVIRONMENTBRDF
fn getFuzzBRDFLookup(NdotV: f32,perceptualRoughness: f32)->vec3f {let UV: vec2f=vec2f(perceptualRoughness,NdotV);var brdfLookup: vec4f=textureSample(environmentFuzzBrdfSampler,environmentFuzzBrdfSamplerSampler,UV);const RiRange: vec2f=vec2f(0.0f,0.75f);const ARange: vec2f=vec2f(0.005f,0.88f);const BRange: vec2f=vec2f(-0.18f,0.002f);brdfLookup.r=mix(ARange.x, ARange.y, brdfLookup.r);brdfLookup.g=mix(BRange.x, BRange.y, brdfLookup.g);brdfLookup.b=mix(RiRange.x,RiRange.y,brdfLookup.b);return brdfLookup.rgb;}
#endif
#ifdef ENVIRONMENTBRDF
fn getBRDFLookup(NdotV: f32,perceptualRoughness: f32)->vec3f {var UV: vec2f= vec2f(NdotV,perceptualRoughness);var brdfLookup: vec4f= textureSample(environmentBrdfSampler,environmentBrdfSamplerSampler,UV);
#ifdef ENVIRONMENTBRDF_RGBD
brdfLookup=vec4f(fromRGBD(brdfLookup.rgba),brdfLookup.a);
#endif
return brdfLookup.rgb;}
fn getReflectanceFromBRDFWithEnvLookup(specularEnvironmentR0: vec3f,specularEnvironmentR90: vec3f,environmentBrdf: vec3f)->vec3f {
#ifdef BRDF_V_HEIGHT_CORRELATED
var reflectance: vec3f=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;
#else
var reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;
#endif
return reflectance;}
fn getReflectanceFromBRDFLookup(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f {
#ifdef BRDF_V_HEIGHT_CORRELATED
var reflectance: vec3f=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);
#else
var reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;
#endif
return reflectance;}
#endif
/* NOT USED
#if defined(SHEEN) && defined(SHEEN_SOFTER)
fn getBRDFLookupCharlieSheen(NdotV: f32,perceptualRoughness: f32)->f32
{var c: f32=1.0-NdotV;var c3: f32=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}
#endif
*/
#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)
fn getReflectanceFromAnalyticalBRDFLookup_Jones(VdotN: f32,reflectance0: vec3f,reflectance90: vec3f,smoothness: f32)->vec3f
{var weight: f32=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF)
/**
* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.
* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table
*/
fn getSheenReflectanceFromBRDFLookup(reflectance0: vec3f,environmentBrdf: vec3f)->vec3f {var sheenEnvironmentReflectance: vec3f=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}
#endif
fn fresnelSchlickGGXVec3(VdotH: f32,reflectance0: vec3f,reflectance90: vec3f)->vec3f
{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}
fn fresnelSchlickGGX(VdotH: f32,reflectance0: f32,reflectance90: f32)->f32
{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}
#ifdef CLEARCOAT
fn getR0RemappedForClearCoat(f0: vec3f)->vec3f {
#ifdef CLEARCOAT_DEFAULTIOR
#ifdef MOBILE
return saturateVec3(f0*(f0*0.526868+0.529324)-0.0482256);
#else
return saturateVec3(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);
#endif
#else
var s: vec3f=sqrt(f0);var t: vec3f=(uniforms.vClearCoatRefractionParams.z+uniforms.vClearCoatRefractionParams.w*s)/(uniforms.vClearCoatRefractionParams.w+uniforms.vClearCoatRefractionParams.z*s);return squareVec3(t);
#endif
}
#endif
#ifdef IRIDESCENCE
const XYZ_TO_REC709: mat3x3f= mat3x3f(
3.2404542,-0.9692660, 0.0556434,
-1.5371385, 1.8760108,-0.2040259,
-0.4985314, 0.0415560, 1.0572252
);fn getIORTfromAirToSurfaceR0(f0: vec3f)->vec3f {var sqrtF0: vec3f=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}
fn getR0fromIORsVec3(iorT: vec3f,iorI: f32)->vec3f {return squareVec3((iorT- vec3f(iorI))/(iorT+ vec3f(iorI)));}
fn getR0fromIORs(iorT: f32,iorI: f32)->f32 {return square((iorT-iorI)/(iorT+iorI));}
fn evalSensitivity(opd: f32,shift: vec3f)->vec3f {var phase: f32=2.0*PI*opd*1.0e-9;const val: vec3f= vec3f(5.4856e-13,4.4201e-13,5.2481e-13);const pos: vec3f= vec3f(1.6810e+06,1.7953e+06,2.2084e+06);const vr: vec3f= vec3f(4.3278e+09,9.3046e+09,6.6121e+09);var xyz: vec3f=val*sqrt(2.0*PI*vr)*cos(pos*phase+shift)*exp(-square(phase)*vr);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;var srgb: vec3f=XYZ_TO_REC709*xyz;return srgb;}
fn evalIridescence(outsideIOR: f32,eta2: f32,cosTheta1: f32,thinFilmThickness: f32,baseF0: vec3f)->vec3f {var I: vec3f= vec3f(1.0);var iridescenceIOR: f32=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));var sinTheta2Sq: f32=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));var cosTheta2Sq: f32=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}
var cosTheta2: f32=sqrt(cosTheta2Sq);var R0: f32=getR0fromIORs(iridescenceIOR,outsideIOR);var R12: f32=fresnelSchlickGGX(cosTheta1,R0,1.);var R21: f32=R12;var T121: f32=1.0-R12;var phi12: f32=0.0;if (iridescenceIOR<outsideIOR) {phi12=PI;}
var phi21: f32=PI-phi12;var baseIOR: vec3f=getIORTfromAirToSurfaceR0(clamp(baseF0,vec3f(0.0),vec3f(0.9999)));
var R1: vec3f=getR0fromIORsVec3(baseIOR,iridescenceIOR);let maxR1: f32=max(R1.r,max(R1.g,R1.b));if (maxR1<1e-6) {return max(vec3f(R12),vec3f(0.0));}
var R23: vec3f=fresnelSchlickGGXVec3(cosTheta2,R1,vec3f(1.));var phi23: vec3f=vec3f(0.0);if (baseIOR[0]<iridescenceIOR) {phi23[0]=PI;}
if (baseIOR[1]<iridescenceIOR) {phi23[1]=PI;}
if (baseIOR[2]<iridescenceIOR) {phi23[2]=PI;}
var opd: f32=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;var phi: vec3f=vec3f(phi21)+phi23;var R123: vec3f=clamp(R12*R23,vec3f(1e-5),vec3f(0.9999));var r123: vec3f=sqrt(R123);var Rs: vec3f=(T121*T121)*R23/(vec3f(1.0)-R123);var C0: vec3f=R12+Rs;I=C0;var Cm: vec3f=Rs-T121;for (var m: i32=1; m<=2; m++)
{Cm*=r123;var Sm: vec3f=2.0*evalSensitivity(f32(m)*opd,f32(m)*phi);I+=Cm*Sm;}
return max(I,vec3f(0.0));}
#endif
fn normalDistributionFunction_TrowbridgeReitzGGX(NdotH: f32,alphaG: f32)->f32
{var a2: f32=alphaG*alphaG;var d: f32=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);}
#ifdef SHEEN
fn normalDistributionFunction_CharlieSheen(NdotH: f32,alphaG: f32)->f32
{var invR: f32=1./alphaG;var cos2h: f32=NdotH*NdotH;var sin2h: f32=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);}
#endif
#ifdef ANISOTROPIC
fn normalDistributionFunction_BurleyGGX_Anisotropic(NdotH: f32,TdotH: f32,BdotH: f32,alphaTB: vec2f)->f32 {var a2: f32=alphaTB.x*alphaTB.y;var v: vec3f= vec3f(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);var v2: f32=dot(v,v);var w2: f32=a2/v2;return a2*w2*w2*RECIPROCAL_PI;}
#endif
#ifdef BRDF_V_HEIGHT_CORRELATED
fn smithVisibility_GGXCorrelated(NdotL: f32,NdotV: f32,alphaG: f32)->f32 {
#ifdef MOBILE
var GGXV: f32=NdotL*(NdotV*(1.0-alphaG)+alphaG);var GGXL: f32=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL);
#else
var a2: f32=alphaG*alphaG;var GGXV: f32=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);var GGXL: f32=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL);
#endif
}
#else
fn smithVisibilityG1_TrowbridgeReitzGGXFast(dot: f32,alphaG: f32)->f32
{
#ifdef MOBILE
return 1.0/(dot+alphaG+(1.0-alphaG)*dot ));
#else
var alphaSquared: f32=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));
#endif
}
fn smithVisibility_TrowbridgeReitzGGXFast(NdotL: f32,NdotV: f32,alphaG: f32)->f32
{var visibility: f32=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;}
#endif
#ifdef ANISOTROPIC
fn smithVisibility_GGXCorrelated_Anisotropic(NdotL: f32,NdotV: f32,TdotV: f32,BdotV: f32,TdotL: f32,BdotL: f32,alphaTB: vec2f)->f32 {var lambdaV: f32=NdotL*length( vec3f(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));var lambdaL: f32=NdotV*length( vec3f(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));var v: f32=0.5/(lambdaV+lambdaL);return v;}
#endif
#ifdef CLEARCOAT
fn visibility_Kelemen(VdotH: f32)->f32 {return 0.25/(VdotH*VdotH); }
#endif
#ifdef SHEEN
fn visibility_Ashikhmin(NdotL: f32,NdotV: f32)->f32
{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));}
/* NOT USED
#ifdef SHEEN_SOFTER
fn l(x: f32,alphaG: f32)->f32
{var oneMinusAlphaSq: f32=(1.0-alphaG)*(1.0-alphaG);var a: f32=mix(21.5473,25.3245,oneMinusAlphaSq);var b: f32=mix(3.82987,3.32435,oneMinusAlphaSq);var c: f32=mix(0.19823,0.16801,oneMinusAlphaSq);var d: f32=mix(-1.97760,-1.27393,oneMinusAlphaSq);var e: f32=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;}
fn lambdaSheen(cosTheta: f32,alphaG: f32)->f32
{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));}
fn visibility_CharlieSheen(NdotL: f32,NdotV: f32,alphaG: f32)->f32
{var G: f32=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);}
#endif
*/
#endif
const constant1_FON: f32=0.5f-2.0f/(3.0f*PI);const constant2_FON: f32=2.0f/3.0f-28.0f/(15.0f*PI);fn E_FON_approx(mu: f32,roughness: f32)->f32
{var sigma: f32=roughness;
var mucomp: f32=1.0f-mu;var mucomp2: f32=mucomp*mucomp;const Gcoeffs: mat2x2f=mat2x2f(0.0571085289f,-0.332181442f,
0.491881867f,0.0714429953f);var GoverPi: f32=dot(Gcoeffs*vec2f(mucomp,mucomp2),vec2f(1.0f,mucomp2));return (1.0f+sigma*GoverPi)/(1.0f+constant1_FON*sigma);}
fn diffuseBRDF_EON(albedo: vec3f,roughness: f32,NdotL: f32,NdotV: f32,LdotV: f32)->vec3f
{var rho: vec3f=albedo;var sigma: f32=roughness;
var mu_i: f32=NdotL;
var mu_o: f32=NdotV;
var s: f32=LdotV-mu_i*mu_o;
var sovertF: f32=select(s,s/max(mu_i,mu_o),s>0.0f);
var AF: f32=1.0f/(1.0f+constant1_FON*sigma);
var f_ss: vec3f=(rho*RECIPROCAL_PI)*AF*(1.0f+sigma*sovertF);
var EFo: f32=E_FON_approx(mu_o,sigma);
var EFi: f32=E_FON_approx(mu_i,sigma);
var avgEF: f32=AF*(1.0f+constant2_FON*sigma);
var rho_ms: vec3f=(rho*rho)*avgEF/(vec3f(1.0f)-rho*(1.0f-avgEF));const eps: f32=1.0e-7f;var f_ms: vec3f=(rho_ms*RECIPROCAL_PI)*max(eps,1.0f-EFo)
* max(eps,1.0f-EFi)
/ max(eps,1.0f-avgEF);return (f_ss+f_ms);}
fn diffuseBRDF_Burley(NdotL: f32,NdotV: f32,VdotH: f32,roughness: f32)->f32 {var diffuseFresnelNV: f32=pow5(saturateEps(1.0-NdotL));var diffuseFresnelNL: f32=pow5(saturateEps(1.0-NdotV));var diffuseFresnel90: f32=0.5+2.0*VdotH*VdotH*roughness;var fresnel: f32 =
(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *
(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;}
#ifdef SS_TRANSLUCENCY
fn transmittanceBRDF_Burley(tintColor: vec3f,diffusionDistance: vec3f,thickness: f32)->vec3f {var S: vec3f=1./maxEpsVec3(diffusionDistance);var temp: vec3f=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);}
fn computeWrappedDiffuseNdotL(NdotL: f32,w: f32)->f32 {var t: f32=1.0+w;var invt2: f32=1.0/(t*t);return saturate((NdotL+w)*invt2);}
#endif
#endif
`;x.IncludesShadersStoreWGSL[A7]||(x.IncludesShadersStoreWGSL[A7]=V_e)});var x7,G_e,Fw=y(()=>{k();x7="openpbrDielectricReflectance",G_e=`struct ReflectanceParams
{F0: f32,
F90: f32,
coloredF0: vec3f,
coloredF90: vec3f,};
#define pbr_inline
fn dielectricReflectance(
insideIOR: f32,outsideIOR: f32,specularColor: vec3f,specularWeight: f32
)->ReflectanceParams
{var outParams: ReflectanceParams;let dielectricF0=pow((insideIOR-outsideIOR)/(insideIOR+outsideIOR),2.0);
#if DIELECTRIC_SPECULAR_MODEL==DIELECTRIC_SPECULAR_MODEL_GLTF
let maxF0=max(specularColor.r,max(specularColor.g,specularColor.b));outParams.F0=dielectricF0*maxF0*specularWeight;
#else
outParams.F0=dielectricF0*specularWeight;
#endif
let f90Scale=clamp(2.0f*abs(insideIOR-outsideIOR),0.0f,1.0f);outParams.F90=f90Scale*specularWeight;outParams.coloredF0=vec3f(dielectricF0*specularWeight)*specularColor.rgb;
#if (DIELECTRIC_SPECULAR_MODEL==DIELECTRIC_SPECULAR_MODEL_OPENPBR)
let dielectricColorF90: vec3f=specularColor.rgb*vec3f(f90Scale)*specularWeight;
#else
let dielectricColorF90: vec3f=vec3f(f90Scale)*specularWeight;
#endif
outParams.coloredF90=dielectricColorF90;return outParams;}
`;x.IncludesShadersStoreWGSL[x7]||(x.IncludesShadersStoreWGSL[x7]=G_e)});var R7,k_e,ry=y(()=>{k();R7="pbrIBLFunctions",k_e=`#if defined(REFLECTION) || defined(SS_REFRACTION)
fn getLodFromAlphaG(cubeMapDimensionPixels: f32,microsurfaceAverageSlope: f32)->f32 {var microsurfaceAverageSlopeTexels: f32=cubeMapDimensionPixels*microsurfaceAverageSlope;var lod: f32=log2(microsurfaceAverageSlopeTexels);return lod;}
fn getLinearLodFromRoughness(cubeMapDimensionPixels: f32,roughness: f32)->f32 {var lod: f32=log2(cubeMapDimensionPixels)*roughness;return lod;}
#endif
#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)
fn environmentRadianceOcclusion(ambientOcclusion: f32,NdotVUnclamped: f32)->f32 {var temp: f32=NdotVUnclamped+ambientOcclusion;return saturate(temp*temp-1.0+ambientOcclusion);}
#endif
#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)
fn environmentHorizonOcclusion(view: vec3f,normal: vec3f,geometricNormal: vec3f)->f32 {var reflection: vec3f=reflect(view,normal);var temp: f32=saturate(1.0+1.1*dot(reflection,geometricNormal));return temp*temp;}
#endif
#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)
fn UNPACK_LOD(x: f32)->f32 {return (1.0-x)*255.0;}
fn getLodFromAlphaGNdotV(cubeMapDimensionPixels: f32,alphaG: f32,NdotV: f32)->f32 {var microsurfaceAverageSlope: f32=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);}
#endif
`;x.IncludesShadersStoreWGSL[R7]||(x.IncludesShadersStoreWGSL[R7]=k_e)});var b7,z_e,Bw=y(()=>{k();b7="openpbrGeometryInfo",z_e=`struct geometryInfoOutParams
{NdotV: f32,
NdotVUnclamped: f32,
environmentBrdf: vec3f,
horizonOcclusion: f32};struct geometryInfoAnisoOutParams
{NdotV: f32,
NdotVUnclamped: f32,
environmentBrdf: vec3f,
horizonOcclusion: f32,
anisotropy: f32,
anisotropicTangent: vec3f,
anisotropicBitangent: vec3f,
TBN: mat3x3<f32>};fn geometryInfo(
normalW: vec3f,viewDirectionW: vec3f,roughness: f32,geometricNormalW: vec3f
)->geometryInfoOutParams
{var outParams: geometryInfoOutParams;outParams.NdotVUnclamped=dot(normalW,viewDirectionW);outParams.NdotV=absEps(outParams.NdotVUnclamped);
#if defined(ENVIRONMENTBRDF)
outParams.environmentBrdf=getBRDFLookup(outParams.NdotV,roughness);
#else
outParams.environmentBrdf=vec3f(0.0);
#endif
outParams.horizonOcclusion=1.0f;
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
#ifdef HORIZONOCCLUSION
#if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL)
#ifdef REFLECTIONMAP_3D
outParams.horizonOcclusion=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);
#endif
#endif
#endif
#endif
return outParams;}
fn geometryInfoAniso(
normalW: vec3f,viewDirectionW: vec3f,roughness: f32,geometricNormalW: vec3f
,vAnisotropy: vec3f,TBN: mat3x3<f32>
)->geometryInfoAnisoOutParams
{let geoInfo: geometryInfoOutParams=geometryInfo(normalW,viewDirectionW,roughness,geometricNormalW);var outParams: geometryInfoAnisoOutParams;outParams.NdotV=geoInfo.NdotV;outParams.NdotVUnclamped=geoInfo.NdotVUnclamped;outParams.environmentBrdf=geoInfo.environmentBrdf;outParams.horizonOcclusion=geoInfo.horizonOcclusion;outParams.anisotropy=vAnisotropy.b;let anisotropyDirection: vec3f=vec3f(vAnisotropy.xy,0.);let anisoTBN: mat3x3<f32>=mat3x3<f32>(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));outParams.anisotropicTangent=normalize(anisoTBN*anisotropyDirection);outParams.anisotropicBitangent=normalize(cross(anisoTBN[2],outParams.anisotropicTangent));outParams.TBN=TBN;return outParams;}
`;x.IncludesShadersStoreWGSL[b7]||(x.IncludesShadersStoreWGSL[b7]=z_e)});var M7,W_e,Uw=y(()=>{k();M7="openpbrIblFunctions",W_e=`#ifdef REFLECTION
fn sampleIrradiance(
surfaceNormal: vec3f
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,vEnvironmentIrradianceSH: vec3f
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,iblMatrix: mat4x4f
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
,irradianceSampler: texture_cube<f32>
,irradianceSamplerSampler: sampler
#else
,irradianceSampler: texture_2d<f32>
,irradianceSamplerSampler: sampler
#endif
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
,reflectionDominantDirection: vec3f
#endif
#endif
#ifdef REALTIME_FILTERING
,reflectionFilteringInfo: vec2f
#ifdef IBL_CDF_FILTERING
,icdfSampler: texture_2d<f32>
,icdfSamplerSampler: sampler
#endif
#endif
,reflectionInfos: vec2f
,viewDirectionW: vec3f
,diffuseRoughness: f32
,surfaceAlbedo: vec3f
)->vec3f {var environmentIrradiance=vec3f(0.,0.,0.);
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
var irradianceVector=(iblMatrix*vec4f(surfaceNormal,0.0f)).xyz;var irradianceView=(iblMatrix*vec4f(viewDirectionW,0.0f)).xyz;
#if !defined(USE_IRRADIANCE_DOMINANT_DIRECTION) && !defined(REALTIME_FILTERING)
#if BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LAMBERT && BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LEGACY
{let NdotV=max(dot(surfaceNormal,viewDirectionW),0.0f);irradianceVector=mix(irradianceVector,irradianceView,(0.5f*(1.0f-NdotV))*diffuseRoughness);}
#endif
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;irradianceView.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;irradianceView.y*=-1.0;
#endif
#endif
#ifdef USESPHERICALFROMREFLECTIONMAP
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
environmentIrradiance=vEnvironmentIrradianceSH;
#else
#if defined(REALTIME_FILTERING)
environmentIrradiance=irradiance(reflectionSampler,reflectionSamplerSampler,irradianceVector,reflectionFilteringInfo,diffuseRoughness,surfaceAlbedo,irradianceView
#ifdef IBL_CDF_FILTERING
,icdfSampler
,icdfSamplerSampler
#endif
);
#else
environmentIrradiance=computeEnvironmentIrradiance(irradianceVector);
#endif
#endif
#elif defined(USEIRRADIANCEMAP)
#ifdef REFLECTIONMAP_3D
let environmentIrradianceFromTexture: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,irradianceVector);
#else
let environmentIrradianceFromTexture: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,reflectionCoords);
#endif
environmentIrradiance=environmentIrradianceFromTexture.rgb;
#ifdef RGBDREFLECTION
environmentIrradiance.rgb=fromRGBD(environmentIrradianceFromTexture);
#endif
#ifdef GAMMAREFLECTION
environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);
#endif
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
let Ls: vec3f=normalize(reflectionDominantDirection);let NoL: f32=dot(irradianceVector,Ls);let NoV: f32=dot(irradianceVector,irradianceView);var diffuseRoughnessTerm=vec3f(1.0f);
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
let LoV: f32=dot (Ls,irradianceView);let mag: f32=length(reflectionDominantDirection)*2.0f;let clampedAlbedo: vec3f=clamp(surfaceAlbedo,vec3f(0.1f),vec3f(1.0f));diffuseRoughnessTerm=diffuseBRDF_EON(clampedAlbedo,diffuseRoughness,NoL,NoV,LoV)*PI;diffuseRoughnessTerm=diffuseRoughnessTerm/clampedAlbedo;diffuseRoughnessTerm=mix(vec3f(1.0f),diffuseRoughnessTerm,sqrt(clamp(mag*NoV,0.0f,1.0f)));
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
let H: vec3f=(irradianceView+Ls)*0.5f;let VoH: f32=dot(irradianceView,H);diffuseRoughnessTerm=vec3f(diffuseBRDF_Burley(NoL,NoV,VoH,diffuseRoughness)*PI);
#endif
environmentIrradiance=environmentIrradiance.rgb*diffuseRoughnessTerm;
#endif
#endif
environmentIrradiance*=reflectionInfos.x;return environmentIrradiance;}
#ifdef REFLECTIONMAP_3D
fn createReflectionCoords(vPositionW: vec3f,normalW: vec3f)->vec3f
#else
fn createReflectionCoords(vPositionW: vec3f,normalW: vec3f)->vec2f
#endif
{var reflectionVector: vec3f=computeReflectionCoords(vec4f(vPositionW,1.0f),normalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
var reflectionCoords: vec3f=reflectionVector;
#else
var reflectionCoords: vec2f=reflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
reflectionCoords/=reflectionVector.z;
#endif
reflectionCoords.y=1.0f-reflectionCoords.y;
#endif
return reflectionCoords;}
fn sampleRadiance(
alphaG: f32
,reflectionMicrosurfaceInfos: vec3f
,reflectionInfos: vec2f
,geoInfo: geometryInfoOutParams
#ifdef REFLECTIONMAP_3D
,reflectionSampler: texture_cube<f32>
,reflectionSamplerSampler: sampler
,reflectionCoords: vec3f
#else
,reflectionSampler: texture_2d<f32>
,reflectionSamplerSampler: sampler
,reflectionCoords: vec2f
#endif
#ifdef REALTIME_FILTERING
,reflectionFilteringInfo: vec2f
#endif
)->vec3f {var environmentRadiance: vec4f=vec4f(0.f,0.f,0.f,0.f);
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
var reflectionLOD: f32=getLodFromAlphaG(reflectionMicrosurfaceInfos.x,alphaG,geoInfo.NdotVUnclamped);
#elif defined(LINEARSPECULARREFLECTION)
var reflectionLOD: f32=getLinearLodFromRoughness(reflectionMicrosurfaceInfos.x,roughness);
#else
var reflectionLOD: f32=getLodFromAlphaG(reflectionMicrosurfaceInfos.x,alphaG);
#endif
reflectionLOD=reflectionLOD*reflectionMicrosurfaceInfos.y+reflectionMicrosurfaceInfos.z;
#ifdef REALTIME_FILTERING
environmentRadiance=vec4f(radiance(alphaG,reflectionSampler,reflectionSamplerSampler,reflectionCoords,reflectionFilteringInfo),1.0f);
#else
environmentRadiance=textureSampleLevel(reflectionSampler,reflectionSamplerSampler,reflectionCoords,reflectionLOD);
#endif
#ifdef RGBDREFLECTION
environmentRadiance.rgb=fromRGBD(environmentRadiance);
#endif
#ifdef GAMMAREFLECTION
environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);
#endif
environmentRadiance=vec4f(environmentRadiance.rgb*reflectionInfos.x,environmentRadiance.a);return environmentRadiance.rgb;}
#if defined(ANISOTROPIC)
fn sampleRadianceAnisotropic(
alphaG: f32
,reflectionMicrosurfaceInfos: vec3f
,reflectionInfos: vec2f
,geoInfo: geometryInfoAnisoOutParams
,normalW: vec3f
,viewDirectionW: vec3f
,positionW: vec3f
,noise: vec3f
,isRefraction: bool
,ior: f32
#ifdef REFLECTIONMAP_3D
,reflectionSampler: texture_cube<f32>
,reflectionSamplerSampler: sampler
#else
,reflectionSampler: texture_2d<f32>
,reflectionSamplerSampler: sampler
#endif
#ifdef REALTIME_FILTERING
,reflectionFilteringInfo: vec2f
#endif
)->vec3f {var environmentRadiance: vec4f=vec4f(0.f,0.f,0.f,0.f);let alphaT=alphaG*sqrt(2.0f/(1.0f+(1.0f-geoInfo.anisotropy)*(1.0f-geoInfo.anisotropy)));let alphaB=(1.0f-geoInfo.anisotropy)*alphaT;let modifiedAlphaG=alphaB;
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
var reflectionLOD: f32=getLodFromAlphaG(reflectionMicrosurfaceInfos.x,modifiedAlphaG,geoInfo.NdotVUnclamped);
#elif defined(LINEARSPECULARREFLECTION)
var reflectionLOD: f32=getLinearLodFromRoughness(reflectionMicrosurfaceInfos.x,roughness);
#else
var reflectionLOD: f32=getLodFromAlphaG(reflectionMicrosurfaceInfos.x,modifiedAlphaG);
#endif
reflectionLOD=reflectionLOD*reflectionMicrosurfaceInfos.y+reflectionMicrosurfaceInfos.z;
#ifdef REALTIME_FILTERING
var view=(uniforms.reflectionMatrix*vec4f(viewDirectionW,0.0f)).xyz;var tangent=(uniforms.reflectionMatrix*vec4f(geoInfo.anisotropicTangent,0.0f)).xyz;var bitangent=(uniforms.reflectionMatrix*vec4f(geoInfo.anisotropicBitangent,0.0f)).xyz;var normal=(uniforms.reflectionMatrix*vec4f(normalW,0.0f)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
view.z*=-1.0f;tangent.z*=-1.0f;bitangent.z*=-1.0f;normal.z*=-1.0f;
#endif
environmentRadiance =
vec4f(radianceAnisotropic(alphaT,alphaB,reflectionSampler,reflectionSamplerSampler,
view,tangent,
bitangent,normal,
reflectionFilteringInfo,noise.xy,isRefraction,ior),
1.0f);
#else
const samples: i32=16;var radianceSample=vec4f(0.0);var accumulatedRadiance=vec3f(0.0);var reflectionCoords=vec3f(0.0);var sample_weight=0.0f;var total_weight=0.0f;let step=1.0f/f32(max(samples-1,1));for (var i: i32=0; i<samples; i++) {var t: f32=mix(-1.0,1.0,f32(i)*step);t+=step*2.0*noise.x;sample_weight=max(1.0-abs(t),0.001);sample_weight*=sample_weight;t*=min(4.0*alphaT*geoInfo.anisotropy,1.0);var bentNormal: vec3f;if (t<0.0) {let blend: f32=t+1.0;bentNormal=normalize(mix(-geoInfo.anisotropicTangent,normalW,blend));} else if (t>0.0) {let blend: f32=t;bentNormal=normalize(mix(normalW,geoInfo.anisotropicTangent,blend));} else {bentNormal=normalW;}
if (isRefraction) {reflectionCoords=double_refract(-viewDirectionW,bentNormal,ior);} else {reflectionCoords=reflect(-viewDirectionW,bentNormal);}
reflectionCoords=(uniforms.reflectionMatrix*vec4f(reflectionCoords,0.f)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionCoords.z*=-1.0f;
#endif
radianceSample=textureSampleLevel(reflectionSampler,reflectionSamplerSampler,reflectionCoords,reflectionLOD);
#ifdef RGBDREFLECTION
accumulatedRadiance+=vec3f(sample_weight)*fromRGBD(radianceSample);
#elif defined(GAMMAREFLECTION)
accumulatedRadiance+=vec3f(sample_weight)*toLinearSpace(radianceSample.rgb);
#else
accumulatedRadiance+=vec3f(sample_weight)*radianceSample.rgb;
#endif
total_weight+=sample_weight;}
environmentRadiance=vec4f(accumulatedRadiance/vec3f(total_weight),1.0f);
#endif
environmentRadiance=vec4f(environmentRadiance.rgb*reflectionInfos.xxx,environmentRadiance.a);return environmentRadiance.rgb;}
#endif
#endif
#ifdef ENVIRONMENTBRDF
fn computeDielectricIblFresnel(reflectance: ReflectanceParams,environmentBrdf: vec3f)->f32
{let dielectricIblFresnel: f32=getReflectanceFromBRDFWithEnvLookup(vec3f(reflectance.F0),vec3f(reflectance.F90),environmentBrdf).r;let dielectricECF: f32=1.0+reflectance.F0*(1.0/environmentBrdf.y-1.0);return clamp(dielectricIblFresnel*dielectricECF,0.0,1.0);}
fn computeConductorIblFresnel(reflectance: ReflectanceParams,environmentBrdf: vec3f)->vec3f
{
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR)
let openPBRBrdf: vec3f=vec3f(environmentBrdf.xy,environmentBrdf.z/BRDF_Z_SCALE);let b: vec3f =getF82B(reflectance.coloredF0,reflectance.coloredF90);let E_F82: vec3f=getF82DirectionalAlbedo(reflectance.coloredF0,vec3f(1.0),b,openPBRBrdf);let F_avg: vec3f=getF82AverageFresnel(reflectance.coloredF0,b);let ECF: vec3f =vec3f(1.0)+F_avg*(vec3f(1.0)/openPBRBrdf.y-vec3f(1.0));return clamp(E_F82*ECF,vec3f(0.0),vec3f(1.0));
#else
return getReflectanceFromBRDFLookup(reflectance.coloredF0,reflectance.coloredF90,environmentBrdf);
#endif
}
#endif
`;x.IncludesShadersStoreWGSL[M7]||(x.IncludesShadersStoreWGSL[M7]=W_e)});var y7,H_e,Vw=y(()=>{k();y7="openpbrSubsurfaceLayerData",H_e=`var subsurface_weight: f32=uniforms.vSubsurfaceWeight;var subsurface_color: vec3f=uniforms.vSubsurfaceColor.rgb;var subsurface_radius: f32=uniforms.vSubsurfaceRadius;var subsurface_radius_scale: vec3f=uniforms.vSubsurfaceRadiusScale;var subsurface_scatter_anisotropy: f32=clamp(uniforms.vSubsurfaceScatterAnisotropy,-0.9999f,0.9999f);
#ifdef SUBSURFACE_WEIGHT
let subsurfaceWeightFromTexture: vec4f=textureSample(subsurfaceWeightSampler,subsurfaceWeightSamplerSampler,fragmentInputs.vSubsurfaceWeightUV+uvOffset);
#endif
#ifdef SUBSURFACE_COLOR
let subsurfaceColorFromTexture: vec4f=textureSample(subsurfaceColorSampler,subsurfaceColorSamplerSampler,fragmentInputs.vSubsurfaceColorUV+uvOffset);
#endif
#ifdef SUBSURFACE_RADIUS_SCALE
let subsurfaceRadiusScaleFromTexture: vec4f=textureSample(subsurfaceRadiusScaleSampler,subsurfaceRadiusScaleSamplerSampler,fragmentInputs.vSubsurfaceRadiusScaleUV+uvOffset);
#endif
#ifdef SUBSURFACE_WEIGHT
subsurface_weight*=subsurfaceWeightFromTexture.r;
#endif
#ifdef SUBSURFACE_COLOR
#ifdef SUBSURFACE_COLOR_GAMMA
subsurface_color*=toLinearSpaceVec3(subsurfaceColorFromTexture.rgb);
#else
subsurface_color*=subsurfaceColorFromTexture.rgb;
#endif
subsurface_color*=uniforms.vSubsurfaceColorInfos.y;
#endif
#ifdef SUBSURFACE_RADIUS_SCALE
subsurface_radius_scale*=subsurfaceRadiusScaleFromTexture.rgb;
#endif
`;x.IncludesShadersStoreWGSL[y7]||(x.IncludesShadersStoreWGSL[y7]=H_e)});var I7,X_e,Gw=y(()=>{k();I7="openpbrTransmissionLayerData",X_e=`var transmission_weight: f32=uniforms.vTransmissionWeight;var transmission_color: vec3f=uniforms.vTransmissionColor.rgb;var transmission_depth: f32=uniforms.vTransmissionDepth;var transmission_scatter: vec3f=uniforms.vTransmissionScatter.rgb;var transmission_scatter_anisotropy: f32=clamp(uniforms.vTransmissionScatterAnisotropy,-0.9999f,0.9999f);var transmission_dispersion_scale: f32=uniforms.vTransmissionDispersionScale;var transmission_dispersion_abbe_number: f32=uniforms.vTransmissionDispersionAbbeNumber;
#ifdef TRANSMISSION_WEIGHT
let transmissionWeightFromTexture: vec4f=textureSample(transmissionWeightSampler,transmissionWeightSamplerSampler,fragmentInputs.vTransmissionWeightUV+uvOffset);
#endif
#ifdef TRANSMISSION_COLOR
let transmissionColorFromTexture: vec4f=textureSample(transmissionColorSampler,transmissionColorSamplerSampler,fragmentInputs.vTransmissionColorUV+uvOffset);
#endif
#ifdef TRANSMISSION_DEPTH
let transmissionDepthFromTexture: vec4f=textureSample(transmissionDepthSampler,transmissionDepthSamplerSampler,fragmentInputs.vTransmissionDepthUV+uvOffset);
#endif
#ifdef TRANSMISSION_SCATTER
let transmissionScatterFromTexture: vec4f=textureSample(transmissionScatterSampler,transmissionScatterSamplerSampler,fragmentInputs.vTransmissionScatterUV+uvOffset);
#endif
#ifdef TRANSMISSION_DISPERSION_SCALE
let transmissionDispersionScaleFromTexture: vec4f=textureSample(transmissionDispersionScaleSampler,transmissionDispersionScaleSamplerSampler,fragmentInputs.vTransmissionDispersionScaleUV+uvOffset);
#endif
#ifdef TRANSMISSION_WEIGHT
transmission_weight*=transmissionWeightFromTexture.r;
#endif
#ifdef TRANSMISSION_COLOR
#ifdef TRANSMISSION_COLOR_GAMMA
transmission_color*=toLinearSpace(transmissionColorFromTexture.rgb);
#else
transmission_color*=transmissionColorFromTexture.rgb;
#endif
transmission_color*=uniforms.vTransmissionColorInfos.y;
#endif
#ifdef TRANSMISSION_DEPTH
transmission_depth*=transmissionDepthFromTexture.r;
#endif
#ifdef TRANSMISSION_SCATTER
transmission_scatter*=transmissionScatterFromTexture.rgb;
#endif
#ifdef TRANSMISSION_DISPERSION_SCALE
transmission_dispersion_scale*=transmissionDispersionScaleFromTexture.r;
#endif
`;x.IncludesShadersStoreWGSL[I7]||(x.IncludesShadersStoreWGSL[I7]=X_e)});var P7={};Be(P7,{geometryPixelShaderWGSL:()=>Y_e});var kw,C7,Y_e,L7=y(()=>{k();qc();Qb();$b();ao();iy();sh();Eg();Fw();ry();gE();Bw();Uw();oh();Qc();Jb();Vw();Gw();kw="geometryPixelShader",C7=`#ifdef BUMP
varying vWorldView0: vec4f;varying vWorldView1: vec4f;varying vWorldView2: vec4f;varying vWorldView3: vec4f;varying vNormalW: vec3f;
#else
varying vNormalV: vec3f;
#endif
varying vViewPos: vec4f;
#if defined(POSITION) || defined(BUMP) || defined(IRRADIANCE)
varying vPositionW: vec3f;
#endif
#if defined(VELOCITY) || defined(VELOCITY_LINEAR)
varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;
#endif
#ifdef NEED_UV
varying vUV: vec2f;
#endif
#ifdef BUMP
uniform vBumpInfos: vec3f;uniform vTangentSpaceParams: vec2f;
#endif
#if defined(REFLECTIVITY)
#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)
var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d<f32>;varying vReflectivityUV: vec2f;
#else
#ifdef METALLIC_TEXTURE
var metallicSamplerSampler: sampler;var metallicSampler: texture_2d<f32>;varying vMetallicUV: vec2f;
#endif
#ifdef ROUGHNESS_TEXTURE
var roughnessSamplerSampler: sampler;var roughnessSampler: texture_2d<f32>;varying vRoughnessUV: vec2f;
#endif
#endif
#ifdef ALBEDOTEXTURE
varying vAlbedoUV: vec2f;var albedoSamplerSampler: sampler;var albedoSampler: texture_2d<f32>;
#endif
#ifdef REFLECTIVITYCOLOR
uniform reflectivityColor: vec3f;
#endif
#ifdef ALBEDOCOLOR
uniform albedoColor: vec3f;
#endif
#ifdef METALLIC
uniform metallic: f32;
#endif
#if defined(ROUGHNESS) || defined(GLOSSINESS)
uniform glossiness: f32;
#endif
#endif
#if defined(ALPHATEST) && defined(NEED_UV)
var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d<f32>;
#endif
#include<clipPlaneFragmentDeclaration>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#include<helperFunctions>
#ifdef IRRADIANCE
#include<pbrFragmentReflectionDeclaration>
#ifdef REFLECTION
#ifdef USEIRRADIANCEMAP
#include<sceneUboDeclaration>
uniform reflectionMatrix: mat4x4f;uniform vReflectionInfos: vec2f;uniform vReflectionDominantDirection: vec3f;
#include<pbrBRDFFunctions>
#include<openpbrDielectricReflectance>
#include<pbrIBLFunctions>
#include<reflectionFunction>
#include<openpbrGeometryInfo>
#include<openpbrIblFunctions>
#elif defined(USESPHERICALFROMREFLECTIONMAP)
varying vEnvironmentIrradiance: vec3f;
#endif
#ifdef IBL_SHADOW_TEXTURE
var iblShadowSampler: texture_2d<f32>;var iblShadowSamplerSampler: sampler;uniform shadowTextureSize: vec2f;
#endif
#ifdef IRRADIANCE_SCATTER_MASK
uniform vSubsurfaceWeight: f32;
#include<samplerFragmentDeclaration>(_DEFINENAME_,SUBSURFACE_WEIGHT,_VARYINGNAME_,SubsurfaceWeight,_SAMPLERNAME_,subsurfaceWeight)
uniform vSubsurfaceScatterAnisotropy: f32;uniform vTransmissionWeight: f32;
#include<samplerFragmentDeclaration>(_DEFINENAME_,TRANSMISSION_WEIGHT,_VARYINGNAME_,TransmissionWeight,_SAMPLERNAME_,transmissionWeight)
uniform vTransmissionScatterAnisotropy: f32;
#endif
#endif
#endif
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;}
#endif
var normalOutput: vec3f;
#ifdef BUMP
var normalW: vec3f=normalize(input.vNormalW);
#include<bumpFragment>
#ifdef NORMAL_WORLDSPACE
normalOutput=normalW;
#else
normalOutput=normalize( (mat4x4f(input.vWorldView0,input.vWorldView1,input.vWorldView2,input.vWorldView3)* vec4f(normalW,0.0)).xyz);
#endif
#elif defined(HAS_NORMAL_ATTRIBUTE)
normalOutput=normalize(input.vNormalV);
#elif defined(POSITION)
normalOutput=normalize(-cross(dpdx(input.vPositionW),dpdy(input.vPositionW)));
#endif
#ifdef ENCODE_NORMAL
normalOutput=normalOutput*0.5+0.5;
#endif
var fragData: array<vec4<f32>,SCENE_MRT_COUNT>;
#ifdef DEPTH
fragData[DEPTH_INDEX]=vec4f(input.vViewPos.z/input.vViewPos.w,0.0,0.0,1.0);
#endif
#ifdef NORMAL
fragData[NORMAL_INDEX]=vec4f(normalOutput,1.0);
#endif
#ifdef SCREENSPACE_DEPTH
fragData[SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,1.0);
#endif
#ifdef POSITION
fragData[POSITION_INDEX]= vec4f(input.vPositionW,1.0);
#endif
#ifdef VELOCITY
var a: vec2f=(input.vCurrentPosition.xy/input.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(input.vPreviousPosition.xy/input.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[VELOCITY_INDEX]= vec4f(velocity,0.0,1.0);
#endif
#ifdef VELOCITY_LINEAR
var velocity : vec2f=vec2f(0.5)*((input.vPreviousPosition.xy /
input.vPreviousPosition.w) -
(input.vCurrentPosition.xy /
input.vCurrentPosition.w));fragData[VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,1.0);
#endif
#ifdef REFLECTIVITY
var reflectivity: vec4f= vec4f(0.0,0.0,0.0,1.0);
#ifdef METALLICWORKFLOW
var metal: f32=1.0;var roughness: f32=1.0;
#ifdef ORMTEXTURE
metal*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).b;roughness*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).g;
#else
#ifdef METALLIC_TEXTURE
metal*=textureSample(metallicSampler,metallicSamplerSampler,input.vMetallicUV).r;
#endif
#ifdef ROUGHNESS_TEXTURE
roughness*=textureSample(roughnessSampler,roughnessSamplerSampler,input.vRoughnessUV).r;
#endif
#endif
#ifdef METALLIC
metal*=uniforms.metallic;
#endif
#ifdef ROUGHNESS
roughness*=(1.0-uniforms.glossiness);
#endif
reflectivity=vec4f(reflectivity.rgb,reflectivity.a-roughness);var color: vec3f= vec3f(1.0);
#ifdef ALBEDOTEXTURE
color=textureSample(albedoSampler,albedoSamplerSampler,input.vAlbedoUV).rgb;
#ifdef GAMMAALBEDO
color=toLinearSpaceVec4(color);
#endif
#endif
#ifdef ALBEDOCOLOR
color*=uniforms.albedoColor.xyz;
#endif
reflectivity=vec4f(mix( vec3f(0.04),color,metal),reflectivity.a);
#else
#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)
reflectivity=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV);
#ifdef GAMMAREFLECTIVITYTEXTURE
reflectivity=vec4f(toLinearSpaceVec3(reflectivity.rgb),reflectivity.a);
#endif
#else
#ifdef REFLECTIVITYCOLOR
reflectivity=vec4f(toLinearSpaceVec3(uniforms.reflectivityColor.xyz),1.0);
#endif
#endif
#ifdef GLOSSINESSS
reflectivity=vec4f(reflectivity.rgb,reflectivity.a*glossiness);
#endif
#endif
fragData[REFLECTIVITY_INDEX]=reflectivity;
#endif
#ifdef IRRADIANCE
var irradiance: vec3f=vec3f(0.0);var irradiance_alpha: f32=1.0;
#ifdef REFLECTION
#ifdef IRRADIANCE_SCATTER_MASK
var vSubsurfaceColor: vec3f=vec3f(1.0);var vSubsurfaceRadius: f32=0.0;var vSubsurfaceRadiusScale: vec3f=vec3f(1.0);
#include<openpbrSubsurfaceLayerData>(uniforms.vSubsurfaceColor,vSubsurfaceColor,uniforms.vSubsurfaceRadius,vSubsurfaceRadius,uniforms.vSubsurfaceRadiusScale,vSubsurfaceRadiusScale)
var vTransmissionDepth: f32=1.0;var vTransmissionColor: vec3f=vec3f(1.0);var vTransmissionScatter: vec3f=vec3f(0.0);var vTransmissionDispersionScale: f32=0.0;var vTransmissionDispersionAbbeNumber: f32=0.0;
#include<openpbrTransmissionLayerData>(uniforms.vTransmissionDispersionScale,vTransmissionDispersionScale,uniforms.vTransmissionDispersionAbbeNumber,vTransmissionDispersionAbbeNumber,uniforms.vTransmissionColor,vTransmissionColor,uniforms.vTransmissionDepth,vTransmissionDepth,uniforms.vTransmissionScatter\\.,vTransmissionScatter.)
#endif
#ifdef IBL_SHADOW_TEXTURE
#ifdef COLORED_IBL_SHADOWS
let iblShadowValue: vec3f=textureSample(iblShadowSampler,iblShadowSamplerSampler,fragmentInputs.position.xy/uniforms.shadowTextureSize).rgb;
#else
let iblShadowValue: vec3f=vec3f(textureSample(iblShadowSampler,iblShadowSamplerSampler,fragmentInputs.position.xy/uniforms.shadowTextureSize).r);
#endif
#endif
#if defined(USEIRRADIANCEMAP)
#ifdef IRRADIANCE_SCATTER_MASK
let bendAmount: f32=subsurface_weight*-min(subsurface_scatter_anisotropy,0.0);let mixedBendAmount: f32=mix(bendAmount,-min(transmission_scatter_anisotropy,0.0),transmission_weight);let viewVector: vec3f=normalize(scene.vEyePosition.xyz-input.vPositionW);let bentNormal: vec3f=mix(normalOutput,viewVector,mixedBendAmount*dot(normalOutput,viewVector));
#else
let bentNormal: vec3f=normalOutput;
#endif
irradiance=sampleIrradiance(
bentNormal
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,input.vEnvironmentIrradiance
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,uniforms.reflectionMatrix
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
,irradianceSamplerSampler
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
,uniforms.vReflectionDominantDirection
#endif
#endif
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
,icdfSamplerSampler
#endif
#endif
,uniforms.vReflectionInfos
,input.vViewPos.xyz
,1.0
,vec3f(1.0)
);
#elif defined(USESPHERICALFROMREFLECTIONMAP)
irradiance=input.vEnvironmentIrradiance;
#endif
#ifdef IBL_SHADOW_TEXTURE
irradiance*=iblShadowValue;
#endif
#ifndef BUMP
let uvOffset: vec2f=vec2f(0.0);
#endif
#ifdef IRRADIANCE_SCATTER_MASK
irradiance_alpha=min(subsurface_weight+transmission_weight,1.0);
#endif
#endif
fragData[IRRADIANCE_INDEX]=vec4f(irradiance,irradiance_alpha);
#endif
#if SCENE_MRT_COUNT>0
fragmentOutputs.fragData0=fragData[0];
#endif
#if SCENE_MRT_COUNT>1
fragmentOutputs.fragData1=fragData[1];
#endif
#if SCENE_MRT_COUNT>2
fragmentOutputs.fragData2=fragData[2];
#endif
#if SCENE_MRT_COUNT>3
fragmentOutputs.fragData3=fragData[3];
#endif
#if SCENE_MRT_COUNT>4
fragmentOutputs.fragData4=fragData[4];
#endif
#if SCENE_MRT_COUNT>5
fragmentOutputs.fragData5=fragData[5];
#endif
#if SCENE_MRT_COUNT>6
fragmentOutputs.fragData6=fragData[6];
#endif
#if SCENE_MRT_COUNT>7
fragmentOutputs.fragData7=fragData[7];
#endif
}
`;x.ShadersStoreWGSL[kw]||(x.ShadersStoreWGSL[kw]=C7);Y_e={name:kw,shader:C7}});var D7,zw,ws,O7=y(()=>{He();qi();Kr();q9();$t();Mn();ls();Dw();Nw();co();Hl();os();Rw();D7=["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler","transmissionWeightSampler","subsurfaceWeightSampler","iblShadowSampler"],zw=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","reflectionMatrix","vTransmissionWeight","vSubsurfaceWeight","vEyePosition","vTransmissionScatterAnisotropy","vSubsurfaceScatterAnisotropy","shadowTextureSize","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureInfo"];md(zw,D7,!0);ns(zw);ws=class n{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add(()=>{}))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enableDepth=!0,this._enableNormal=!0,this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._enableVelocityLinear=!1,this._enableScreenspaceDepth=!1,this._enableIrradiance=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===n.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===n.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===n.VELOCITY_LINEAR_TEXTURE_TYPE?(this._velocityLinearIndex=t,this._enableVelocityLinear=!0):e===n.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===n.DEPTH_TEXTURE_TYPE?(this._depthIndex=t,this._enableDepth=!0):e===n.NORMAL_TEXTURE_TYPE?(this._normalIndex=t,this._enableNormal=!0):e===n.SCREENSPACE_DEPTH_TEXTURE_TYPE?(this._screenspaceDepthIndex=t,this._enableScreenspaceDepth=!0):e===n.IRRADIANCE_TEXTURE_TYPE&&(this._irradianceIndex=t,this._enableIrradiance=!0)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case n.POSITION_TEXTURE_TYPE:return this._positionIndex;case n.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case n.VELOCITY_LINEAR_TEXTURE_TYPE:return this._velocityLinearIndex;case n.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case n.DEPTH_TEXTURE_TYPE:return this._depthIndex;case n.NORMAL_TEXTURE_TYPE:return this._normalIndex;case n.SCREENSPACE_DEPTH_TEXTURE_TYPE:return this._screenspaceDepthIndex;case n.IRRADIANCE_TEXTURE_TYPE:return this._irradianceIndex;default:return-1}}get enableDepth(){return this._enableDepth}set enableDepth(e){this._enableDepth=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableNormal(){return this._enableNormal}set enableNormal(e){this._enableNormal=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableVelocityLinear(){return this._enableVelocityLinear}set enableVelocityLinear(e){this._enableVelocityLinear=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableScreenspaceDepth(){return this._enableScreenspaceDepth}set enableScreenspaceDepth(e){this._enableScreenspaceDepth=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableIrradiance(){return this._enableIrradiance}set enableIrradiance(e){this._enableIrradiance=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return typeof this._ratioOrDimensions=="object"?1:this._ratioOrDimensions}get shaderLanguage(){return this._shaderLanguage}constructor(e,t=1,i=15,r){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enableDepth=!0,this._enableNormal=!0,this._enablePosition=!1,this._enableVelocity=!1,this._enableVelocityLinear=!1,this._enableReflectivity=!1,this._enableScreenspaceDepth=!1,this._enableIrradiance=!1,this._clearColor=new ht(0,0,0,0),this._clearDepthColor=new ht(0,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._velocityLinearIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._screenspaceDepthIndex=-1,this._irradianceIndex=-1,this._linkedWithPrePass=!1,this.generateIrradianceWithScatterMask=!1,this.useSpecificClearForDepthTexture=!1,this._shaderLanguage=0,this._shadersLoaded=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=r||{},this._initShaderSourceAsync(),n._SceneComponentInitialization(this._scene),this._createRenderTargets()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU&&!n.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Promise.resolve().then(()=>(S7(),E7)),Promise.resolve().then(()=>(L7(),P7))])):await Promise.all([Promise.resolve().then(()=>(Nw(),g7)),Promise.resolve().then(()=>(Dw(),c7))]),this._shadersLoaded=!0}isReady(e,t){if(!this._shadersLoaded)return!1;let i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;let r=[],s=[D.PositionKind],a=e.getMesh();a.isVerticesDataPresent(D.NormalKind)&&(r.push("#define HAS_NORMAL_ATTRIBUTE"),s.push(D.NormalKind));let l=!1,c=!1,f=!1;if(i){let p=!1;if(i.needAlphaTestingForMesh(a)&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),p=!0),(i.bumpTexture||i.normalTexture||i.geometryNormalTexture)&&fe.BumpTextureEnabled){let _=i.bumpTexture||i.normalTexture||i.geometryNormalTexture;r.push("#define BUMP"),r.push(`#define BUMP_UV${_.coordinatesIndex+1}`),p=!0}if(this._enableReflectivity){let _=!1;if(i.getClassName()==="PBRMetallicRoughnessMaterial")i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),p=!0,_=!0),i.metallic!=null&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),_=!0),i.roughness!=null&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),_=!0),_&&(i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),p=!0),i.baseColor&&r.push("#define ALBEDOCOLOR"));else if(i.getClassName()==="PBRSpecularGlossinessMaterial")i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),p=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),i.glossiness!=null&&r.push("#define GLOSSINESS");else if(i.getClassName()==="PBRMaterial")i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),p=!0,_=!0),i.metallic!=null&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),_=!0),i.roughness!=null&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),_=!0),_?(i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),p=!0),i.albedoColor&&r.push("#define ALBEDOCOLOR")):(i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),p=!0):i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),i.microSurface!=null&&r.push("#define GLOSSINESS"));else if(i.getClassName()==="StandardMaterial")i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),p=!0),i.specularColor&&r.push("#define REFLECTIVITYCOLOR");else if(i.getClassName()==="OpenPBRMaterial"){let v=i;r.push("#define METALLIC"),r.push("#define ROUGHNESS"),v._useRoughnessFromMetallicTextureGreen&&v.baseMetalnessTexture?(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${v.baseMetalnessTexture.coordinatesIndex+1}`),p=!0):v.baseMetalnessTexture?(r.push("#define METALLIC_TEXTURE"),r.push(`#define METALLIC_UV${v.baseMetalnessTexture.coordinatesIndex+1}`),p=!0):v.specularRoughnessTexture&&(r.push("#define ROUGHNESS_TEXTURE"),r.push(`#define ROUGHNESS_UV${v.specularRoughnessTexture.coordinatesIndex+1}`),p=!0),v.baseColorTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${v.baseColorTexture.coordinatesIndex+1}`),v.baseColorTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),p=!0),v.baseColor&&r.push("#define ALBEDOCOLOR")}}if(this._enableIrradiance&&this.generateIrradianceWithScatterMask&&(r.push("#define IRRADIANCE_SCATTER_MASK"),i.getClassName()==="OpenPBRMaterial")){let _=i;_.subsurfaceWeight>0&&_.subsurfaceWeightTexture&&(r.push("#define SUBSURFACE_WEIGHT"),r.push(`#define SUBSURFACEWEIGHT_UV${_.subsurfaceWeightTexture.coordinatesIndex+1}`),p=!0),_.transmissionWeight>0&&_.transmissionWeightTexture&&(r.push("#define TRANSMISSION_WEIGHT"),r.push(`#define TRANSMISSIONWEIGHT_UV${_.transmissionWeightTexture.coordinatesIndex+1}`),p=!0)}p&&(r.push("#define NEED_UV"),a.isVerticesDataPresent(D.UVKind)&&(s.push(D.UVKind),r.push("#define UV1"),l=!0),a.isVerticesDataPresent(D.UV2Kind)&&(s.push(D.UV2Kind),r.push("#define UV2"),c=!0))}if(this._enableDepth&&(r.push("#define DEPTH"),r.push("#define DEPTH_INDEX "+this._depthIndex)),this._enableNormal&&(r.push("#define NORMAL"),r.push("#define NORMAL_INDEX "+this._normalIndex)),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),this.excludedSkinnedMeshesFromVelocity.indexOf(a)===-1&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableVelocityLinear&&(r.push("#define VELOCITY_LINEAR"),r.push("#define VELOCITY_LINEAR_INDEX "+this._velocityLinearIndex),this.excludedSkinnedMeshesFromVelocity.indexOf(a)===-1&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this._enableScreenspaceDepth&&this._screenspaceDepthIndex!==-1&&(r.push("#define SCREENSPACE_DEPTH_INDEX "+this._screenspaceDepthIndex),r.push("#define SCREENSPACE_DEPTH")),this._enableIrradiance&&this._irradianceIndex!==-1){r.push("#define IRRADIANCE_INDEX "+this._irradianceIndex),r.push("#define IRRADIANCE");let p=this._scene;if(p.environmentTexture){let _={},v=!1,E=0;(i.getClassName()==="OpenPBRMaterial"||i.getClassName()==="StandardMaterial"||i.getClassName()==="PBRMetallicRoughnessMaterial"||i.getClassName()==="PBRSpecularGlossinessMaterial"||i.getClassName()==="PBRMaterial")&&(v=!!i.realtimeFiltering,E=i.realtimeFilteringQuality||0),hd(p,p.environmentTexture,_,v,E,!0);for(let T in _)_[T]&&r.push("#define "+T);_.USEIRRADIANCEMAP||r.push("#define SPHERICAL_HARMONICS");let S=p.postProcessRenderPipelineManager.supportedPipelines.find(T=>T.getClassName()==="IBLShadowsRenderPipeline");if(S){let T=S;T._getAccumulatedTexture()&&(r.push("#define IBL_SHADOW_TEXTURE"),T.coloredShadows&&r.push("#define COLORED_IBL_SHADOWS"))}}}this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&r.push("#define ENCODE_NORMAL"),a.useBones&&a.computeBonesUsingShaders&&a.skeleton?(s.push(D.MatricesIndicesKind),s.push(D.MatricesWeightsKind),a.numBoneInfluencers>4&&(s.push(D.MatricesIndicesExtraKind),s.push(D.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),r.push("#define BONETEXTURE "+a.skeleton.isUsingTextureForMatrices),r.push("#define BonesPerMesh "+(a.skeleton.bones.length+1))):(r.push("#define NUM_BONE_INFLUENCERS 0"),r.push("#define BONETEXTURE false"),r.push("#define BonesPerMesh 0"));let d=a.morphTargetManager?Xl(a.morphTargetManager,r,s,a,!0,!0,!1,l,c,f):0;t&&(r.push("#define INSTANCES"),Qo(s,this._enableVelocity||this._enableVelocityLinear),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define SCENE_MRT_COUNT "+this._attachmentsFromPrePass.length):r.push("#define SCENE_MRT_COUNT "+this._multiRenderTarget.textures.length),Wl(i,this._scene,r);let u=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),m=h.defines,g=r.join(`
`);return m!==g&&h.setEffect(u.createEffect("geometry",{attributes:s,uniformsNames:zw,samplers:D7,defines:g,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:d},shaderLanguage:this.shaderLanguage},u),g),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){var e,t;this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),(e=this._multiRenderTarget)!=null&&e.renderTarget&&this.scene.getEngine()._currentRenderTarget===this._multiRenderTarget.renderTarget&&this.scene.getEngine().unBindFramebuffer((t=this._multiRenderTarget)==null?void 0:t.renderTarget),this.getGBuffer().dispose()}_assignRenderTargetIndices(){let e=[],t=[],i=0;return this._enableDepth&&(this._depthIndex=i,i++,e.push("gBuffer_Depth"),t.push(this._textureTypesAndFormats[n.DEPTH_TEXTURE_TYPE])),this._enableNormal&&(this._normalIndex=i,i++,e.push("gBuffer_Normal"),t.push(this._textureTypesAndFormats[n.NORMAL_TEXTURE_TYPE])),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[n.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[n.VELOCITY_TEXTURE_TYPE])),this._enableVelocityLinear&&(this._velocityLinearIndex=i,i++,e.push("gBuffer_VelocityLinear"),t.push(this._textureTypesAndFormats[n.VELOCITY_LINEAR_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[n.REFLECTIVITY_TEXTURE_TYPE])),this._enableScreenspaceDepth&&(this._screenspaceDepthIndex=i,i++,e.push("gBuffer_ScreenspaceDepth"),t.push(this._textureTypesAndFormats[n.SCREENSPACE_DEPTH_TEXTURE_TYPE])),this._enableIrradiance&&(this._irradianceIndex=i,i++,e.push("gBuffer_Irradiance"),t.push(this._textureTypesAndFormats[n.IRRADIANCE_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){var _;let e=this._scene.getEngine(),[t,i,r]=this._assignRenderTargetIndices(),s=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?s=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(s=2);let a=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],l=[],c=[];for(let v of r)v?(o.push(v.textureType),l.push(v.textureFormat),c.push((_=v.samplingMode)!=null?_:2)):(o.push(s),l.push(5),c.push(2));if(this._normalsAreUnsigned=o[n.NORMAL_TEXTURE_TYPE]===11||o[n.NORMAL_TEXTURE_TYPE]===13,this._multiRenderTarget=new JM("gBuffer",a,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:l,samplingModes:c,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=_e.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=_e.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;let f=[!0],d=[!1],u=[!0];for(let v=1;v<t;++v)f.push(!0),u.push(!1),d.push(!0);let h=e.buildTextureLayout(f),m=e.buildTextureLayout(d),g=e.buildTextureLayout(u);this._multiRenderTarget.onClearObservable.add(v=>{v.bindAttachments(this.useSpecificClearForDepthTexture?m:h),v.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(v.bindAttachments(g),v.clear(this._clearDepthColor,!0,!0,!0)),v.bindAttachments(h)}),this._resizeObserver=e.onResizeObservable.add(()=>{if(this._multiRenderTarget){let v=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(v)}});let p=v=>{let E=v.getRenderingMesh(),S=v.getEffectiveMesh(),T=this._scene,A=T.getEngine(),R=v.getMaterial();if(!R)return;if(S._internalAbstractMeshDataInfo._isActiveIntermediate=!1,(this._enableVelocity||this._enableVelocityLinear)&&!this._previousTransformationMatrices[S.uniqueId]&&(this._previousTransformationMatrices[S.uniqueId]={world:Q.Identity(),viewProjection:T.getTransformMatrix()},E.skeleton)){let L=E.skeleton.getTransformMatrices(E);this._previousBonesTransformationMatrices[E.uniqueId]=this._copyBonesTransformationMatrices(L,new Float32Array(L.length))}let M=E._getInstancesRenderList(v._id,!!v.getReplacementMesh());if(M.mustReturn)return;let I=A.getCaps().instancedArrays&&(M.visibleInstances[v._id]!==null||E.hasThinInstances),C=S.getWorldMatrix();if(this.isReady(v,I)){let L=v._getDrawWrapper();if(!L)return;let w=L.effect;A.enableEffect(L),I||E._bind(v,w,R.fillMode),this._useUbo?(ud(w,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(w.setMatrix("viewProjection",T.getTransformMatrix()),w.setMatrix("view",T.getViewMatrix()),this._scene.bindEyePosition(w,"vEyePosition"));let G;if(!E._instanceDataStorage.isFrozen&&(R.backFaceCulling||R.sideOrientation!==null)){let N=S._getWorldMatrixDeterminant();G=R._getEffectiveOrientation(E),N<0&&(G=G===Ae.ClockWiseSideOrientation?Ae.CounterClockWiseSideOrientation:Ae.ClockWiseSideOrientation)}else G=E._effectiveSideOrientation;if(R._preBind(L,G),R.needAlphaTestingForMesh(S)){let N=R.getAlphaTestTexture();N&&(w.setTexture("diffuseSampler",N),w.setMatrix("diffuseMatrix",N.getTextureMatrix()))}if((R.bumpTexture||R.normalTexture||R.geometryNormalTexture)&&T.getEngine().getCaps().standardDerivatives&&fe.BumpTextureEnabled){let N=R.bumpTexture||R.normalTexture||R.geometryNormalTexture;w.setFloat3("vBumpInfos",N.coordinatesIndex,1/N.level,R.parallaxScaleBias),w.setMatrix("bumpMatrix",N.getTextureMatrix()),w.setTexture("bumpSampler",N),w.setFloat2("vTangentSpaceParams",R.invertNormalMapX?-1:1,R.invertNormalMapY?-1:1)}if(this._enableReflectivity){if(R.getClassName()==="PBRMetallicRoughnessMaterial")R.metallicRoughnessTexture!==null&&(w.setTexture("reflectivitySampler",R.metallicRoughnessTexture),w.setMatrix("reflectivityMatrix",R.metallicRoughnessTexture.getTextureMatrix())),R.metallic!==null&&w.setFloat("metallic",R.metallic),R.roughness!==null&&w.setFloat("glossiness",1-R.roughness),R.baseTexture!==null&&(w.setTexture("albedoSampler",R.baseTexture),w.setMatrix("albedoMatrix",R.baseTexture.getTextureMatrix())),R.baseColor!==null&&w.setColor3("albedoColor",R.baseColor);else if(R.getClassName()==="PBRSpecularGlossinessMaterial")R.specularGlossinessTexture!==null?(w.setTexture("reflectivitySampler",R.specularGlossinessTexture),w.setMatrix("reflectivityMatrix",R.specularGlossinessTexture.getTextureMatrix())):R.specularColor!==null&&w.setColor3("reflectivityColor",R.specularColor),R.glossiness!==null&&w.setFloat("glossiness",R.glossiness);else if(R.getClassName()==="PBRMaterial")R.metallicTexture!==null&&(w.setTexture("reflectivitySampler",R.metallicTexture),w.setMatrix("reflectivityMatrix",R.metallicTexture.getTextureMatrix())),R.metallic!==null&&w.setFloat("metallic",R.metallic),R.roughness!==null&&w.setFloat("glossiness",1-R.roughness),R.roughness!==null||R.metallic!==null||R.metallicTexture!==null?(R.albedoTexture!==null&&(w.setTexture("albedoSampler",R.albedoTexture),w.setMatrix("albedoMatrix",R.albedoTexture.getTextureMatrix())),R.albedoColor!==null&&w.setColor3("albedoColor",R.albedoColor)):(R.reflectivityTexture!==null?(w.setTexture("reflectivitySampler",R.reflectivityTexture),w.setMatrix("reflectivityMatrix",R.reflectivityTexture.getTextureMatrix())):R.reflectivityColor!==null&&w.setColor3("reflectivityColor",R.reflectivityColor),R.microSurface!==null&&w.setFloat("glossiness",R.microSurface));else if(R.getClassName()==="StandardMaterial")R.specularTexture!==null&&(w.setTexture("reflectivitySampler",R.specularTexture),w.setMatrix("reflectivityMatrix",R.specularTexture.getTextureMatrix())),R.specularColor!==null&&w.setColor3("reflectivityColor",R.specularColor);else if(R.getClassName()==="OpenPBRMaterial"){let N=R;N._useRoughnessFromMetallicTextureGreen&&N.baseMetalnessTexture?(w.setTexture("reflectivitySampler",N.baseMetalnessTexture),w.setMatrix("reflectivityMatrix",N.baseMetalnessTexture.getTextureMatrix())):N.baseMetalnessTexture?(w.setTexture("metallicSampler",N.baseMetalnessTexture),w.setMatrix("metallicMatrix",N.baseMetalnessTexture.getTextureMatrix())):N.specularRoughnessTexture&&(w.setTexture("roughnessSampler",N.specularRoughnessTexture),w.setMatrix("roughnessMatrix",N.specularRoughnessTexture.getTextureMatrix())),w.setFloat("metallic",N.baseMetalness),w.setFloat("glossiness",1-N.specularRoughness),N.baseColorTexture!==null&&(w.setTexture("albedoSampler",N.baseColorTexture),w.setMatrix("albedoMatrix",N.baseColorTexture.getTextureMatrix())),N.baseColor!==null&&w.setColor3("albedoColor",N.baseColor)}}if(this._enableIrradiance&&T.environmentTexture){let N=T.environmentTexture,B=T.postProcessRenderPipelineManager.supportedPipelines.find(V=>V.getClassName()==="IBLShadowsRenderPipeline");if(B){let q=B._getAccumulatedTexture();q&&(w.setTexture("iblShadowSampler",q),w.setFloat2("shadowTextureSize",q.getSize().width,q.getSize().height))}if(w.setMatrix("reflectionMatrix",N.getReflectionTextureMatrix()),w.setFloat2("vReflectionInfos",N.level*T.iblIntensity,0),w.setTexture("reflectionSampler",N),N.irradianceTexture&&(w.setTexture("irradianceSampler",N.irradianceTexture),N.irradianceTexture._dominantDirection&&w.setVector3("vReflectionDominantDirection",N.irradianceTexture._dominantDirection)),N.sphericalPolynomial){let V=N.sphericalPolynomial;if(V.preScaledHarmonics){let q=V.preScaledHarmonics;w.setVector3("vSphericalL00",q.l00),w.setVector3("vSphericalL1_1",q.l1_1),w.setVector3("vSphericalL10",q.l10),w.setVector3("vSphericalL11",q.l11),w.setVector3("vSphericalL2_2",q.l2_2),w.setVector3("vSphericalL2_1",q.l2_1),w.setVector3("vSphericalL20",q.l20),w.setVector3("vSphericalL21",q.l21),w.setVector3("vSphericalL22",q.l22)}else w.setFloat3("vSphericalX",V.x.x,V.x.y,V.x.z),w.setFloat3("vSphericalY",V.y.x,V.y.y,V.y.z),w.setFloat3("vSphericalZ",V.z.x,V.z.y,V.z.z),w.setFloat3("vSphericalXX_ZZ",V.xx.x-V.zz.x,V.xx.y-V.zz.y,V.xx.z-V.zz.z),w.setFloat3("vSphericalYY_ZZ",V.yy.x-V.zz.x,V.yy.y-V.zz.y,V.yy.z-V.zz.z),w.setFloat3("vSphericalZZ",V.zz.x,V.zz.y,V.zz.z),w.setFloat3("vSphericalXY",V.xy.x,V.xy.y,V.xy.z),w.setFloat3("vSphericalYZ",V.yz.x,V.yz.y,V.yz.z),w.setFloat3("vSphericalZX",V.zx.x,V.zx.y,V.zx.z)}if(this.generateIrradianceWithScatterMask&&R.getClassName()==="OpenPBRMaterial"){let V=R;w.setFloat("vSubsurfaceWeight",V.subsurfaceWeight),V.subsurfaceWeightTexture&&(w.setTexture("subsurfaceWeightSampler",V.subsurfaceWeightTexture),w.setMatrix("subsurfaceWeightMatrix",V.subsurfaceWeightTexture.getTextureMatrix())),w.setFloat("vTransmissionWeight",V.transmissionWeight),V.transmissionWeightTexture&&(w.setTexture("transmissionWeightSampler",V.transmissionWeightTexture),w.setMatrix("transmissionWeightMatrix",V.transmissionWeightTexture.getTextureMatrix())),w.setFloat("vTransmissionScatterAnisotropy",V.transmissionScatterAnisotropy),w.setFloat("vSubsurfaceScatterAnisotropy",V.subsurfaceScatterAnisotropy)}}if(ss(w,R,this._scene),E.useBones&&E.computeBonesUsingShaders&&E.skeleton){let N=E.skeleton;if(N.isUsingTextureForMatrices&&w.getUniformIndex("boneTextureInfo")>-1){let B=N.getTransformMatrixTexture(E);w.setTexture("boneSampler",B),w.setFloat2("boneTextureInfo",N._textureWidth,N._textureHeight)}else w.setMatrices("mBones",E.skeleton.getTransformMatrices(E));(this._enableVelocity||this._enableVelocityLinear)&&w.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[E.uniqueId])}as(E,w),E.morphTargetManager&&E.morphTargetManager.isUsingTextureForTargets&&E.morphTargetManager._bind(w),(this._enableVelocity||this._enableVelocityLinear)&&(w.setMatrix("previousWorld",this._previousTransformationMatrices[S.uniqueId].world),w.setMatrix("previousViewProjection",this._previousTransformationMatrices[S.uniqueId].viewProjection)),I&&E.hasThinInstances&&w.setMatrix("world",C),E._processRendering(S,v,w,R.fillMode,M,I,(N,B)=>{N||w.setMatrix("world",B)})}(this._enableVelocity||this._enableVelocityLinear)&&(this._previousTransformationMatrices[S.uniqueId].world=C.clone(),this._previousTransformationMatrices[S.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),E.skeleton&&this._copyBonesTransformationMatrices(E.skeleton.getTransformMatrices(E),this._previousBonesTransformationMatrices[S.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(v,E,S)=>{if((S||E===0)&&v.subMeshes)for(let T=0;T<v.subMeshes.length;++T){let A=v.subMeshes[T],R=A.getMaterial(),M=A.getRenderingMesh();if(!R)continue;let I=M._getInstancesRenderList(A._id,!!A.getReplacementMesh()),C=e.getCaps().instancedArrays&&(I.visibleInstances[A._id]!==null||M.hasThinInstances);if(!this.isReady(A,C))return!1}return!0},this._multiRenderTarget.customRenderFunction=(v,E,S,T)=>{let A;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(T.length){for(e.setColorWrite(!1),A=0;A<T.length;A++)p(T.data[A]);e.setColorWrite(!0)}for(A=0;A<v.length;A++)p(v.data[A]);for(e.setDepthWrite(!1),A=0;A<E.length;A++)p(E.data[A]);if(this.renderTransparentMeshes)for(A=0;A<S.length;A++)p(S.data[A]);e.setDepthWrite(!0)}}_copyBonesTransformationMatrices(e,t){for(let i=0;i<e.length;i++)t[i]=e[i];return t}};ws.ForceGLSL=!1;ws.DEPTH_TEXTURE_TYPE=0;ws.NORMAL_TEXTURE_TYPE=1;ws.POSITION_TEXTURE_TYPE=2;ws.VELOCITY_TEXTURE_TYPE=3;ws.REFLECTIVITY_TEXTURE_TYPE=4;ws.SCREENSPACE_DEPTH_TEXTURE_TYPE=5;ws.VELOCITY_LINEAR_TEXTURE_TYPE=6;ws.IRRADIANCE_TEXTURE_TYPE=7;ws._SceneComponentInitialization=n=>{throw $e("GeometryBufferRendererSceneComponent")}});var N7,K_e,Ww=y(()=>{k();sh();pE();N7="openpbrUboDeclaration",K_e=`uniform vTangentSpaceParams: vec2f;uniform vLightingIntensity: vec4f;uniform pointSize: f32;uniform vDebugMode: vec2f;uniform renderTargetSize: vec2f;uniform cameraInfo: vec4f;uniform backgroundRefractionMatrix: mat4x4f;uniform vBackgroundRefractionInfos: vec3f;uniform vReflectionInfos: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vReflectionFilteringInfo: vec2f;uniform vReflectionDominantDirection: vec3f;uniform vReflectionColor: vec3f;uniform vSphericalL00: vec3f;uniform vSphericalL1_1: vec3f;uniform vSphericalL10: vec3f;uniform vSphericalL11: vec3f;uniform vSphericalL2_2: vec3f;uniform vSphericalL2_1: vec3f;uniform vSphericalL20: vec3f;uniform vSphericalL21: vec3f;uniform vSphericalL22: vec3f;uniform vSphericalX: vec3f;uniform vSphericalY: vec3f;uniform vSphericalZ: vec3f;uniform vSphericalXX_ZZ: vec3f;uniform vSphericalYY_ZZ: vec3f;uniform vSphericalZZ: vec3f;uniform vSphericalXY: vec3f;uniform vSphericalYZ: vec3f;uniform vSphericalZX: vec3f;uniform vBaseWeight: f32;uniform vBaseColor: vec4f;uniform vBaseDiffuseRoughness: f32;uniform vReflectanceInfo: vec4f;uniform vSpecularColor: vec4f;uniform vSpecularAnisotropy: vec3f;uniform vTransmissionWeight : f32;uniform vTransmissionColor : vec3f;uniform vTransmissionDepth : f32;uniform vTransmissionScatter : vec3f;uniform vTransmissionScatterAnisotropy : f32;uniform vTransmissionDispersionScale : f32;uniform vTransmissionDispersionAbbeNumber : f32;uniform vSubsurfaceWeight: f32;uniform vSubsurfaceColor: vec3f;uniform vSubsurfaceRadius: f32;uniform vSubsurfaceRadiusScale: vec3f;uniform vSubsurfaceScatterAnisotropy: f32;uniform vCoatWeight: f32;uniform vCoatColor: vec3f;uniform vCoatRoughness: f32;uniform vCoatRoughnessAnisotropy: f32;uniform vCoatIor: f32;uniform vCoatDarkening : f32;uniform vFuzzWeight: f32;uniform vFuzzColor: vec3f;uniform vFuzzRoughness: f32;uniform vGeometryThinWalled: f32;uniform vGeometryCoatTangent: vec2f;uniform vGeometryThickness: f32;uniform vEmissionColor: vec3f;uniform vThinFilmWeight: f32;uniform vThinFilmThickness: vec2f;uniform vThinFilmIor: f32;uniform vBaseWeightInfos: vec2f;uniform baseWeightMatrix: mat4x4f;uniform vBaseColorInfos: vec2f;uniform baseColorMatrix: mat4x4f;uniform vBaseDiffuseRoughnessInfos: vec2f;uniform baseDiffuseRoughnessMatrix: mat4x4f;uniform vBaseMetalnessInfos: vec2f;uniform baseMetalnessMatrix: mat4x4f;uniform vSpecularWeightInfos: vec2f;uniform specularWeightMatrix: mat4x4f;uniform vSpecularColorInfos: vec2f;uniform specularColorMatrix: mat4x4f;uniform vSpecularRoughnessInfos: vec2f;uniform specularRoughnessMatrix: mat4x4f;uniform vSpecularRoughnessAnisotropyInfos: vec2f;uniform specularRoughnessAnisotropyMatrix: mat4x4f;uniform vTransmissionWeightInfos : vec2f;uniform transmissionWeightMatrix : mat4x4f;uniform vTransmissionColorInfos : vec2f;uniform transmissionColorMatrix : mat4x4f;uniform vTransmissionDepthInfos : vec2f;uniform transmissionDepthMatrix : mat4x4f;uniform vTransmissionScatterInfos : vec2f;uniform transmissionScatterMatrix : mat4x4f;uniform vTransmissionDispersionScaleInfos : vec2f;uniform transmissionDispersionScaleMatrix : mat4x4f;uniform vSubsurfaceWeightInfos: vec2f;uniform subsurfaceWeightMatrix: mat4x4f;uniform vSubsurfaceColorInfos: vec2f;uniform subsurfaceColorMatrix: mat4x4f;uniform vSubsurfaceRadiusScaleInfos: vec2f;uniform subsurfaceRadiusScaleMatrix: mat4x4f;uniform vCoatWeightInfos: vec2f;uniform coatWeightMatrix: mat4x4f;uniform vCoatColorInfos: vec2f;uniform coatColorMatrix: mat4x4f;uniform vCoatRoughnessInfos: vec2f;uniform coatRoughnessMatrix: mat4x4f;uniform vCoatRoughnessAnisotropyInfos: vec2f;uniform coatRoughnessAnisotropyMatrix: mat4x4f;uniform vCoatDarkeningInfos : vec2f;uniform coatDarkeningMatrix : mat4x4f;uniform vFuzzWeightInfos: vec2f;uniform fuzzWeightMatrix: mat4x4f;uniform vFuzzColorInfos: vec2f;uniform fuzzColorMatrix: mat4x4f;uniform vFuzzRoughnessInfos: vec2f;uniform fuzzRoughnessMatrix: mat4x4f;uniform vGeometryNormalInfos: vec2f;uniform geometryNormalMatrix: mat4x4f;uniform vGeometryTangentInfos: vec2f;uniform geometryTangentMatrix: mat4x4f;uniform vGeometryCoatNormalInfos: vec2f;uniform geometryCoatNormalMatrix: mat4x4f;uniform vGeometryCoatTangentInfos: vec2f;uniform geometryCoatTangentMatrix: mat4x4f;uniform vGeometryOpacityInfos: vec2f;uniform geometryOpacityMatrix: mat4x4f;uniform vGeometryThicknessInfos: vec2f;uniform geometryThicknessMatrix: mat4x4f;uniform vEmissionInfos: vec2f;uniform emissionMatrix: mat4x4f;uniform vThinFilmWeightInfos: vec2f;uniform thinFilmWeightMatrix: mat4x4f;uniform vThinFilmThicknessInfos: vec2f;uniform thinFilmThicknessMatrix: mat4x4f;uniform vAmbientOcclusionInfos: vec2f;uniform ambientOcclusionMatrix: mat4x4f;
#define ADDITIONAL_UBO_DECLARATION
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;x.IncludesShadersStoreWGSL[N7]||(x.IncludesShadersStoreWGSL[N7]=K_e)});var w7,j_e,F7=y(()=>{k();w7="openpbrNormalMapVertexDeclaration",j_e=`#if defined(GEOMETRY_NORMAL) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(FUZZ)
#if defined(TANGENT) && defined(NORMAL)
varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f;
#endif
#endif
`;x.IncludesShadersStoreWGSL[w7]||(x.IncludesShadersStoreWGSL[w7]=j_e)});var B7,Z_e,U7=y(()=>{k();B7="openpbrNormalMapVertex",Z_e=`#if defined(GEOMETRY_NORMAL) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(FUZZ)
#if defined(TANGENT) && defined(NORMAL)
var tbnNormal: vec3f=normalize(normalUpdated);var tbnTangent: vec3f=normalize(tangentUpdated.xyz);var tbnBitangent: vec3f=cross(tbnNormal,tbnTangent)*tangentUpdated.w;var matTemp= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz)* mat3x3f(tbnTangent,tbnBitangent,tbnNormal);vertexOutputs.vTBN0=matTemp[0];vertexOutputs.vTBN1=matTemp[1];vertexOutputs.vTBN2=matTemp[2];
#endif
#endif
`;x.IncludesShadersStoreWGSL[B7]||(x.IncludesShadersStoreWGSL[B7]=Z_e)});var G7={};Be(G7,{openpbrVertexShaderWGSL:()=>q_e});var Hw,V7,q_e,k7=y(()=>{k();Ww();Ob();lg();ao();Eg();Wc();Hc();Rd();Nb();wb();vg();F7();Xc();eE();Fb();yd();Id();ah();Bb();Ub();Cd();Pd();Yc();Kc();jc();Vb();Gb();kb();U7();Zc();tE();Wb();iE();Hb();Hw="openpbrVertexShader",V7=`#define OPENPBR_VERTEX_SHADER
#include<openpbrUboDeclaration>
#define CUSTOM_VERTEX_BEGIN
#ifndef USE_VERTEX_PULLING
attribute position: vec3f;
#ifdef NORMAL
attribute normal: vec3f;
#endif
#ifdef TANGENT
attribute tangent: vec4f;
#endif
#ifdef UV1
attribute uv: vec2f;
#endif
#include<uvAttributeDeclaration>[2..7]
#ifdef VERTEXCOLOR
attribute color: vec4f;
#endif
#endif
#include<mainUVVaryingDeclaration>[1..7]
#include<helperFunctions>
#include<pbrBRDFFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<samplerVertexDeclaration>(_DEFINENAME_,BASE_COLOR,_VARYINGNAME_,BaseColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,BASE_METALNESS,_VARYINGNAME_,BaseMetalness)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR_WEIGHT,_VARYINGNAME_,SpecularWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR_COLOR,_VARYINGNAME_,SpecularColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR_ROUGHNESS,_VARYINGNAME_,SpecularRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR_ROUGHNESS_ANISOTROPY,_VARYINGNAME_,SpecularRoughnessAnisotropy)
#include<samplerVertexDeclaration>(_DEFINENAME_,TRANSMISSION_WEIGHT,_VARYINGNAME_,TransmissionWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,TRANSMISSION_COLOR,_VARYINGNAME_,TransmissionColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,TRANSMISSION_DEPTH,_VARYINGNAME_,TransmissionDepth)
#include<samplerVertexDeclaration>(_DEFINENAME_,TRANSMISSION_SCATTER,_VARYINGNAME_,TransmissionScatter)
#include<samplerVertexDeclaration>(_DEFINENAME_,TRANSMISSION_DISPERSION_SCALE,_VARYINGNAME_,TransmissionDispersionScale)
#include<samplerVertexDeclaration>(_DEFINENAME_,SUBSURFACE_WEIGHT,_VARYINGNAME_,SubsurfaceWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,SUBSURFACE_COLOR,_VARYINGNAME_,SubsurfaceColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,SUBSURFACE_RADIUS_SCALE,_VARYINGNAME_,SubsurfaceRadiusScale)
#include<samplerVertexDeclaration>(_DEFINENAME_,COAT_WEIGHT,_VARYINGNAME_,CoatWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,COAT_COLOR,_VARYINGNAME_,CoatColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,COAT_ROUGHNESS,_VARYINGNAME_,CoatRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,COAT_ROUGHNESS_ANISOTROPY,_VARYINGNAME_,CoatRoughnessAnisotropy)
#include<samplerVertexDeclaration>(_DEFINENAME_,COAT_DARKENING,_VARYINGNAME_,CoatDarkening)
#include<samplerVertexDeclaration>(_DEFINENAME_,FUZZ_WEIGHT,_VARYINGNAME_,FuzzWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,FUZZ_COLOR,_VARYINGNAME_,FuzzColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,FUZZ_ROUGHNESS,_VARYINGNAME_,FuzzRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,GEOMETRY_NORMAL,_VARYINGNAME_,GeometryNormal)
#include<samplerVertexDeclaration>(_DEFINENAME_,GEOMETRY_TANGENT,_VARYINGNAME_,GeometryTangent)
#include<samplerVertexDeclaration>(_DEFINENAME_,GEOMETRY_COAT_NORMAL,_VARYINGNAME_,GeometryCoatNormal)
#include<samplerVertexDeclaration>(_DEFINENAME_,GEOMETRY_OPACITY,_VARYINGNAME_,GeometryOpacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,GEOMETRY_THICKNESS,_VARYINGNAME_,GeometryThickness)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSION_COLOR,_VARYINGNAME_,EmissionColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,THIN_FILM_WEIGHT,_VARYINGNAME_,ThinFilmWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,THIN_FILM_THICKNESS,_VARYINGNAME_,ThinFilmThickness)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT_OCCLUSION,_VARYINGNAME_,AmbientOcclusion)
#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
varying vPositionW: vec3f;
#if DEBUGMODE>0
varying vClipSpacePosition: vec4f;
#endif
#ifdef NORMAL
varying vNormalW: vec3f;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vEnvironmentIrradiance: vec3f;
#include<harmonicsFunctions>
#endif
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vColor: vec4f;
#endif
#include<openpbrNormalMapVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<lightVxUboDeclaration>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vPositionUVW: vec3f;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vDirectionW: vec3f;
#endif
#include<logDepthDeclaration>
#include<vertexPullingDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef USE_VERTEX_PULLING
var positionUpdated: vec3f=vec3f(0.0);
#ifdef NORMAL
var normalUpdated: vec3f=vec3f(0.0);
#endif
#ifdef TANGENT
var tangentUpdated: vec4f=vec4f(0.0);
#endif
#ifdef UV1
var uvUpdated: vec2f=vec2f(0.0);
#endif
#ifdef UV2
var uv2Updated: vec2f=vec2f(0.0);
#endif
#ifdef VERTEXCOLOR
var colorUpdated: vec4f=vec4f(0.0);
#endif
#else
var positionUpdated: vec3f=vertexInputs.position;
#ifdef NORMAL
var normalUpdated: vec3f=vertexInputs.normal;
#endif
#ifdef TANGENT
var tangentUpdated: vec4f=vertexInputs.tangent;
#endif
#ifdef UV1
var uvUpdated: vec2f=vertexInputs.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=vertexInputs.uv2;
#endif
#ifdef VERTEXCOLOR
var colorUpdated: vec4f=vertexInputs.color;
#endif
#endif
#include<vertexPullingVertex>
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vertexOutputs.vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)
vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*vec4f(positionUpdated,1.0);
#endif
#ifdef USE_VERTEX_PULLING
#include<bonesVertex>(vertexInputs.matricesIndices,vp_matricesIndices,vertexInputs.matricesWeights,vp_matricesWeights,vertexInputs.matricesIndicesExtra,vp_matricesIndicesExtra,vertexInputs.matricesWeightsExtra,vp_matricesWeightsExtra)
#include<bakedVertexAnimation>(vertexInputs.matricesIndices,vp_matricesIndices,vertexInputs.matricesWeights,vp_matricesWeights,vertexInputs.matricesIndicesExtra,vp_matricesIndicesExtra,vertexInputs.matricesWeightsExtra,vp_matricesWeightsExtra)
#else
#include<bonesVertex>
#include<bakedVertexAnimation>
#endif
var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);vertexOutputs.vPositionW= worldPos.xyz;
#ifdef PREPASS
#include<prePassVertex>
#endif
#ifdef NORMAL
var normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated);
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
#if BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LAMBERT && BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LEGACY
var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-vertexOutputs.vPositionW);var NdotV: f32=max(dot(vertexOutputs.vNormalW,viewDirectionW),0.0);var roughNormal: vec3f=mix(vertexOutputs.vNormalW,viewDirectionW,(0.5*(1.0-NdotV))*uniforms.vBaseDiffuseRoughness);var reflectionVector: vec3f= (uniforms.reflectionMatrix* vec4f(roughNormal,0)).xyz;
#else
var reflectionVector: vec3f= (uniforms.reflectionMatrix* vec4f(vertexOutputs.vNormalW,0)).xyz;
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
vertexOutputs.vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;}
#else
vertexOutputs.position=scene.viewProjection*worldPos;
#endif
#if DEBUGMODE>0
vertexOutputs.vClipSpacePosition=vertexOutputs.position;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vertexOutputs.vDirectionW=normalize((finalWorld*vec4f(positionUpdated,0.0)).xyz);
#endif
#ifndef UV1
var uvUpdated: vec2f= vec2f(0.,0.);
#endif
#ifdef MAINUV1
vertexOutputs.vMainUV1=uvUpdated;
#endif
#ifndef UV2
var uv2Updated: vec2f= vec2f(0.,0.);
#endif
#ifdef MAINUV2
vertexOutputs.vMainUV2=uv2Updated;
#endif
#include<uvVariableDeclaration>[3..7]
#include<samplerVertexImplementation>(_DEFINENAME_,BASE_COLOR,_VARYINGNAME_,BaseColor,_MATRIXNAME_,baseColor,_INFONAME_,BaseColorInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight,_MATRIXNAME_,baseWeight,_INFONAME_,BaseWeightInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness,_MATRIXNAME_,baseDiffuseRoughness,_INFONAME_,BaseDiffuseRoughnessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BASE_METALNESS,_VARYINGNAME_,BaseMetalness,_MATRIXNAME_,baseMetalness,_INFONAME_,BaseMetalnessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR_WEIGHT,_VARYINGNAME_,SpecularWeight,_MATRIXNAME_,specularWeight,_INFONAME_,SpecularWeightInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR_COLOR,_VARYINGNAME_,SpecularColor,_MATRIXNAME_,specularColor,_INFONAME_,SpecularColorInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR_ROUGHNESS,_VARYINGNAME_,SpecularRoughness,_MATRIXNAME_,specularRoughness,_INFONAME_,SpecularRoughnessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR_ROUGHNESS_ANISOTROPY,_VARYINGNAME_,SpecularRoughnessAnisotropy,_MATRIXNAME_,specularRoughnessAnisotropy,_INFONAME_,SpecularRoughnessAnisotropyInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,TRANSMISSION_WEIGHT,_VARYINGNAME_,TransmissionWeight,_MATRIXNAME_,transmissionWeight,_INFONAME_,TransmissionWeightInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,TRANSMISSION_COLOR,_VARYINGNAME_,TransmissionColor,_MATRIXNAME_,transmissionColor,_INFONAME_,TransmissionColorInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,TRANSMISSION_DEPTH,_VARYINGNAME_,TransmissionDepth,_MATRIXNAME_,transmissionDepth,_INFONAME_,TransmissionDepthInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,TRANSMISSION_SCATTER,_VARYINGNAME_,TransmissionScatter,_MATRIXNAME_,transmissionScatter,_INFONAME_,TransmissionScatterInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,TRANSMISSION_DISPERSION_SCALE,_VARYINGNAME_,TransmissionDispersionScale,_MATRIXNAME_,transmissionDispersionScale,_INFONAME_,TransmissionDispersionScaleInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SUBSURFACE_WEIGHT,_VARYINGNAME_,SubsurfaceWeight,_MATRIXNAME_,subsurfaceWeight,_INFONAME_,SubsurfaceWeightInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SUBSURFACE_COLOR,_VARYINGNAME_,SubsurfaceColor,_MATRIXNAME_,subsurfaceColor,_INFONAME_,SubsurfaceColorInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SUBSURFACE_RADIUS_SCALE,_VARYINGNAME_,SubsurfaceRadiusScale,_MATRIXNAME_,subsurfaceRadiusScale,_INFONAME_,SubsurfaceRadiusScaleInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,COAT_WEIGHT,_VARYINGNAME_,CoatWeight,_MATRIXNAME_,coatWeight,_INFONAME_,CoatWeightInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,COAT_COLOR,_VARYNAME_,CoatColor,_MATRIXNAME_,coatColor,_INFONAME_,CoatColorInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,COAT_ROUGHNESS,_VARYINGNAME_,CoatRoughness,_MATRIXNAME_,coatRoughness,_INFONAME_,CoatRoughnessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,COAT_ROUGHNESS_ANISOTROPY,_VARYINGNAME_,CoatRoughnessAnisotropy,_MATRIXNAME_,coatRoughnessAnisotropy,_INFONAME_,CoatRoughnessAnisotropyInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,COAT_DARKENING,_VARYINGNAME_,CoatDarkening,_MATRIXNAME_,coatDarkening,_INFONAME_,CoatDarkeningInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,FUZZ_WEIGHT,_VARYINGNAME_,FuzzWeight,_MATRIXNAME_,fuzzWeight,_INFONAME_,FuzzWeightInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,FUZZ_COLOR,_VARYINGNAME_,FuzzColor,_MATRIXNAME_,fuzzColor,_INFONAME_,FuzzColorInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,FUZZ_ROUGHNESS,_VARYINGNAME_,FuzzRoughness,_MATRIXNAME_,fuzzRoughness,_INFONAME_,FuzzRoughnessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,GEOMETRY_NORMAL,_VARYINGNAME_,GeometryNormal,_MATRIXNAME_,geometryNormal,_INFONAME_,GeometryNormalInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,GEOMETRY_TANGENT,_VARYINGNAME_,GeometryTangent,_MATRIXNAME_,geometryTangent,_INFONAME_,GeometryTangentInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,GEOMETRY_COAT_NORMAL,_VARYINGNAME_,GeometryCoatNormal,_MATRIXNAME_,geometryCoatNormal,_INFONAME_,GeometryCoatNormalInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,GEOMETRY_OPACITY,_VARYINGNAME_,GeometryOpacity,_MATRIXNAME_,geometryOpacity,_INFONAME_,GeometryOpacityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,GEOMETRY_THICKNESS,_VARYINGNAME_,GeometryThickness,_MATRIXNAME_,geometryThickness,_INFONAME_,GeometryThicknessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,EMISSION_COLOR,_VARYINGNAME_,EmissionColor,_MATRIXNAME_,emissionColor,_INFONAME_,EmissionColorInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,THIN_FILM_WEIGHT,_VARYINGNAME_,ThinFilmWeight,_MATRIXNAME_,thinFilmWeight,_INFONAME_,ThinFilmWeightInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,THIN_FILM_THICKNESS,_VARYINGNAME_,ThinFilmThickness,_MATRIXNAME_,thinFilmThickness,_INFONAME_,ThinFilmThicknessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT_OCCLUSION,_VARYINGNAME_,AmbientOcclusion,_MATRIXNAME_,ambientOcclusion,_INFONAME_,AmbientOcclusionInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<openpbrNormalMapVertex>
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#include<vertexColorMixing>
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`;x.ShadersStoreWGSL[Hw]||(x.ShadersStoreWGSL[Hw]=V7);q_e={name:Hw,shader:V7}});var z7,Q_e,Xw=y(()=>{k();lg();z7="pbrFragmentExtraDeclaration",Q_e=`varying vPositionW: vec3f;
#if DEBUGMODE>0
varying vClipSpacePosition: vec4f;
#endif
#include<mainUVVaryingDeclaration>[1..7]
#ifdef NORMAL
varying vNormalW: vec3f;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vEnvironmentIrradiance: vec3f;
#endif
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vColor: vec4f;
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
varying vViewDepth: f32;
#endif
`;x.IncludesShadersStoreWGSL[z7]||(x.IncludesShadersStoreWGSL[z7]=Q_e)});var W7,$_e,H7=y(()=>{k();oh();iy();W7="openpbrFragmentSamplersDeclaration",$_e=`#include<samplerFragmentDeclaration>(_DEFINENAME_,BASE_COLOR,_VARYINGNAME_,BaseColor,_SAMPLERNAME_,baseColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight,_SAMPLERNAME_,baseWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness,_SAMPLERNAME_,baseDiffuseRoughness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BASE_METALNESS,_VARYINGNAME_,BaseMetalness,_SAMPLERNAME_,baseMetalness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR_WEIGHT,_VARYINGNAME_,SpecularWeight,_SAMPLERNAME_,specularWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR_COLOR,_VARYINGNAME_,SpecularColor,_SAMPLERNAME_,specularColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR_ROUGHNESS,_VARYINGNAME_,SpecularRoughness,_SAMPLERNAME_,specularRoughness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR_ROUGHNESS_ANISOTROPY,_VARYINGNAME_,SpecularRoughnessAnisotropy,_SAMPLERNAME_,specularRoughnessAnisotropy)
#include<samplerFragmentDeclaration>(_DEFINENAME_,TRANSMISSION_WEIGHT,_VARYINGNAME_,TransmissionWeight,_SAMPLERNAME_,transmissionWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,TRANSMISSION_COLOR,_VARYINGNAME_,TransmissionColor,_SAMPLERNAME_,transmissionColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,TRANSMISSION_DEPTH,_VARYINGNAME_,TransmissionDepth,_SAMPLERNAME_,transmissionDepth)
#include<samplerFragmentDeclaration>(_DEFINENAME_,TRANSMISSION_SCATTER,_VARYINGNAME_,TransmissionScatter,_SAMPLERNAME_,transmissionScatter)
#include<samplerFragmentDeclaration>(_DEFINENAME_,TRANSMISSION_DISPERSION_SCALE,_VARYINGNAME_,TransmissionDispersionScale,_SAMPLERNAME_,transmissionDispersionScale)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SUBSURFACE_WEIGHT,_VARYINGNAME_,SubsurfaceWeight,_SAMPLERNAME_,subsurfaceWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SUBSURFACE_COLOR,_VARYINGNAME_,SubsurfaceColor,_SAMPLERNAME_,subsurfaceColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SUBSURFACE_RADIUS_SCALE,_VARYINGNAME_,SubsurfaceRadiusScale,_SAMPLERNAME_,subsurfaceRadiusScale)
#include<samplerFragmentDeclaration>(_DEFINENAME_,COAT_WEIGHT,_VARYINGNAME_,CoatWeight,_SAMPLERNAME_,coatWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,COAT_COLOR,_VARYINGNAME_,CoatColor,_SAMPLERNAME_,coatColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,COAT_ROUGHNESS,_VARYINGNAME_,CoatRoughness,_SAMPLERNAME_,coatRoughness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,COAT_ROUGHNESS_ANISOTROPY,_VARYINGNAME_,CoatRoughnessAnisotropy,_SAMPLERNAME_,coatRoughnessAnisotropy)
#include<samplerFragmentDeclaration>(_DEFINENAME_,COAT_DARKENING,_VARYINGNAME_,CoatDarkening,_SAMPLERNAME_,coatDarkening)
#include<samplerFragmentDeclaration>(_DEFINENAME_,FUZZ_WEIGHT,_VARYINGNAME_,FuzzWeight,_SAMPLERNAME_,fuzzWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,FUZZ_COLOR,_VARYINGNAME_,FuzzColor,_SAMPLERNAME_,fuzzColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,FUZZ_ROUGHNESS,_VARYINGNAME_,FuzzRoughness,_SAMPLERNAME_,fuzzRoughness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,GEOMETRY_OPACITY,_VARYINGNAME_,GeometryOpacity,_SAMPLERNAME_,geometryOpacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,GEOMETRY_TANGENT,_VARYINGNAME_,GeometryTangent,_SAMPLERNAME_,geometryTangent)
#include<samplerFragmentDeclaration>(_DEFINENAME_,GEOMETRY_COAT_TANGENT,_VARYINGNAME_,GeometryCoatTangent,_SAMPLERNAME_,geometryCoatTangent)
#include<samplerFragmentDeclaration>(_DEFINENAME_,GEOMETRY_THICKNESS,_VARYINGNAME_,GeometryThickness,_SAMPLERNAME_,geometryThickness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSION_COLOR,_VARYINGNAME_,EmissionColor,_SAMPLERNAME_,emissionColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,THIN_FILM_WEIGHT,_VARYINGNAME_,ThinFilmWeight,_SAMPLERNAME_,thinFilmWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,THIN_FILM_THICKNESS,_VARYINGNAME_,ThinFilmThickness,_SAMPLERNAME_,thinFilmThickness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT_OCCLUSION,_VARYINGNAME_,AmbientOcclusion,_SAMPLERNAME_,ambientOcclusion)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)
#include<pbrFragmentReflectionDeclaration>
#ifdef ENVIRONMENTBRDF
var environmentBrdfSamplerSampler: sampler;var environmentBrdfSampler: texture_2d<f32>;
#endif
#ifdef FUZZENVIRONMENTBRDF
var environmentFuzzBrdfSamplerSampler: sampler;var environmentFuzzBrdfSampler: texture_2d<f32>;
#endif
#ifdef REFRACTED_BACKGROUND
var backgroundRefractionSamplerSampler: sampler;var backgroundRefractionSampler: texture_2d<f32>;
#endif
#ifdef USE_IRRADIANCE_TEXTURE_FOR_SCATTERING
var sceneIrradianceSampler: texture_2d<f32>;var sceneDepthSampler: texture_2d<f32>;
#endif
#if defined(ANISOTROPIC) || defined(FUZZ) || defined(REFRACTED_BACKGROUND) || defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING)
var blueNoiseSamplerSampler: sampler;var blueNoiseSampler: texture_2d<f32>;
#endif
#ifdef IBL_CDF_FILTERING
var icdfSamplerSampler: sampler;var icdfSampler: texture_2d<f32>;
#endif
`;x.IncludesShadersStoreWGSL[W7]||(x.IncludesShadersStoreWGSL[W7]=$_e)});var X7,J_e,Yw=y(()=>{k();X7="subSurfaceScatteringFunctions",J_e=`fn testLightingForSSS(diffusionProfile: f32)->bool
{return diffusionProfile<1.;}`;x.IncludesShadersStoreWGSL[X7]||(x.IncludesShadersStoreWGSL[X7]=J_e)});var Y7,eve,Kw=y(()=>{k();Y7="importanceSampling",eve=`fn hemisphereCosSample(u: vec2f)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=1.-u.y;var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}
fn hemisphereImportanceSampleDggx(u: vec2f,a: f32)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}
fn hemisphereImportanceSampleDggxAnisotropic(Xi: vec2f,alphaTangent: f32,alphaBitangent: f32)->vec3f
{let alphaT: f32=max(alphaTangent,0.0001);let alphaB: f32=max(alphaBitangent,0.0001);var phi: f32=atan(alphaB/alphaT*tan(2.0f*PI*Xi.x));if (Xi.x>0.5) {phi+=PI; }
let cosPhi: f32=cos(phi);let sinPhi: f32=sin(phi);let alpha2: f32=(cosPhi*cosPhi)/(alphaT*alphaT) +
(sinPhi*sinPhi)/(alphaB*alphaB);let tanTheta2: f32=Xi.y/(1.0f-Xi.y)/alpha2;let cosTheta: f32=1.0f/sqrt(1.0f+tanTheta2);let sinTheta: f32=sqrt(max(0.0f,1.0f-cosTheta*cosTheta));return vec3f(sinTheta*cosPhi,sinTheta*sinPhi,cosTheta);}
fn hemisphereImportanceSampleDCharlie(u: vec2f,a: f32)->vec3f {
var phi: f32=2.*PI*u.x;var sinTheta: f32=pow(u.y,a/(2.*a+1.));var cosTheta: f32=sqrt(1.-sinTheta*sinTheta);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;x.IncludesShadersStoreWGSL[Y7]||(x.IncludesShadersStoreWGSL[Y7]=eve)});var K7,tve,jw=y(()=>{k();K7="pbrHelperFunctions",tve=`#define MINIMUMVARIANCE 0.0005
fn convertRoughnessToAverageSlope(roughness: f32)->f32
{return roughness*roughness+MINIMUMVARIANCE;}
fn fresnelGrazingReflectance(reflectance0: f32)->f32 {var reflectance90: f32=saturate(reflectance0*25.0);return reflectance90;}
fn getAARoughnessFactors(normalVector: vec3f)->vec2f {
#ifdef SPECULARAA
var nDfdx: vec3f=dpdx(normalVector.xyz);var nDfdy: vec3f=dpdy(normalVector.xyz);var slopeSquare: f32=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));var geometricRoughnessFactor: f32=pow(saturate(slopeSquare),0.333);var geometricAlphaGFactor: f32=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2f(geometricRoughnessFactor,geometricAlphaGFactor);
#else
return vec2f(0.);
#endif
}
#ifdef ANISOTROPIC
#ifdef ANISOTROPIC_LEGACY
fn getAnisotropicRoughness(alphaG: f32,anisotropy: f32)->vec2f {var alphaT: f32=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);var alphaB: f32=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2f(alphaT,alphaB);}
fn getAnisotropicBentNormals(T: vec3f,B: vec3f,N: vec3f,V: vec3f,anisotropy: f32,roughness: f32)->vec3f {var anisotropicFrameDirection: vec3f=select(T,B,anisotropy>=0.0);var anisotropicFrameTangent: vec3f=cross(normalize(anisotropicFrameDirection),V);var anisotropicFrameNormal: vec3f=cross(anisotropicFrameTangent,anisotropicFrameDirection);var anisotropicNormal: vec3f=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}
#elif ANISOTROPIC_OPENPBR
fn getAnisotropicRoughness(alphaG: f32,anisotropy: f32)->vec2f {var alphaT: f32=max(alphaG*alphaG*sqrt(2.0/(1.0+(1.0-anisotropy)*(1.0-anisotropy))),MINIMUMVARIANCE);var alphaB: f32=max(alphaT*(1.0-anisotropy),MINIMUMVARIANCE);return vec2f(alphaT,alphaB);}
#else
fn getAnisotropicRoughness(alphaG: f32,anisotropy: f32)->vec2f {var alphaT: f32=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);var alphaB: f32=max(alphaG,MINIMUMVARIANCE);return vec2f(alphaT,alphaB);}
fn getAnisotropicBentNormals(T: vec3f,B: vec3f,N: vec3f,V: vec3f,anisotropy: f32,roughness: f32)->vec3f {var bentNormal: vec3f=cross(B,V);bentNormal=normalize(cross(bentNormal,B));var sq=1.0-anisotropy*(1.0-roughness);var a: f32=sq*sq*sq*sq;bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}
#endif
#endif
#if defined(CLEARCOAT) || defined(SS_REFRACTION)
fn cocaLambertVec3(alpha: vec3f,distance: f32)->vec3f {return exp(-alpha*distance);}
fn cocaLambert(NdotVRefract: f32,NdotLRefract: f32,alpha: vec3f,thickness: f32)->vec3f {return cocaLambertVec3(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}
fn computeColorAtDistanceInMedia(color: vec3f,distance: f32)->vec3f {return -log(color)/distance;}
fn computeClearCoatAbsorption(NdotVRefract: f32,NdotLRefract: f32,clearCoatColor: vec3f,clearCoatThickness: f32,clearCoatIntensity: f32)->vec3f {var clearCoatAbsorption: vec3f=mix( vec3f(1.0),
cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),
clearCoatIntensity);return clearCoatAbsorption;}
#endif
#ifdef MICROSURFACEAUTOMATIC
fn computeDefaultMicroSurface(microSurface: f32,reflectivityColor: vec3f)->f32
{const kReflectivityNoAlphaWorkflow_SmoothnessMax: f32=0.95;var reflectivityLuminance: f32=getLuminance(reflectivityColor);var reflectivityLuma: f32=sqrt(reflectivityLuminance);var resultMicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return resultMicroSurface;}
#endif
`;x.IncludesShadersStoreWGSL[K7]||(x.IncludesShadersStoreWGSL[K7]=tve)});var j7,ive,Zw=y(()=>{k();rN();j7="pbrDirectLightingSetupFunctions",ive=`struct preLightingInfo
{lightOffset: vec3f,
lightDistanceSquared: f32,
lightDistance: f32,
attenuation: f32,
L: vec3f,
H: vec3f,
NdotV: f32,
NdotLUnclamped: f32,
NdotL: f32,
VdotH: f32,
LdotV: f32,
roughness: f32,
diffuseRoughness: f32,
surfaceAlbedo: vec3f,
#ifdef IRIDESCENCE
iridescenceIntensity: f32
#endif
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
areaLightDiffuse: vec3f,
#ifdef SPECULARTERM
areaLightSpecular: vec3f,
areaLightFresnel: vec4f
#endif
#endif
};fn computePointAndSpotPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f,posW: vec3f)->preLightingInfo {var result: preLightingInfo;result.lightOffset=lightData.xyz-posW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}
fn computeDirectionalPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f)->preLightingInfo {var result: preLightingInfo;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);result.LdotV=dot(result.L,V);return result;}
fn computeHemisphericPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f)->preLightingInfo {var result: preLightingInfo;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;
#ifdef SPECULARTERM
result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));
#endif
return result;}
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
#include<ltcHelperFunctions>
var areaLightsLTC1SamplerSampler: sampler;var areaLightsLTC1Sampler: texture_2d<f32>;var areaLightsLTC2SamplerSampler: sampler;var areaLightsLTC2Sampler: texture_2d<f32>;fn computeAreaPreLightingInfo(ltc1: texture_2d<f32>,ltc1Sampler:sampler,ltc2:texture_2d<f32>,ltc2Sampler:sampler,viewDirectionW: vec3f,vNormal:vec3f,vPosition:vec3f,lightCenter:vec3f,halfWidth:vec3f, halfHeight:vec3f,roughness:f32)->preLightingInfo {var result: preLightingInfo;var data: areaLightData=computeAreaLightSpecularDiffuseFresnel(ltc1,ltc1Sampler,ltc2,ltc2Sampler,viewDirectionW,vNormal,vPosition,lightCenter,halfWidth,halfHeight,roughness);
#ifdef SPECULARTERM
result.areaLightFresnel=data.Fresnel;result.areaLightSpecular=data.Specular;
#endif
result.areaLightDiffuse+=data.Diffuse;return result;}
fn computeAreaPreLightingInfoWithTexture(ltc1: texture_2d<f32>,ltc1Sampler:sampler,ltc2:texture_2d<f32>,ltc2Sampler:sampler,emissionTexture:texture_2d<f32>,emissionTextureSampler:sampler,viewDirectionW: vec3f,vNormal:vec3f,vPosition:vec3f,lightCenter:vec3f,halfWidth:vec3f, halfHeight:vec3f,roughness:f32)->preLightingInfo {var result: preLightingInfo;result.lightOffset=lightCenter-vPosition;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);var data: areaLightData=computeAreaLightSpecularDiffuseFresnelWithEmission(ltc1,ltc1Sampler,ltc2,ltc2Sampler,emissionTexture,emissionTextureSampler,viewDirectionW,vNormal,vPosition,lightCenter,halfWidth,halfHeight,roughness);
#ifdef SPECULARTERM
result.areaLightFresnel=data.Fresnel;result.areaLightSpecular=data.Specular;
#endif
result.areaLightDiffuse=data.Diffuse;result.LdotV=0.;result.roughness=0.;result.diffuseRoughness=0.;result.surfaceAlbedo=vec3f(0.);return result;}
#endif
`;x.IncludesShadersStoreWGSL[j7]||(x.IncludesShadersStoreWGSL[j7]=ive)});var Z7,rve,qw=y(()=>{k();Z7="pbrDirectLightingFalloffFunctions",rve=`fn computeDistanceLightFalloff_Standard(lightOffset: vec3f,range: f32)->f32
{return max(0.,1.0-length(lightOffset)/range);}
fn computeDistanceLightFalloff_Physical(lightDistanceSquared: f32)->f32
{return 1.0/maxEps(lightDistanceSquared);}
fn computeDistanceLightFalloff_GLTF(lightDistanceSquared: f32,inverseSquaredRange: f32)->f32
{var lightDistanceFalloff: f32=1.0/maxEps(lightDistanceSquared);var factor: f32=lightDistanceSquared*inverseSquaredRange;var attenuation: f32=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}
fn computeDirectionalLightFalloff_IES(lightDirection: vec3f,directionToLightCenterW: vec3f,iesLightTexture: texture_2d<f32>,iesLightTextureSampler: sampler)->f32
{var cosAngle: f32=dot(-lightDirection,directionToLightCenterW);var angle=acos(cosAngle)/PI;return textureSampleLevel(iesLightTexture,iesLightTextureSampler,vec2f(angle,0),0.).r;}
fn computeDistanceLightFalloff(lightOffset: vec3f,lightDistanceSquared: f32,range: f32,inverseSquaredRange: f32)->f32
{
#ifdef USEPHYSICALLIGHTFALLOFF
return computeDistanceLightFalloff_Physical(lightDistanceSquared);
#elif defined(USEGLTFLIGHTFALLOFF)
return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);
#else
return computeDistanceLightFalloff_Standard(lightOffset,range);
#endif
}
fn computeDirectionalLightFalloff_Standard(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32,exponent: f32)->f32
{var falloff: f32=0.0;var cosAngle: f32=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)
{falloff=max(0.,pow(cosAngle,exponent));}
return falloff;}
fn computeDirectionalLightFalloff_Physical(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32)->f32
{const kMinusLog2ConeAngleIntensityRatio: f32=6.64385618977;
var concentrationKappa: f32=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);var lightDirectionSpreadSG: vec4f= vec4f(-lightDirection*concentrationKappa,-concentrationKappa);var falloff: f32=exp2(dot( vec4f(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}
fn computeDirectionalLightFalloff_GLTF(lightDirection: vec3f,directionToLightCenterW: vec3f,lightAngleScale: f32,lightAngleOffset: f32)->f32
{var cd: f32=dot(-lightDirection,directionToLightCenterW);var falloff: f32=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}
fn computeDirectionalLightFalloff(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32,exponent: f32,lightAngleScale: f32,lightAngleOffset: f32)->f32
{
#ifdef USEPHYSICALLIGHTFALLOFF
return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);
#elif defined(USEGLTFLIGHTFALLOFF)
return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);
#else
return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);
#endif
}`;x.IncludesShadersStoreWGSL[Z7]||(x.IncludesShadersStoreWGSL[Z7]=rve)});var q7,nve,Qw=y(()=>{k();q7="hdrFilteringFunctions",nve=`#ifdef NUM_SAMPLES
#if NUM_SAMPLES>0
fn radicalInverse_VdC(value: u32)->f32
{var bits=(value<<16u) | (value>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return f32(bits)*2.3283064365386963e-10; }
fn hammersley(i: u32,N: u32)->vec2f
{return vec2f( f32(i)/ f32(N),radicalInverse_VdC(i));}
fn log4(x: f32)->f32 {return log2(x)/2.;}
fn uv_to_normal(uv: vec2f)->vec3f {var N: vec3f;var uvRange: vec2f=uv;var theta: f32=uvRange.x*2.0*PI;var phi: f32=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;}
const NUM_SAMPLES_FLOAT: f32= f32(NUM_SAMPLES);const NUM_SAMPLES_FLOAT_INVERSED: f32=1./NUM_SAMPLES_FLOAT;const K: f32=4.;fn irradiance(
#ifdef CUSTOM_IRRADIANCE_FILTERING_INPUT
CUSTOM_IRRADIANCE_FILTERING_INPUT
#else
inputTexture: texture_cube<f32>,inputSampler: sampler,
#endif
inputN: vec3f,
filteringInfo: vec2f,
diffuseRoughness: f32,
surfaceAlbedo: vec3f,
inputV: vec3f
#ifdef IBL_CDF_FILTERING
,icdfSampler: texture_2d<f32>,icdfSamplerSampler: sampler
#endif
)->vec3f
{var n: vec3f=normalize(inputN);var result: vec3f= vec3f(0.0);
#ifndef IBL_CDF_FILTERING
var tangent: vec3f=select(vec3f(1.,0.,0.),vec3f(0.,0.,1.),abs(n.z)<0.999);tangent=normalize(cross(tangent,n));var bitangent: vec3f=cross(n,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,n);var tbnInverse: mat3x3f=transpose(tbn);
#endif
var maxLevel: f32=filteringInfo.y;var dim0: f32=filteringInfo.x;var omegaP: f32=(4.*PI)/(6.*dim0*dim0);var clampedAlbedo: vec3f=clamp(surfaceAlbedo,vec3f(0.1),vec3f(1.0));for(var i: u32=0u; i<NUM_SAMPLES; i++)
{var Xi: vec2f=hammersley(i,NUM_SAMPLES);
#ifdef IBL_CDF_FILTERING
var T: vec2f;T.x=textureSampleLevel(icdfSampler,icdfSamplerSampler,vec2(Xi.x,0.0),0.0).x;T.y=textureSampleLevel(icdfSampler,icdfSamplerSampler,vec2(T.x,Xi.y),0.0).y;var Ls: vec3f=uv_to_normal(vec2f(1.0-fract(T.x+0.25),T.y));var NoL: f32=dot(n,Ls);var NoV: f32=dot(n,inputV);
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
var LoV: f32=dot(Ls,inputV);
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
var H: vec3f=(inputV+Ls)*0.5;var VoH: f32=dot(inputV,H);
#endif
#else
var Ls: vec3f=hemisphereCosSample(Xi);Ls=normalize(Ls);var Ns: vec3f= vec3f(0.,0.,1.);var NoL: f32=dot(Ns,Ls);var V: vec3f=tbnInverse*inputV;var NoV: f32=dot(Ns,V);
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
var LoV: f32=dot(Ls,V);
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
var H: vec3f=(V+Ls)*0.5;var VoH: f32=dot(V,H);
#endif
#endif
if (NoL>0.) {
#ifdef IBL_CDF_FILTERING
var pdf: f32=textureSampleLevel(icdfSampler,icdfSamplerSampler,T,0.0).z;var c: vec3f=textureSampleLevel(inputTexture,inputSampler,Ls,0.0).rgb;
#else
var pdf_inversed: f32=PI/NoL;var omegaS: f32=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;var l: f32=log4(omegaS)-log4(omegaP)+log4(K);var mipLevel: f32=clamp(l,0.0,maxLevel);
#ifdef CUSTOM_IRRADIANCE_FILTERING_FUNCTION
CUSTOM_IRRADIANCE_FILTERING_FUNCTION
#else
var c: vec3f=textureSampleLevel(inputTexture,inputSampler,tbn*Ls,mipLevel).rgb;
#endif
#endif
#ifdef GAMMA_INPUT
c=toLinearSpaceVec3(c);
#endif
var diffuseRoughnessTerm: vec3f=vec3f(1.0);
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
diffuseRoughnessTerm=diffuseBRDF_EON(clampedAlbedo,diffuseRoughness,NoL,NoV,LoV)*PI;
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
diffuseRoughnessTerm=vec3f(diffuseBRDF_Burley(NoL,NoV,VoH,diffuseRoughness)*PI);
#endif
#ifdef IBL_CDF_FILTERING
var light: vec3f=vec3f(0.0);if (pdf>1e-6) {light=vec3f(1.0)/vec3f(pdf)*c;}
result+=NoL*diffuseRoughnessTerm*light;
#else
result+=c*diffuseRoughnessTerm;
#endif
}}
result=result*NUM_SAMPLES_FLOAT_INVERSED;
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
result=result/clampedAlbedo;
#endif
return result;}
fn radiance(alphaG: f32,inputTexture: texture_cube<f32>,inputSampler: sampler,inputN: vec3f,filteringInfo: vec2f)->vec3f
{var n: vec3f=normalize(inputN);var c: vec3f=textureSampleLevel(inputTexture,inputSampler,n,0.0).rgb;
if (alphaG==0.) {
#ifdef GAMMA_INPUT
c=toLinearSpaceVec3(c);
#endif
return c;} else {var result: vec3f= vec3f(0.);var tangent: vec3f=select(vec3f(1.,0.,0.),vec3f(0.,0.,1.),abs(n.z)<0.999);tangent=normalize(cross(tangent,n));var bitangent: vec3f=cross(n,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,n);var maxLevel: f32=filteringInfo.y;var dim0: f32=filteringInfo.x;var omegaP: f32=(4.*PI)/(6.*dim0*dim0);var weight: f32=0.;for(var i: u32=0u; i<NUM_SAMPLES; i++)
{var Xi: vec2f=hammersley(i,NUM_SAMPLES);var H: vec3f=hemisphereImportanceSampleDggx(Xi,alphaG);var NoV: f32=1.;var NoH: f32=H.z;var NoH2: f32=H.z*H.z;var NoL: f32=2.*NoH2-1.;var L: vec3f= vec3f(2.*NoH*H.x,2.*NoH*H.y,NoL);L=normalize(L);if (NoL>0.) {var pdf_inversed: f32=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);var omegaS: f32=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;var l: f32=log4(omegaS)-log4(omegaP)+log4(K);var mipLevel: f32=clamp( f32(l),0.0,maxLevel);weight+=NoL;var c: vec3f=textureSampleLevel(inputTexture,inputSampler,tbn*L,mipLevel).rgb;
#ifdef GAMMA_INPUT
c=toLinearSpaceVec3(c);
#endif
result+=c*NoL;}}
result=result/weight;return result;}}
#ifdef ANISOTROPIC
fn radianceAnisotropic(
alphaTangent: f32,
alphaBitangent: f32,
inputTexture: texture_cube<f32>,
inputSampler: sampler,
inputView: vec3f,
inputTangent: vec3f,
inputBitangent: vec3f,
inputNormal: vec3f,
filteringInfo: vec2f,
noiseInput: vec2f,
isRefraction: bool,
ior: f32
)->vec3f {var V: vec3f=inputView;var N: vec3f=inputNormal;var T: vec3f=inputTangent;var B: vec3f=inputBitangent;var result: vec3f=vec3f(0.f);var maxLevel: f32=filteringInfo.y;var dim0: f32=filteringInfo.x;let clampedAlphaT: f32=max(alphaTangent,MINIMUMVARIANCE);let clampedAlphaB: f32=max(alphaBitangent,MINIMUMVARIANCE);var effectiveDim: f32=dim0*sqrt(clampedAlphaT*clampedAlphaB);var omegaP: f32=(4.f*PI)/(6.f*effectiveDim*effectiveDim);let noiseScale: f32=clamp(log2(f32(NUM_SAMPLES))/12.0f,0.0f,1.0f);var weight: f32=0.f;for(var i: u32=0u; i<NUM_SAMPLES; i++)
{var Xi: vec2f=hammersley(i,NUM_SAMPLES);Xi=fract(Xi+noiseInput*mix(0.5f,0.015f,noiseScale));
var H_tangent: vec3f=hemisphereImportanceSampleDggxAnisotropic(Xi,clampedAlphaT,clampedAlphaB);var H: vec3f=normalize(H_tangent.x*T+H_tangent.y*B+H_tangent.z*N);var L: vec3f;if (isRefraction) {L=refract(-V,H,1.0/ior);} else {L=reflect(-V,H);}
var NoH: f32=max(dot(N,H),0.001f);var VoH: f32=max(dot(V,H),0.001f);var NoL: f32=max(dot(N,L),0.001f);if (NoL>0.f) {var pdf_inversed: f32=4./normalDistributionFunction_BurleyGGX_Anisotropic(
H_tangent.z,H_tangent.x,H_tangent.y,vec2f(clampedAlphaT,clampedAlphaB)
);var omegaS: f32=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;var l: f32=log4(omegaS)-log4(omegaP)+log4(K);var mipLevel: f32=clamp(l,0.0f,maxLevel);weight+=NoL;var c: vec3f=textureSampleLevel(inputTexture,inputSampler,L,mipLevel).rgb;
#if GAMMA_INPUT
c=toLinearSpaceVec3(c);
#endif
result+=c*NoL;}}
result=result/weight;return result;}
#endif
#endif
#endif
`;x.IncludesShadersStoreWGSL[q7]||(x.IncludesShadersStoreWGSL[q7]=nve)});var Q7,sve,$w=y(()=>{k();Q7="pbrBlockReflectance0",sve=`var reflectanceF0: f32=reflectivityOut.reflectanceF0;var specularEnvironmentR0: vec3f=reflectivityOut.colorReflectanceF0;var specularEnvironmentR90: vec3f= reflectivityOut.reflectanceF90;
#ifdef ALPHAFRESNEL
var reflectance90: f32=fresnelGrazingReflectance(reflectanceF0);specularEnvironmentR90=specularEnvironmentR90*reflectance90;
#endif
`;x.IncludesShadersStoreWGSL[Q7]||(x.IncludesShadersStoreWGSL[Q7]=sve)});var $7,ave,Jw=y(()=>{k();nN();$w();$7="pbrDirectLightingFunctions",ave=`#define CLEARCOATREFLECTANCE90 1.0
struct lightingInfo
{diffuse: vec3f,
#ifdef SS_TRANSLUCENCY
diffuseTransmission: vec3f,
#endif
#ifdef SPECULARTERM
specular: vec3f,
#endif
#ifdef CLEARCOAT
clearCoat: vec4f,
#endif
#ifdef SHEEN
sheen: vec3f
#endif
};fn adjustRoughnessFromLightProperties(roughness: f32,lightRadius: f32,lightDistance: f32)->f32 {
#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)
var lightRoughness: f32=lightRadius/lightDistance;var totalRoughness: f32=saturate(lightRoughness+roughness);return totalRoughness;
#else
return roughness;
#endif
}
fn computeHemisphericDiffuseLighting(info: preLightingInfo,lightColor: vec3f,groundColor: vec3f)->vec3f {return mix(groundColor,lightColor,info.NdotL);}
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
fn computeAreaDiffuseLighting(info: preLightingInfo,lightColor: vec3f)->vec3f {return info.areaLightDiffuse*lightColor;}
#endif
fn computeDiffuseLighting(info: preLightingInfo,lightColor: vec3f)->vec3f {var diffuseTerm: vec3f=vec3f(1.0/PI);
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_LEGACY
diffuseTerm=vec3f(diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness));
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
diffuseTerm=vec3f(diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.diffuseRoughness));
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
var clampedAlbedo: vec3f=clamp(info.surfaceAlbedo,vec3f(0.1),vec3f(1.0));diffuseTerm=diffuseBRDF_EON(clampedAlbedo,info.diffuseRoughness,info.NdotL,info.NdotV,info.LdotV);diffuseTerm/=clampedAlbedo;
#endif
return diffuseTerm*info.attenuation*info.NdotL*lightColor;}
fn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d<f32>,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f,posW: vec3f)->vec3f{var strq: vec4f=textureProjectionMatrix* vec4f(posW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return toLinearSpaceVec3(textureColor);}
#ifdef SS_TRANSLUCENCY
fn computeDiffuseTransmittedLighting(info: preLightingInfo,lightColor: vec3f,transmittance: vec3f)->vec3f {var transmittanceNdotL=vec3f(0.0);var NdotL: f32=absEps(info.NdotLUnclamped);
#ifndef SS_TRANSLUCENCY_LEGACY
if (info.NdotLUnclamped<0.0) {
#endif
var wrapNdotL: f32=computeWrappedDiffuseNdotL(NdotL,0.02);var trAdapt: f32=step(0.,info.NdotLUnclamped);transmittanceNdotL=mix(transmittance*wrapNdotL, vec3f(wrapNdotL),trAdapt);
#ifndef SS_TRANSLUCENCY_LEGACY
}
var diffuseTerm : vec3f=vec3f(1.0/PI);
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_LEGACY
diffuseTerm=vec3f(diffuseBRDF_Burley(
info.NdotL,info.NdotV,info.VdotH,info.roughness));
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
diffuseTerm=vec3f(diffuseBRDF_Burley(
info.NdotL,info.NdotV,info.VdotH,info.diffuseRoughness));
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
var clampedAlbedo: vec3f=clamp(info.surfaceAlbedo,vec3f(0.1),vec3f(1.0));diffuseTerm=diffuseBRDF_EON(clampedAlbedo,info.diffuseRoughness,
info.NdotL,info.NdotV,info.LdotV);diffuseTerm/=clampedAlbedo;
#endif
return (transmittanceNdotL*diffuseTerm)*info.attenuation*lightColor;
#else
let diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;
#endif
}
#endif
#ifdef SPECULARTERM
fn computeSpecularLighting(info: preLightingInfo,N: vec3f,reflectance0: vec3f,fresnel: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var roughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var modifiedFresnel: vec3f=fresnel;
#ifdef IRIDESCENCE
modifiedFresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);
#endif
var distribution: f32=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);
#ifdef BRDF_V_HEIGHT_CORRELATED
var smithVisibility: f32=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);
#else
var smithVisibility: f32=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);
#endif
var specTerm: vec3f=modifiedFresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
fn computeAreaSpecularLighting(info: preLightingInfo,specularColor: vec3f,reflectance0: vec3f,reflectance90: vec3f)->vec3f {var fresnel:vec3f =reflectance0*specularColor*info.areaLightFresnel.x+( vec3f( 1.0 )-specularColor )*info.areaLightFresnel.y*reflectance90;return specularColor*fresnel*info.areaLightSpecular;}
#endif
#endif
#ifdef FUZZ
fn evalFuzz(L: vec3f,NdotL: f32,NdotV: f32,T: vec3f,B: vec3f,ltcLut: vec3f)->f32
{if (NdotL<=0.0f || NdotV<=0.0f) {return 0.0f;}
let M=mat3x3f(
vec3f(ltcLut.r,0.0f,0.0f),
vec3f(ltcLut.g,1.0f,0.0f),
vec3f(0.0f,0.0f,1.0f)
);let Llocal: vec3f=vec3f(dot(L,T),dot(L,B),NdotL);let Lwarp: vec3f=normalize(M*Llocal);let cosThetaWarp: f32=max(Lwarp.z,0.0f);return cosThetaWarp*NdotL;}
#endif
#if defined(ANISOTROPIC) && defined(ANISOTROPIC_OPENPBR)
fn computeAnisotropicSpecularLighting(info: preLightingInfo,V: vec3f,N: vec3f,T: vec3f,B: vec3f,anisotropy: f32,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var TdotH: f32=dot(T,info.H);var BdotH: f32=dot(B,info.H);var TdotV: f32=dot(T,V);var BdotV: f32=dot(B,V);var TdotL: f32=dot(T,info.L);var BdotL: f32=dot(B,info.L);var alphaG: f32=convertRoughnessToAverageSlope(info.roughness);var alphaTB: vec2f=getAnisotropicRoughness(alphaG,anisotropy);var distribution: f32=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);var smithVisibility: f32=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);var specTerm: vec3f=vec3f(distribution*smithVisibility);return specTerm*info.attenuation*info.NdotL*lightColor;}
#elif defined(ANISOTROPIC)
fn computeAnisotropicSpecularLighting(info: preLightingInfo,V: vec3f,N: vec3f,T: vec3f,B: vec3f,anisotropy: f32,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var TdotH: f32=dot(T,info.H);var BdotH: f32=dot(B,info.H);var TdotV: f32=dot(T,V);var BdotV: f32=dot(B,V);var TdotL: f32=dot(T,info.L);var BdotL: f32=dot(B,info.L);var alphaG: f32=convertRoughnessToAverageSlope(info.roughness);var alphaTB: vec2f=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,vec2f(geometricRoughnessFactor*geometricRoughnessFactor));var fresnel: vec3f=fresnelSchlickGGXVec3(info.VdotH,reflectance0,reflectance90);
#ifdef IRIDESCENCE
fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);
#endif
var distribution: f32=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);var smithVisibility: f32=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);var specTerm: vec3f=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}
#endif
#ifdef CLEARCOAT
fn computeClearCoatLighting(info: preLightingInfo,Ncc: vec3f,geometricRoughnessFactor: f32,clearCoatIntensity: f32,lightColor: vec3f)->vec4f {var NccdotL: f32=saturateEps(dot(Ncc,info.L));var NccdotH: f32=saturateEps(dot(Ncc,info.H));var clearCoatRoughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(clearCoatRoughness);var fresnel: f32=fresnelSchlickGGX(info.VdotH,uniforms.vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;var distribution: f32=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);var kelemenVisibility: f32=visibility_Kelemen(info.VdotH);var clearCoatTerm: f32=fresnel*distribution*kelemenVisibility;return vec4f(
clearCoatTerm*info.attenuation*NccdotL*lightColor,
1.0-fresnel
);}
fn computeClearCoatLightingAbsorption(NdotVRefract: f32,L: vec3f,Ncc: vec3f,clearCoatColor: vec3f,clearCoatThickness: f32,clearCoatIntensity: f32)->vec3f {var LRefract: vec3f=-refract(L,Ncc,uniforms.vClearCoatRefractionParams.y);var NdotLRefract: f32=saturateEps(dot(Ncc,LRefract));var absorption: vec3f=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;}
#endif
#ifdef SHEEN
fn computeSheenLighting(info: preLightingInfo,N: vec3f,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var roughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var fresnel: f32=1.;var distribution: f32=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER
var visibility: f32=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);
#else */
var visibility: f32=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */
var sheenTerm: f32=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;}
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
#include<clusteredLightingFunctions>
fn computeClusteredLighting(
lightDataTexture: texture_2d<f32>,
tileMaskBuffer: ptr<storage,array<u32>>,
lightData: vec4f,
sliceRange: vec2u,
V: vec3f,
N: vec3f,
posW: vec3f,
surfaceAlbedo: vec3f,
reflectivityOut: reflectivityOutParams,
#ifdef IRIDESCENCE
iridescenceIntensity: f32,
#endif
#ifdef SS_TRANSLUCENCY
subSurfaceOut: subSurfaceOutParams,
#endif
#ifdef SPECULARTERM
AARoughnessFactor: f32,
#endif
#ifdef ANISOTROPIC
anisotropicOut: anisotropicOutParams,
#endif
#ifdef SHEEN
sheenOut: sheenOutParams,
#endif
#ifdef CLEARCOAT
clearcoatOut: clearcoatOutParams,
#endif
)->lightingInfo {let NdotV=absEps(dot(N,V));
#include<pbrBlockReflectance0>
#ifdef CLEARCOAT
specularEnvironmentR0=clearcoatOut.specularEnvironmentR0;
#endif
var result: lightingInfo;let tilePosition=vec2u(fragmentInputs.position.xy*lightData.xy);let maskResolution=vec2u(lightData.zw);var tileIndex=(tilePosition.x*maskResolution.x+tilePosition.y)*maskResolution.y;let batchRange=sliceRange/CLUSTLIGHT_BATCH;var batchOffset=batchRange.x*CLUSTLIGHT_BATCH;tileIndex+=batchRange.x;for (var i=batchRange.x; i<=batchRange.y; i+=1) {var mask=tileMaskBuffer[tileIndex];tileIndex+=1;let maskOffset=max(sliceRange.x,batchOffset)-batchOffset;
let maskWidth=min(sliceRange.y-batchOffset+1,CLUSTLIGHT_BATCH);mask=extractBits(mask,maskOffset,maskWidth);while mask != 0 {let trailing=firstTrailingBit(mask);mask ^= 1u<<trailing;let light=getClusteredLight(lightDataTexture,batchOffset+maskOffset+trailing);var preInfo=computePointAndSpotPreLightingInfo(light.vLightData,V,N,posW);preInfo.NdotV=NdotV;preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light.vLightFalloff.x,light.vLightFalloff.y);if light.vLightDirection.w>=0.0 {preInfo.attenuation*=computeDirectionalLightFalloff(light.vLightDirection.xyz,preInfo.L,light.vLightDirection.w,light.vLightData.w,light.vLightFalloff.z,light.vLightFalloff.w);}
preInfo.roughness=adjustRoughnessFromLightProperties(reflectivityOut.roughness,light.vLightSpecular.a,preInfo.lightDistance);preInfo.diffuseRoughness=reflectivityOut.diffuseRoughness;preInfo.surfaceAlbedo=surfaceAlbedo;
#ifdef IRIDESCENCE
preInfo.iridescenceIntensity=iridescenceIntensity;
#endif
var info: lightingInfo;
#ifdef SS_TRANSLUCENCY
#ifdef SS_TRANSLUCENCY_LEGACY
info.diffuse=computeDiffuseTransmittedLighting(preInfo,light.vLightDiffuse.rgb,subSurfaceOut.transmittance);info.diffuseTransmission=vec3(0);
#else
info.diffuse=computeDiffuseLighting(preInfo,light.vLightDiffuse.rgb)*(1.0-subSurfaceOut.translucencyIntensity);info.diffuseTransmission=computeDiffuseTransmittedLighting(preInfo,light.vLightDiffuse.rgb,subSurfaceOut.transmittance);
#endif
#else
info.diffuse=computeDiffuseLighting(preInfo,light.vLightDiffuse.rgb);
#endif
#ifdef SPECULARTERM
#if CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR
let metalFresnel=reflectivityOut.specularWeight*getF82Specular(preInfo.VdotH,specularEnvironmentR0,reflectivityOut.colorReflectanceF90,reflectivityOut.roughness);let dielectricFresnel=fresnelSchlickGGXVec3(preInfo.VdotH,reflectivityOut.dielectricColorF0,reflectivityOut.colorReflectanceF90);let coloredFresnel=mix(dielectricFresnel,metalFresnel,reflectivityOut.metallic);
#else
let coloredFresnel=fresnelSchlickGGXVec3(preInfo.VdotH,specularEnvironmentR0,reflectivityOut.colorReflectanceF90);
#endif
#ifndef LEGACY_SPECULAR_ENERGY_CONSERVATION
let NdotH=dot(N,preInfo.H);let fresnel=fresnelSchlickGGXVec3(NdotH,vec3(reflectanceF0),specularEnvironmentR90);info.diffuse*=(vec3(1.0)-fresnel);
#endif
#ifdef ANISOTROPIC
info.specular=computeAnisotropicSpecularLighting(preInfo,V,N,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactor,light.vLightDiffuse.rgb);
#else
info.specular=computeSpecularLighting(preInfo,N,specularEnvironmentR0,coloredFresnel,AARoughnessFactor,light.vLightDiffuse.rgb);
#endif
#endif
#ifdef SHEEN
#ifdef SHEEN_LINKWITHALBEDO
preInfo.roughness=sheenOut.sheenIntensity;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light.vLightSpecular.a,preInfo.lightDistance);
#endif
info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactor,light.vLightDiffuse.rgb);
#endif
#ifdef CLEARCOAT
preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light.vLightSpecular.a,preInfo.lightDistance);info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light.vLightDiffuse.rgb);
#ifdef CLEARCOAT_TINT
let absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;
#ifdef SS_TRANSLUCENCY
info.diffuseTransmission*=absorption;
#endif
#ifdef SPECULARTERM
info.specular*=absorption;
#endif
#endif
info.diffuse*=info.clearCoat.w;
#ifdef SS_TRANSLUCENCY
info.diffuseTransmission*=info.clearCoat.w;
#endif
#ifdef SPECULARTERM
info.specular*=info.clearCoat.w;
#endif
#ifdef SHEEN
info.sheen*=info.clearCoat.w;
#endif
#endif
result.diffuse+=info.diffuse;
#ifdef SS_TRANSLUCENCY
result.diffuseTransmission+=info.diffuseTransmission;
#endif
#ifdef SPECULARTERM
result.specular+=info.specular;
#endif
#ifdef CLEARCOAT
result.clearCoat+=info.clearCoat;
#endif
#ifdef SHEEN
result.sheen+=info.sheen;
#endif
}
batchOffset+=CLUSTLIGHT_BATCH;}
return result;}
#endif
`;x.IncludesShadersStoreWGSL[$7]||(x.IncludesShadersStoreWGSL[$7]=ave)});var J7,ove,eK=y(()=>{k();J7="openpbrNormalMapFragmentMainFunctions",ove=`#if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL) || defined(ANISOTROPIC) || defined(FUZZ) || defined(DETAIL)
#if defined(TANGENT) && defined(NORMAL)
varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f;
#endif
#ifdef OBJECTSPACE_NORMALMAP
uniform normalMatrix: mat4x4f;fn toNormalMatrix(m: mat4x4f)->mat4x4f
{var a00=m[0][0];var a01=m[0][1];var a02=m[0][2];var a03=m[0][3];var a10=m[1][0];var a11=m[1][1];var a12=m[1][2];var a13=m[1][3];var a20=m[2][0];
var a21=m[2][1];var a22=m[2][2];var a23=m[2][3];var a30=m[3][0];
var a31=m[3][1];var a32=m[3][2];var a33=m[3][3];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;var det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;var mi=mat4x4<f32>(
(a11*b11-a12*b10+a13*b09)/det,
(a02*b10-a01*b11-a03*b09)/det,
(a31*b05-a32*b04+a33*b03)/det,
(a22*b04-a21*b05-a23*b03)/det,
(a12*b08-a10*b11-a13*b07)/det,
(a00*b11-a02*b08+a03*b07)/det,
(a32*b02-a30*b05-a33*b01)/det,
(a20*b05-a22*b02+a23*b01)/det,
(a10*b10-a11*b08+a13*b06)/det,
(a01*b08-a00*b10-a03*b06)/det,
(a30*b04-a31*b02+a33*b00)/det,
(a21*b02-a20*b04-a23*b00)/det,
(a11*b07-a10*b09-a12*b06)/det,
(a00*b09-a01*b07+a02*b06)/det,
(a31*b01-a30*b03-a32*b00)/det,
(a20*b03-a21*b01+a22*b00)/det);return mat4x4<f32>(mi[0][0],mi[1][0],mi[2][0],mi[3][0],
mi[0][1],mi[1][1],mi[2][1],mi[3][1],
mi[0][2],mi[1][2],mi[2][2],mi[3][2],
mi[0][3],mi[1][3],mi[2][3],mi[3][3]);}
#endif
fn perturbNormalBase(cotangentFrame: mat3x3f,normal: vec3f,scale: f32)->vec3f
{var output=normal;
#ifdef NORMALXYSCALE
output=normalize(output* vec3f(scale,scale,1.0));
#endif
return normalize(cotangentFrame*output);}
fn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f
{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}
fn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f
{var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);}
#endif
`;x.IncludesShadersStoreWGSL[J7]||(x.IncludesShadersStoreWGSL[J7]=ove)});var tK,lve,iK=y(()=>{k();oh();tK="openpbrNormalMapFragmentFunctions",lve=`#if defined(GEOMETRY_NORMAL)
#include<samplerFragmentDeclaration>(_DEFINENAME_,GEOMETRY_NORMAL,_VARYINGNAME_,GeometryNormal,_SAMPLERNAME_,geometryNormal)
#endif
#if defined(GEOMETRY_COAT_NORMAL)
#include<samplerFragmentDeclaration>(_DEFINENAME_,GEOMETRY_COAT_NORMAL,_VARYINGNAME_,GeometryCoatNormal,_SAMPLERNAME_,geometryCoatNormal)
#endif
#if defined(DETAIL)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)
#endif
#if defined(GEOMETRY_NORMAL) && defined(PARALLAX)
const minSamples: f32=4.;const maxSamples: f32=15.;const iMaxSamples: i32=15;fn parallaxOcclusion(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32)->vec2f {var parallaxLimit: f32=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;var vOffsetDir: vec2f=normalize(vViewDirCoT.xy);var vMaxOffset: vec2f=vOffsetDir*parallaxLimit;var numSamples: f32=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));var stepSize: f32=1.0/numSamples;var currRayHeight: f32=1.0;var vCurrOffset: vec2f= vec2f(0,0);var vLastOffset: vec2f= vec2f(0,0);var lastSampledHeight: f32=1.0;var currSampledHeight: f32=1.0;var keepWorking: bool=true;for (var i: i32=0; i<iMaxSamples; i++)
{currSampledHeight=textureSample(geometryNormalSampler,geometryNormalSamplerSampler,texCoord+vCurrOffset).w;if (!keepWorking)
{}
else if (currSampledHeight>currRayHeight)
{var delta1: f32=currSampledHeight-currRayHeight;var delta2: f32=(currRayHeight+stepSize)-lastSampledHeight;var ratio: f32=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}
else
{currRayHeight-=stepSize;vLastOffset=vCurrOffset;
#ifdef PARALLAX_RHS
vCurrOffset-=stepSize*vMaxOffset;
#else
vCurrOffset+=stepSize*vMaxOffset;
#endif
lastSampledHeight=currSampledHeight;}}
return vCurrOffset;}
fn parallaxOffset(viewDir: vec3f,heightScale: f32)->vec2f
{var height: f32=textureSample(geometryNormalSampler,geometryNormalSamplerSampler,fragmentInputs.vGeometryNormalUV).w;var texCoordOffset: vec2f=heightScale*viewDir.xy*height;
#ifdef PARALLAX_RHS
return texCoordOffset;
#else
return -texCoordOffset;
#endif
}
#endif
`;x.IncludesShadersStoreWGSL[tK]||(x.IncludesShadersStoreWGSL[tK]=lve)});var rK,cve,nK=y(()=>{k();rK="openpbrConductorReflectance",cve=`#define pbr_inline
fn conductorReflectance(baseColor: vec3f,specularColor: vec3f,specularWeight: f32)->ReflectanceParams
{var outParams: ReflectanceParams;
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR)
outParams.coloredF0=baseColor*specularWeight;outParams.coloredF90=specularColor*specularWeight;
#else
outParams.coloredF0=baseColor;outParams.coloredF90=vec3f(1.0f);
#endif
outParams.F0=1.0f;outParams.F90=1.0f;return outParams;}`;x.IncludesShadersStoreWGSL[rK]||(x.IncludesShadersStoreWGSL[rK]=cve)});var sK,fve,aK=y(()=>{k();sK="openpbrAmbientOcclusionFunctions",fve=`fn compute_specular_occlusion(n_dot_v: f32,metallic: f32,ambient_occlusion: f32,roughness: f32)->f32
{let specular_occlusion: f32=saturate(pow(n_dot_v+ambient_occlusion,exp2(-16.0*roughness-1.0))-1.0+ambient_occlusion);return mix(specular_occlusion,1.0,metallic*square(1.0-roughness));}
`;x.IncludesShadersStoreWGSL[sK]||(x.IncludesShadersStoreWGSL[sK]=fve)});var oK,dve,lK=y(()=>{k();oK="openpbrVolumeFunctions",dve=`struct OpenPBRHomogeneousVolume {extinction_coeff: vec3f,
ss_albedo: vec3f,
multi_scatter_color: vec3f,
absorption_coeff: vec3f,
scatter_coeff: vec3f,
anisotropy: f32, };fn computeOpenPBRTransmissionVolume(
transmission_color: vec3f,
transmission_depth: f32,
transmission_scatter: vec3f,
anisotropy: f32
)->OpenPBRHomogeneousVolume
{var volumeParams: OpenPBRHomogeneousVolume;volumeParams.absorption_coeff=vec3f(0.0f);volumeParams.scatter_coeff=vec3f(0.0f);volumeParams.anisotropy=anisotropy;
#ifdef GEOMETRY_THIN_WALLED
volumeParams.scatter_coeff=vec3f(1.0f);volumeParams.anisotropy=1.0f;
volumeParams.extinction_coeff=volumeParams.absorption_coeff+volumeParams.scatter_coeff;volumeParams.ss_albedo=vec3f(1.0f);
#else
if (transmission_depth>0.0f) {let invDepth: vec3f=vec3f(1.f/maxEps(transmission_depth));volumeParams.extinction_coeff=-log(maxEpsVec3(transmission_color.rgb))*invDepth;volumeParams.scatter_coeff=transmission_scatter.rgb*invDepth;volumeParams.absorption_coeff=volumeParams.extinction_coeff-volumeParams.scatter_coeff.rgb;let minCoeff: f32=min3(volumeParams.absorption_coeff);if (minCoeff<0.0f) {volumeParams.absorption_coeff-=vec3f(minCoeff);}
volumeParams.extinction_coeff=volumeParams.absorption_coeff+volumeParams.scatter_coeff;volumeParams.ss_albedo=volumeParams.scatter_coeff/(volumeParams.extinction_coeff);} else {volumeParams.extinction_coeff=volumeParams.absorption_coeff+volumeParams.scatter_coeff;volumeParams.ss_albedo=vec3f(0.0f);}
#endif
return volumeParams;}
fn computeOpenPBRSubsurfaceVolume(
subsurface_color: vec3f,
subsurface_radius: f32,
subsurface_radius_scale: vec3f,
anisotropy: f32
)->OpenPBRHomogeneousVolume
{var volumeParams: OpenPBRHomogeneousVolume;volumeParams.absorption_coeff=vec3f(0.0f);volumeParams.scatter_coeff=vec3f(0.0f);volumeParams.anisotropy=anisotropy;volumeParams.multi_scatter_color=subsurface_color;let mfp: vec3f=subsurface_radius_scale*vec3f(subsurface_radius);volumeParams.extinction_coeff=vec3f(1.0f)/maxEpsVec3(mfp);volumeParams.ss_albedo=multiScatterToSingleScatterAlbedoWithAniso(subsurface_color,anisotropy);volumeParams.scatter_coeff=volumeParams.ss_albedo*volumeParams.extinction_coeff;volumeParams.absorption_coeff=volumeParams.extinction_coeff-volumeParams.scatter_coeff.rgb;let minCoeff: f32=min3(volumeParams.absorption_coeff);if (minCoeff<0.0f) {volumeParams.absorption_coeff-=vec3f(minCoeff);}
volumeParams.extinction_coeff=volumeParams.absorption_coeff+volumeParams.scatter_coeff;return volumeParams;}
fn sss_pdf(r: f32,d: vec3f)->vec3f
{let d_clamped=max(vec3f(1e-4f),d);return (exp(-r/d_clamped)+exp(-r/(3.0f*d_clamped)))/max(vec3f(1e-5f),8.0f*PI*d_clamped*r);}
fn sss_samples_pdf(r: f32,d: f32)->f32
{let d_clamped=max(1e-4f,d);return exp(-r/(3.0f*d_clamped))/(6.0f*PI*d_clamped*r);}
fn sss_samples_icdf(x: f32,d: f32)->f32
{let d_clamped=max(1e-4f,d);let x_clamped=max(1e-4f,x);return -3.0f*log(x_clamped)*d_clamped;}
fn samples_scale(x: f32,d: f32)->f32
{return 1.0f-exp(-x/(3.0f*d));}
fn sss_get_position(depth_texture: texture_2d<f32>,tex_coord: vec2f,render_resolution: vec2f,inv_proj: mat4x4f)->vec3f
{var P: vec4f=vec4f(tex_coord,textureLoad(depth_texture,vec2i(tex_coord*render_resolution),0).x,1.0f);P.x=2.0f*P.x-1.0f;P.y=2.0f*P.y-1.0f;P=inv_proj*P;return P.xyz/P.w;}
fn sss_filter_scale(currZ: f32,proj: mat4x4f)->f32
{return 1.0f/dot(vec2f(proj[2].w,proj[3].w),vec2f(currZ,1.0f));}
fn projective_to_pixels(proj_dist: f32,proj: mat4x4f,resolution: vec2f)->f32
{return proj_dist*proj[1][1]*resolution.y;}
fn pixels_to_projective(pixel_dist: f32,proj: mat4x4f,resolution: vec2f)->f32
{return pixel_dist/(proj[1][1]*resolution.y);}
fn sss_convolve(sss_irradiance_texture: texture_2d<f32>,depth_texture: texture_2d<f32>,render_resolution: vec2f,d: vec3f,proj: mat4x4f,inv_proj: mat4x4f,sample_count: i32,noise: vec2f)->vec3f
{let tex_coord: vec2f=fragmentInputs.position.xy/render_resolution;let unconvolved_irradiance: vec3f=textureLoad(sss_irradiance_texture,vec2i(fragmentInputs.position.xy),0).rgb;let curr_pos: vec3f=sss_get_position(depth_texture,tex_coord,render_resolution,inv_proj);var dmax: f32=max3(d);let max_dmax: f32=0.1*f32(sample_count);var d_adjusted=d;if (dmax>max_dmax)
{d_adjusted*=max_dmax/dmax;dmax=max_dmax;}
var dz: f32=dmax*sss_filter_scale(curr_pos.z,proj);let projMat2d: mat2x2f=mat2x2f(proj[0].xy,proj[1].xy);if (determinant(projMat2d)*dz<1e-4f) {return unconvolved_irradiance;}
let overscan_size_in_pixels: f32=max(render_resolution.x,render_resolution.y)*0.1;let filter_crop_ratio: f32=0.8f;
let crop_radius: f32=projective_to_pixels(sss_samples_icdf(1.0f-filter_crop_ratio,dz),proj,render_resolution);if (crop_radius>overscan_size_in_pixels)
{d_adjusted*=overscan_size_in_pixels/crop_radius;dz*=overscan_size_in_pixels/crop_radius;}
let filter_samples_scale: f32=samples_scale(pixels_to_projective(overscan_size_in_pixels,proj,render_resolution),dz);var irradiance_sum: vec3f=vec3f(0.0f);var weight_sum: vec3f=vec3f(0.0f);for (var i: i32=0; i<sample_count; i++)
{var r: vec2f=fract(plasticSequence(u32(i))+noise);r.x*=TWO_PI;r.y*=filter_samples_scale;let icdf: f32=sss_samples_icdf(1.0-r.y,dz);let sample_uv: vec2f=tex_coord+icdf*projMat2d*vec2f(cos(r.x),sin(r.x));let sss_irradiance: vec4f=textureLoad(sss_irradiance_texture,vec2i(sample_uv*render_resolution),0);let dist: f32=distance(curr_pos,sss_get_position(depth_texture,sample_uv,render_resolution,inv_proj));if (dist>0.0f)
{let weights: vec3f=sss_irradiance.a/sss_samples_pdf(icdf,dz)*sss_pdf(dist,d_adjusted);irradiance_sum+=weights*sss_irradiance.rgb;weight_sum+=weights;}}
return vec3f(select(unconvolved_irradiance.r,irradiance_sum.r/weight_sum.r,weight_sum.r>=1e-5f),
select(unconvolved_irradiance.g,irradiance_sum.g/weight_sum.g,weight_sum.g>=1e-5f),
select(unconvolved_irradiance.b,irradiance_sum.b/weight_sum.b,weight_sum.b>=1e-5f));}
`;x.IncludesShadersStoreWGSL[oK]||(x.IncludesShadersStoreWGSL[oK]=dve)});var cK,uve,eF=y(()=>{k();cK="pbrBlockNormalGeometric",uve=`var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-input.vPositionW);
#ifdef NORMAL
var normalW: vec3f=normalize(input.vNormalW);
#else
var normalW: vec3f=normalize(cross(dpdx(input.vPositionW),dpdy(input.vPositionW)))*scene.vEyePosition.w;
#endif
var geometricNormalW: vec3f=normalW;
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
geometricNormalW=select(-geometricNormalW,geometricNormalW,fragmentInputs.frontFacing);
#endif
`;x.IncludesShadersStoreWGSL[cK]||(x.IncludesShadersStoreWGSL[cK]=uve)});var fK,hve,dK=y(()=>{k();fK="openpbrNormalMapFragment",hve=`var uvOffset: vec2f= vec2f(0.0,0.0);
#if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL) || defined(PARALLAX) || defined(DETAIL)
#ifdef NORMALXYSCALE
var normalScale: f32=1.0;
#elif defined(GEOMETRY_NORMAL)
var normalScale: f32=uniforms.vGeometryNormalInfos.y;
#else
var normalScale: f32=1.0;
#endif
#if defined(TANGENT) && defined(NORMAL)
var TBN: mat3x3f=mat3x3<f32>(input.vTBN0,input.vTBN1,input.vTBN2);
#elif defined(GEOMETRY_NORMAL)
var TBNUV: vec2f=select(-fragmentInputs.vGeometryNormalUV,fragmentInputs.vGeometryNormalUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV,uniforms.vTangentSpaceParams);
#elif defined(GEOMETRY_COAT_NORMAL)
var TBNUV: vec2f=select(-fragmentInputs.vGeometryCoatNormalUV,fragmentInputs.vGeometryCoatNormalUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV,uniforms.vTangentSpaceParams);
#else
var TBNUV: vec2f=select(-fragmentInputs.vDetailUV,fragmentInputs.vDetailUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV, vec2f(1.,1.));
#endif
#elif defined(ANISOTROPIC) || defined(FUZZ)
#if defined(TANGENT) && defined(NORMAL)
var TBN: mat3x3f=mat3x3<f32>(input.vTBN0,input.vTBN1,input.vTBN2);
#else
var TBNUV: vec2f=select( -fragmentInputs.vMainUV1,fragmentInputs.vMainUV1,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW,input.vPositionW,TBNUV, vec2f(1.,1.));
#endif
#endif
#ifdef PARALLAX
var invTBN: mat3x3f=transposeMat3(TBN);
#ifdef PARALLAXOCCLUSION
#else
#endif
#endif
#ifdef DETAIL
var detailColor: vec4f=textureSample(detailSampler,detailSamplerSampler,fragmentInputs.vDetailUV+uvOffset);var detailNormalRG: vec2f=detailColor.wy*2.0-1.0;var detailNormalB: f32=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));var detailNormal: vec3f= vec3f(detailNormalRG,detailNormalB);
#endif
#ifdef GEOMETRY_COAT_NORMAL
coatNormalW=perturbNormal(TBN,textureSample(geometryCoatNormalSampler,geometryCoatNormalSamplerSampler,fragmentInputs.vGeometryCoatNormalUV+uvOffset).xyz,uniforms.vGeometryCoatNormalInfos.y);
#endif
#ifdef GEOMETRY_NORMAL
#ifdef OBJECTSPACE_NORMALMAP
#define CUSTOM_FRAGMENT_BUMP_FRAGMENT
normalW=normalize(textureSample(geometryNormalSampler,geometryNormalSamplerSampler,fragmentInputs.vGeometryNormalUV).xyz *2.0-1.0);normalW=normalize(mat3x3f(uniforms.normalMatrix[0].xyz,uniforms.normalMatrix[1].xyz,uniforms.normalMatrix[2].xyz)*normalW);
#elif !defined(DETAIL)
normalW=perturbNormal(TBN,textureSample(geometryNormalSampler,geometryNormalSamplerSampler,fragmentInputs.vGeometryNormalUV+uvOffset).xyz,uniforms.vGeometryNormalInfos.y);
#else
var sampledNormal: vec3f=textureSample(geometryNormalSampler,geometryNormalSamplerSampler,fragmentInputs.vGeometryNormalUV+uvOffset).xyz*2.0-1.0;
#if DETAIL_NORMALBLENDMETHOD==0
detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);var blendedNormal: vec3f=normalize( vec3f(sampledNormal.xy+detailNormal.xy,sampledNormal.z*detailNormal.z));
#elif DETAIL_NORMALBLENDMETHOD==1
detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);sampledNormal+= vec3f(0.0,0.0,1.0);detailNormal*= vec3f(-1.0,-1.0,1.0);var blendedNormal: vec3f=sampledNormal*dot(sampledNormal,detailNormal)/sampledNormal.z-detailNormal;
#endif
normalW=perturbNormalBase(TBN,blendedNormal,uniforms.vGeometryNormalInfos.y);
#endif
#elif defined(DETAIL)
detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);normalW=perturbNormalBase(TBN,detailNormal,uniforms.vDetailInfos.z);
#endif
`;x.IncludesShadersStoreWGSL[fK]||(x.IncludesShadersStoreWGSL[fK]=hve)});var uK,mve,hK=y(()=>{k();uK="openpbrBlockNormalFinal",mve=`#if defined(FORCENORMALFORWARD) && defined(NORMAL)
var faceNormal: vec3f=normalize(cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW)))*scene.vEyePosition.w;
#if defined(TWOSIDEDLIGHTING)
faceNormal=select(-faceNormal,faceNormal,fragmentInputs.frontFacing);
#endif
normalW*=sign(dot(normalW,faceNormal));coatNormalW*=sign(dot(coatNormalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
#if defined(MIRRORED)
normalW=select(normalW,-normalW,fragmentInputs.frontFacing);coatNormalW=select(coatNormalW,-coatNormalW,fragmentInputs.frontFacing);
#else
normalW=select(-normalW,normalW,fragmentInputs.frontFacing);coatNormalW=select(-coatNormalW,coatNormalW,fragmentInputs.frontFacing);
#endif
#endif
`;x.IncludesShadersStoreWGSL[uK]||(x.IncludesShadersStoreWGSL[uK]=mve)});var mK,pve,pK=y(()=>{k();mK="openpbrBaseLayerData",pve=`var base_color=vec3f(0.8);var base_metalness: f32=0.0;var base_diffuse_roughness: f32=0.0;var specular_weight: f32=1.0;var specular_roughness: f32=0.3;var specular_color: vec3f=vec3f(1.0);var specular_roughness_anisotropy: f32=0.0;var specular_ior: f32=1.5;var alpha: f32=1.0;var geometry_tangent: vec2f=vec2f(1.0,0.0);var geometry_thickness: f32=0.0;
#ifdef BASE_WEIGHT
let baseWeightFromTexture: vec4f=textureSample(baseWeightSampler,baseWeightSamplerSampler,fragmentInputs.vBaseWeightUV+uvOffset);
#endif
#ifdef BASE_COLOR
let baseColorFromTexture: vec4f=textureSample(baseColorSampler,baseColorSamplerSampler,fragmentInputs.vBaseColorUV+uvOffset);
#endif
#ifdef BASE_METALNESS
let metallicFromTexture: vec4f=textureSample(baseMetalnessSampler,baseMetalnessSamplerSampler,fragmentInputs.vBaseMetalnessUV+uvOffset);
#endif
#ifdef BASE_DIFFUSE_ROUGHNESS
let baseDiffuseRoughnessFromTexture: f32=textureSample(baseDiffuseRoughnessSampler,baseDiffuseRoughnessSamplerSampler,fragmentInputs.vBaseDiffuseRoughnessUV+uvOffset).r;
#endif
#ifdef GEOMETRY_TANGENT
let geometryTangentFromTexture: vec3f=textureSample(geometryTangentSampler,geometryTangentSamplerSampler,fragmentInputs.vGeometryTangentUV+uvOffset).rgb;
#endif
#ifdef SPECULAR_ROUGHNESS_ANISOTROPY
let anisotropyFromTexture: f32=textureSample(specularRoughnessAnisotropySampler,specularRoughnessAnisotropySamplerSampler,fragmentInputs.vSpecularRoughnessAnisotropyUV+uvOffset).r*uniforms.vSpecularRoughnessAnisotropyInfos.y;
#endif
#ifdef GEOMETRY_OPACITY
let opacityFromTexture: vec4f=textureSample(geometryOpacitySampler,geometryOpacitySamplerSampler,fragmentInputs.vGeometryOpacityUV+uvOffset);
#endif
#ifdef GEOMETRY_THICKNESS
let thicknessFromTexture: vec4f=textureSample(geometryThicknessSampler,geometryThicknessSamplerSampler,fragmentInputs.vGeometryThicknessUV+uvOffset);
#endif
#ifdef DECAL
let decalFromTexture: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset);
#endif
#ifdef SPECULAR_COLOR
let specularColorFromTexture: vec4f=textureSample(specularColorSampler,specularColorSamplerSampler,fragmentInputs.vSpecularColorUV+uvOffset);
#endif
#if defined(SPECULAR_WEIGHT)
#ifdef SPECULAR_WEIGHT_IN_ALPHA
let specularWeightFromTexture: f32=textureSample(specularWeightSampler,specularWeightSamplerSampler,fragmentInputs.vSpecularWeightUV+uvOffset).a;
#else
let specularWeightFromTexture: f32=textureSample(specularWeightSampler,specularWeightSamplerSampler,fragmentInputs.vSpecularWeightUV+uvOffset).r;
#endif
#endif
#if defined(ANISOTROPIC) || defined(FUZZ) || defined(REFRACTED_BACKGROUND) || defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING)
let noise=vec3f(2.0)*textureSample(blueNoiseSampler,blueNoiseSamplerSampler,fragmentInputs.position.xy/256.0).xyz-vec3f(1.0);
#endif
#if defined(SPECULAR_ROUGHNESS_FROM_METALNESS_TEXTURE_GREEN) && defined(BASE_METALNESS)
let roughnessFromTexture: f32=metallicFromTexture.g;
#elif defined(SPECULAR_ROUGHNESS)
let roughnessFromTexture: f32=textureSample(specularRoughnessSampler,specularRoughnessSamplerSampler,fragmentInputs.vSpecularRoughnessUV+uvOffset).r;
#endif
base_color=uniforms.vBaseColor.rgb;
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
base_color*=fragmentInputs.vColor.rgb;
#endif
#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)
alpha*=fragmentInputs.vColor.a;
#endif
base_color*=vec3(uniforms.vBaseWeight);alpha=uniforms.vBaseColor.a;base_metalness=uniforms.vReflectanceInfo.x;base_diffuse_roughness=uniforms.vBaseDiffuseRoughness;specular_roughness=uniforms.vReflectanceInfo.y;specular_color=uniforms.vSpecularColor.rgb;specular_weight=uniforms.vReflectanceInfo.a;specular_ior=uniforms.vReflectanceInfo.z;specular_roughness_anisotropy=uniforms.vSpecularAnisotropy.b;geometry_tangent=uniforms.vSpecularAnisotropy.rg;geometry_thickness=uniforms.vGeometryThickness;
#ifdef BASE_COLOR
#ifdef BASE_COLOR_GAMMA
base_color*=toLinearSpace(baseColorFromTexture.rgb);
#else
base_color*=baseColorFromTexture.rgb;
#endif
base_color*=uniforms.vBaseColorInfos.y;
#endif
#ifdef BASE_WEIGHT
base_color*=baseWeightFromTexture.r;
#endif
#if defined(BASE_COLOR) && defined(ALPHA_FROM_BASE_COLOR_TEXTURE)
alpha*=baseColorFromTexture.a;
#elif defined(GEOMETRY_OPACITY)
alpha*=opacityFromTexture.a;alpha*=uniforms.vGeometryOpacityInfos.y;
#endif
#ifdef GEOMETRY_THICKNESS
#ifdef GEOMETRY_THICKNESS_FROM_GREEN_CHANNEL
geometry_thickness*=thicknessFromTexture.g;
#else
geometry_thickness*=thicknessFromTexture.r;
#endif
geometry_thickness*=uniforms.vGeometryThicknessInfos.y;
#endif
#ifdef ALPHATEST
#if DEBUGMODE != 88
if (alpha<ALPHATESTVALUE)
discard;
#endif
#ifndef ALPHABLEND
alpha=1.0;
#endif
#endif
#ifdef BASE_METALNESS
#ifdef BASE_METALNESS_FROM_METALNESS_TEXTURE_BLUE
base_metalness*=metallicFromTexture.b;
#else
base_metalness*=metallicFromTexture.r;
#endif
#endif
#ifdef BASE_DIFFUSE_ROUGHNESS
base_diffuse_roughness*=baseDiffuseRoughnessFromTexture*uniforms.vBaseDiffuseRoughnessInfos.y;
#endif
#ifdef SPECULAR_COLOR
#ifdef SPECULAR_COLOR_GAMMA
specular_color*=toLinearSpace(specularColorFromTexture.rgb);
#else
specular_color*=specularColorFromTexture.rgb;
#endif
#endif
#ifdef SPECULAR_WEIGHT_FROM_SPECULAR_COLOR_TEXTURE
specular_weight*=specularColorFromTexture.a;
#elif defined(SPECULAR_WEIGHT)
specular_weight*=specularWeightFromTexture;
#endif
#if defined(SPECULAR_ROUGHNESS) || (defined(SPECULAR_ROUGHNESS_FROM_METALNESS_TEXTURE_GREEN) && defined(BASE_METALNESS))
specular_roughness*=roughnessFromTexture;
#endif
#ifdef GEOMETRY_TANGENT
{let tangentFromTexture: vec2f=normalize(geometryTangentFromTexture.xy*vec2f(2.0f)-vec2f(1.0f));let tangent_angle_texture: f32=atan2(tangentFromTexture.y,tangentFromTexture.x);let tangent_angle_uniform: f32=atan2(geometry_tangent.y,geometry_tangent.x);let tangent_angle: f32=tangent_angle_texture+tangent_angle_uniform;geometry_tangent=vec2f(cos(tangent_angle),sin(tangent_angle));}
#endif
#if defined(GEOMETRY_TANGENT) && defined(SPECULAR_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE)
specular_roughness_anisotropy*=geometryTangentFromTexture.b;
#elif defined(SPECULAR_ROUGHNESS_ANISOTROPY)
specular_roughness_anisotropy*=anisotropyFromTexture;
#endif
#ifdef DETAIL
let detailRoughness: f32=mix(0.5f,detailColor.b,vDetailInfos.w);let loLerp: f32=mix(0.f,specular_roughness,detailRoughness*2.f);let hiLerp: f32=mix(specular_roughness,1.f,(detailRoughness-0.5f)*2.f);specular_roughness=mix(loLerp,hiLerp,step(detailRoughness,0.5f));
#endif
#ifdef USE_GLTF_STYLE_ANISOTROPY
let baseAlpha: f32=specular_roughness*specular_roughness;let roughnessT: f32=mix(baseAlpha,1.0f,specular_roughness_anisotropy*specular_roughness_anisotropy);let roughnessB: f32=baseAlpha;specular_roughness_anisotropy=1.0f-roughnessB/max(roughnessT,0.00001f);specular_roughness=sqrt(roughnessT/sqrt(2.0f/(1.0f+(1.0f-specular_roughness_anisotropy)*(1.0f-specular_roughness_anisotropy))));
#endif
`;x.IncludesShadersStoreWGSL[mK]||(x.IncludesShadersStoreWGSL[mK]=pve)});var gK,gve,_K=y(()=>{k();gK="openpbrCoatLayerData",gve=`var coat_weight: f32=0.0f;var coat_color: vec3f=vec3f(1.0f);var coat_roughness: f32=0.0f;var coat_roughness_anisotropy: f32=0.0f;var coat_ior: f32=1.6f;var coat_darkening: f32=1.0f;var geometry_coat_tangent: vec2f=vec2f(1.0f,0.0f);
#ifdef COAT_WEIGHT
var coatWeightFromTexture: vec4f=textureSample(coatWeightSampler,coatWeightSamplerSampler,fragmentInputs.vCoatWeightUV+uvOffset);
#endif
#ifdef COAT_COLOR
var coatColorFromTexture: vec4f=textureSample(coatColorSampler,coatColorSamplerSampler,fragmentInputs.vCoatColorUV+uvOffset);
#endif
#ifdef COAT_ROUGHNESS
var coatRoughnessFromTexture: vec4f=textureSample(coatRoughnessSampler,coatRoughnessSamplerSampler,fragmentInputs.vCoatRoughnessUV+uvOffset);
#endif
#ifdef COAT_ROUGHNESS_ANISOTROPY
var coatRoughnessAnisotropyFromTexture: f32=textureSample(coatRoughnessAnisotropySampler,coatRoughnessAnisotropySamplerSampler,fragmentInputs.vCoatRoughnessAnisotropyUV+uvOffset).r;
#endif
#ifdef COAT_DARKENING
var coatDarkeningFromTexture: vec4f=textureSample(coatDarkeningSampler,coatDarkeningSamplerSampler,fragmentInputs.vCoatDarkeningUV+uvOffset);
#endif
#ifdef GEOMETRY_COAT_TANGENT
var geometryCoatTangentFromTexture: vec3f=textureSample(geometryCoatTangentSampler,geometryCoatTangentSamplerSampler,fragmentInputs.vGeometryCoatTangentUV+uvOffset).rgb;
#endif
coat_color=uniforms.vCoatColor.rgb;coat_weight=uniforms.vCoatWeight;coat_roughness=uniforms.vCoatRoughness;coat_roughness_anisotropy=uniforms.vCoatRoughnessAnisotropy;coat_ior=uniforms.vCoatIor;coat_darkening=uniforms.vCoatDarkening;geometry_coat_tangent=uniforms.vGeometryCoatTangent.rg;
#ifdef COAT_WEIGHT
coat_weight*=coatWeightFromTexture.r;
#endif
#ifdef COAT_COLOR
#ifdef COAT_COLOR_GAMMA
coat_color*=toLinearSpace(coatColorFromTexture.rgb);
#else
coat_color*=coatColorFromTexture.rgb;
#endif
coat_color*=uniforms.vCoatColorInfos.y;
#endif
#ifdef COAT_ROUGHNESS
#ifdef COAT_ROUGHNESS_FROM_GREEN_CHANNEL
coat_roughness*=coatRoughnessFromTexture.g;
#else
coat_roughness*=coatRoughnessFromTexture.r;
#endif
#endif
#if defined(GEOMETRY_COAT_TANGENT) && defined(COAT_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE)
coat_roughness_anisotropy*=geometryCoatTangentFromTexture.b;
#elif defined(COAT_ROUGHNESS_ANISOTROPY)
coat_roughness_anisotropy*=coatRoughnessAnisotropyFromTexture;
#endif
#ifdef COAT_DARKENING
coat_darkening*=coatDarkeningFromTexture.r;
#endif
#ifdef GEOMETRY_COAT_TANGENT
{let tangentFromTexture: vec2f=normalize(geometryCoatTangentFromTexture.xy*vec2f(2.0f)-vec2f(1.0f));let tangent_angle_texture: f32=atan2(tangentFromTexture.y,tangentFromTexture.x);let tangent_angle_uniform: f32=atan2(geometry_coat_tangent.y,geometry_coat_tangent.x);let tangent_angle: f32=tangent_angle_texture+tangent_angle_uniform;geometry_coat_tangent=vec2f(cos(tangent_angle),sin(tangent_angle));}
#endif
#ifdef USE_GLTF_STYLE_ANISOTROPY
let coatAlpha: f32=coat_roughness*coat_roughness;let coatRoughnessT: f32=mix(coatAlpha,1.0f,coat_roughness_anisotropy*coat_roughness_anisotropy);let coatRoughnessB: f32=coatAlpha;coat_roughness_anisotropy=1.0f-coatRoughnessB/max(coatRoughnessT,0.00001f);coat_roughness=sqrt(coatRoughnessT/sqrt(2.0f/(1.0f+(1.0f-coat_roughness_anisotropy)*(1.0f-coat_roughness_anisotropy))));
#endif
`;x.IncludesShadersStoreWGSL[gK]||(x.IncludesShadersStoreWGSL[gK]=gve)});var vK,_ve,EK=y(()=>{k();vK="openpbrThinFilmLayerData",_ve=`#ifdef THIN_FILM
var thin_film_weight: f32=uniforms.vThinFilmWeight;var thin_film_thickness: f32=uniforms.vThinFilmThickness.r*1000.0f;
var thin_film_ior: f32=uniforms.vThinFilmIor;
#ifdef THIN_FILM_WEIGHT
var thinFilmWeightFromTexture: f32=textureSample(thinFilmWeightSampler,thinFilmWeightSamplerSampler,fragmentInputs.vThinFilmWeightUV+uvOffset).r*uniforms.vThinFilmWeightInfos.y;
#endif
#ifdef THIN_FILM_THICKNESS
var thinFilmThicknessFromTexture: f32=textureSample(thinFilmThicknessSampler,thinFilmThicknessSamplerSampler,fragmentInputs.vThinFilmThicknessUV+uvOffset).g*uniforms.vThinFilmThicknessInfos.y;
#endif
#ifdef THIN_FILM_WEIGHT
thin_film_weight*=thinFilmWeightFromTexture;
#endif
#ifdef THIN_FILM_THICKNESS
thin_film_thickness*=thinFilmThicknessFromTexture;
#endif
let thin_film_ior_scale: f32=clamp(2.0f*abs(thin_film_ior-1.0f),0.0f,1.0f);
#endif
`;x.IncludesShadersStoreWGSL[vK]||(x.IncludesShadersStoreWGSL[vK]=_ve)});var SK,vve,TK=y(()=>{k();SK="openpbrFuzzLayerData",vve=`var fuzz_weight: f32=0.0f;var fuzz_color: vec3f=vec3f(1.0f);var fuzz_roughness: f32=0.0f;
#ifdef FUZZ
#ifdef FUZZ_WEIGHT
let fuzzWeightFromTexture: vec4f=textureSample(fuzzWeightSampler,fuzzWeightSamplerSampler,fragmentInputs.vFuzzWeightUV+uvOffset);
#endif
#ifdef FUZZ_COLOR
var fuzzColorFromTexture: vec4f=textureSample(fuzzColorSampler,fuzzColorSamplerSampler,fragmentInputs.vFuzzColorUV+uvOffset);
#endif
#ifdef FUZZ_ROUGHNESS
let fuzzRoughnessFromTexture: vec4f=textureSample(fuzzRoughnessSampler,fuzzRoughnessSamplerSampler,fragmentInputs.vFuzzRoughnessUV+uvOffset);
#endif
fuzz_color=uniforms.vFuzzColor.rgb;fuzz_weight=uniforms.vFuzzWeight;fuzz_roughness=uniforms.vFuzzRoughness;
#ifdef FUZZ_WEIGHT
fuzz_weight*=fuzzWeightFromTexture.r;
#endif
#ifdef FUZZ_COLOR
#ifdef FUZZ_COLOR_GAMMA
fuzz_color*=toLinearSpace(fuzzColorFromTexture.rgb);
#else
fuzz_color*=fuzzColorFromTexture.rgb;
#endif
fuzz_color*=uniforms.vFuzzColorInfos.y;
#endif
#if defined(FUZZ_ROUGHNESS) && defined(FUZZ_ROUGHNESS_FROM_TEXTURE_ALPHA)
fuzz_roughness*=fuzzRoughnessFromTexture.a;
#elif defined(FUZZ_ROUGHNESS)
fuzz_roughness*=fuzzRoughnessFromTexture.r;
#endif
#endif
`;x.IncludesShadersStoreWGSL[SK]||(x.IncludesShadersStoreWGSL[SK]=vve)});var AK,Eve,xK=y(()=>{k();AK="openpbrAmbientOcclusionData",Eve=`var ambient_occlusion: vec3f=vec3f(1.0f,1.0f,1.0f);var specular_ambient_occlusion: f32=1.0f;var coat_specular_ambient_occlusion: f32=1.0f;
#ifdef AMBIENT_OCCLUSION
var ambientOcclusionFromTexture: vec3f=textureSample(ambientOcclusionSampler,ambientOcclusionSamplerSampler,fragmentInputs.vAmbientOcclusionUV+uvOffset).rgb;ambient_occlusion=vec3f(ambientOcclusionFromTexture.r*uniforms.vAmbientOcclusionInfos.y+(1.0f-uniforms.vAmbientOcclusionInfos.y));
#endif
`;x.IncludesShadersStoreWGSL[AK]||(x.IncludesShadersStoreWGSL[AK]=Eve)});var RK,Sve,bK=y(()=>{k();RK="openpbrBackgroundTransmission",Sve=`var slab_translucent_background: vec4f=vec4f(0.,0.,0.,1.);
#ifdef REFRACTED_BACKGROUND
{let refractionLOD: f32=min(transmission_roughness,0.7)*uniforms.vBackgroundRefractionInfos.x;let lodTexelSize: f32=pow(2.0f,refractionLOD-uniforms.vBackgroundRefractionInfos.x);
#ifdef DISPERSION
{
#ifdef REFRACTION_HIGH_QUALITY_BLUR
{var dispResult: vec3f=vec3f(0.0);var dispWeight: vec3f=vec3f(0.0);let noiseOffset: vec2f=noise.xy*select(0.0f,lodTexelSize,refractionLOD>0.0f);for (var k: i32=0; k<6; k++) {let t: f32=(f32(k)+noise.y)/6.0f;let t_rg: f32=clamp(t*2.0f,0.0f,1.0f);let t_gb: f32=clamp((t-0.5f)*2.0f,0.0f,1.0f);let refVec: vec3f=mix(mix(refractedViewVectors[0],refractedViewVectors[1],t_rg),refractedViewVectors[2],t_gb);let uvw: vec3f=vec3f((uniforms.backgroundRefractionMatrix*(scene.view*vec4f(fragmentInputs.vPositionW+refVec*geometry_thickness,1.0f))).xyz);var coords: vec2f=uvw.xy/uvw.z;coords.y=1.0f-coords.y;let s: vec4f=textureSampleLevel(backgroundRefractionSampler,backgroundRefractionSamplerSampler,coords+noiseOffset,refractionLOD);let rw: f32=max(0.0f,1.0f-2.0f*t);let gw: f32=max(0.0f,1.0f-abs(2.0f*t-1.0f));let bw: f32=max(0.0f,2.0f*t-1.0f);let w: vec3f=vec3f(rw,gw,bw);dispResult+=s.rgb*w;dispWeight+=w;}
slab_translucent_background=vec4f(dispResult/max(dispWeight,vec3f(1e-6)),1.0f);}
#else
for (var i: i32=0; i<3; i++) {let refractedViewVector: vec3f=refractedViewVectors[i];let uvw: vec3f=vec3f((uniforms.backgroundRefractionMatrix*(scene.view*vec4f(fragmentInputs.vPositionW+refractedViewVector*geometry_thickness,1.0f))).xyz);var coords: vec2f=uvw.xy/uvw.z;coords.y=1.0f-coords.y;if (refractionLOD>0.0f) {let noiseOffset: vec2f=noise.xy*lodTexelSize;slab_translucent_background[i]=textureSampleLevel(backgroundRefractionSampler,backgroundRefractionSamplerSampler,coords+noiseOffset,refractionLOD)[i];} else {slab_translucent_background[i]=textureSampleLevel(backgroundRefractionSampler,backgroundRefractionSamplerSampler,coords,0.0f)[i];}}
#endif
}
#else
{let refractionUVW: vec3f=vec3f((uniforms.backgroundRefractionMatrix*(scene.view*vec4f(fragmentInputs.vPositionW+refractedViewVector*geometry_thickness,1.0f))).xyz);var refractionCoords: vec2f=refractionUVW.xy/refractionUVW.z;refractionCoords.y=1.0f-refractionCoords.y;if (refractionLOD>0.0f) {
#ifdef REFRACTION_HIGH_QUALITY_BLUR
let cosA: f32=cos(noise.x*PI);let sinA: f32=sin(noise.x*PI);let u: vec2f=vec2f( cosA,sinA)*(0.5f*lodTexelSize);let v: vec2f=vec2f(-sinA,cosA)*(0.5f*lodTexelSize);slab_translucent_background=0.25f*(
textureSampleLevel(backgroundRefractionSampler,backgroundRefractionSamplerSampler,refractionCoords+u+v,refractionLOD) +
textureSampleLevel(backgroundRefractionSampler,backgroundRefractionSamplerSampler,refractionCoords-u+v,refractionLOD) +
textureSampleLevel(backgroundRefractionSampler,backgroundRefractionSamplerSampler,refractionCoords+u-v,refractionLOD) +
textureSampleLevel(backgroundRefractionSampler,backgroundRefractionSamplerSampler,refractionCoords-u-v,refractionLOD)
);
#else
let noiseOffset: vec2f=noise.xy*lodTexelSize;slab_translucent_background=textureSampleLevel(backgroundRefractionSampler,backgroundRefractionSamplerSampler,refractionCoords+noiseOffset,refractionLOD);
#endif
} else {slab_translucent_background=textureSampleLevel(backgroundRefractionSampler,backgroundRefractionSamplerSampler,refractionCoords,0.0f);}}
#endif
}
#endif
`;x.IncludesShadersStoreWGSL[RK]||(x.IncludesShadersStoreWGSL[RK]=Sve)});var MK,Tve,yK=y(()=>{k();MK="openpbrEnvironmentLighting",Tve=`#if defined(REFLECTION) || defined(REFRACTED_BACKGROUND)
var coatAbsorption=vec3f(1.0f);var coatIblFresnel: f32=0.0;if (coat_weight>0.0) {coatIblFresnel=computeDielectricIblFresnel(coatReflectance,coatGeoInfo.environmentBrdf);let hemisphere_avg_fresnel: f32=coatReflectance.F0+0.5f*(1.0f-coatReflectance.F0);var averageReflectance: f32=(coatIblFresnel+hemisphere_avg_fresnel)*0.5f;let roughnessFactor=1.0f-coat_roughness*0.5f;averageReflectance*=roughnessFactor;var darkened_transmission: f32=(1.0f-averageReflectance)*(1.0f-averageReflectance);darkened_transmission=mix(1.0,darkened_transmission,coat_darkening);var sin2: f32=1.0f-coatGeoInfo.NdotV*coatGeoInfo.NdotV;sin2=sin2/(coat_ior*coat_ior);let cos_t: f32=sqrt(1.0f-sin2);let coatPathLength=1.0f/cos_t;let colored_transmission: vec3f=pow(coat_color,vec3f(coatPathLength));coatAbsorption=mix(vec3f(1.0f),colored_transmission*darkened_transmission,coat_weight);}
#endif
#ifdef REFLECTION
#ifdef FUZZ
let environmentFuzzBrdf: vec3f=getFuzzBRDFLookup(fuzzGeoInfo.NdotV,sqrt(fuzz_roughness));
#endif
var baseDiffuseEnvironmentLight: vec3f=sampleIrradiance(
normalW
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,vEnvironmentIrradiance
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,uniforms.reflectionMatrix
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
,irradianceSamplerSampler
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
,uniforms.vReflectionDominantDirection
#endif
#endif
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
,icdfSamplerSampler
#endif
#endif
,uniforms.vReflectionInfos
,viewDirectionW
,base_diffuse_roughness
,base_color
);
#ifdef REFLECTIONMAP_3D
var reflectionCoords: vec3f=vec3f(0.f,0.f,0.f);
#else
var reflectionCoords: vec2f=vec2f(0.f,0.f);
#endif
let specularAlphaG: f32=specular_roughness*specular_roughness;
#ifdef ANISOTROPIC_BASE
var baseSpecularEnvironmentLight: vec3f=sampleRadianceAnisotropic(specularAlphaG,uniforms.vReflectionMicrosurfaceInfos.rgb,uniforms.vReflectionInfos
,baseGeoInfo
,normalW
,viewDirectionW
,fragmentInputs.vPositionW
,noise
,false
,1.0
,reflectionSampler
,reflectionSamplerSampler
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#endif
);
#else
reflectionCoords=createReflectionCoords(fragmentInputs.vPositionW,normalW);var baseSpecularEnvironmentLight: vec3f=sampleRadiance(specularAlphaG,uniforms.vReflectionMicrosurfaceInfos.rgb,uniforms.vReflectionInfos
,baseGeoInfo
,reflectionSampler
,reflectionSamplerSampler
,reflectionCoords
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#endif
);
#endif
#ifdef ANISOTROPIC_BASE
baseSpecularEnvironmentLight=mix(baseSpecularEnvironmentLight.rgb,baseDiffuseEnvironmentLight,specularAlphaG*specularAlphaG *max(1.0f-baseGeoInfo.anisotropy,0.3f));
#else
baseSpecularEnvironmentLight=mix(baseSpecularEnvironmentLight.rgb,baseDiffuseEnvironmentLight,specularAlphaG);
#endif
var coatEnvironmentLight: vec3f=vec3f(0.f,0.f,0.f);if (coat_weight>0.0) {
#ifdef REFLECTIONMAP_3D
var reflectionCoords: vec3f=vec3f(0.f,0.f,0.f);
#else
var reflectionCoords: vec2f=vec2f(0.f,0.f);
#endif
reflectionCoords=createReflectionCoords(fragmentInputs.vPositionW,coatNormalW);var coatAlphaG: f32=coat_roughness*coat_roughness;
#ifdef ANISOTROPIC_COAT
coatEnvironmentLight=sampleRadianceAnisotropic(coatAlphaG,uniforms.vReflectionMicrosurfaceInfos.rgb,uniforms.vReflectionInfos
,coatGeoInfo
,coatNormalW
,viewDirectionW
,fragmentInputs.vPositionW
,noise
,false
,1.0
,reflectionSampler
,reflectionSamplerSampler
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#endif
);
#else
coatEnvironmentLight=sampleRadiance(coatAlphaG,uniforms.vReflectionMicrosurfaceInfos.rgb,uniforms.vReflectionInfos
,coatGeoInfo
,reflectionSampler
,reflectionSamplerSampler
,reflectionCoords
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#endif
);
#endif
}
#ifdef FUZZ
let modifiedFuzzRoughness: f32=clamp(fuzz_roughness*(1.0f-0.5f*environmentFuzzBrdf.y),0.0f,1.0f);var fuzzEnvironmentLight=vec3f(0.0f,0.0f,0.0f);var totalWeight=0.0f;let fuzzIblFresnel: f32=sqrt(environmentFuzzBrdf.z);for (var i: i32=0; i<i32(FUZZ_IBL_SAMPLES); i++) {var angle: f32=(f32(i)+noise.x)*(3.141592f*2.0f/f32(FUZZ_IBL_SAMPLES));var fiberCylinderNormal: vec3f=normalize(cos(angle)*fuzzTangent+sin(angle)*fuzzBitangent);let fiberBend=min(environmentFuzzBrdf.x*environmentFuzzBrdf.x*modifiedFuzzRoughness,1.0f);fiberCylinderNormal=normalize(mix(fiberCylinderNormal,fuzzNormalW,fiberBend));let sampleWeight=max(dot(viewDirectionW,fiberCylinderNormal),0.0f);var fuzzReflectionCoords=createReflectionCoords(fragmentInputs.vPositionW,fiberCylinderNormal);let radianceSample: vec3f=sampleRadiance(modifiedFuzzRoughness,uniforms.vReflectionMicrosurfaceInfos.rgb,uniforms.vReflectionInfos
,fuzzGeoInfo
,reflectionSampler
,reflectionSamplerSampler
,fuzzReflectionCoords
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#endif
);fuzzEnvironmentLight+=sampleWeight*mix(radianceSample,baseDiffuseEnvironmentLight,fiberBend);totalWeight+=sampleWeight;}
fuzzEnvironmentLight/=totalWeight;
#endif
var dielectricIblFresnel: f32=computeDielectricIblFresnel(baseDielectricReflectance,baseGeoInfo.environmentBrdf);var dielectricIblColoredFresnel: vec3f=dielectricIblFresnel*specular_color;
#ifdef THIN_FILM
let thin_film_cos_theta: f32=max(baseGeoInfo.NdotV,specularAlphaG);let thin_film_desaturation_scale=(thin_film_ior-1.0)*sqrt(thin_film_thickness*0.001f*thin_film_cos_theta);let tf_brdf_x: f32=baseGeoInfo.environmentBrdf.x;let tf_E_ss: f32 =baseGeoInfo.environmentBrdf.y;var thinFilmDielectricF0: vec3f=evalIridescence(thin_film_outside_ior,thin_film_ior,1.0,thin_film_thickness,vec3f(baseDielectricReflectance.F0));thinFilmDielectricF0=mix(thinFilmDielectricF0,vec3(dot(thinFilmDielectricF0,vec3f(0.3333f))),thin_film_desaturation_scale);var thinFilmDielectricDir: vec3f=evalIridescence(thin_film_outside_ior,thin_film_ior,thin_film_cos_theta,thin_film_thickness,vec3f(baseDielectricReflectance.F0));thinFilmDielectricDir=mix(thinFilmDielectricDir,vec3(dot(thinFilmDielectricDir,vec3f(0.3333f))),thin_film_desaturation_scale);let tf_f0d_avg: f32 =dot(thinFilmDielectricF0, vec3f(0.3333f));let tf_dird_avg: f32=dot(thinFilmDielectricDir,vec3f(0.3333f));var thin_film_dielectric: vec3f=thinFilmDielectricDir*(tf_f0d_avg/max(tf_dird_avg,1e-5));let tf_E_dielectric: vec3f=(vec3f(1.0)-thin_film_dielectric)*vec3f(tf_brdf_x)+thin_film_dielectric*vec3f(tf_E_ss);let tf_F_avg_dielectric: vec3f=thin_film_dielectric+(vec3f(1.0)-thin_film_dielectric)/21.0;let tf_ECF_dielectric: vec3f=vec3f(1.0)+tf_F_avg_dielectric*(vec3f(1.0)/vec3f(tf_E_ss)-vec3f(1.0));thin_film_dielectric=clamp(tf_E_dielectric*tf_ECF_dielectric,vec3f(0.0),vec3f(1.0));dielectricIblColoredFresnel=mix(dielectricIblColoredFresnel,thin_film_dielectric*specular_color,thin_film_weight*thin_film_ior_scale);dielectricIblFresnel=max(dielectricIblColoredFresnel.r,max(dielectricIblColoredFresnel.g,dielectricIblColoredFresnel.b));
#endif
var conductorIblFresnel: vec3f=computeConductorIblFresnel(baseConductorReflectance,baseGeoInfo.environmentBrdf);
#ifdef THIN_FILM
var thinFilmConductorF0: vec3f=evalIridescence(thin_film_outside_ior,thin_film_ior,1.0,thin_film_thickness,baseConductorReflectance.coloredF0);thinFilmConductorF0=mix(thinFilmConductorF0,vec3(dot(thinFilmConductorF0,vec3f(0.3333f))),thin_film_desaturation_scale);var thinFilmConductorDir: vec3f=evalIridescence(thin_film_outside_ior,thin_film_ior,thin_film_cos_theta,thin_film_thickness,baseConductorReflectance.coloredF0);thinFilmConductorDir=mix(thinFilmConductorDir,vec3(dot(thinFilmConductorDir,vec3f(0.3333f))),thin_film_desaturation_scale);let tf_f0c_avg: f32 =dot(thinFilmConductorF0, vec3f(0.3333f));let tf_dirc_avg: f32=dot(thinFilmConductorDir,vec3f(0.3333f));var thinFilmConductorRaw: vec3f=thinFilmConductorDir*(tf_f0c_avg/max(tf_dirc_avg,1e-5));
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR) && defined(ENVIRONMENTBRDF)
let tf_b: vec3f=getF82B(baseConductorReflectance.coloredF0,baseConductorReflectance.coloredF90);let tf_brdf_z: f32=baseGeoInfo.environmentBrdf.z/BRDF_Z_SCALE;let tf_E_conductor: vec3f=(vec3f(1.0)-thinFilmConductorRaw)*vec3f(tf_brdf_x)+thinFilmConductorRaw*vec3f(tf_E_ss)-tf_b*vec3f(tf_brdf_z);let tf_F_avg_conductor: vec3f=thinFilmConductorRaw+(vec3f(1.0)-thinFilmConductorRaw)/21.0-tf_b/126.0;
#else
let tf_E_conductor: vec3f=(vec3f(1.0)-thinFilmConductorRaw)*vec3f(tf_brdf_x)+thinFilmConductorRaw*vec3f(tf_E_ss);let tf_F_avg_conductor: vec3f=thinFilmConductorRaw+(vec3f(1.0)-thinFilmConductorRaw)/21.0;
#endif
let tf_ECF_conductor: vec3f=vec3f(1.0)+tf_F_avg_conductor*(vec3f(1.0)/vec3f(tf_E_ss)-vec3f(1.0));var thinFilmConductorFresnel: vec3f=specular_weight*clamp(tf_E_conductor*tf_ECF_conductor,vec3f(0.0),vec3f(1.0));conductorIblFresnel=mix(conductorIblFresnel,thinFilmConductorFresnel,thin_film_weight*thin_film_ior_scale);
#endif
var slab_diffuse_ibl: vec3f=vec3f(0.,0.,0.);var slab_glossy_ibl: vec3f=vec3f(0.,0.,0.);var slab_metal_ibl: vec3f=vec3f(0.,0.,0.);var slab_coat_ibl: vec3f=vec3f(0.,0.,0.);slab_diffuse_ibl=baseDiffuseEnvironmentLight*uniforms.vLightingIntensity.z;
#ifdef AMBIENT_OCCLUSION
specular_ambient_occlusion=compute_specular_occlusion(baseGeoInfo.NdotV,base_metalness,ambient_occlusion.x,specular_roughness);
#endif
slab_glossy_ibl=baseSpecularEnvironmentLight*uniforms.vLightingIntensity.z;slab_metal_ibl=baseSpecularEnvironmentLight*conductorIblFresnel*uniforms.vLightingIntensity.z;if (coat_weight>0.0) {slab_coat_ibl=coatEnvironmentLight*uniforms.vLightingIntensity.z;
#ifdef AMBIENT_OCCLUSION
coat_specular_ambient_occlusion=compute_specular_occlusion(coatGeoInfo.NdotV,0.0,ambient_occlusion.x,coat_roughness);
#endif
}
#ifdef FUZZ
var slab_fuzz_ibl=fuzzEnvironmentLight*uniforms.vLightingIntensity.z;
#endif
var slab_translucent_base_ibl: vec3f=vec3f(0.0f,0.0f,0.0f);
#ifdef REFRACTED_ENVIRONMENT
#ifdef ANISOTROPIC_BASE
var forwardScatteredEnvironmentLight: vec3f=sampleRadianceAnisotropic(transmission_roughness_alpha,uniforms.vReflectionMicrosurfaceInfos.rgb,uniforms.vReflectionInfos
,baseGeoInfo
#ifdef GEOMETRY_THIN_WALLED
,viewDirectionW
#else
,normalW
#endif
,viewDirectionW
,fragmentInputs.vPositionW
,noise
,true
#ifdef GEOMETRY_THIN_WALLED
,1.05f
#else
,specular_ior
#endif
,reflectionSampler
,reflectionSamplerSampler
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#endif
);
#else
var forwardScatteredEnvironmentLight: vec3f=vec3f(0.,0.,0.);
#ifdef DISPERSION
for (var i: i32=0; i<3; i++) {var iblRefractionCoords: vec3f=refractedViewVectors[i];
#else
var iblRefractionCoords: vec3f=refractedViewVector;
#endif
#ifdef REFRACTED_ENVIRONMENT_OPPOSITEZ
iblRefractionCoords.z*=-1.0f;
#endif
#ifdef REFRACTED_ENVIRONMENT_LOCAL_CUBE
iblRefractionCoords=parallaxCorrectNormal(fragmentInputs.vPositionW,refractedViewVector,uniforms.refractionSize,uniforms.refractionPosition);
#endif
iblRefractionCoords=(uniforms.reflectionMatrix*vec4f(iblRefractionCoords,0.0f)).xyz;
#ifdef DISPERSION
forwardScatteredEnvironmentLight[i]=sampleRadiance(transmission_roughness_alpha,uniforms.vReflectionMicrosurfaceInfos.rgb,uniforms.vReflectionInfos
,baseGeoInfo
,reflectionSampler
,reflectionSamplerSampler
,iblRefractionCoords
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#endif
)[i];
#else
forwardScatteredEnvironmentLight=sampleRadiance(transmission_roughness_alpha,uniforms.vReflectionMicrosurfaceInfos.rgb,uniforms.vReflectionInfos
,baseGeoInfo
,reflectionSampler
,reflectionSamplerSampler
,iblRefractionCoords
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#endif
);
#endif
#ifdef DISPERSION
}
#endif
#endif
#ifdef REFRACTED_BACKGROUND
#ifdef GEOMETRY_THIN_WALLED
forwardScatteredEnvironmentLight=mix(slab_translucent_background.rgb,forwardScatteredEnvironmentLight.rgb,0.2*transmission_roughness_alpha);
#else
forwardScatteredEnvironmentLight=max(slab_translucent_background.rgb,mix(slab_translucent_background.rgb,forwardScatteredEnvironmentLight,transmission_roughness_alpha));
#endif
#endif
#ifdef SCATTERING
#ifdef GEOMETRY_THIN_WALLED
var scatterVector: vec3f=normalW;
#else
#if defined(USEIRRADIANCEMAP) && defined(USE_IRRADIANCE_DOMINANT_DIRECTION)
var scatterVector: vec3f=mix(uniforms.vReflectionDominantDirection,normalW,max3(iso_scatter_density));
#else
var scatterVector: vec3f=normalW;
#endif
scatterVector=mix(viewDirectionW,scatterVector,back_to_iso_scattering_blend);
#endif
#if defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING) && !defined(GEOMETRY_THIN_WALLED)
var scatteredEnvironmentLight: vec3f=scattered_light_from_irradiance_texture;
#else
var scatteredEnvironmentLight: vec3f=sampleIrradiance(
scatterVector
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,vEnvironmentIrradiance
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,uniforms.reflectionMatrix
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
,irradianceSamplerSampler
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
,uniforms.vReflectionDominantDirection
#endif
#endif
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
,icdfSamplerSampler
#endif
#endif
,uniforms.vReflectionInfos
,viewDirectionW
#if defined(GEOMETRY_THIN_WALLED)
,base_diffuse_roughness
,subsurface_color.rgb
#else
,1.0f
,volumeParams.multi_scatter_color
#endif
);
#endif
#ifdef GEOMETRY_THIN_WALLED
let forward_scattered_light: vec3f=forwardScatteredEnvironmentLight*transmission_tint*volumeParams.multi_scatter_color;let back_scattered_light: vec3f=scatteredEnvironmentLight*volumeParams.multi_scatter_color;slab_translucent_base_ibl=mix(back_scattered_light,forward_scattered_light,0.5f+0.5f*volumeParams.anisotropy);
#else
let forward_scattered_light: vec3f=forwardScatteredEnvironmentLight*volume_absorption;let back_scattered_light: vec3f=mix(forward_scattered_light,scatteredEnvironmentLight*backscatter_color,iso_scatter_density);let iso_scattered_light: vec3f=mix(forward_scattered_light,scatteredEnvironmentLight*volumeParams.multi_scatter_color,iso_scatter_density);slab_translucent_base_ibl=mix(back_scattered_light,iso_scattered_light,back_to_iso_scattering_blend);slab_translucent_base_ibl=mix(slab_translucent_base_ibl,forward_scattered_light,iso_to_forward_scattering_blend)*transmission_tint;
#endif
#else
slab_translucent_base_ibl+=forwardScatteredEnvironmentLight*transmission_tint*volume_absorption;
#endif
#endif
#define CUSTOM_FRAGMENT_BEFORE_IBLLAYERCOMPOSITION
slab_diffuse_ibl*=ambient_occlusion;slab_metal_ibl*=specular_ambient_occlusion;slab_glossy_ibl*=specular_ambient_occlusion;slab_coat_ibl*=coat_specular_ambient_occlusion;let material_dielectric_base_ibl: vec3f=mix(slab_diffuse_ibl*base_color.rgb,slab_translucent_base_ibl,surface_translucency_weight);let material_dielectric_gloss_ibl: vec3f=material_dielectric_base_ibl*(1.0-dielectricIblFresnel)+slab_glossy_ibl*dielectricIblColoredFresnel;let material_base_substrate_ibl: vec3f=mix(material_dielectric_gloss_ibl,slab_metal_ibl,base_metalness);let material_coated_base_ibl: vec3f=layer(material_base_substrate_ibl,slab_coat_ibl,coatIblFresnel,coatAbsorption,vec3f(1.0f));
#ifdef FUZZ
slab_fuzz_ibl*=min(vec3(specular_ambient_occlusion),ambient_occlusion);material_surface_ibl=layer(material_coated_base_ibl,slab_fuzz_ibl,fuzzIblFresnel*fuzz_weight,vec3f(1.0f),fuzz_color);
#else
material_surface_ibl=material_coated_base_ibl;
#endif
#elif defined(REFRACTED_BACKGROUND)
let black=vec3f(0.0f);var slab_translucent_base_ibl: vec3f=vec3f(0.0f);
#ifdef GEOMETRY_THIN_WALLED
#ifdef SCATTERING
let forward_scattered_light: vec3f=slab_translucent_background.rgb*transmission_tint*volumeParams.multi_scatter_color;slab_translucent_base_ibl=mix(black,forward_scattered_light,0.5f+0.5f*volumeParams.anisotropy);
#else
slab_translucent_base_ibl=slab_translucent_background.rgb*transmission_tint;
#endif
#else
#ifdef SCATTERING
let forward_scattered_light: vec3f=slab_translucent_background.rgb*volume_absorption;let iso_scattered_light: vec3f=(1.0f-iso_scatter_density)*forward_scattered_light;slab_translucent_base_ibl=mix(black,iso_scattered_light,back_to_iso_scattering_blend);slab_translucent_base_ibl=mix(slab_translucent_base_ibl,forward_scattered_light,iso_to_forward_scattering_blend)*transmission_tint;
#else
slab_translucent_base_ibl=slab_translucent_background.rgb*volume_absorption*transmission_tint;
#endif
#endif
let material_dielectric_base_ibl: vec3f=mix(black,slab_translucent_base_ibl.rgb,surface_translucency_weight);let material_dielectric_gloss_ibl: vec3f=material_dielectric_base_ibl*(baseGeoInfo.NdotV);let material_base_substrate_ibl: vec3f=mix(material_dielectric_gloss_ibl,black,base_metalness);let material_coated_base_ibl: vec3f=layer(material_base_substrate_ibl,black,coatIblFresnel,coatAbsorption,vec3f(1.0f));material_surface_ibl=material_coated_base_ibl;
#endif
`;x.IncludesShadersStoreWGSL[MK]||(x.IncludesShadersStoreWGSL[MK]=Tve)});var IK,Ave,CK=y(()=>{k();IK="openpbrDirectLightingInit",Ave=`#ifdef LIGHT{X}
var preInfo{X}: preLightingInfo;var preInfoCoat{X}: preLightingInfo;let lightColor{X}: vec4f=light{X}.vLightDiffuse;var shadow{X}: f32=1.0f;
#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})
#else
#define CUSTOM_LIGHT{X}_COLOR
#ifdef SPOTLIGHT{X}
preInfo{X}=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,fragmentInputs.vPositionW);preInfoCoat{X}=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,coatNormalW,fragmentInputs.vPositionW);
#elif defined(POINTLIGHT{X})
preInfo{X}=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,fragmentInputs.vPositionW);preInfoCoat{X}=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,coatNormalW,fragmentInputs.vPositionW);
#elif defined(HEMILIGHT{X})
preInfo{X}=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);preInfoCoat{X}=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,coatNormalW);
#elif defined(DIRLIGHT{X})
preInfo{X}=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);preInfoCoat{X}=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,coatNormalW);
#elif defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
preInfo{X}=computeAreaPreLightingInfo(areaLightsLTC1Sampler,areaLightsLTC2Sampler,viewDirectionW,normalW,fragmentInputs.vPositionW,light{X}.vLightData,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,specular_roughness);preInfoCoat{X}=computeAreaPreLightingInfo(areaLightsLTC1Sampler,areaLightsLTC2Sampler,viewDirectionW,coatNormalW,fragmentInputs.vPositionW,light{X}.vLightData,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,coat_roughness);
#endif
preInfo{X}.NdotV=baseGeoInfo.NdotV;preInfoCoat{X}.NdotV=coatGeoInfo.NdotV;
#ifdef SPOTLIGHT{X}
#ifdef LIGHT_FALLOFF_GLTF{X}
preInfo{X}.attenuation=computeDistanceLightFalloff_GLTF(preInfo{X}.lightDistanceSquared,light{X}.vLightFalloff.y);
#ifdef IESLIGHTTEXTURE{X}
preInfo{X}.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo{X}.L,iesLightTexture{X});
#else
preInfo{X}.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo{X}.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
#endif
#elif defined(LIGHT_FALLOFF_PHYSICAL{X})
preInfo{X}.attenuation=computeDistanceLightFalloff_Physical(preInfo{X}.lightDistanceSquared);
#ifdef IESLIGHTTEXTURE{X}
preInfo{X}.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo{X}.L,iesLightTexture{X});
#else
preInfo{X}.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo{X}.L,light{X}.vLightDirection.w);
#endif
#elif defined(LIGHT_FALLOFF_STANDARD{X})
preInfo{X}.attenuation=computeDistanceLightFalloff_Standard(preInfo{X}.lightOffset,light{X}.vLightFalloff.x);
#ifdef IESLIGHTTEXTURE{X}
preInfo{X}.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo{X}.L,iesLightTexture{X});
#else
preInfo{X}.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo{X}.L,light{X}.vLightDirection.w,light{X}.vLightData.w);
#endif
#else
preInfo{X}.attenuation=computeDistanceLightFalloff(preInfo{X}.lightOffset,preInfo{X}.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);
#ifdef IESLIGHTTEXTURE{X}
preInfo{X}.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo{X}.L,iesLightTexture{X});
#else
preInfo{X}.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo{X}.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
#endif
#endif
#elif defined(POINTLIGHT{X})
#ifdef LIGHT_FALLOFF_GLTF{X}
preInfo{X}.attenuation=computeDistanceLightFalloff_GLTF(preInfo{X}.lightDistanceSquared,light{X}.vLightFalloff.y);
#elif defined(LIGHT_FALLOFF_PHYSICAL{X})
preInfo{X}.attenuation=computeDistanceLightFalloff_Physical(preInfo{X}.lightDistanceSquared);
#elif defined(LIGHT_FALLOFF_STANDARD{X})
preInfo{X}.attenuation=computeDistanceLightFalloff_Standard(preInfo{X}.lightOffset,light{X}.vLightFalloff.x);
#else
preInfo{X}.attenuation=computeDistanceLightFalloff(preInfo{X}.lightOffset,preInfo{X}.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);
#endif
#else
preInfo{X}.attenuation=1.0f;
#endif
preInfoCoat{X}.attenuation=preInfo{X}.attenuation;
#if defined(HEMILIGHT{X})
preInfo{X}.roughness=specular_roughness;preInfoCoat{X}.roughness=coat_roughness;
#elif defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
preInfo{X}.roughness=specular_roughness;preInfoCoat{X}.roughness=coat_roughness;
#else
preInfo{X}.roughness=adjustRoughnessFromLightProperties(specular_roughness,light{X}.vLightSpecular.a,preInfo{X}.lightDistance);preInfoCoat{X}.roughness=adjustRoughnessFromLightProperties(coat_roughness,light{X}.vLightSpecular.a,preInfoCoat{X}.lightDistance);
#endif
preInfo{X}.diffuseRoughness=base_diffuse_roughness;preInfo{X}.surfaceAlbedo=base_color.rgb;
#endif
#endif
`;x.IncludesShadersStoreWGSL[IK]||(x.IncludesShadersStoreWGSL[IK]=Ave)});var PK,xve,LK=y(()=>{k();PK="openpbrDirectLighting",xve=`#ifdef LIGHT{X}
{var slab_diffuse: vec3f=vec3f(0.f,0.f,0.f);var slab_translucent: vec3f=vec3f(0.f,0.f,0.f);var slab_glossy: vec3f=vec3f(0.f,0.f,0.f);var specularFresnel: f32=0.0f;var specularColoredFresnel: vec3f=vec3f(0.f,0.f,0.f);var slab_metal: vec3f=vec3f(0.f,0.f,0.f);var slab_coat: vec3f=vec3f(0.f,0.f,0.f);var coatFresnel: f32=0.0f;var slab_fuzz: vec3f=vec3f(0.f,0.f,0.f);var fuzzFresnel: f32=0.0f;
#ifdef HEMILIGHT{X}
slab_diffuse=computeHemisphericDiffuseLighting(preInfo{X},lightColor{X}.rgb,light{X}.vLightGround);
#elif defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
slab_diffuse=computeAreaDiffuseLighting(preInfo{X},lightColor{X}.rgb);
#else
slab_diffuse=computeDiffuseLighting(preInfo{X},lightColor{X}.rgb);
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
slab_diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},textureProjectionMatrix{X},fragmentInputs.vPositionW);
#endif
#ifdef FUZZ
let fuzzNdotH: f32=max(dot(fuzzNormalW,preInfo{X}.H),0.0f);let fuzzBrdf: vec3f=getFuzzBRDFLookup(fuzzNdotH,sqrt(fuzz_roughness));
#endif
#ifdef THIN_FILM
let thin_film_desaturation_scale: f32=(thin_film_ior-1.0f)*sqrt(thin_film_thickness*0.001f);
#endif
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
slab_glossy=computeAreaSpecularLighting(preInfo{X},light{X}.vLightSpecular.rgb,baseConductorReflectance.F0,baseConductorReflectance.F90);
#else
{
#ifdef ANISOTROPIC_BASE
slab_glossy=computeAnisotropicSpecularLighting(preInfo{X},viewDirectionW,normalW,
baseGeoInfo.anisotropicTangent,baseGeoInfo.anisotropicBitangent,baseGeoInfo.anisotropy,
0.0f,lightColor{X}.rgb);
#else
slab_glossy=computeSpecularLighting(preInfo{X},normalW,vec3(1.0),vec3(1.0),specular_roughness,lightColor{X}.rgb);
#endif
specularFresnel=fresnelSchlickGGX(preInfo{X}.VdotH,baseDielectricReflectance.F0,baseDielectricReflectance.F90);specularColoredFresnel=specularFresnel*specular_color;
#ifdef THIN_FILM
var thinFilmDielectricFresnel: vec3f=evalIridescence(thin_film_outside_ior,thin_film_ior,preInfo{X}.VdotH,thin_film_thickness,vec3f(baseDielectricReflectance.F0));thinFilmDielectricFresnel=mix(thinFilmDielectricFresnel,vec3f(dot(thinFilmDielectricFresnel,vec3f(0.3333f))),thin_film_desaturation_scale);specularColoredFresnel=mix(specularColoredFresnel,thinFilmDielectricFresnel*specular_color,thin_film_weight*thin_film_ior_scale);
#endif
}
#endif
#ifdef REFRACTED_LIGHTS
var forwardScatteredLight: vec3f=vec3f(0.0f);
#if AREALIGHT{X}
#else
{var preInfoTrans=preInfo{X};
#ifdef SCATTERING
preInfoTrans.roughness=sqrt(sqrt(max(transmission_roughness_alpha,0.05f)));
#else
preInfoTrans.roughness=transmission_roughness;
#endif
if (preInfoTrans.NdotLUnclamped<=0.0) {specularFresnel=0.0;specularColoredFresnel=specularFresnel*specular_color;}
#ifdef GEOMETRY_THIN_WALLED
let refractNormalW: vec3f=viewDirectionW;
#else
let refractNormalW: vec3f=normalW;
#endif
preInfoTrans.NdotL=0.5f*max(dot(-refractNormalW,preInfoTrans.L),0.0f)+0.5f;
#if defined(DISPERSION) && !defined(GEOMETRY_THIN_WALLED)
var dispersion_iors_local: vec3f=dispersion_iors;let diff: f32=min(dispersion_iors_local[2]-dispersion_iors_local[0],max(dispersion_iors_local[0]-1.0f,1.0f));dispersion_iors_local[2]+=diff;dispersion_iors_local[0]-=diff;for (var i: i32=0; i<3; i++) {let eta: f32=1.0f/dispersion_iors_local[i];
#elif defined(GEOMETRY_THIN_WALLED)
let eta: f32=1.0f;
#else
let eta: f32=1.0f/specular_ior;
#endif
preInfoTrans.H=preInfoTrans.L+min(eta,0.95f)*viewDirectionW;let len2: f32=dot(preInfoTrans.H,preInfoTrans.H);if (len2<1e-6f) {preInfoTrans.H=preInfoTrans.L;} else {preInfoTrans.H=preInfoTrans.H*inverseSqrt(len2);}
#ifdef ANISOTROPIC_BASE
preInfoTrans.H=-preInfoTrans.H;
#endif
preInfoTrans.VdotH=dot(viewDirectionW,preInfoTrans.H);
#if defined(DISPERSION) && !defined(GEOMETRY_THIN_WALLED)
forwardScatteredLight[i]+=
#else
forwardScatteredLight+=
#endif
#if defined(ANISOTROPIC_BASE)
computeAnisotropicSpecularLighting(preInfoTrans,viewDirectionW,refractNormalW,
baseGeoInfo.anisotropicTangent,baseGeoInfo.anisotropicBitangent,baseGeoInfo.anisotropy,
transmission_roughness_alpha,lightColor{X}.rgb
#else
computeSpecularLighting(preInfoTrans,-refractNormalW,vec3f(1.0f),vec3f(1.0f),transmission_roughness_alpha,lightColor{X}.rgb
#endif
#if defined(DISPERSION) && !defined(GEOMETRY_THIN_WALLED)
)[i];}
#else
);
#endif
#if !defined(GEOMETRY_THIN_WALLED)
forwardScatteredLight=mix(forwardScatteredLight,0.25f*preInfoTrans.attenuation*lightColor{X}.rgb,clamp(1.0f-pow(baseGeoInfo.NdotV,transmission_roughness_alpha),0.0f,1.0f));
#endif
#ifdef REFRACTED_BACKGROUND
#ifdef GEOMETRY_THIN_WALLED
forwardScatteredLight=mix(vec3f(0.0f),forwardScatteredLight.rgb,0.2*transmission_roughness_alpha);
#else
forwardScatteredLight=max(vec3f(0.0f),mix(vec3f(0.0f),forwardScatteredLight,transmission_roughness_alpha));
#endif
#endif
#ifdef SCATTERING
#if !defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING) || defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING_GBUFFER)
preInfoTrans.roughness=1.0f;let diffused_forward_scattered_light: vec3f=computeSpecularLighting(preInfoTrans,normalW,vec3f(1.0f),vec3f(1.0f),1.0f,lightColor{X}.rgb)*volume_absorption;
#endif
#ifdef GEOMETRY_THIN_WALLED
let forward_scattered_light: vec3f=forwardScatteredLight*transmission_tint*volumeParams.multi_scatter_color;let back_scattered_light: vec3f=slab_diffuse*volumeParams.multi_scatter_color;slab_translucent=mix(back_scattered_light,forward_scattered_light,0.5f+0.5f*volumeParams.anisotropy);
#else
let back_scattered_normal: vec3f=normalize(normalW+viewDirectionW);preInfoTrans.NdotL=max(dot(back_scattered_normal,preInfoTrans.L),0.0f);preInfoTrans.NdotV=dot(back_scattered_normal,viewDirectionW);preInfoTrans.H=normalize(viewDirectionW+preInfoTrans.L);preInfoTrans.VdotH=clamp(dot(viewDirectionW,preInfoTrans.H),0.0f,1.0f);preInfoTrans.roughness=0.2f;let back_scattered_light: vec3f=computeSpecularLighting(preInfoTrans,viewDirectionW,vec3f(1.0f),vec3f(0.08f),0.0f,lightColor{X}.rgb);let forward_scattered_light: vec3f=(forwardScatteredLight*volume_absorption);let iso_scattered_light: vec3f=slab_diffuse;let back_scattering: vec3f=mix(forward_scattered_light,forward_scattered_light+back_scattered_light*backscatter_color,iso_scatter_density);
#if defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING) && !defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING_GBUFFER)
let iso_scattering: vec3f=mix(forward_scattered_light,scattered_light_from_irradiance_texture*volumeParams.multi_scatter_color,iso_scatter_density);
#else
let iso_scattering: vec3f=mix(forward_scattered_light,(diffused_forward_scattered_light+iso_scattered_light)*volumeParams.multi_scatter_color,iso_scatter_density);
#endif
slab_translucent=mix(back_scattering,iso_scattering,back_to_iso_scattering_blend);slab_translucent=mix(slab_translucent,forward_scattered_light,iso_to_forward_scattering_blend)*transmission_tint;
#endif
#else
slab_translucent=forwardScatteredLight*transmission_tint*volume_absorption;
#endif
}
#endif
#endif
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
slab_metal=computeAreaSpecularLighting(preInfo{X},light{X}.vLightSpecular.rgb,baseConductorReflectance.F0,baseConductorReflectance.F90);
#else
{
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR)
var coloredFresnel: vec3f=getF82Specular(preInfo{X}.VdotH,baseConductorReflectance.coloredF0,baseConductorReflectance.coloredF90,specular_roughness);
#else
var coloredFresnel: vec3f=fresnelSchlickGGX(preInfo{X}.VdotH,baseConductorReflectance.coloredF0,baseConductorReflectance.coloredF90);
#endif
#ifdef THIN_FILM
let thinFilmConductorAngle: f32=max(preInfo{X}.VdotH,specular_roughness);var thinFilmConductorFresnel: vec3f=evalIridescence(thin_film_outside_ior,thin_film_ior,thinFilmConductorAngle,thin_film_thickness,baseConductorReflectance.coloredF0);thinFilmConductorFresnel=mix(thinFilmConductorFresnel,vec3f(dot(thinFilmConductorFresnel,vec3f(0.3333f))),thin_film_desaturation_scale);coloredFresnel=mix(coloredFresnel,specular_weight*thinFilmConductorFresnel,thin_film_weight*thin_film_ior_scale);
#endif
#ifdef ANISOTROPIC_BASE
slab_metal=computeAnisotropicSpecularLighting(preInfo{X},viewDirectionW,normalW,baseGeoInfo.anisotropicTangent,baseGeoInfo.anisotropicBitangent,baseGeoInfo.anisotropy,0.0,lightColor{X}.rgb);
#else
slab_metal=computeSpecularLighting(preInfo{X},normalW,vec3f(baseConductorReflectance.coloredF0),coloredFresnel,specular_roughness,lightColor{X}.rgb);
#endif
}
#endif
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
slab_coat=computeAreaSpecularLighting(preInfoCoat{X},light{X}.vLightSpecular.rgb,coatReflectance.F0,coatReflectance.F90);
#else
{
#ifdef ANISOTROPIC_COAT
slab_coat=computeAnisotropicSpecularLighting(preInfoCoat{X},viewDirectionW,coatNormalW,
coatGeoInfo.anisotropicTangent,coatGeoInfo.anisotropicBitangent,coatGeoInfo.anisotropy,0.0,
lightColor{X}.rgb);
#else
slab_coat=computeSpecularLighting(preInfoCoat{X},coatNormalW,vec3f(coatReflectance.F0),vec3f(1.0f),coat_roughness,lightColor{X}.rgb);
#endif
let NdotH: f32=saturateEps(dot(coatNormalW,preInfoCoat{X}.H));coatFresnel=fresnelSchlickGGX(NdotH,coatReflectance.F0,coatReflectance.F90);}
#endif
var coatAbsorption=vec3f(1.0f);if (coat_weight>0.0) {let cosTheta_view: f32=max(preInfoCoat{X}.NdotV,0.001f);let cosTheta_light: f32=max(preInfoCoat{X}.NdotL,0.001f);let fresnel_view: f32=coatReflectance.F0+(1.0f-coatReflectance.F0)*pow(1.0f-cosTheta_view,5.0);let fresnel_light: f32=coatReflectance.F0+(1.0f-coatReflectance.F0)*pow(1.0f-cosTheta_light,5.0);let averageReflectance: f32=(fresnel_view+fresnel_light)*0.5;var darkened_transmission: f32=(1.0f-averageReflectance)/(1.0f+averageReflectance);darkened_transmission=mix(1.0f,darkened_transmission,coat_darkening);var sin2: f32=1.0f-coatGeoInfo.NdotV*coatGeoInfo.NdotV;sin2=sin2/(coat_ior*coat_ior);let cos_t: f32=sqrt(1.0f-sin2);let coatPathLength=1.0f/cos_t;let colored_transmission: vec3f=pow(coat_color,vec3f(coatPathLength));coatAbsorption=mix(vec3f(1.0f),colored_transmission*vec3f(darkened_transmission),coat_weight);}
#ifdef FUZZ
fuzzFresnel=fuzzBrdf.z;let fuzzNormalW=mix(normalW,coatNormalW,coat_weight);let fuzzNdotV: f32=max(dot(fuzzNormalW,viewDirectionW.xyz),0.0f);let fuzzNdotL: f32=max(dot(fuzzNormalW,preInfo{X}.L),0.0);slab_fuzz=lightColor{X}.rgb*preInfo{X}.attenuation*evalFuzz(preInfo{X}.L,fuzzNdotL,fuzzNdotV,fuzzTangent,fuzzBitangent,fuzzBrdf);
#else
let fuzz_color=vec3f(0.0);
#endif
#ifdef PREPASS_IRRADIANCE
total_direct_diffuse+=slab_diffuse;
#endif
let material_dielectric_base: vec3f=mix(slab_diffuse*base_color.rgb,slab_translucent,surface_translucency_weight);let material_dielectric_gloss: vec3f=material_dielectric_base*(1.0f-specularFresnel)+slab_glossy*specularColoredFresnel;let material_base_substrate: vec3f=mix(material_dielectric_gloss,slab_metal,base_metalness);let material_coated_base: vec3f=layer(material_base_substrate,slab_coat,coatFresnel,coatAbsorption,vec3f(1.0f));material_surface_direct+=layer(material_coated_base,slab_fuzz,fuzzFresnel*fuzz_weight,vec3f(1.0f),fuzz_color);}
#endif
`;x.IncludesShadersStoreWGSL[PK]||(x.IncludesShadersStoreWGSL[PK]=xve)});var DK,Rve,tF=y(()=>{k();DK="pbrBlockImageProcessing",Rve=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)
#if !defined(SKIPFINALCOLORCLAMP)
finalColor=vec4f(clamp(finalColor.rgb,vec3f(0.),vec3f(30.0)),finalColor.a);
#endif
#else
finalColor=applyImageProcessing(finalColor);
#endif
finalColor=vec4f(finalColor.rgb,finalColor.a*mesh.visibility);
#ifdef PREMULTIPLYALPHA
finalColor=vec4f(finalColor.rgb*finalColor.a,finalColor.a);;
#endif
`;x.IncludesShadersStoreWGSL[DK]||(x.IncludesShadersStoreWGSL[DK]=Rve)});var OK,bve,NK=y(()=>{k();OK="openpbrBlockPrePass",bve=`#if SCENE_MRT_COUNT>0
var writeGeometryInfo: f32=select(0.0,1.0,finalColor.a>ALPHATESTVALUE);var fragData: array<vec4<f32>,SCENE_MRT_COUNT>;
#ifdef PREPASS_POSITION
fragData[PREPASS_POSITION_INDEX]= vec4f(fragmentInputs.vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_LOCAL_POSITION
fragData[PREPASS_LOCAL_POSITION_INDEX]=vec4f(fragmentInputs.vPosition,writeGeometryInfo);
#endif
#ifdef PREPASS_VELOCITY
var a: vec2f=(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[PREPASS_VELOCITY_INDEX]= vec4f(velocity,0.0,writeGeometryInfo);
#elif defined(PREPASS_VELOCITY_LINEAR)
var velocity : vec2f=vec2f(0.5)*((fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w) -
(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w));fragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO
fragData[PREPASS_ALBEDO_INDEX]=vec4f(surfaceAlbedo,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
var sqAlbedo : vec3f=sqrt(surfaceAlbedo);
#endif
#ifdef PREPASS_IRRADIANCE
var irradiance : vec3f=total_direct_diffuse;
#ifndef UNLIT
#ifdef REFLECTION
irradiance+=slab_diffuse_ibl;
#endif
#endif
#ifdef SCATTERING
let scatter_mask: f32=min(subsurface_weight+transmission_weight,1.0);
#else
let scatter_mask: f32=0.0;
#endif
fragData[PREPASS_IRRADIANCE_INDEX]=vec4f(irradiance,writeGeometryInfo*scatter_mask);
#elif defined(PREPASS_COLOR)
fragData[PREPASS_COLOR_INDEX]=vec4f(finalColor.rgb,finalColor.a);
#endif
#ifdef PREPASS_DEPTH
fragData[PREPASS_DEPTH_INDEX]=vec4f(fragmentInputs.vViewPos.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_SCREENSPACE_DEPTH
fragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
fragData[PREPASS_NORMALIZED_VIEW_DEPTH_INDEX]=vec4f(fragmentInputs.vNormViewDepth,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMAL
#ifdef PREPASS_NORMAL_WORLDSPACE
fragData[PREPASS_NORMAL_INDEX]=vec4f(normalW,writeGeometryInfo);
#else
fragData[PREPASS_NORMAL_INDEX]=vec4f(normalize((scene.view*vec4f(normalW,0.0)).rgb),writeGeometryInfo);
#endif
#endif
#ifdef PREPASS_WORLD_NORMAL
fragData[PREPASS_WORLD_NORMAL_INDEX]=vec4f(normalW*0.5+0.5,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
fragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4f(sqAlbedo,writeGeometryInfo);
#endif
#ifdef PREPASS_REFLECTIVITY
#ifndef UNLIT
fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(specularEnvironmentR0,microSurface)*writeGeometryInfo;
#else
fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(0.0,0.0,0.0,1.0)*writeGeometryInfo;
#endif
#endif
#if SCENE_MRT_COUNT>0
fragmentOutputs.fragData0=fragData[0];
#endif
#if SCENE_MRT_COUNT>1
fragmentOutputs.fragData1=fragData[1];
#endif
#if SCENE_MRT_COUNT>2
fragmentOutputs.fragData2=fragData[2];
#endif
#if SCENE_MRT_COUNT>3
fragmentOutputs.fragData3=fragData[3];
#endif
#if SCENE_MRT_COUNT>4
fragmentOutputs.fragData4=fragData[4];
#endif
#if SCENE_MRT_COUNT>5
fragmentOutputs.fragData5=fragData[5];
#endif
#if SCENE_MRT_COUNT>6
fragmentOutputs.fragData6=fragData[6];
#endif
#if SCENE_MRT_COUNT>7
fragmentOutputs.fragData7=fragData[7];
#endif
#endif
`;x.IncludesShadersStoreWGSL[OK]||(x.IncludesShadersStoreWGSL[OK]=bve)});var wK,Mve,iF=y(()=>{k();wK="pbrDebug",Mve=`#if DEBUGMODE>0
if (input.vClipSpacePosition.x/input.vClipSpacePosition.w>=uniforms.vDebugMode.x) {var color: vec3f;
#if DEBUGMODE==1
color=fragmentInputs.vPositionW.rgb;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==2 && defined(NORMAL)
color=fragmentInputs.vNormalW.rgb;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC)
color=TBN[0];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC)
color=TBN[1];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==5
color=normalW;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==6 && defined(MAINUV1)
color= vec3f(input.vMainUV1,0.0);
#elif DEBUGMODE==7 && defined(MAINUV2)
color= vec3f(input.vMainUV2,0.0);
#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)
color=clearcoatOut.TBNClearCoat[0];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)
color=clearcoatOut.TBNClearCoat[1];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==10 && defined(CLEARCOAT)
color=clearcoatOut.clearCoatNormalW;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==11 && defined(ANISOTROPIC)
color=anisotropicOut.anisotropicNormal;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==12 && defined(ANISOTROPIC)
color=anisotropicOut.anisotropicTangent;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==13 && defined(ANISOTROPIC)
color=anisotropicOut.anisotropicBitangent;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==20 && defined(ALBEDO)
color=albedoTexture.rgb;
#ifndef GAMMAALBEDO
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==21 && defined(AMBIENT)
color=aoOut.ambientOcclusionColorMap.rgb;
#elif DEBUGMODE==22 && defined(OPACITY)
color=opacityMap.rgb;
#elif DEBUGMODE==23 && defined(EMISSIVE)
color=emissiveColorTex.rgb;
#ifndef GAMMAEMISSIVE
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==24 && defined(LIGHTMAP)
color=lightmapColor;
#ifndef GAMMALIGHTMAP
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)
color=reflectivityOut.surfaceMetallicColorMap.rgb;
#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)
color=reflectivityOut.surfaceReflectivityColorMap.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)
color= vec3f(clearcoatOut.clearCoatMapData.rg,0.0);
#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
color=clearcoatOut.clearCoatTintMapData.rgb;
#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE)
color=sheenOut.sheenMapData.rgb;
#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)
color=anisotropicOut.anisotropyMapData.rgb;
#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)
color=subSurfaceOut.thicknessMap.rgb;
#elif DEBUGMODE==32 && defined(BUMP)
color=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).rgb;
#elif DEBUGMODE==40 && defined(SS_REFRACTION)
color=subSurfaceOut.environmentRefraction.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==41 && defined(REFLECTION)
color=reflectionOut.environmentRadiance.rgb;
#ifndef GAMMAREFLECTION
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION)
color=clearcoatOut.environmentClearCoatRadiance.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==50
color=diffuseBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==51 && defined(SPECULARTERM)
color=specularBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==52 && defined(CLEARCOAT)
color=clearCoatBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==53 && defined(SHEEN)
color=sheenBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==54 && defined(REFLECTION)
color=reflectionOut.environmentIrradiance.rgb;
#ifndef GAMMAREFLECTION
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==60
color=surfaceAlbedo.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==61
color=clearcoatOut.specularEnvironmentR0;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==62 && defined(METALLICWORKFLOW)
color= vec3f(reflectivityOut.metallic);
#elif DEBUGMODE==71 && defined(METALLICWORKFLOW)
color=reflectivityOut.metallicF0;
#elif DEBUGMODE==63
color= vec3f(roughness);
#elif DEBUGMODE==64
color= vec3f(alphaG);
#elif DEBUGMODE==65
color= vec3f(NdotV);
#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
color=clearcoatOut.clearCoatColor;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==67 && defined(CLEARCOAT)
color= vec3f(clearcoatOut.clearCoatRoughness);
#elif DEBUGMODE==68 && defined(CLEARCOAT)
color= vec3f(clearcoatOut.clearCoatNdotV);
#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)
color=subSurfaceOut.transmittance;
#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION)
color=subSurfaceOut.refractionTransmittance;
#elif DEBUGMODE==72
color= vec3f(microSurface);
#elif DEBUGMODE==73
color=uniforms.vAlbedoColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW)
color=uniforms.vReflectivityColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==75
color=uniforms.vEmissiveColor;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION)
color= vec3f(seo);
#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
color= vec3f(eho);
#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION)
color= vec3f(energyConservationFactor);
#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
color=baseSpecularEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
color=clearcoatOut.clearCoatEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION)
color=sheenOut.sheenEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==86 && defined(ALPHABLEND)
color= vec3f(luminanceOverAlpha);
#elif DEBUGMODE==87
color= vec3f(alpha);
#elif DEBUGMODE==88 && defined(ALBEDO)
color= vec3f(albedoTexture.a);
#elif DEBUGMODE==89
color=aoOut.ambientOcclusionColor;
#else
var stripeWidth: f32=30.;var stripePos: f32=abs(floor(input.position.x/stripeWidth));var whichColor: f32=((stripePos)%(2.));var color1: vec3f= vec3f(.6,.2,.2);var color2: vec3f= vec3f(.3,.1,.1);color=mix(color1,color2,whichColor);
#endif
color*=uniforms.vDebugMode.y;
#ifdef DEBUGMODE_NORMALIZE
color=normalize(color)*0.5+0.5;
#endif
#ifdef DEBUGMODE_GAMMA
color=toGammaSpaceVec3(color);
#endif
fragmentOutputs.color=vec4f(color,1.0);
#ifdef PREPASS
fragmentOutputs.fragData0=toLinearSpaceVec3(color);
fragmentOutputs.fragData1=vec4f(0.,0.,0.,0.);
#endif
#ifdef DEBUGMODE_FORCERETURN
return fragmentOutputs;
#endif
}
#endif
`;x.IncludesShadersStoreWGSL[wK]||(x.IncludesShadersStoreWGSL[wK]=Mve)});var BK={};Be(BK,{openpbrPixelShaderWGSL:()=>yve});var rF,FK,yve,UK=y(()=>{k();Xb();Yb();Ww();Xw();Kb();H7();Zb();qc();ah();rE();ao();Yw();Kw();jw();qb();jb();vg();Zw();qw();Eg();Qw();Jw();ry();eK();iK();gE();Fw();nK();aK();Bw();Uw();lK();Qc();eF();dK();hK();pK();Gw();Vw();_K();EK();TK();xK();eM();bK();yK();CK();LK();tM();nE();tF();NK();iM();iF();rF="openpbrPixelShader",FK=`#define OPENPBR_FRAGMENT_SHADER
#define CUSTOM_FRAGMENT_BEGIN
#include<prePassDeclaration>[SCENE_MRT_COUNT]
#include<oitDeclaration>
#ifndef FROMLINEARSPACE
#define FROMLINEARSPACE
#endif
#include<openpbrUboDeclaration>
#include<pbrFragmentExtraDeclaration>
#include<lightUboDeclaration>[0..maxSimultaneousLights]
#include<openpbrFragmentSamplersDeclaration>
#include<imageProcessingDeclaration>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
#include<helperFunctions>
#include<subSurfaceScatteringFunctions>
#include<importanceSampling>
#include<pbrHelperFunctions>
#include<imageProcessingFunctions>
#include<shadowsFragmentFunctions>
#include<harmonicsFunctions>
#include<pbrDirectLightingSetupFunctions>
#include<pbrDirectLightingFalloffFunctions>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
#include<pbrDirectLightingFunctions>
#include<pbrIBLFunctions>
#include<openpbrNormalMapFragmentMainFunctions>
#include<openpbrNormalMapFragmentFunctions>
#ifdef REFLECTION
#include<reflectionFunction>
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
#include<openpbrDielectricReflectance>
#include<openpbrConductorReflectance>
#include<openpbrAmbientOcclusionFunctions>
#include<openpbrGeometryInfo>
#include<openpbrIblFunctions>
#include<openpbrVolumeFunctions>
fn layer(slab_bottom: vec3f,slab_top: vec3f,lerp_factor: f32,bottom_multiplier: vec3f,top_multiplier: vec3f)->vec3f {return mix(slab_bottom*bottom_multiplier,slab_top*top_multiplier,lerp_factor);}
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#ifdef PREPASS_IRRADIANCE
var total_direct_diffuse: vec3f=vec3f(0.0f);
#endif
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#include<pbrBlockNormalGeometric>
var coatNormalW: vec3f=normalW;
#include<openpbrNormalMapFragment>
#include<openpbrBlockNormalFinal>
#include<openpbrBaseLayerData>
#include<openpbrTransmissionLayerData>
#include<openpbrSubsurfaceLayerData>
#include<openpbrCoatLayerData>
#include<openpbrThinFilmLayerData>
#include<openpbrFuzzLayerData>
#include<openpbrAmbientOcclusionData>
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
#include<depthPrePass>
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS
#ifdef ANISOTROPIC_COAT
let coatGeoInfo: geometryInfoAnisoOutParams=geometryInfoAniso(
coatNormalW,viewDirectionW.xyz,coat_roughness,geometricNormalW
,vec3f(geometry_coat_tangent.x,geometry_coat_tangent.y,coat_roughness_anisotropy),TBN
);
#else
let coatGeoInfo: geometryInfoOutParams=geometryInfo(
coatNormalW,viewDirectionW.xyz,coat_roughness,geometricNormalW
);
#endif
specular_roughness=mix(specular_roughness,pow(min(1.0f,pow(specular_roughness,4.0f)+2.0f*pow(coat_roughness,4.0f)),0.25f),coat_weight);
#ifdef ANISOTROPIC_BASE
let baseGeoInfo: geometryInfoAnisoOutParams=geometryInfoAniso(
normalW,viewDirectionW.xyz,specular_roughness,geometricNormalW
,vec3f(geometry_tangent.x,geometry_tangent.y,specular_roughness_anisotropy),TBN
);
#else
let baseGeoInfo: geometryInfoOutParams=geometryInfo(
normalW,viewDirectionW.xyz,specular_roughness,geometricNormalW
);
#endif
#ifdef FUZZ
let fuzzNormalW=normalize(mix(normalW,coatNormalW,coat_weight));var fuzzTangent=normalize(TBN[0]);fuzzTangent=normalize(fuzzTangent-dot(fuzzTangent,fuzzNormalW)*fuzzNormalW);let fuzzBitangent=cross(fuzzNormalW,fuzzTangent);let fuzzGeoInfo: geometryInfoOutParams=geometryInfo(
fuzzNormalW,viewDirectionW.xyz,fuzz_roughness,geometricNormalW
);
#endif
let coatReflectance: ReflectanceParams=dielectricReflectance(
coat_ior
,1.0f
,vec3f(1.0f)
,coat_weight
);
#ifdef THIN_FILM
let thin_film_outside_ior: f32=mix(1.0f,coat_ior,coat_weight);
#endif
let baseDielectricReflectance: ReflectanceParams=dielectricReflectance(
specular_ior
,mix(1.0f,coat_ior,coat_weight)
,specular_color
,specular_weight
);let baseConductorReflectance: ReflectanceParams=conductorReflectance(base_color,specular_color,specular_weight);var volume_absorption: vec3f=vec3f(1.0f);var transmission_tint: vec3f=vec3f(1.0f);var surface_translucency_weight: f32=0.0f;
#if defined(REFRACTED_BACKGROUND) || defined(REFRACTED_ENVIRONMENT) || defined(REFRACTED_LIGHTS)
#if defined(GEOMETRY_THIN_WALLED)
let refractedViewVector: vec3f=-viewDirectionW;
#else
#ifdef DISPERSION
var refractedViewVectors: array<vec3f,3>;let iorDispersionSpread: f32=transmission_dispersion_scale/transmission_dispersion_abbe_number*(specular_ior-1.0f);let dispersion_iors: vec3f=vec3f(specular_ior-iorDispersionSpread,specular_ior,specular_ior+iorDispersionSpread);for (var i: i32=0; i<3; i++) {refractedViewVectors[i]=double_refract(-viewDirectionW,normalW,dispersion_iors[i]); }
#else
let refractedViewVector: vec3f=double_refract(-viewDirectionW,normalW,specular_ior);
#endif
#endif
#ifdef GEOMETRY_THIN_WALLED
var transmission_roughness: f32=specular_roughness;
#else
var transmission_roughness: f32=specular_roughness*clamp(4.0f*(specular_ior-1.0f),0.001f,1.0f);
#endif
#if (defined(TRANSMISSION_SLAB) || defined(SUBSURFACE_SLAB))
var volumeParams: OpenPBRHomogeneousVolume;{
#if defined(TRANSMISSION_SLAB)
let transmissionVolumeParams: OpenPBRHomogeneousVolume=computeOpenPBRTransmissionVolume(
transmission_color.rgb,
transmission_depth,
transmission_scatter.rgb,
transmission_scatter_anisotropy
);
#endif
#if defined(SUBSURFACE_SLAB)
let subsurfaceVolumeParams: OpenPBRHomogeneousVolume=computeOpenPBRSubsurfaceVolume(
subsurface_color.rgb,
subsurface_radius,
subsurface_radius_scale.rgb,
subsurface_scatter_anisotropy
);
#endif
#if !defined(TRANSMISSION_SLAB)
volumeParams=subsurfaceVolumeParams;surface_translucency_weight=subsurface_weight;
#elif !defined(SUBSURFACE_SLAB)
volumeParams=transmissionVolumeParams;
#ifdef TRANSMISSION_SLAB_VOLUME
volumeParams.multi_scatter_color=singleScatterToMultiScatterAlbedo(volumeParams.ss_albedo);
#endif
surface_translucency_weight=transmission_weight;
#else
let subsurface_fraction_of_dielectric: f32=(1.0f-transmission_weight)*subsurface_weight;let subsurface_and_transmission_fraction_of_dielectric: f32=subsurface_fraction_of_dielectric+transmission_weight;let reciprocal_of_subsurface_and_transmission_fraction_of_dielectric: f32 =
1.0f/maxEps(subsurface_and_transmission_fraction_of_dielectric);let trans_weight: f32=transmission_weight*reciprocal_of_subsurface_and_transmission_fraction_of_dielectric;let subsurf_weight: f32=subsurface_fraction_of_dielectric*reciprocal_of_subsurface_and_transmission_fraction_of_dielectric;volumeParams.scatter_coeff=transmissionVolumeParams.scatter_coeff*trans_weight+subsurfaceVolumeParams.scatter_coeff*subsurf_weight;volumeParams.absorption_coeff=transmissionVolumeParams.absorption_coeff*trans_weight+subsurfaceVolumeParams.absorption_coeff*subsurf_weight;volumeParams.anisotropy=(transmissionVolumeParams.anisotropy*trans_weight+subsurfaceVolumeParams.anisotropy*subsurf_weight)/maxEps(trans_weight+subsurf_weight);volumeParams.extinction_coeff=volumeParams.absorption_coeff+volumeParams.scatter_coeff;volumeParams.ss_albedo=volumeParams.scatter_coeff/maxEpsVec3(volumeParams.extinction_coeff);volumeParams.multi_scatter_color=singleScatterToMultiScatterAlbedo(volumeParams.ss_albedo);surface_translucency_weight=subsurface_and_transmission_fraction_of_dielectric;
#endif
}
volume_absorption=exp(-volumeParams.absorption_coeff*geometry_thickness);var backscatter_color: vec3f=vec3f(1.0f);{let reduced_scatter: vec3f=volumeParams.scatter_coeff*vec3f(1.0f-volumeParams.anisotropy);let reduced_albedo: vec3f=reduced_scatter/(volumeParams.absorption_coeff+reduced_scatter);let sqrt_term: vec3f=max(sqrt(vec3f(1.0f)-reduced_albedo),vec3f(0.0001f));backscatter_color=(vec3f(1.0f)-sqrt_term)/(vec3f(1.0f)+sqrt_term);}
#elif defined(TRANSMISSION_SLAB)
surface_translucency_weight=transmission_weight;
#endif
#ifdef SCATTERING
#ifdef GEOMETRY_THIN_WALLED
var iso_scatter_density: vec3f=vec3f(1.0f);
#else
#ifdef USE_IRRADIANCE_TEXTURE_FOR_SCATTERING
let mfp: vec3f=vec3f(100.0f)/volumeParams.extinction_coeff;var scattered_light_from_irradiance_texture: vec3f=sss_convolve(sceneIrradianceSampler,sceneDepthSampler,uniforms.renderTargetSize,mfp,scene.projection,scene.inverseProjection,SSS_SAMPLE_COUNT,noise.xy);var numLights=f32(LIGHTCOUNT);
#ifdef REFLECTION
numLights+=1.0f;
#endif
scattered_light_from_irradiance_texture/=vec3f(numLights);
#else
let scattered_light_from_irradiance_texture: vec3f=vec3f(0.0f);
#endif
let back_to_iso_scattering_blend: f32=min(1.0f+volumeParams.anisotropy,1.0f);let iso_to_forward_scattering_blend: f32=max(volumeParams.anisotropy,0.0f);let iso_scatter_transmittance: vec3f=pow(exp(-volumeParams.scatter_coeff*geometry_thickness),vec3f(0.2f));var iso_scatter_density: vec3f=clamp(vec3f(1.0f)-iso_scatter_transmittance,vec3f(0.0f),vec3f(1.0f));transmission_roughness=min(transmission_roughness+pow((1.0f-abs(volumeParams.anisotropy))*max3(iso_scatter_density*iso_scatter_density),3.0f),1.0f);
#endif
volumeParams.multi_scatter_color=mix(volumeParams.ss_albedo,volumeParams.multi_scatter_color,max3(iso_scatter_density));
#endif
#if defined(TRANSMISSION_SLAB) && (!defined(TRANSMISSION_SLAB_VOLUME) || defined(GEOMETRY_THIN_WALLED))
transmission_tint*=transmission_color.rgb;
#ifdef GEOMETRY_THIN_WALLED
var sin2: f32=1.0f-baseGeoInfo.NdotV*baseGeoInfo.NdotV;sin2=sin2/(specular_ior*specular_ior);let cos_t: f32=sqrt(1.0f-sin2);let pathLength: f32=1.0f/cos_t;transmission_tint=pow(transmission_tint,vec3f(pathLength));
#else
transmission_tint*=transmission_color.rgb;
#endif
#endif
#if defined(SUBSURFACE_SLAB) && defined(GEOMETRY_THIN_WALLED)
let unweighted_translucency: f32=mix(subsurface_weight,1.0f,transmission_weight);transmission_tint=mix(vec3f(1.0f),transmission_tint,transmission_weight/unweighted_translucency);transmission_roughness=mix(1.0f,transmission_roughness,transmission_weight/unweighted_translucency);
#endif
let transmission_roughness_alpha: f32=transmission_roughness*transmission_roughness;
#endif
#include<openpbrBackgroundTransmission>
var material_surface_ibl: vec3f=vec3f(0.f,0.f,0.f);
#include<openpbrEnvironmentLighting>
var material_surface_direct: vec3f=vec3f(0.f,0.f,0.f);
#if defined(LIGHT0)
var aggShadow: f32=0.f;
#include<openpbrDirectLightingInit>[0..maxSimultaneousLights]
#include<openpbrDirectLighting>[0..maxSimultaneousLights]
#endif
var material_surface_emission: vec3f=uniforms.vEmissionColor;
#ifdef EMISSION_COLOR
let emissionColorTex: vec3f=textureSample(emissionColorSampler,emissionColorSamplerSampler,uniforms.vEmissionColorUV+uvOffset).rgb;
#ifdef EMISSION_COLOR_GAMMA
material_surface_emission*=toLinearSpace(emissionColorTex.rgb);
#else
material_surface_emission*=emissionColorTex.rgb;
#endif
material_surface_emission*= uniforms.vEmissionColorInfos.y;
#endif
material_surface_emission*=uniforms.vLightingIntensity.y;
#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION
var finalColor: vec4f=vec4f(material_surface_ibl+material_surface_direct+material_surface_emission,alpha);
#define CUSTOM_FRAGMENT_BEFORE_FOG
finalColor=max(finalColor,vec4f(0.0));
#include<logDepthFragment>
#include<fogFragment>(color,finalColor)
#include<pbrBlockImageProcessing>
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
#include<openpbrBlockPrePass>
#endif
#if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY)
fragmentOutputs.color=finalColor;
#endif
#include<oitFragment>
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+finalColor.rgb*finalColor.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-finalColor.a));} else {fragmentOutputs.backColor+=finalColor;}
#endif
#include<pbrDebug>
#define CUSTOM_FRAGMENT_MAIN_END
}
`;x.ShadersStoreWGSL[rF]||(x.ShadersStoreWGSL[rF]=FK);yve={name:rF,shader:FK}});var VK,Ive,GK=y(()=>{k();VN();rM();VK="openpbrVertexDeclaration",Ive=`#include<sceneVertexDeclaration>
#ifdef BASE_COLOR
uniform vec2 vBaseColorInfos;uniform mat4 baseColorMatrix;
#endif
#ifdef BASE_WEIGHT
uniform mat4 baseWeightMatrix;uniform vec2 vBaseWeightInfos;
#endif
uniform float vBaseDiffuseRoughness;
#ifdef BASE_DIFFUSE_ROUGHNESS
uniform mat4 baseDiffuseRoughnessMatrix;uniform vec2 vBaseDiffuseRoughnessInfos;
#endif
#ifdef AMBIENT_OCCLUSION
uniform vec2 vAmbientOcclusionInfos;uniform mat4 ambientOcclusionMatrix;
#endif
#ifdef EMISSION_COLOR
uniform vec2 vEmissionColorInfos;uniform mat4 emissionColorMatrix;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;
#endif
#ifdef BASE_METALNESS
uniform vec2 vBaseMetalnessInfos;uniform mat4 baseMetalnessMatrix;
#endif
#ifdef SPECULAR_WEIGHT
uniform vec2 vSpecularWeightInfos;uniform mat4 specularWeightMatrix;
#endif
#ifdef SPECULAR_COLOR
uniform vec2 vSpecularColorInfos;uniform mat4 specularColorMatrix;
#endif
#ifdef SPECULAR_ROUGHNESS
uniform vec2 vSpecularRoughnessInfos;uniform mat4 specularRoughnessMatrix;
#endif
#ifdef SPECULAR_ROUGHNESS_ANISOTROPY
uniform vec2 vSpecularRoughnessAnisotropyInfos;uniform mat4 specularRoughnessAnisotropyMatrix;
#endif
#ifdef TRANSMISSION_WEIGHT
uniform vec2 vTransmissionWeightInfos;uniform mat4 transmissionWeightMatrix;
#endif
#ifdef TRANSMISSION_COLOR
uniform vec2 vTransmissionColorInfos;uniform mat4 transmissionColorMatrix;
#endif
#ifdef TRANSMISSION_DEPTH
uniform vec2 vTransmissionDepthInfos;uniform mat4 transmissionDepthMatrix;
#endif
#ifdef TRANSMISSION_DISPERSION_SCALE
uniform vec2 vTransmissionDispersionScaleInfos;uniform mat4 transmissionDispersionScaleMatrix;
#endif
#ifdef SUBSURFACE_WEIGHT
uniform vec2 vSubsurfaceWeightInfos;uniform mat4 subsurfaceWeightMatrix;
#endif
#ifdef SUBSURFACE_COLOR
uniform vec2 vSubsurfaceColorInfos;uniform mat4 subsurfaceColorMatrix;
#endif
#ifdef SUBSURFACE_RADIUS_SCALE
uniform vec2 vSubsurfaceRadiusScaleInfos;uniform mat4 subsurfaceRadiusScaleMatrix;
#endif
#ifdef COAT_WEIGHT
uniform vec2 vCoatWeightInfos;uniform mat4 coatWeightMatrix;
#endif
#ifdef COAT_COLOR
uniform vec2 vCoatColorInfos;uniform mat4 coatColorMatrix;
#endif
#ifdef COAT_ROUGHNESS
uniform vec2 vCoatRoughnessInfos;uniform mat4 coatRoughnessMatrix;
#endif
#ifdef COAT_ROUGHNESS_ANISOTROPY
uniform vec2 vCoatRoughnessAnisotropyInfos;uniform mat4 coatRoughnessAnisotropyMatrix;
#endif
#ifdef COAT_IOR
uniform vec2 vCoatIorInfos;uniform mat4 coatIorMatrix;
#endif
#ifdef COAT_DARKENING
uniform vec2 vCoatDarkeningInfos;uniform mat4 coatDarkeningMatrix;
#endif
#ifdef FUZZ_WEIGHT
uniform vec2 vFuzzWeightInfos;uniform mat4 fuzzWeightMatrix;
#endif
#ifdef FUZZ_COLOR
uniform vec2 vFuzzColorInfos;uniform mat4 fuzzColorMatrix;
#endif
#ifdef FUZZ_ROUGHNESS
uniform vec2 vFuzzRoughnessInfos;uniform mat4 fuzzRoughnessMatrix;
#endif
#ifdef GEOMETRY_NORMAL
uniform vec2 vGeometryNormalInfos;uniform mat4 geometryNormalMatrix;
#endif
#ifdef GEOMETRY_TANGENT
uniform vec2 vGeometryTangentInfos;uniform mat4 geometryTangentMatrix;
#endif
#ifdef GEOMETRY_COAT_NORMAL
uniform vec2 vGeometryCoatNormalInfos;uniform mat4 geometryCoatNormalMatrix;
#endif
#ifdef THIN_FILM_WEIGHT
uniform vec2 vThinFilmWeightInfos;uniform mat4 thinFilmWeightMatrix;
#endif
#ifdef THIN_FILM_THICKNESS
uniform vec2 vThinFilmThicknessInfos;uniform mat4 thinFilmThicknessMatrix;
#endif
#ifdef GEOMETRY_OPACITY
uniform mat4 geometryOpacityMatrix;uniform vec2 vGeometryOpacityInfos;
#endif
#ifdef GEOMETRY_THICKNESS
uniform mat4 geometryThicknessMatrix;uniform vec2 vGeometryThicknessInfos;
#endif
#ifdef POINTSIZE
uniform float pointSize;
#endif
uniform vec4 cameraInfo;
#ifdef REFLECTION
uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;
#endif
#ifdef NORMAL
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;
#else
uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;
#endif
#endif
#endif
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;uniform mat4 detailMatrix;
#endif
#include<decalVertexDeclaration>
#define ADDITIONAL_VERTEX_DECLARATION
`;x.IncludesShadersStore[VK]||(x.IncludesShadersStore[VK]=Ive)});var kK,Cve,nF=y(()=>{k();lh();_E();kK="openpbrUboDeclaration",Cve=`layout(std140,column_major) uniform;uniform Material {vec2 vTangentSpaceParams;vec4 vLightingIntensity;float pointSize;vec2 vDebugMode;vec2 renderTargetSize;vec4 cameraInfo;mat4 backgroundRefractionMatrix;vec3 vBackgroundRefractionInfos;vec2 vReflectionInfos;mat4 reflectionMatrix;vec3 vReflectionMicrosurfaceInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vReflectionFilteringInfo;vec3 vReflectionDominantDirection;vec3 vReflectionColor;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;float vBaseWeight;vec4 vBaseColor;float vBaseDiffuseRoughness;vec4 vReflectanceInfo;vec4 vSpecularColor;vec3 vSpecularAnisotropy;float vTransmissionWeight;vec3 vTransmissionColor;float vTransmissionDepth;vec3 vTransmissionScatter;float vTransmissionScatterAnisotropy;float vTransmissionDispersionScale;float vTransmissionDispersionAbbeNumber;float vSubsurfaceWeight;vec3 vSubsurfaceColor;float vSubsurfaceRadius;vec3 vSubsurfaceRadiusScale;float vSubsurfaceScatterAnisotropy;float vCoatWeight;vec3 vCoatColor;float vCoatRoughness;float vCoatRoughnessAnisotropy;float vCoatIor;float vCoatDarkening;float vFuzzWeight;vec3 vFuzzColor;float vFuzzRoughness;float vGeometryThinWalled;vec2 vGeometryCoatTangent;float vGeometryThickness;vec3 vEmissionColor;float vThinFilmWeight;vec2 vThinFilmThickness;float vThinFilmIor;vec2 vBaseWeightInfos;mat4 baseWeightMatrix;vec2 vBaseColorInfos;mat4 baseColorMatrix;vec2 vBaseDiffuseRoughnessInfos;mat4 baseDiffuseRoughnessMatrix;vec2 vBaseMetalnessInfos;mat4 baseMetalnessMatrix;vec2 vSpecularWeightInfos;mat4 specularWeightMatrix;vec2 vSpecularColorInfos;mat4 specularColorMatrix;vec2 vSpecularRoughnessInfos;mat4 specularRoughnessMatrix;vec2 vSpecularRoughnessAnisotropyInfos;mat4 specularRoughnessAnisotropyMatrix;vec2 vTransmissionWeightInfos;mat4 transmissionWeightMatrix;vec2 vTransmissionColorInfos;mat4 transmissionColorMatrix;vec2 vTransmissionDepthInfos;mat4 transmissionDepthMatrix;vec2 vTransmissionScatterInfos;mat4 transmissionScatterMatrix;vec2 vTransmissionDispersionScaleInfos;mat4 transmissionDispersionScaleMatrix;vec2 vSubsurfaceWeightInfos;mat4 subsurfaceWeightMatrix;vec2 vSubsurfaceColorInfos;mat4 subsurfaceColorMatrix;vec2 vSubsurfaceRadiusScaleInfos;mat4 subsurfaceRadiusScaleMatrix;vec2 vCoatWeightInfos;mat4 coatWeightMatrix;vec2 vCoatColorInfos;mat4 coatColorMatrix;vec2 vCoatRoughnessInfos;mat4 coatRoughnessMatrix;vec2 vCoatRoughnessAnisotropyInfos;mat4 coatRoughnessAnisotropyMatrix;vec2 vCoatDarkeningInfos;mat4 coatDarkeningMatrix;vec2 vFuzzWeightInfos;mat4 fuzzWeightMatrix;vec2 vFuzzColorInfos;mat4 fuzzColorMatrix;vec2 vFuzzRoughnessInfos;mat4 fuzzRoughnessMatrix;vec2 vGeometryNormalInfos;mat4 geometryNormalMatrix;vec2 vGeometryTangentInfos;mat4 geometryTangentMatrix;vec2 vGeometryCoatNormalInfos;mat4 geometryCoatNormalMatrix;vec2 vGeometryCoatTangentInfos;mat4 geometryCoatTangentMatrix;vec2 vGeometryOpacityInfos;mat4 geometryOpacityMatrix;vec2 vGeometryThicknessInfos;mat4 geometryThicknessMatrix;vec2 vEmissionColorInfos;mat4 emissionColorMatrix;vec2 vThinFilmWeightInfos;mat4 thinFilmWeightMatrix;vec2 vThinFilmThicknessInfos;mat4 thinFilmThicknessMatrix;vec2 vAmbientOcclusionInfos;mat4 ambientOcclusionMatrix;
#define ADDITIONAL_UBO_DECLARATION
};
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;x.IncludesShadersStore[kK]||(x.IncludesShadersStore[kK]=Cve)});var zK,Pve,WK=y(()=>{k();zK="openpbrNormalMapVertexDeclaration",Pve=`#if defined(GEOMETRY_NORMAL) || defined(PARALLAX) || defined(GEOMETRY_COAT_NORMAL) || defined(ANISOTROPIC) || defined(FUZZ)
#if defined(TANGENT) && defined(NORMAL)
varying mat3 vTBN;
#endif
#endif
`;x.IncludesShadersStore[zK]||(x.IncludesShadersStore[zK]=Pve)});var HK,Lve,XK=y(()=>{k();HK="openpbrNormalMapVertex",Lve=`#if defined(GEOMETRY_NORMAL) || defined(PARALLAX) || defined(GEOMETRY_COAT_NORMAL) || defined(ANISOTROPIC) || defined(FUZZ)
#if defined(TANGENT) && defined(NORMAL)
vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);
#endif
#endif
`;x.IncludesShadersStore[HK]||(x.IncludesShadersStore[HK]=Lve)});var KK={};Be(KK,{openpbrVertexShader:()=>Dve});var sF,YK,Dve,jK=y(()=>{k();GK();nF();nM();cg();oo();gg();$c();Jc();bd();sM();aM();_g();WK();ef();sE();oM();lM();Ld();Dd();ch();Od();Nd();tf();rf();nf();cM();fM();dM();XK();sf();aE();hM();oE();mM();sF="openpbrVertexShader",YK=`#define OPENPBR_VERTEX_SHADER
#define CUSTOM_VERTEX_EXTENSION
precision highp float;
#include<__decl__openpbrVertex>
#define CUSTOM_VERTEX_BEGIN
attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#ifdef TANGENT
attribute vec4 tangent;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#include<uvAttributeDeclaration>[2..7]
#include<mainUVVaryingDeclaration>[1..7]
#ifdef VERTEXCOLOR
attribute vec4 color;
#endif
#include<helperFunctions>
#include<pbrBRDFFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<samplerVertexDeclaration>(_DEFINENAME_,BASE_COLOR,_VARYINGNAME_,BaseColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,BASE_METALNESS,_VARYINGNAME_,BaseMetalness)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR_WEIGHT,_VARYINGNAME_,SpecularWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR_COLOR,_VARYINGNAME_,SpecularColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR_ROUGHNESS,_VARYINGNAME_,SpecularRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR_ROUGHNESS_ANISOTROPY,_VARYINGNAME_,SpecularRoughnessAnisotropy)
#include<samplerVertexDeclaration>(_DEFINENAME_,TRANSMISSION_WEIGHT,_VARYINGNAME_,TransmissionWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,TRANSMISSION_COLOR,_VARYINGNAME_,TransmissionColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,TRANSMISSION_DEPTH,_VARYINGNAME_,TransmissionDepth)
#include<samplerVertexDeclaration>(_DEFINENAME_,TRANSMISSION_SCATTER,_VARYINGNAME_,TransmissionScatter)
#include<samplerVertexDeclaration>(_DEFINENAME_,TRANSMISSION_DISPERSION_SCALE,_VARYINGNAME_,TransmissionDispersionScale)
#include<samplerVertexDeclaration>(_DEFINENAME_,SUBSURFACE_WEIGHT,_VARYINGNAME_,SubsurfaceWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,SUBSURFACE_COLOR,_VARYINGNAME_,SubsurfaceColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,SUBSURFACE_RADIUS_SCALE,_VARYINGNAME_,SubsurfaceRadiusScale)
#include<samplerVertexDeclaration>(_DEFINENAME_,COAT_WEIGHT,_VARYINGNAME_,CoatWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,COAT_COLOR,_VARYINGNAME_,CoatColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,COAT_ROUGHNESS,_VARYINGNAME_,CoatRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,COAT_ROUGHNESS_ANISOTROPY,_VARYINGNAME_,CoatRoughnessAnisotropy)
#include<samplerVertexDeclaration>(_DEFINENAME_,COAT_DARKENING,_VARYINGNAME_,CoatDarkening)
#include<samplerVertexDeclaration>(_DEFINENAME_,FUZZ_WEIGHT,_VARYINGNAME_,FuzzWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,FUZZ_COLOR,_VARYINGNAME_,FuzzColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,FUZZ_ROUGHNESS,_VARYINGNAME_,FuzzRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,GEOMETRY_NORMAL,_VARYINGNAME_,GeometryNormal)
#include<samplerVertexDeclaration>(_DEFINENAME_,GEOMETRY_TANGENT,_VARYINGNAME_,GeometryTangent)
#include<samplerVertexDeclaration>(_DEFINENAME_,GEOMETRY_COAT_NORMAL,_VARYINGNAME_,GeometryCoatNormal)
#include<samplerVertexDeclaration>(_DEFINENAME_,GEOMETRY_OPACITY,_VARYINGNAME_,GeometryOpacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,GEOMETRY_THICKNESS,_VARYINGNAME_,GeometryThickness)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSION_COLOR,_VARYINGNAME_,EmissionColor)
#include<samplerVertexDeclaration>(_DEFINENAME_,THIN_FILM_WEIGHT,_VARYINGNAME_,ThinFilmWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,THIN_FILM_THICKNESS,_VARYINGNAME_,ThinFilmThickness)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT_OCCLUSION,_VARYINGNAME_,AmbientOcclusion)
#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
varying vec3 vPositionW;
#if DEBUGMODE>0
varying vec4 vClipSpacePosition;
#endif
#ifdef NORMAL
varying vec3 vNormalW;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vec3 vEnvironmentIrradiance;
#include<harmonicsFunctions>
#endif
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#include<openpbrNormalMapVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec3 positionUpdated=position;
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#ifdef TANGENT
vec4 tangentUpdated=tangent;
#endif
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#ifdef VERTEXCOLOR
vec4 colorUpdated=color;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos);
#ifdef PREPASS
#include<prePassVertex>
#endif
#ifdef NORMAL
mat3 normalWorld=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vNormalW=normalize(normalWorld*normalUpdated);
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
#if BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LAMBERT && BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LEGACY
vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);
#if !defined(NATIVE) && !defined(WEBGPU)
bool bbb=any(isnan(position));if (bbb) { }
#endif
float NdotV=max(dot(vNormalW,viewDirectionW),0.0);vec3 roughNormal=mix(vNormalW,viewDirectionW,(0.5*(1.0-NdotV))*vBaseDiffuseRoughness);vec3 reflectionVector=vec3(reflectionMatrix*vec4(roughNormal,0)).xyz;
#else
vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}
#else
gl_Position=viewProjection*worldPos;
#endif
#if DEBUGMODE>0
vClipSpacePosition=gl_Position;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));
#endif
#ifndef UV1
vec2 uvUpdated=vec2(0.,0.);
#endif
#ifndef UV2
vec2 uv2Updated=vec2(0.,0.);
#endif
#ifdef MAINUV1
vMainUV1=uvUpdated;
#endif
#ifdef MAINUV2
vMainUV2=uv2Updated;
#endif
#include<uvVariableDeclaration>[3..7]
#include<samplerVertexImplementation>(_DEFINENAME_,BASE_COLOR,_VARYINGNAME_,BaseColor,_MATRIXNAME_,baseColor,_INFONAME_,BaseColorInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight,_MATRIXNAME_,baseWeight,_INFONAME_,BaseWeightInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness,_MATRIXNAME_,baseDiffuseRoughness,_INFONAME_,BaseDiffuseRoughnessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BASE_METALNESS,_VARYINGNAME_,BaseMetalness,_MATRIXNAME_,baseMetalness,_INFONAME_,BaseMetalnessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR_WEIGHT,_VARYINGNAME_,SpecularWeight,_MATRIXNAME_,specularWeight,_INFONAME_,SpecularWeightInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR_COLOR,_VARYINGNAME_,SpecularColor,_MATRIXNAME_,specularColor,_INFONAME_,SpecularColorInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR_ROUGHNESS,_VARYINGNAME_,SpecularRoughness,_MATRIXNAME_,specularRoughness,_INFONAME_,SpecularRoughnessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR_ROUGHNESS_ANISOTROPY,_VARYINGNAME_,SpecularRoughnessAnisotropy,_MATRIXNAME_,specularRoughnessAnisotropy,_INFONAME_,SpecularRoughnessAnisotropyInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,TRANSMISSION_WEIGHT,_VARYINGNAME_,TransmissionWeight,_MATRIXNAME_,transmissionWeight,_INFONAME_,TransmissionWeightInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,TRANSMISSION_COLOR,_VARYINGNAME_,TransmissionColor,_MATRIXNAME_,transmissionColor,_INFONAME_,TransmissionColorInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,TRANSMISSION_DEPTH,_VARYINGNAME_,TransmissionDepth,_MATRIXNAME_,transmissionDepth,_INFONAME_,TransmissionDepthInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,TRANSMISSION_SCATTER,_VARYINGNAME_,TransmissionScatter,_MATRIXNAME_,transmissionScatter,_INFONAME_,TransmissionScatterInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,TRANSMISSION_DISPERSION_SCALE,_VARYINGNAME_,TransmissionDispersionScale,_MATRIXNAME_,transmissionDispersionScale,_INFONAME_,TransmissionDispersionScaleInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,SUBSURFACE_WEIGHT,_VARYINGNAME_,SubsurfaceWeight,_MATRIXNAME_,subsurfaceWeight,_INFONAME_,SubsurfaceWeightInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,SUBSURFACE_COLOR,_VARYINGNAME_,SubsurfaceColor,_MATRIXNAME_,subsurfaceColor,_INFONAME_,SubsurfaceColorInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,SUBSURFACE_RADIUS_SCALE,_VARYINGNAME_,SubsurfaceRadiusScale,_MATRIXNAME_,subsurfaceRadiusScale,_INFONAME_,SubsurfaceRadiusScaleInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,COAT_WEIGHT,_VARYINGNAME_,CoatWeight,_MATRIXNAME_,coatWeight,_INFONAME_,CoatWeightInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,COAT_COLOR,_VARYINGNAME_,CoatColor,_MATRIXNAME_,coatColor,_INFONAME_,CoatColorInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,COAT_ROUGHNESS,_VARYINGNAME_,CoatRoughness,_MATRIXNAME_,coatRoughness,_INFONAME_,CoatRoughnessInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,COAT_ROUGHNESS_ANISOTROPY,_VARYINGNAME_,CoatRoughnessAnisotropy,_MATRIXNAME_,coatRoughnessAnisotropy,_INFONAME_,CoatRoughnessAnisotropyInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,COAT_DARKENING,_VARYINGNAME_,CoatDarkening,_MATRIXNAME_,coatDarkening,_INFONAME_,CoatDarkeningInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,FUZZ_WEIGHT,_VARYINGNAME_,FuzzWeight,_MATRIXNAME_,fuzzWeight,_INFONAME_,FuzzWeightInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,FUZZ_COLOR,_VARYINGNAME_,FuzzColor,_MATRIXNAME_,fuzzColor,_INFONAME_,FuzzColorInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,FUZZ_ROUGHNESS,_VARYINGNAME_,FuzzRoughness,_MATRIXNAME_,fuzzRoughness,_INFONAME_,FuzzRoughnessInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,GEOMETRY_NORMAL,_VARYINGNAME_,GeometryNormal,_MATRIXNAME_,geometryNormal,_INFONAME_,GeometryNormalInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,GEOMETRY_COAT_NORMAL,_VARYINGNAME_,GeometryCoatNormal,_MATRIXNAME_,geometryCoatNormal,_INFONAME_,GeometryCoatNormalInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,GEOMETRY_OPACITY,_VARYINGNAME_,GeometryOpacity,_MATRIXNAME_,geometryOpacity,_INFONAME_,GeometryOpacityInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,GEOMETRY_THICKNESS,_VARYINGNAME_,GeometryThickness,_MATRIXNAME_,geometryThickness,_INFONAME_,GeometryThicknessInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,GEOMETRY_TANGENT,_VARYINGNAME_,GeometryTangent,_MATRIXNAME_,geometryTangent,_INFONAME_,GeometryTangentInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,EMISSION_COLOR,_VARYINGNAME_,EmissionColor,_MATRIXNAME_,emissionColor,_INFONAME_,EmissionColorInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,THIN_FILM_WEIGHT,_VARYINGNAME_,ThinFilmWeight,_MATRIXNAME_,thinFilmWeight,_INFONAME_,ThinFilmWeightInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,THIN_FILM_THICKNESS,_VARYINGNAME_,ThinFilmThickness,_MATRIXNAME_,thinFilmThickness,_INFONAME_,ThinFilmThicknessInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,AMBIENT_OCCLUSION,_VARYINGNAME_,AmbientOcclusion,_MATRIXNAME_,ambientOcclusion,_INFONAME_,AmbientOcclusionInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)
#include <samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<openpbrNormalMapVertex>
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#include<vertexColorMixing>
#if defined(POINTSIZE) && !defined(WEBGPU)
gl_PointSize=pointSize;
#endif
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}
`;x.ShadersStore[sF]||(x.ShadersStore[sF]=YK);Dve={name:sF,shader:YK}});var ZK,Ove,qK=y(()=>{k();bw();pM();ZK="openpbrFragmentDeclaration",Ove=`uniform float vBaseWeight;uniform vec4 vBaseColor;uniform float vBaseDiffuseRoughness;uniform vec4 vReflectanceInfo;uniform vec4 vSpecularColor;uniform vec3 vSpecularAnisotropy;uniform float vTransmissionWeight;uniform vec3 vTransmissionColor;uniform float vTransmissionDepth;uniform vec3 vTransmissionScatter;uniform float vTransmissionScatterAnisotropy;uniform float vTransmissionDispersionScale;uniform float vTransmissionDispersionAbbeNumber;uniform float vSubsurfaceWeight;uniform vec3 vSubsurfaceColor;uniform float vSubsurfaceRadius;uniform vec3 vSubsurfaceRadiusScale;uniform float vSubsurfaceScatterAnisotropy;uniform float vCoatWeight;uniform vec3 vCoatColor;uniform float vCoatRoughness;uniform float vCoatRoughnessAnisotropy;uniform float vCoatIor;uniform float vCoatDarkening;uniform float vFuzzWeight;uniform vec3 vFuzzColor;uniform float vFuzzRoughness;uniform vec2 vGeometryCoatTangent;uniform float vGeometryThickness;uniform vec3 vEmissionColor;uniform float vThinFilmWeight;uniform vec2 vThinFilmThickness;uniform float vThinFilmIor;uniform float vGeometryThinWalled;uniform vec4 vLightingIntensity;uniform float visibility;uniform vec2 renderTargetSize;
#ifdef BASE_COLOR
uniform vec2 vBaseColorInfos;
#endif
#ifdef BASE_WEIGHT
uniform vec2 vBaseWeightInfos;
#endif
#ifdef BASE_METALNESS
uniform vec2 vBaseMetalnessInfos;
#endif
#ifdef BASE_DIFFUSE_ROUGHNESS
uniform vec2 vBaseDiffuseRoughnessInfos;
#endif
#ifdef SPECULAR_WEIGHT
uniform vec2 vSpecularWeightInfos;
#endif
#ifdef SPECULAR_COLOR
uniform vec2 vSpecularColorInfos;
#endif
#ifdef SPECULAR_ROUGHNESS
uniform vec2 vSpecularRoughnessInfos;
#endif
#ifdef SPECULAR_ROUGHNESS_ANISOTROPY
uniform vec2 vSpecularRoughnessAnisotropyInfos;
#endif
#ifdef SPECULAR_IOR
uniform vec2 vSpecularIorInfos;
#endif
#ifdef AMBIENT_OCCLUSION
uniform vec2 vAmbientOcclusionInfos;
#endif
#ifdef GEOMETRY_NORMAL
uniform vec2 vGeometryNormalInfos;
#endif
#ifdef GEOMETRY_TANGENT
uniform vec2 vGeometryTangentInfos;
#endif
#if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL)
uniform vec2 vTangentSpaceParams;
#endif
#ifdef GEOMETRY_COAT_NORMAL
uniform vec2 vGeometryCoatNormalInfos;
#endif
#ifdef GEOMETRY_OPACITY
uniform vec2 vGeometryOpacityInfos;
#endif
#ifdef GEOMETRY_THICKNESS
uniform vec2 vGeometryThicknessInfos;
#endif
#ifdef EMISSION_COLOR
uniform vec2 vEmissionColorInfos;
#endif
#ifdef TRANSMISSION_WEIGHT
uniform vec2 vTransmissionWeightInfos;
#endif
#ifdef TRANSMISSION_COLOR
uniform vec2 vTransmissionColorInfos;
#endif
#ifdef TRANSMISSION_DEPTH
uniform vec2 vTransmissionDepthInfos;
#endif
#ifdef TRANSMISSION_SCATTER
uniform vec2 vTransmissionScatterInfos;
#endif
#ifdef TRANSMISSION_DISPERSION_SCALE
uniform vec2 vTransmissionDispersionScaleInfos;
#endif
#ifdef SUBSURFACE_WEIGHT
uniform vec2 vSubsurfaceWeightInfos;
#endif
#ifdef SUBSURFACE_COLOR
uniform vec2 vSubsurfaceColorInfos;
#endif
#ifdef SUBSURFACE_RADIUS_SCALE
uniform vec2 vSubsurfaceRadiusScaleInfos;
#endif
#ifdef COAT_WEIGHT
uniform vec2 vCoatWeightInfos;
#endif
#ifdef COAT_COLOR
uniform vec2 vCoatColorInfos;
#endif
#ifdef COAT_ROUGHNESS
uniform vec2 vCoatRoughnessInfos;
#endif
#ifdef COAT_ROUGHNESS_ANISOTROPY
uniform vec2 vCoatRoughnessAnisotropyInfos;
#endif
#ifdef COAT_IOR
uniform vec2 vCoatIorInfos;
#endif
#ifdef COAT_DARKENING
uniform vec2 vCoatDarkeningInfos;
#endif
#ifdef FUZZ_WEIGHT
uniform vec2 vFuzzWeightInfos;
#endif
#ifdef FUZZ_COLOR
uniform vec2 vFuzzColorInfos;
#endif
#ifdef FUZZ_ROUGHNESS
uniform vec2 vFuzzRoughnessInfos;
#endif
#ifdef GEOMETRY_COAT_TANGENT
uniform vec2 vGeometryCoatTangentInfos;
#endif
#ifdef THIN_FILM_WEIGHT
uniform vec2 vThinFilmWeightInfos;
#endif
#ifdef THIN_FILM_THICKNESS
uniform vec2 vThinFilmThicknessInfos;
#endif
#include<sceneFragmentDeclaration>
#ifdef REFLECTION
uniform vec2 vReflectionInfos;
#ifdef REALTIME_FILTERING
uniform vec2 vReflectionFilteringInfo;
#endif
uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;
#if defined(USEIRRADIANCEMAP) && defined(USE_IRRADIANCE_DOMINANT_DIRECTION)
uniform vec3 vReflectionDominantDirection;
#endif
#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)
uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;
#endif
#endif
#ifdef PREPASS
#ifdef SS_SCATTERING
uniform float scatteringDiffusionProfile;
#endif
#endif
#if DEBUGMODE>0
uniform vec2 vDebugMode;
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;
#endif
#include<decalFragmentDeclaration>
#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;
#else
uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;
#endif
#endif
#ifdef REFRACTED_BACKGROUND
uniform mat4 backgroundRefractionMatrix;uniform vec3 vBackgroundRefractionInfos;
#endif
#define ADDITIONAL_FRAGMENT_DECLARATION
`;x.IncludesShadersStore[ZK]||(x.IncludesShadersStore[ZK]=Ove)});var QK,Nve,aF=y(()=>{k();cg();QK="pbrFragmentExtraDeclaration",Nve=`varying vec3 vPositionW;
#if DEBUGMODE>0
varying vec4 vClipSpacePosition;
#endif
#include<mainUVVaryingDeclaration>[1..7]
#ifdef NORMAL
varying vec3 vNormalW;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vec3 vEnvironmentIrradiance;
#endif
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
varying float vViewDepth;
#endif
`;x.IncludesShadersStore[QK]||(x.IncludesShadersStore[QK]=Nve)});var $K,wve,JK=y(()=>{k();fh();ey();$K="openpbrFragmentSamplersDeclaration",wve=`#include<samplerFragmentDeclaration>(_DEFINENAME_,BASE_COLOR,_VARYINGNAME_,BaseColor,_SAMPLERNAME_,baseColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight,_SAMPLERNAME_,baseWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness,_SAMPLERNAME_,baseDiffuseRoughness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BASE_METALNESS,_VARYINGNAME_,BaseMetalness,_SAMPLERNAME_,baseMetalness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR_WEIGHT,_VARYINGNAME_,SpecularWeight,_SAMPLERNAME_,specularWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR_COLOR,_VARYINGNAME_,SpecularColor,_SAMPLERNAME_,specularColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR_ROUGHNESS,_VARYINGNAME_,SpecularRoughness,_SAMPLERNAME_,specularRoughness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR_ROUGHNESS_ANISOTROPY,_VARYINGNAME_,SpecularRoughnessAnisotropy,_SAMPLERNAME_,specularRoughnessAnisotropy)
#include<samplerFragmentDeclaration>(_DEFINENAME_,TRANSMISSION_WEIGHT,_VARYINGNAME_,TransmissionWeight,_SAMPLERNAME_,transmissionWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,TRANSMISSION_COLOR,_VARYINGNAME_,TransmissionColor,_SAMPLERNAME_,transmissionColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,TRANSMISSION_DEPTH,_VARYINGNAME_,TransmissionDepth,_SAMPLERNAME_,transmissionDepth)
#include<samplerFragmentDeclaration>(_DEFINENAME_,TRANSMISSION_SCATTER,_VARYINGNAME_,TransmissionScatter,_SAMPLERNAME_,transmissionScatter)
#include<samplerFragmentDeclaration>(_DEFINENAME_,TRANSMISSION_DISPERSION_SCALE,_VARYINGNAME_,TransmissionDispersionScale,_SAMPLERNAME_,transmissionDispersionScale)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SUBSURFACE_WEIGHT,_VARYINGNAME_,SubsurfaceWeight,_SAMPLERNAME_,subsurfaceWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SUBSURFACE_COLOR,_VARYINGNAME_,SubsurfaceColor,_SAMPLERNAME_,subsurfaceColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SUBSURFACE_RADIUS_SCALE,_VARYINGNAME_,SubsurfaceRadiusScale,_SAMPLERNAME_,subsurfaceRadiusScale)
#include<samplerFragmentDeclaration>(_DEFINENAME_,COAT_WEIGHT,_VARYINGNAME_,CoatWeight,_SAMPLERNAME_,coatWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,COAT_COLOR,_VARYINGNAME_,CoatColor,_SAMPLERNAME_,coatColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,COAT_ROUGHNESS,_VARYINGNAME_,CoatRoughness,_SAMPLERNAME_,coatRoughness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,COAT_ROUGHNESS_ANISOTROPY,_VARYINGNAME_,CoatRoughnessAnisotropy,_SAMPLERNAME_,coatRoughnessAnisotropy)
#include<samplerFragmentDeclaration>(_DEFINENAME_,COAT_DARKENING,_VARYINGNAME_,CoatDarkening,_SAMPLERNAME_,coatDarkening)
#include<samplerFragmentDeclaration>(_DEFINENAME_,FUZZ_WEIGHT,_VARYINGNAME_,FuzzWeight,_SAMPLERNAME_,fuzzWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,FUZZ_COLOR,_VARYINGNAME_,FuzzColor,_SAMPLERNAME_,fuzzColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,FUZZ_ROUGHNESS,_VARYINGNAME_,FuzzRoughness,_SAMPLERNAME_,fuzzRoughness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,GEOMETRY_OPACITY,_VARYINGNAME_,GeometryOpacity,_SAMPLERNAME_,geometryOpacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,GEOMETRY_TANGENT,_VARYINGNAME_,GeometryTangent,_SAMPLERNAME_,geometryTangent)
#include<samplerFragmentDeclaration>(_DEFINENAME_,GEOMETRY_COAT_TANGENT,_VARYINGNAME_,GeometryCoatTangent,_SAMPLERNAME_,geometryCoatTangent)
#include<samplerFragmentDeclaration>(_DEFINENAME_,GEOMETRY_THICKNESS,_VARYINGNAME_,GeometryThickness,_SAMPLERNAME_,geometryThickness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSION_COLOR,_VARYINGNAME_,EmissionColor,_SAMPLERNAME_,emissionColor)
#include<samplerFragmentDeclaration>(_DEFINENAME_,THIN_FILM_WEIGHT,_VARYINGNAME_,ThinFilmWeight,_SAMPLERNAME_,thinFilmWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,THIN_FILM_THICKNESS,_VARYINGNAME_,ThinFilmThickness,_SAMPLERNAME_,thinFilmThickness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT_OCCLUSION,_VARYINGNAME_,AmbientOcclusion,_SAMPLERNAME_,ambientOcclusion)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)
#include<pbrFragmentReflectionDeclaration>
#ifdef ENVIRONMENTBRDF
uniform sampler2D environmentBrdfSampler;
#endif
#ifdef FUZZENVIRONMENTBRDF
uniform sampler2D environmentFuzzBrdfSampler;
#endif
#ifdef REFRACTED_BACKGROUND
uniform sampler2D backgroundRefractionSampler;
#endif
#ifdef USE_IRRADIANCE_TEXTURE_FOR_SCATTERING
uniform sampler2D sceneIrradianceSampler;uniform sampler2D sceneDepthSampler;
#endif
#if defined(ANISOTROPIC) || defined(FUZZ) || defined(REFRACTED_BACKGROUND) || defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING)
uniform sampler2D blueNoiseSampler;
#endif
#ifdef IBL_CDF_FILTERING
uniform sampler2D icdfSampler;
#endif
`;x.IncludesShadersStore[$K]||(x.IncludesShadersStore[$K]=wve)});var ej,Fve,oF=y(()=>{k();ej="subSurfaceScatteringFunctions",Fve=`bool testLightingForSSS(float diffusionProfile)
{return diffusionProfile<1.;}`;x.IncludesShadersStore[ej]||(x.IncludesShadersStore[ej]=Fve)});var tj,Bve,lF=y(()=>{k();tj="importanceSampling",Bve=`vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}
vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}
vec3 hemisphereImportanceSampleDggxAnisotropic(vec2 Xi,float alphaTangent,float alphaBitangent)
{alphaTangent=max(alphaTangent,0.0001);alphaBitangent=max(alphaBitangent,0.0001);float phi=atan(alphaBitangent/alphaTangent*tan(2.0*3.14159265*Xi.x));if (Xi.x>0.5) phi+=3.14159265;
float cosPhi=cos(phi);float sinPhi=sin(phi);float alpha2=(cosPhi*cosPhi)/(alphaTangent*alphaTangent) +
(sinPhi*sinPhi)/(alphaBitangent*alphaBitangent);float tanTheta2=Xi.y/(1.0-Xi.y)/alpha2;float cosTheta=1.0/sqrt(1.0+tanTheta2);float sinTheta=sqrt(max(0.0,1.0-cosTheta*cosTheta));return vec3(sinTheta*cosPhi,sinTheta*sinPhi,cosTheta);}
vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) {
float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;x.IncludesShadersStore[tj]||(x.IncludesShadersStore[tj]=Bve)});var ij,Uve,cF=y(()=>{k();ij="pbrHelperFunctions",Uve=`#define MINIMUMVARIANCE 0.0005
float convertRoughnessToAverageSlope(float roughness)
{return square(roughness)+MINIMUMVARIANCE;}
float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;}
vec2 getAARoughnessFactors(vec3 normalVector) {
#ifdef SPECULARAA
vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor);
#else
return vec2(0.);
#endif
}
#ifdef ANISOTROPIC
#ifdef ANISOTROPIC_LEGACY
vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);}
vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection;if (anisotropy>=0.0) {anisotropicFrameDirection=B;} else {anisotropicFrameDirection=T;}
vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}
#elif ANISOTROPIC_OPENPBR
vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*alphaG*sqrt(2.0/(1.0+(1.0-anisotropy)*(1.0-anisotropy))),MINIMUMVARIANCE);float alphaB=max(alphaT*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);}
#else
vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);}
vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}
#endif
#endif
#if defined(CLEARCOAT) || defined(SS_REFRACTION)
vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);}
vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}
vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;}
vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0),
cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),
clearCoatIntensity);return clearCoatAbsorption;}
#endif
#ifdef MICROSURFACEAUTOMATIC
float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)
{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;}
#endif
`;x.IncludesShadersStore[ij]||(x.IncludesShadersStore[ij]=Uve)});var rj,Vve,fF=y(()=>{k();uN();rj="pbrDirectLightingSetupFunctions",Vve=`struct preLightingInfo
{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float LdotV;float roughness;float diffuseRoughness;vec3 surfaceAlbedo;
#ifdef IRIDESCENCE
float iridescenceIntensity;
#endif
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
vec3 areaLightDiffuse;
#ifdef SPECULARTERM
vec3 areaLightSpecular;vec4 areaLightFresnel;
#endif
#endif
};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N,vec3 posW) {preLightingInfo result;result.lightOffset=lightData.xyz-posW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);result.LdotV=0.;result.roughness=0.;result.diffuseRoughness=0.;result.surfaceAlbedo=vec3(0.);return result;}
preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);result.LdotV=dot(result.L,V);result.roughness=0.;result.diffuseRoughness=0.;result.surfaceAlbedo=vec3(0.);return result;}
preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;
#ifdef SPECULARTERM
result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));
#endif
result.LdotV=0.;result.roughness=0.;result.diffuseRoughness=0.;result.surfaceAlbedo=vec3(0.);return result;}
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
#include<ltcHelperFunctions>
uniform sampler2D areaLightsLTC1Sampler;uniform sampler2D areaLightsLTC2Sampler;preLightingInfo computeAreaPreLightingInfo(sampler2D ltc1,sampler2D ltc2,vec3 viewDirectionW,vec3 vNormal,vec3 vPosition,vec4 lightData,vec3 halfWidth,vec3 halfHeight,float roughness )
{preLightingInfo result;result.lightOffset=lightData.xyz-vPosition;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);areaLightData data=computeAreaLightSpecularDiffuseFresnel(ltc1,ltc2,viewDirectionW,vNormal,vPosition,lightData.xyz,halfWidth,halfHeight,roughness);
#ifdef SPECULARTERM
result.areaLightFresnel=data.Fresnel;result.areaLightSpecular=data.Specular;
#endif
result.areaLightDiffuse=data.Diffuse;result.LdotV=0.;result.roughness=0.;result.diffuseRoughness=0.;result.surfaceAlbedo=vec3(0.);return result;}
preLightingInfo computeAreaPreLightingInfoWithTexture(sampler2D ltc1,sampler2D ltc2,sampler2D emissionTexture,vec3 viewDirectionW,vec3 vNormal,vec3 vPosition,vec4 lightData,vec3 halfWidth,vec3 halfHeight,float roughness )
{preLightingInfo result;result.lightOffset=lightData.xyz-vPosition;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);areaLightData data=computeAreaLightSpecularDiffuseFresnelWithEmission(ltc1,ltc2,emissionTexture,viewDirectionW,vNormal,vPosition,lightData.xyz,halfWidth,halfHeight,roughness);
#ifdef SPECULARTERM
result.areaLightFresnel=data.Fresnel;result.areaLightSpecular=data.Specular;
#endif
result.areaLightDiffuse=data.Diffuse;result.LdotV=0.;result.roughness=0.;result.diffuseRoughness=0.;result.surfaceAlbedo=vec3(0.);return result;}
#endif
`;x.IncludesShadersStore[rj]||(x.IncludesShadersStore[rj]=Vve)});var nj,Gve,dF=y(()=>{k();nj="pbrDirectLightingFalloffFunctions",Gve=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)
{return max(0.,1.0-length(lightOffset)/range);}
float computeDistanceLightFalloff_Physical(float lightDistanceSquared)
{return 1.0/maxEps(lightDistanceSquared);}
float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)
{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}
float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)
{
#ifdef USEPHYSICALLIGHTFALLOFF
return computeDistanceLightFalloff_Physical(lightDistanceSquared);
#elif defined(USEGLTFLIGHTFALLOFF)
return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);
#else
return computeDistanceLightFalloff_Standard(lightOffset,range);
#endif
}
float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)
{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)
{falloff=max(0.,pow(cosAngle,exponent));}
return falloff;}
float computeDirectionalLightFalloff_IES(vec3 lightDirection,vec3 directionToLightCenterW,sampler2D iesLightSampler)
{float cosAngle=dot(-lightDirection,directionToLightCenterW);float angle=acos(cosAngle)/PI;return texture2D(iesLightSampler,vec2(angle,0.)).r;}
float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)
{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977;
float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}
float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)
{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}
float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)
{
#ifdef USEPHYSICALLIGHTFALLOFF
return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);
#elif defined(USEGLTFLIGHTFALLOFF)
return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);
#else
return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);
#endif
}`;x.IncludesShadersStore[nj]||(x.IncludesShadersStore[nj]=Gve)});var sj,kve,uF=y(()=>{k();sj="hdrFilteringFunctions",kve=`#if NUM_SAMPLES
#if NUM_SAMPLES>0
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
float radicalInverse_VdC(uint bits)
{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; }
vec2 hammersley(uint i,uint N)
{return vec2(float(i)/float(N),radicalInverse_VdC(i));}
#else
float vanDerCorpus(int n,int base)
{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i)
{if(n>0)
{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}}
return result;}
vec2 hammersley(int i,int N)
{return vec2(float(i)/float(N),vanDerCorpus(i,2));}
#endif
float log4(float x) {return log2(x)/2.;}
vec3 uv_to_normal(vec2 uv) {vec3 N;vec2 uvRange=uv;float theta=uvRange.x*2.*PI;float phi=uvRange.y*PI;float sinPhi=sin(phi);N.x=cos(theta)*sinPhi;N.z=sin(theta)*sinPhi;N.y=cos(phi);return N;}
const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.;
#define inline
vec3 irradiance(
#ifdef CUSTOM_IRRADIANCE_FILTERING_INPUT
CUSTOM_IRRADIANCE_FILTERING_INPUT
#else
samplerCube inputTexture,
#endif
vec3 inputN,vec2 filteringInfo,
float diffuseRoughness,
vec3 surfaceAlbedo,
vec3 inputV
#if IBL_CDF_FILTERING
,sampler2D icdfSampler
#endif
)
{vec3 n=normalize(inputN);vec3 result=vec3(0.);
#ifndef IBL_CDF_FILTERING
vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);mat3 tbnInverse=mat3(tangent.x,bitangent.x,n.x,tangent.y,bitangent.y,n.y,tangent.z,bitangent.z,n.z);
#endif
float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);vec3 clampedAlbedo=clamp(surfaceAlbedo,vec3(0.1),vec3(1.0));
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
for(uint i=0u; i<NUM_SAMPLES; ++i)
#else
for(int i=0; i<NUM_SAMPLES; ++i)
#endif
{vec2 Xi=hammersley(i,NUM_SAMPLES);
#if IBL_CDF_FILTERING
vec2 T;T.x=texture2D(icdfSampler,vec2(Xi.x,0.)).x;T.y=texture2D(icdfSampler,vec2(T.x,Xi.y)).y;vec3 Ls=uv_to_normal(vec2(1.0-fract(T.x+0.25),T.y));float NoL=dot(n,Ls);float NoV=dot(n,inputV);
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
float LoV=dot (Ls,inputV);
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
vec3 H=(inputV+Ls)*0.5;float VoH=dot(inputV,H);
#endif
#else
vec3 Ls=hemisphereCosSample(Xi);Ls=normalize(Ls);float NoL=Ls.z;
vec3 V=tbnInverse*inputV;float NoV=V.z;
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
float LoV=dot (Ls,V);
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
vec3 H=(V+Ls)*0.5;float VoH=dot(V,H);
#endif
#endif
if (NoL>0.) {
#if IBL_CDF_FILTERING
float pdf=texture2D(icdfSampler,T).z;vec3 c=textureCubeLodEXT(inputTexture,Ls,0.).rgb;
#else
float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.,maxLevel);
#ifdef CUSTOM_IRRADIANCE_FILTERING_FUNCTION
CUSTOM_IRRADIANCE_FILTERING_FUNCTION
#else
vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb;
#endif
#endif
#if GAMMA_INPUT
c=toLinearSpace(c);
#endif
vec3 diffuseRoughnessTerm=vec3(1.0);
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
diffuseRoughnessTerm=diffuseBRDF_EON(clampedAlbedo,diffuseRoughness,NoL,NoV,LoV)*PI;
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
diffuseRoughnessTerm=vec3(diffuseBRDF_Burley(NoL,NoV,VoH,diffuseRoughness)*PI);
#endif
#if IBL_CDF_FILTERING
vec3 light=pdf<1e-6 ? vec3(0.0) : vec3(1.0)/vec3(pdf)*c;result+=NoL*diffuseRoughnessTerm*light;
#else
result+=c*diffuseRoughnessTerm;
#endif
}}
result=result*NUM_SAMPLES_FLOAT_INVERSED;
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
result=result/clampedAlbedo;
#endif
return result;}
#define inline
vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)
{vec3 n=normalize(inputN);vec3 c=textureCubeLodEXT(inputTexture,n,0.).rgb;
if (alphaG==0.) {
#if GAMMA_INPUT
c=toLinearSpace(c);
#endif
return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.;
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
for(uint i=0u; i<NUM_SAMPLES; ++i)
#else
for(int i=0; i<NUM_SAMPLES; ++i)
#endif
{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 H=hemisphereImportanceSampleDggx(Xi,alphaG);float NoV=1.;float NoH=H.z;float NoH2=H.z*H.z;float NoL=2.*NoH2-1.;vec3 L=vec3(2.*NoH*H.x,2.*NoH*H.y,NoL);L=normalize(L);if (NoL>0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb;
#if GAMMA_INPUT
c=toLinearSpace(c);
#endif
result+=c*NoL;}}
result=result/weight;return result;}}
#ifdef ANISOTROPIC
#define inline
vec3 radianceAnisotropic(
float alphaTangent,
float alphaBitangent,
samplerCube inputTexture,
vec3 inputView,
vec3 inputTangent,
vec3 inputBitangent,
vec3 inputNormal,
vec2 filteringInfo,
vec2 noiseInput,
bool isRefraction,
float ior
)
{vec3 V=inputView;vec3 N=inputNormal;vec3 T=inputTangent;vec3 B=inputBitangent;vec3 result=vec3(0.);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float clampedAlphaT=max(alphaTangent,MINIMUMVARIANCE);float clampedAlphaB=max(alphaBitangent,MINIMUMVARIANCE);float effectiveDim=dim0*sqrt(clampedAlphaT*clampedAlphaB);float omegaP=(4.*PI)/(6.*effectiveDim*effectiveDim);const float noiseScale=clamp(log2(float(NUM_SAMPLES))/12.0f,0.0f,1.0f);float weight=0.;
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
for(uint i=0u; i<NUM_SAMPLES; ++i)
#else
for(int i=0; i<NUM_SAMPLES; ++i)
#endif
{vec2 Xi=hammersley(i,NUM_SAMPLES);Xi=fract(Xi+noiseInput*mix(0.5f,0.015f,noiseScale));
vec3 H_tangent=hemisphereImportanceSampleDggxAnisotropic(Xi,clampedAlphaT,clampedAlphaB);vec3 H=normalize(H_tangent.x*T+H_tangent.y*B+H_tangent.z*N);vec3 L;if (isRefraction) {L=refract(-V,H,1.0/ior);} else {L=reflect(-V,H);}
float NoH=max(dot(N,H),0.001);float VoH=max(dot(V,H),0.001);float NoL=max(dot(N,L),0.001);if (NoL>0.) {float pdf_inversed=4./normalDistributionFunction_BurleyGGX_Anisotropic(
H_tangent.z,H_tangent.x,H_tangent.y,vec2(clampedAlphaT,clampedAlphaB)
);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,L,mipLevel).rgb;
#if GAMMA_INPUT
c=toLinearSpace(c);
#endif
result+=c*NoL;}}
result=result/weight;return result;}
#endif
#endif
#endif
`;x.IncludesShadersStore[sj]||(x.IncludesShadersStore[sj]=kve)});var aj,zve,hF=y(()=>{k();aj="pbrDirectLightingFunctions",zve=`#define CLEARCOATREFLECTANCE90 1.0
struct lightingInfo
{vec3 diffuse;
#ifdef SS_TRANSLUCENCY
vec3 diffuseTransmission;
#endif
#ifdef SPECULARTERM
vec3 specular;
#endif
#ifdef CLEARCOAT
vec4 clearCoat;
#endif
#ifdef SHEEN
vec3 sheen;
#endif
};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {
#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)
float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness;
#else
return roughness;
#endif
}
vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);}
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
vec3 computeAreaDiffuseLighting(preLightingInfo info,vec3 lightColor) {return info.areaLightDiffuse*lightColor;}
#endif
vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {vec3 diffuseTerm=vec3(1.0/PI);
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_LEGACY
diffuseTerm=vec3(diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness));
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
diffuseTerm=vec3(diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.diffuseRoughness));
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
vec3 clampedAlbedo=clamp(info.surfaceAlbedo,vec3(0.1),vec3(1.0));diffuseTerm=diffuseBRDF_EON(clampedAlbedo,info.diffuseRoughness,info.NdotL,info.NdotV,info.LdotV);diffuseTerm/=clampedAlbedo;
#endif
return diffuseTerm*info.attenuation*info.NdotL*lightColor;}
#define inline
vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);}
#ifdef SS_TRANSLUCENCY
vec3 computeDiffuseTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {vec3 transmittanceNdotL=vec3(0.);float NdotL=absEps(info.NdotLUnclamped);
#ifndef SS_TRANSLUCENCY_LEGACY
if (info.NdotLUnclamped<0.0) {
#endif
float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);
#ifndef SS_TRANSLUCENCY_LEGACY
}
vec3 diffuseTerm=vec3(1.0/PI);
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_LEGACY
diffuseTerm=vec3(diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness));
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
diffuseTerm=vec3(diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.diffuseRoughness));
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
vec3 clampedAlbedo=clamp(info.surfaceAlbedo,vec3(0.1),vec3(1.0));diffuseTerm=diffuseBRDF_EON(clampedAlbedo,info.diffuseRoughness,info.NdotL,info.NdotV,info.LdotV);diffuseTerm/=clampedAlbedo;
#endif
#else
float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);
#endif
return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;}
#endif
#ifdef SPECULARTERM
vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 fresnel,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);
#ifdef IRIDESCENCE
fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);
#endif
float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);
#ifdef BRDF_V_HEIGHT_CORRELATED
float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);
#else
float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);
#endif
vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
vec3 computeAreaSpecularLighting(preLightingInfo info,vec3 specularColor,vec3 reflectance0,vec3 reflectance90) {vec3 fresnel=specularColor*info.areaLightFresnel.x*reflectance0+( vec3( 1.0 )-specularColor )*info.areaLightFresnel.y*reflectance90;return specularColor*fresnel*info.areaLightSpecular;}
#endif
#endif
#ifdef FUZZ
float evalFuzz(vec3 L,float NdotL,float NdotV,vec3 T,vec3 B,vec3 ltcLut)
{if (NdotL<=0.0 || NdotV<=0.0)
return 0.0;mat3 M=mat3(
vec3(ltcLut.r,0.0,0.0),
vec3(ltcLut.g,1.0,0.0),
vec3(0.0,0.0,1.0)
);vec3 Llocal=vec3(dot(L,T),dot(L,B),NdotL);vec3 Lwarp=normalize(M*Llocal);float cosThetaWarp=max(Lwarp.z,0.0);return cosThetaWarp*NdotL;}
#endif
#if defined(ANISOTROPIC) && defined(ANISOTROPIC_OPENPBR)
vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=vec3(distribution*smithVisibility);return specTerm*info.attenuation*info.NdotL*lightColor;}
#elif defined(ANISOTROPIC)
vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);
#ifdef IRIDESCENCE
fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);
#endif
float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}
#endif
#ifdef CLEARCOAT
vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4(
clearCoatTerm*info.attenuation*NccdotL*lightColor,
1.0-fresnel
);}
vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;}
#endif
#ifdef SHEEN
vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER
float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);
#else */
float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */
float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;}
#endif
`;x.IncludesShadersStore[aj]||(x.IncludesShadersStore[aj]=zve)});var oj,Wve,lj=y(()=>{k();oj="openpbrNormalMapFragmentMainFunctions",Wve=`#if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL) || defined(ANISOTROPIC) || defined(FUZZ) || defined(DETAIL)
#if defined(TANGENT) && defined(NORMAL)
varying mat3 vTBN;
#endif
#ifdef OBJECTSPACE_NORMALMAP
uniform mat4 normalMatrix;
#if defined(WEBGL2) || defined(WEBGPU)
mat4 toNormalMatrix(mat4 wMatrix)
{mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;}
#else
mat4 toNormalMatrix(mat4 m)
{float
a00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],
a10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],
a20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],
a30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],
b00=a00*a11-a01*a10,
b01=a00*a12-a02*a10,
b02=a00*a13-a03*a10,
b03=a01*a12-a02*a11,
b04=a01*a13-a03*a11,
b05=a02*a13-a03*a12,
b06=a20*a31-a21*a30,
b07=a20*a32-a22*a30,
b08=a20*a33-a23*a30,
b09=a21*a32-a22*a31,
b10=a21*a33-a23*a31,
b11=a22*a33-a23*a32,
det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4(
a11*b11-a12*b10+a13*b09,
a02*b10-a01*b11-a03*b09,
a31*b05-a32*b04+a33*b03,
a22*b04-a21*b05-a23*b03,
a12*b08-a10*b11-a13*b07,
a00*b11-a02*b08+a03*b07,
a32*b02-a30*b05-a33*b01,
a20*b05-a22*b02+a23*b01,
a10*b10-a11*b08+a13*b06,
a01*b08-a00*b10-a03*b06,
a30*b04-a31*b02+a33*b00,
a21*b02-a20*b04-a23*b00,
a11*b07-a10*b09-a12*b06,
a00*b09-a01*b07+a02*b06,
a31*b01-a30*b03-a32*b00,
a20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0],
mi[0][1],mi[1][1],mi[2][1],mi[3][1],
mi[0][2],mi[1][2],mi[2][2],mi[3][2],
mi[0][3],mi[1][3],mi[2][3],mi[3][3]);}
#endif
#endif
vec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale)
{
#ifdef NORMALXYSCALE
normal=normalize(normal*vec3(scale,scale,1.0));
#endif
return normalize(cotangentFrame*normal);}
vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale)
{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}
mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams)
{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);}
#endif
`;x.IncludesShadersStore[oj]||(x.IncludesShadersStore[oj]=Wve)});var cj,Hve,fj=y(()=>{k();fh();cj="openpbrNormalMapFragmentFunctions",Hve=`#if defined(GEOMETRY_NORMAL)
#include<samplerFragmentDeclaration>(_DEFINENAME_,GEOMETRY_NORMAL,_VARYINGNAME_,GeometryNormal,_SAMPLERNAME_,geometryNormal)
#endif
#if defined(GEOMETRY_COAT_NORMAL)
#include<samplerFragmentDeclaration>(_DEFINENAME_,GEOMETRY_COAT_NORMAL,_VARYINGNAME_,GeometryCoatNormal,_SAMPLERNAME_,geometryCoatNormal)
#endif
#if defined(DETAIL)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)
#endif
#if defined(GEOMETRY_NORMAL) && defined(PARALLAX)
const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; i<iMaxSamples; i++)
{currSampledHeight=texture2D(geometryNormalSampler,texCoord+vCurrOffset).w;if (!keepWorking)
{}
else if (currSampledHeight>currRayHeight)
{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}
else
{currRayHeight-=stepSize;vLastOffset=vCurrOffset;
#ifdef PARALLAX_RHS
vCurrOffset-=stepSize*vMaxOffset;
#else
vCurrOffset+=stepSize*vMaxOffset;
#endif
lastSampledHeight=currSampledHeight;}}
return vCurrOffset;}
vec2 parallaxOffset(vec3 viewDir,float heightScale)
{float height=texture2D(geometryNormalSampler,vGeometryNormalUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height;
#ifdef PARALLAX_RHS
return texCoordOffset;
#else
return -texCoordOffset;
#endif
}
#endif
`;x.IncludesShadersStore[cj]||(x.IncludesShadersStore[cj]=Hve)});var dj,Xve,uj=y(()=>{k();dj="openpbrConductorReflectance",Xve=`#define pbr_inline
ReflectanceParams conductorReflectance(in vec3 baseColor,in vec3 specularColor,in float specularWeight)
{ReflectanceParams outParams;
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR)
outParams.coloredF0=baseColor*specularWeight;outParams.coloredF90=specularColor*specularWeight;
#else
outParams.coloredF0=baseColor;outParams.coloredF90=vec3(1.0);
#endif
outParams.F0=1.0;outParams.F90=1.0;return outParams;}`;x.IncludesShadersStore[dj]||(x.IncludesShadersStore[dj]=Xve)});var hj,Yve,mj=y(()=>{k();hj="openpbrAmbientOcclusionFunctions",Yve=`float compute_specular_occlusion(const float n_dot_v,const float metallic,const float ambient_occlusion,const float roughness)
{float specular_occlusion=saturate(pow(n_dot_v+ambient_occlusion,exp2(-16.0*roughness-1.0))-1.0+ambient_occlusion);return mix(specular_occlusion,1.0,metallic*square(1.0-roughness));}
`;x.IncludesShadersStore[hj]||(x.IncludesShadersStore[hj]=Yve)});var pj,Kve,gj=y(()=>{k();pj="openpbrVolumeFunctions",Kve=`struct OpenPBRHomogeneousVolume {vec3 extinction_coeff;
vec3 ss_albedo;
vec3 multi_scatter_color;
vec3 absorption_coeff;
vec3 scatter_coeff;
float anisotropy; };OpenPBRHomogeneousVolume computeOpenPBRTransmissionVolume(
in vec3 transmission_color,
in float transmission_depth,
in vec3 transmission_scatter,
in float anisotropy
)
{OpenPBRHomogeneousVolume volumeParams;volumeParams.absorption_coeff=vec3(0.0);volumeParams.scatter_coeff=vec3(0.0);volumeParams.anisotropy=anisotropy;
#ifdef GEOMETRY_THIN_WALLED
volumeParams.scatter_coeff=vec3(1.0);volumeParams.anisotropy=1.0;
volumeParams.extinction_coeff=volumeParams.absorption_coeff+volumeParams.scatter_coeff;volumeParams.ss_albedo=vec3(1.0);
#else
if (transmission_depth>0.0) {vec3 invDepth=vec3(1./maxEps(transmission_depth));volumeParams.extinction_coeff=-log(maxEps(transmission_color.rgb))*invDepth;volumeParams.scatter_coeff=transmission_scatter.rgb*invDepth;volumeParams.absorption_coeff=volumeParams.extinction_coeff-volumeParams.scatter_coeff.rgb;float minCoeff=min3(volumeParams.absorption_coeff);if (minCoeff<0.0) {volumeParams.absorption_coeff-=vec3(minCoeff);}
volumeParams.extinction_coeff=volumeParams.absorption_coeff+volumeParams.scatter_coeff;volumeParams.ss_albedo=volumeParams.scatter_coeff/(volumeParams.extinction_coeff);} else {volumeParams.extinction_coeff=volumeParams.absorption_coeff+volumeParams.scatter_coeff;volumeParams.ss_albedo=vec3(0.0);}
#endif
return volumeParams;}
OpenPBRHomogeneousVolume computeOpenPBRSubsurfaceVolume(
in vec3 subsurface_color,
in float subsurface_radius,
in vec3 subsurface_radius_scale,
in float anisotropy
)
{OpenPBRHomogeneousVolume volumeParams;volumeParams.absorption_coeff=vec3(0.0);volumeParams.scatter_coeff=vec3(0.0);volumeParams.anisotropy=anisotropy;volumeParams.multi_scatter_color=subsurface_color;vec3 mfp=subsurface_radius_scale*vec3(subsurface_radius);volumeParams.extinction_coeff=vec3(1.0)/maxEps(mfp);volumeParams.ss_albedo=multiScatterToSingleScatterAlbedo(subsurface_color,anisotropy);volumeParams.scatter_coeff=volumeParams.ss_albedo*volumeParams.extinction_coeff;volumeParams.absorption_coeff=volumeParams.extinction_coeff-volumeParams.scatter_coeff.rgb;float minCoeff=min3(volumeParams.absorption_coeff);if (minCoeff<0.0) {volumeParams.absorption_coeff-=vec3(minCoeff);}
volumeParams.extinction_coeff=volumeParams.absorption_coeff+volumeParams.scatter_coeff;return volumeParams;}
vec3 sss_pdf(float r,vec3 d)
{d=max(vec3(1e-4f),d);return (exp(-r/d)+exp(-r/(3.0f*d)))/max(vec3(1e-5f),8.0f*PI*d*r);}
float sss_samples_pdf(float r,float d)
{d=max(1e-4f,d);return exp(-r/(3.0f*d))/(6.0f*PI*d*r);}
float sss_samples_icdf(float x,float d)
{d=max(1e-4f,d);x=max(1e-4f,x);return -3.0f*log(x)*d;}
float samples_scale(float x,float d)
{return 1.0f-exp(-x/(3.0f*d));}
vec3 sss_get_position(sampler2D depth_texture,vec2 tex_coord,vec2 render_resolution,mat4 inv_proj)
{vec4 P=vec4(tex_coord,texelFetch(depth_texture,ivec2(tex_coord*render_resolution),0).x,1.0f);P.xy=2.0f*P.xy-1.0f;P=inv_proj*P;return P.xyz/P.w;}
float sss_filter_scale(float currZ,mat4 proj)
{return 1.0f/dot(vec2(proj[2].w,proj[3].w),vec2(currZ,1.0f));}
float projective_to_pixels(float proj_dist,mat4 proj,vec2 resolution)
{return proj_dist*proj[1][1]*resolution.y;}
float pixels_to_projective(float pixel_dist,mat4 proj,vec2 resolution)
{return pixel_dist/(proj[1][1]*resolution.y);}
vec3 sss_convolve(sampler2D sss_irradiance_texture,sampler2D depth_texture,vec2 render_resolution,vec3 d,mat4 proj,mat4 inv_proj,int sample_count,vec2 noise)
{vec2 tex_coord=gl_FragCoord.xy/render_resolution;vec3 unconvolved_irradiance=texelFetch(sss_irradiance_texture,ivec2(gl_FragCoord.xy),0).rgb;vec3 curr_pos=sss_get_position(depth_texture,tex_coord,render_resolution,inv_proj);float dmax=max3(d);float max_dmax=0.1*float(sample_count);if (dmax>max_dmax)
{d.rgb*=max_dmax/dmax;dmax=max_dmax;}
float dz=dmax*sss_filter_scale(curr_pos.z,proj);mat2 projMat2d=mat2(proj);if (determinant(projMat2d)*dz<1e-4f)
return unconvolved_irradiance;float overscan_size_in_pixels=max(render_resolution.x,render_resolution.y)*0.1;const float filter_crop_ratio=0.8f;
float crop_radius=projective_to_pixels(sss_samples_icdf(1.0f-filter_crop_ratio,dz),proj,render_resolution);if (crop_radius>overscan_size_in_pixels)
{d.rgb*=overscan_size_in_pixels/crop_radius;dz*=overscan_size_in_pixels/crop_radius;}
float filter_samples_scale=samples_scale(pixels_to_projective(overscan_size_in_pixels,proj,render_resolution),dz);vec3 irradiance_sum=vec3(0.0f);vec3 weight_sum=vec3(0.0f);for (int i=0; i<sample_count; i++)
{vec2 r=fract(plasticSequence(uint(i))+noise);r.x*=TWO_PI;r.y*=filter_samples_scale;float icdf=sss_samples_icdf(1.0-r.y,dz);vec2 sample_uv=tex_coord+icdf*projMat2d*vec2(cos(r.x),sin(r.x));vec4 sss_irradiance=texelFetch(sss_irradiance_texture,ivec2(sample_uv*render_resolution),0);float dist=distance(curr_pos,sss_get_position(depth_texture,sample_uv,render_resolution,inv_proj));if (dist>0.0f)
{vec3 weights=sss_irradiance.a/sss_samples_pdf(icdf,dz)*sss_pdf(dist,d.rgb);irradiance_sum+=weights*sss_irradiance.rgb;weight_sum+=weights;}}
return vec3(weight_sum.r<1e-5f ? unconvolved_irradiance.r : irradiance_sum.r/weight_sum.r,
weight_sum.g<1e-5f ? unconvolved_irradiance.g : irradiance_sum.g/weight_sum.g,
weight_sum.b<1e-5f ? unconvolved_irradiance.b : irradiance_sum.b/weight_sum.b);}`;x.IncludesShadersStore[pj]||(x.IncludesShadersStore[pj]=Kve)});var _j,jve,mF=y(()=>{k();_j="pbrBlockNormalGeometric",jve=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);
#ifdef NORMAL
vec3 normalW=normalize(vNormalW);
#else
vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;
#endif
vec3 geometricNormalW=normalW;
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW;
#endif
`;x.IncludesShadersStore[_j]||(x.IncludesShadersStore[_j]=jve)});var vj,Zve,Ej=y(()=>{k();vj="openpbrNormalMapFragment",Zve=`vec2 uvOffset=vec2(0.0,0.0);
#if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL) || defined(PARALLAX) || defined(DETAIL)
#ifdef NORMALXYSCALE
float normalScale=1.0;
#elif defined(GEOMETRY_NORMAL)
float normalScale=vGeometryNormalInfos.y;
#else
float normalScale=1.0;
#endif
#if defined(TANGENT) && defined(NORMAL)
mat3 TBN=vTBN;
#elif defined(GEOMETRY_NORMAL)
vec2 TBNUV=gl_FrontFacing ? vGeometryNormalUV : -vGeometryNormalUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);
#elif defined(GEOMETRY_COAT_NORMAL)
vec2 TBNUV=gl_FrontFacing ? vGeometryCoatNormalUV : -vGeometryCoatNormalUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);
#else
vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.));
#endif
#elif defined(ANISOTROPIC) || defined(FUZZ)
#if defined(TANGENT) && defined(NORMAL)
mat3 TBN=vTBN;
#else
vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.));
#endif
#endif
#ifdef PARALLAX
mat3 invTBN=transposeMat3(TBN);
#ifdef PARALLAXOCCLUSION
#else
#endif
#endif
#ifdef DETAIL
vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB);
#endif
#ifdef GEOMETRY_COAT_NORMAL
coatNormalW=perturbNormal(TBN,texture2D(geometryCoatNormalSampler,vGeometryCoatNormalUV+uvOffset).xyz,vGeometryCoatNormalInfos.y);
#endif
#ifdef GEOMETRY_NORMAL
#ifdef OBJECTSPACE_NORMALMAP
#define CUSTOM_FRAGMENT_BUMP_FRAGMENT
normalW=normalize(texture2D(geometryNormalSampler,vGeometryNormalUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW);
#elif !defined(DETAIL)
normalW=perturbNormal(TBN,texture2D(geometryNormalSampler,vGeometryNormalUV+uvOffset).xyz,vGeometryNormalInfos.y);
#else
vec3 sampledNormal=texture2D(geometryNormalSampler,vGeometryNormalUV+uvOffset).xyz*2.0-1.0;
#if DETAIL_NORMALBLENDMETHOD==0
detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(sampledNormal.xy+detailNormal.xy,sampledNormal.z*detailNormal.z));
#elif DETAIL_NORMALBLENDMETHOD==1
detailNormal.xy*=vDetailInfos.z;sampledNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=sampledNormal*dot(sampledNormal,detailNormal)/sampledNormal.z-detailNormal;
#endif
normalW=perturbNormalBase(TBN,blendedNormal,vGeometryNormalInfos.y);
#endif
#elif defined(DETAIL)
detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);
#endif
`;x.IncludesShadersStore[vj]||(x.IncludesShadersStore[vj]=Zve)});var Sj,qve,Tj=y(()=>{k();Sj="openpbrBlockNormalFinal",qve=`#if defined(FORCENORMALFORWARD) && defined(NORMAL)
vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;
#if defined(TWOSIDEDLIGHTING)
faceNormal=gl_FrontFacing ? faceNormal : -faceNormal;
#endif
normalW*=sign(dot(normalW,faceNormal));coatNormalW*=sign(dot(coatNormalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
#if defined(MIRRORED)
normalW=gl_FrontFacing ? -normalW : normalW;coatNormalW=gl_FrontFacing ? -coatNormalW : coatNormalW;
#else
normalW=gl_FrontFacing ? normalW : -normalW;coatNormalW=gl_FrontFacing ? coatNormalW : -coatNormalW;
#endif
#endif
`;x.IncludesShadersStore[Sj]||(x.IncludesShadersStore[Sj]=qve)});var Aj,Qve,xj=y(()=>{k();Aj="openpbrBaseLayerData",Qve=`vec3 base_color=vec3(0.8);float base_metalness=0.0;float base_diffuse_roughness=0.0;float specular_weight=1.0;float specular_roughness=0.3;vec3 specular_color=vec3(1.0);float specular_roughness_anisotropy=0.0;float specular_ior=1.5;float alpha=1.0;vec2 geometry_tangent=vec2(1.0,0.0);float geometry_thickness=0.0;
#ifdef BASE_WEIGHT
vec4 baseWeightFromTexture=texture2D(baseWeightSampler,vBaseWeightUV+uvOffset);
#endif
#ifdef BASE_COLOR
vec4 baseColorFromTexture=texture2D(baseColorSampler,vBaseColorUV+uvOffset);
#endif
#ifdef BASE_METALNESS
vec4 metallicFromTexture=texture2D(baseMetalnessSampler,vBaseMetalnessUV+uvOffset);
#endif
#if defined(SPECULAR_ROUGHNESS_FROM_METALNESS_TEXTURE_GREEN) && defined(BASE_METALNESS)
float roughnessFromTexture=metallicFromTexture.g;
#elif defined(SPECULAR_ROUGHNESS)
float roughnessFromTexture=texture2D(specularRoughnessSampler,vSpecularRoughnessUV+uvOffset).r;
#endif
#ifdef GEOMETRY_TANGENT
vec3 geometryTangentFromTexture=texture2D(geometryTangentSampler,vGeometryTangentUV+uvOffset).rgb;
#endif
#ifdef SPECULAR_ROUGHNESS_ANISOTROPY
float anisotropyFromTexture=texture2D(specularRoughnessAnisotropySampler,vSpecularRoughnessAnisotropyUV+uvOffset).r*vSpecularRoughnessAnisotropyInfos.y;
#endif
#ifdef BASE_DIFFUSE_ROUGHNESS
float baseDiffuseRoughnessFromTexture=texture2D(baseDiffuseRoughnessSampler,vBaseDiffuseRoughnessUV+uvOffset).r;
#endif
#ifdef GEOMETRY_OPACITY
vec4 opacityFromTexture=texture2D(geometryOpacitySampler,vGeometryOpacityUV+uvOffset);
#endif
#ifdef GEOMETRY_THICKNESS
vec4 thicknessFromTexture=texture2D(geometryThicknessSampler,vGeometryThicknessUV+uvOffset);
#endif
#ifdef DECAL
vec4 decalFromTexture=texture2D(decalSampler,vDecalUV+uvOffset);
#endif
#ifdef SPECULAR_COLOR
vec4 specularColorFromTexture=texture2D(specularColorSampler,vSpecularColorUV+uvOffset);
#endif
#ifdef SPECULAR_WEIGHT
#ifdef SPECULAR_WEIGHT_IN_ALPHA
float specularWeightFromTexture=texture2D(specularWeightSampler,vSpecularWeightUV+uvOffset).a;
#else
float specularWeightFromTexture=texture2D(specularWeightSampler,vSpecularWeightUV+uvOffset).r;
#endif
#endif
#if defined(ANISOTROPIC) || defined(FUZZ) || defined(REFRACTED_BACKGROUND) || defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING)
vec3 noise=vec3(2.0)*texture2D(blueNoiseSampler,gl_FragCoord.xy/256.0).xyz-vec3(1.0);
#endif
base_color=vBaseColor.rgb;
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
base_color*=vColor.rgb;
#endif
#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)
alpha*=vColor.a;
#endif
base_color*=vec3(vBaseWeight);alpha=vBaseColor.a;base_metalness=vReflectanceInfo.x;base_diffuse_roughness=vBaseDiffuseRoughness;specular_roughness=vReflectanceInfo.y;specular_color=vSpecularColor.rgb;specular_weight=vReflectanceInfo.a;specular_ior=vReflectanceInfo.z;specular_roughness_anisotropy=vSpecularAnisotropy.b;geometry_tangent=vSpecularAnisotropy.rg;geometry_thickness=vGeometryThickness;
#ifdef BASE_COLOR
#ifdef BASE_COLOR_GAMMA
base_color*=toLinearSpace(baseColorFromTexture.rgb);
#else
base_color*=baseColorFromTexture.rgb;
#endif
base_color*=vBaseColorInfos.y;
#endif
#ifdef BASE_WEIGHT
base_color*=baseWeightFromTexture.r;
#endif
#if defined(BASE_COLOR) && defined(ALPHA_FROM_BASE_COLOR_TEXTURE)
alpha*=baseColorFromTexture.a;
#elif defined(GEOMETRY_OPACITY)
alpha*=opacityFromTexture.r;alpha*=vGeometryOpacityInfos.y;
#endif
#ifdef GEOMETRY_THICKNESS
#ifdef GEOMETRY_THICKNESS_FROM_GREEN_CHANNEL
geometry_thickness*=thicknessFromTexture.g;
#else
geometry_thickness*=thicknessFromTexture.r;
#endif
geometry_thickness*=vGeometryThicknessInfos.y;
#endif
#ifdef ALPHATEST
#if DEBUGMODE != 88
if (alpha<ALPHATESTVALUE)
discard;
#endif
#ifndef ALPHABLEND
alpha=1.0;
#endif
#endif
#ifdef BASE_METALNESS
#ifdef BASE_METALNESS_FROM_METALNESS_TEXTURE_BLUE
base_metalness*=metallicFromTexture.b;
#else
base_metalness*=metallicFromTexture.r;
#endif
#endif
#ifdef BASE_DIFFUSE_ROUGHNESS
base_diffuse_roughness*=baseDiffuseRoughnessFromTexture*vBaseDiffuseRoughnessInfos.y;
#endif
#ifdef SPECULAR_COLOR
#ifdef SPECULAR_COLOR_GAMMA
specular_color*=toLinearSpace(specularColorFromTexture.rgb);
#else
specular_color*=specularColorFromTexture.rgb;
#endif
#endif
#ifdef SPECULAR_WEIGHT_FROM_SPECULAR_COLOR_TEXTURE
specular_weight*=specularColorFromTexture.a;
#elif defined(SPECULAR_WEIGHT)
specular_weight*=specularWeightFromTexture;
#endif
#if defined(SPECULAR_ROUGHNESS) || (defined(SPECULAR_ROUGHNESS_FROM_METALNESS_TEXTURE_GREEN) && defined(BASE_METALNESS))
specular_roughness*=roughnessFromTexture;
#endif
#ifdef GEOMETRY_TANGENT
{vec2 tangentFromTexture=normalize(geometryTangentFromTexture.xy*2.0-1.0);float tangent_angle_texture=atan(tangentFromTexture.y,tangentFromTexture.x);float tangent_angle_uniform=atan(geometry_tangent.y,geometry_tangent.x);float tangent_angle=tangent_angle_texture+tangent_angle_uniform;geometry_tangent=vec2(cos(tangent_angle),sin(tangent_angle));}
#endif
#if defined(GEOMETRY_TANGENT) && defined(SPECULAR_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE)
specular_roughness_anisotropy*=geometryTangentFromTexture.b;
#elif defined(SPECULAR_ROUGHNESS_ANISOTROPY)
specular_roughness_anisotropy*=anisotropyFromTexture;
#endif
#ifdef DETAIL
float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,specular_roughness,detailRoughness*2.);float hiLerp=mix(specular_roughness,1.,(detailRoughness-0.5)*2.);specular_roughness=mix(loLerp,hiLerp,step(detailRoughness,0.5));
#endif
#ifdef USE_GLTF_STYLE_ANISOTROPY
float baseAlpha=specular_roughness*specular_roughness;float roughnessT=mix(baseAlpha,1.0,specular_roughness_anisotropy*specular_roughness_anisotropy);float roughnessB=baseAlpha;specular_roughness_anisotropy=1.0-roughnessB/max(roughnessT,0.00001);specular_roughness=sqrt(roughnessT/sqrt(2.0/(1.0+(1.0-specular_roughness_anisotropy)*(1.0-specular_roughness_anisotropy))));
#endif
`;x.IncludesShadersStore[Aj]||(x.IncludesShadersStore[Aj]=Qve)});var Rj,$ve,bj=y(()=>{k();Rj="openpbrCoatLayerData",$ve=`float coat_weight=0.0;vec3 coat_color=vec3(1.0);float coat_roughness=0.0;float coat_roughness_anisotropy=0.0;float coat_ior=1.6;float coat_darkening=1.0;vec2 geometry_coat_tangent=vec2(1.0,0.0);
#ifdef COAT_WEIGHT
vec4 coatWeightFromTexture=texture2D(coatWeightSampler,vCoatWeightUV+uvOffset);
#endif
#ifdef COAT_COLOR
vec4 coatColorFromTexture=texture2D(coatColorSampler,vCoatColorUV+uvOffset);
#endif
#ifdef COAT_ROUGHNESS
vec4 coatRoughnessFromTexture=texture2D(coatRoughnessSampler,vCoatRoughnessUV+uvOffset);
#endif
#ifdef COAT_ROUGHNESS_ANISOTROPY
float coatRoughnessAnisotropyFromTexture=texture2D(coatRoughnessAnisotropySampler,vCoatRoughnessAnisotropyUV+uvOffset).r;
#endif
#ifdef COAT_DARKENING
vec4 coatDarkeningFromTexture=texture2D(coatDarkeningSampler,vCoatDarkeningUV+uvOffset);
#endif
#ifdef GEOMETRY_COAT_TANGENT
vec3 geometryCoatTangentFromTexture=texture2D(geometryCoatTangentSampler,vGeometryCoatTangentUV+uvOffset).rgb;
#endif
coat_color=vCoatColor.rgb;coat_weight=vCoatWeight;coat_roughness=vCoatRoughness;coat_roughness_anisotropy=vCoatRoughnessAnisotropy;coat_ior=vCoatIor;coat_darkening=vCoatDarkening;geometry_coat_tangent=vGeometryCoatTangent.rg;
#ifdef COAT_WEIGHT
coat_weight*=coatWeightFromTexture.r;
#endif
#ifdef COAT_COLOR
#ifdef COAT_COLOR_GAMMA
coat_color*=toLinearSpace(coatColorFromTexture.rgb);
#else
coat_color*=coatColorFromTexture.rgb;
#endif
coat_color*=vCoatColorInfos.y;
#endif
#ifdef COAT_ROUGHNESS
#ifdef COAT_ROUGHNESS_FROM_GREEN_CHANNEL
coat_roughness*=coatRoughnessFromTexture.g;
#else
coat_roughness*=coatRoughnessFromTexture.r;
#endif
#endif
#if defined(GEOMETRY_COAT_TANGENT) && defined(COAT_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE)
coat_roughness_anisotropy*=geometryCoatTangentFromTexture.b;
#elif defined(COAT_ROUGHNESS_ANISOTROPY)
coat_roughness_anisotropy*=coatRoughnessAnisotropyFromTexture;
#endif
#ifdef COAT_DARKENING
coat_darkening*=coatDarkeningFromTexture.r;
#endif
#ifdef GEOMETRY_COAT_TANGENT
{vec2 tangentFromTexture=normalize(geometryCoatTangentFromTexture.xy*2.0-1.0);float tangent_angle_texture=atan(tangentFromTexture.y,tangentFromTexture.x);float tangent_angle_uniform=atan(geometry_coat_tangent.y,geometry_coat_tangent.x);float tangent_angle=tangent_angle_texture+tangent_angle_uniform;geometry_coat_tangent=vec2(cos(tangent_angle),sin(tangent_angle));}
#endif
#ifdef USE_GLTF_STYLE_ANISOTROPY
float coatAlpha=coat_roughness*coat_roughness;float coatRoughnessT=mix(coatAlpha,1.0,coat_roughness_anisotropy*coat_roughness_anisotropy);float coatRoughnessB=coatAlpha;coat_roughness_anisotropy=1.0-coatRoughnessB/max(coatRoughnessT,0.00001);coat_roughness=sqrt(coatRoughnessT/sqrt(2.0/(1.0+(1.0-coat_roughness_anisotropy)*(1.0-coat_roughness_anisotropy))));
#endif
`;x.IncludesShadersStore[Rj]||(x.IncludesShadersStore[Rj]=$ve)});var Mj,Jve,yj=y(()=>{k();Mj="openpbrThinFilmLayerData",Jve=`#ifdef THIN_FILM
float thin_film_weight=vThinFilmWeight;float thin_film_thickness=vThinFilmThickness.r*1000.0;
float thin_film_ior=vThinFilmIor;
#ifdef THIN_FILM_WEIGHT
float thinFilmWeightFromTexture=texture2D(thinFilmWeightSampler,vThinFilmWeightUV+uvOffset).r*vThinFilmWeightInfos.y;
#endif
#ifdef THIN_FILM_THICKNESS
float thinFilmThicknessFromTexture=texture2D(thinFilmThicknessSampler,vThinFilmThicknessUV+uvOffset).g*vThinFilmThicknessInfos.y;
#endif
#ifdef THIN_FILM_WEIGHT
thin_film_weight*=thinFilmWeightFromTexture;
#endif
#ifdef THIN_FILM_THICKNESS
thin_film_thickness*=thinFilmThicknessFromTexture;
#endif
float thin_film_ior_scale=clamp(2.0f*abs(thin_film_ior-1.0f),0.0f,1.0f);
#endif
`;x.IncludesShadersStore[Mj]||(x.IncludesShadersStore[Mj]=Jve)});var Ij,eEe,Cj=y(()=>{k();Ij="openpbrFuzzLayerData",eEe=`float fuzz_weight=0.0;vec3 fuzz_color=vec3(1.0);float fuzz_roughness=0.0;
#ifdef FUZZ
#ifdef FUZZ_WEIGHT
vec4 fuzzWeightFromTexture=texture2D(fuzzWeightSampler,vFuzzWeightUV+uvOffset);
#endif
#ifdef FUZZ_COLOR
vec4 fuzzColorFromTexture=texture2D(fuzzColorSampler,vFuzzColorUV+uvOffset);
#endif
#ifdef FUZZ_ROUGHNESS
vec4 fuzzRoughnessFromTexture=texture2D(fuzzRoughnessSampler,vFuzzRoughnessUV+uvOffset);
#endif
fuzz_color=vFuzzColor.rgb;fuzz_weight=vFuzzWeight;fuzz_roughness=vFuzzRoughness;
#ifdef FUZZ_WEIGHT
fuzz_weight*=fuzzWeightFromTexture.r;
#endif
#ifdef FUZZ_COLOR
#ifdef FUZZ_COLOR_GAMMA
fuzz_color*=toLinearSpace(fuzzColorFromTexture.rgb);
#else
fuzz_color*=fuzzColorFromTexture.rgb;
#endif
fuzz_color*=vFuzzColorInfos.y;
#endif
#if defined(FUZZ_ROUGHNESS) && defined(FUZZ_ROUGHNESS_FROM_TEXTURE_ALPHA)
fuzz_roughness*=fuzzRoughnessFromTexture.a;
#elif defined(FUZZ_ROUGHNESS)
fuzz_roughness*=fuzzRoughnessFromTexture.r;
#endif
#endif
`;x.IncludesShadersStore[Ij]||(x.IncludesShadersStore[Ij]=eEe)});var Pj,tEe,Lj=y(()=>{k();Pj="openpbrAmbientOcclusionData",tEe=`vec3 ambient_occlusion=vec3(1.0);float specular_ambient_occlusion=1.0;float coat_specular_ambient_occlusion=1.0;
#ifdef AMBIENT_OCCLUSION
vec3 ambientOcclusionFromTexture=texture2D(ambientOcclusionSampler,vAmbientOcclusionUV+uvOffset).rgb;ambient_occlusion=vec3(ambientOcclusionFromTexture.r*vAmbientOcclusionInfos.y+(1.0-vAmbientOcclusionInfos.y));
#endif
`;x.IncludesShadersStore[Pj]||(x.IncludesShadersStore[Pj]=tEe)});var Dj,iEe,Oj=y(()=>{k();Dj="openpbrBackgroundTransmission",iEe=`vec4 slab_translucent_background=vec4(0.,0.,0.,1.);
#ifdef REFRACTED_BACKGROUND
{float refractionLOD=min(transmission_roughness,0.7)*vBackgroundRefractionInfos.x;float lodTexelSize=pow(2.0,refractionLOD-vBackgroundRefractionInfos.x);
#ifdef DISPERSION
{
#ifdef REFRACTION_HIGH_QUALITY_BLUR
{vec3 dispResult=vec3(0.0);vec3 dispWeight=vec3(0.0);vec2 noiseOffset=noise.xy*(refractionLOD>0.0 ? lodTexelSize : 0.0);for (int k=0; k<6; k++) {float t=(float(k)+noise.y)/6.0;float t_rg=clamp(t*2.0,0.0,1.0);float t_gb=clamp((t-0.5)*2.0,0.0,1.0);vec3 refVec=mix(mix(refractedViewVectors[0],refractedViewVectors[1],t_rg),refractedViewVectors[2],t_gb);vec3 uvw=vec3(backgroundRefractionMatrix*(view*vec4(vPositionW+refVec*geometry_thickness,1.0)));vec2 coords=uvw.xy/uvw.z;coords.y=1.0-coords.y;vec4 s=texture2DLodEXT(backgroundRefractionSampler,coords+noiseOffset,refractionLOD);float rw=max(0.0,1.0-2.0*t);float gw=max(0.0,1.0-abs(2.0*t-1.0));float bw=max(0.0,2.0*t-1.0);vec3 w=vec3(rw,gw,bw);dispResult+=s.rgb*w;dispWeight+=w;}
slab_translucent_background=vec4(dispResult/max(dispWeight,vec3(1e-6)),1.0);}
#else
for (int i=0; i<3; i++) {vec3 refractedViewVector=refractedViewVectors[i];vec3 uvw=vec3(backgroundRefractionMatrix*(view*vec4(vPositionW+refractedViewVector*geometry_thickness,1.0)));vec2 coords=uvw.xy/uvw.z;coords.y=1.0-coords.y;if (refractionLOD>0.0) {vec2 noiseOffset=noise.xy*lodTexelSize;slab_translucent_background[i]=texture2DLodEXT(backgroundRefractionSampler,coords+noiseOffset,refractionLOD)[i];} else {slab_translucent_background[i]=texture2DLodEXT(backgroundRefractionSampler,coords,0.0)[i];}}
#endif
}
#else
{vec3 refractionUVW=vec3(backgroundRefractionMatrix*(view*vec4(vPositionW+refractedViewVector*geometry_thickness,1.0)));vec2 refractionCoords=refractionUVW.xy/refractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;if (refractionLOD>0.0) {
#ifdef REFRACTION_HIGH_QUALITY_BLUR
float cosA=cos(noise.x*PI);float sinA=sin(noise.x*PI);vec2 u=vec2( cosA,sinA)*(0.5*lodTexelSize);vec2 v=vec2(-sinA,cosA)*(0.5*lodTexelSize);slab_translucent_background=0.25*(
texture2DLodEXT(backgroundRefractionSampler,refractionCoords+u+v,refractionLOD) +
texture2DLodEXT(backgroundRefractionSampler,refractionCoords-u+v,refractionLOD) +
texture2DLodEXT(backgroundRefractionSampler,refractionCoords+u-v,refractionLOD) +
texture2DLodEXT(backgroundRefractionSampler,refractionCoords-u-v,refractionLOD)
);
#else
vec2 noiseOffset=noise.xy*lodTexelSize;slab_translucent_background=texture2DLodEXT(backgroundRefractionSampler,refractionCoords+noiseOffset,refractionLOD);
#endif
} else {slab_translucent_background=texture2DLodEXT(backgroundRefractionSampler,refractionCoords,0.0);}}
#endif
}
#endif
`;x.IncludesShadersStore[Dj]||(x.IncludesShadersStore[Dj]=iEe)});var Nj,rEe,wj=y(()=>{k();Nj="openpbrEnvironmentLighting",rEe=`#if defined(REFLECTION) || defined(REFRACTED_BACKGROUND)
vec3 coatAbsorption=vec3(1.0);float coatIblFresnel=0.0;if (coat_weight>0.0) {coatIblFresnel=computeDielectricIblFresnel(coatReflectance,coatGeoInfo.environmentBrdf);float hemisphere_avg_fresnel=coatReflectance.F0+0.5*(1.0-coatReflectance.F0);float averageReflectance=(coatIblFresnel+hemisphere_avg_fresnel)*0.5;float roughnessFactor=1.0-coat_roughness*0.5;averageReflectance*=roughnessFactor;float darkened_transmission=(1.0-averageReflectance)*(1.0-averageReflectance);darkened_transmission=mix(1.0,darkened_transmission,coat_darkening);float sin2=1.0-coatGeoInfo.NdotV*coatGeoInfo.NdotV;sin2=sin2/(coat_ior*coat_ior);float cos_t=sqrt(1.0-sin2);float coatPathLength=1.0/cos_t;vec3 colored_transmission=pow(coat_color,vec3(coatPathLength));coatAbsorption=mix(vec3(1.0),colored_transmission*darkened_transmission,coat_weight);}
#endif
#ifdef REFLECTION
#if defined(FUZZ) && defined(FUZZENVIRONMENTBRDF)
vec3 environmentFuzzBrdf=getFuzzBRDFLookup(fuzzGeoInfo.NdotV,sqrt(fuzz_roughness));
#endif
vec3 baseDiffuseEnvironmentLight=sampleIrradiance(
normalW
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,vEnvironmentIrradiance
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,reflectionMatrix
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
,vReflectionDominantDirection
#endif
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
#endif
#endif
,vReflectionInfos
,viewDirectionW
,base_diffuse_roughness
,base_color
);
#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords=vec3(0.,0.,0.);
#else
vec2 reflectionCoords=vec2(0.,0.);
#endif
float specularAlphaG=specular_roughness*specular_roughness;
#ifdef ANISOTROPIC_BASE
vec3 baseSpecularEnvironmentLight=sampleRadianceAnisotropic(specularAlphaG,vReflectionMicrosurfaceInfos.rgb,vReflectionInfos
,baseGeoInfo
,normalW
,viewDirectionW
,vPositionW
,noise
,false
,1.0
,reflectionSampler
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
);
#else
reflectionCoords=createReflectionCoords(vPositionW,normalW);vec3 baseSpecularEnvironmentLight=sampleRadiance(specularAlphaG,vReflectionMicrosurfaceInfos.rgb,vReflectionInfos
,baseGeoInfo
,reflectionSampler
,reflectionCoords
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
);
#endif
#ifdef ANISOTROPIC_BASE
baseSpecularEnvironmentLight=mix(baseSpecularEnvironmentLight.rgb,baseDiffuseEnvironmentLight,specularAlphaG*specularAlphaG*max(1.0-baseGeoInfo.anisotropy,0.3));
#else
baseSpecularEnvironmentLight=mix(baseSpecularEnvironmentLight.rgb,baseDiffuseEnvironmentLight,specularAlphaG);
#endif
vec3 coatEnvironmentLight=vec3(0.,0.,0.);if (coat_weight>0.0) {
#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords=vec3(0.,0.,0.);
#else
vec2 reflectionCoords=vec2(0.,0.);
#endif
reflectionCoords=createReflectionCoords(vPositionW,coatNormalW);float coatAlphaG=coat_roughness*coat_roughness;
#ifdef ANISOTROPIC_COAT
coatEnvironmentLight=sampleRadianceAnisotropic(coatAlphaG,vReflectionMicrosurfaceInfos.rgb,vReflectionInfos
,coatGeoInfo
,coatNormalW
,viewDirectionW
,vPositionW
,noise
,false
,1.0
,reflectionSampler
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
);
#else
coatEnvironmentLight=sampleRadiance(coatAlphaG,vReflectionMicrosurfaceInfos.rgb,vReflectionInfos
,coatGeoInfo
,reflectionSampler
,reflectionCoords
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
);
#endif
}
#if defined(FUZZ) &&defined(FUZZENVIRONMENTBRDF)
float modifiedFuzzRoughness=clamp(fuzz_roughness*(1.0-0.5*environmentFuzzBrdf.y),0.0,1.0);vec3 fuzzEnvironmentLight=vec3(0.0);float totalWeight=0.0;float fuzzIblFresnel=sqrt(environmentFuzzBrdf.z);for (int i=0; i<FUZZ_IBL_SAMPLES; ++i) {float angle=(float(i)+noise.x)*(3.141592*2.0/float(FUZZ_IBL_SAMPLES));vec3 fiberCylinderNormal=normalize(cos(angle)*fuzzTangent+sin(angle)*fuzzBitangent);float fiberBend=min(environmentFuzzBrdf.x*environmentFuzzBrdf.x*modifiedFuzzRoughness,1.0);fiberCylinderNormal=normalize(mix(fiberCylinderNormal,fuzzNormalW,fiberBend));float sampleWeight=max(dot(viewDirectionW,fiberCylinderNormal),0.0);vec3 fuzzReflectionCoords=createReflectionCoords(vPositionW,fiberCylinderNormal);vec3 radianceSample=sampleRadiance(modifiedFuzzRoughness,vReflectionMicrosurfaceInfos.rgb,vReflectionInfos
,fuzzGeoInfo
,reflectionSampler
,fuzzReflectionCoords
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
);fuzzEnvironmentLight+=sampleWeight*mix(radianceSample,baseDiffuseEnvironmentLight,fiberBend);totalWeight+=sampleWeight;}
fuzzEnvironmentLight/=totalWeight;
#endif
float dielectricIblFresnel=computeDielectricIblFresnel(baseDielectricReflectance,baseGeoInfo.environmentBrdf);vec3 dielectricIblColoredFresnel=dielectricIblFresnel*specular_color;
#ifdef THIN_FILM
float thin_film_cos_theta=max(baseGeoInfo.NdotV,specularAlphaG);float thin_film_desaturation_scale=(thin_film_ior-1.0)*sqrt(thin_film_thickness*0.001*thin_film_cos_theta);float tf_brdf_x=baseGeoInfo.environmentBrdf.x;float tf_E_ss =baseGeoInfo.environmentBrdf.y;vec3 thinFilmDielectricF0=evalIridescence(thin_film_outside_ior,thin_film_ior,1.0,thin_film_thickness,vec3(baseDielectricReflectance.F0));thinFilmDielectricF0=mix(thinFilmDielectricF0,vec3(dot(thinFilmDielectricF0,vec3(0.3333))),thin_film_desaturation_scale);vec3 thinFilmDielectricDir=evalIridescence(thin_film_outside_ior,thin_film_ior,thin_film_cos_theta,thin_film_thickness,vec3(baseDielectricReflectance.F0));thinFilmDielectricDir=mix(thinFilmDielectricDir,vec3(dot(thinFilmDielectricDir,vec3(0.3333))),thin_film_desaturation_scale);float tf_f0d_avg =dot(thinFilmDielectricF0, vec3(0.3333));float tf_dird_avg=dot(thinFilmDielectricDir,vec3(0.3333));vec3 thinFilmDielectricFresnel=thinFilmDielectricDir*(tf_f0d_avg/max(tf_dird_avg,1e-5));vec3 tf_E_dielectric=(vec3(1.0)-thinFilmDielectricFresnel)*vec3(tf_brdf_x)+thinFilmDielectricFresnel*vec3(tf_E_ss);vec3 tf_F_avg_dielectric=thinFilmDielectricFresnel+(vec3(1.0)-thinFilmDielectricFresnel)/21.0;vec3 tf_ECF_dielectric=vec3(1.0)+tf_F_avg_dielectric*(vec3(1.0)/vec3(tf_E_ss)-vec3(1.0));thinFilmDielectricFresnel=clamp(tf_E_dielectric*tf_ECF_dielectric,vec3(0.0),vec3(1.0));dielectricIblColoredFresnel=mix(dielectricIblColoredFresnel,thinFilmDielectricFresnel*specular_color,thin_film_weight*thin_film_ior_scale);dielectricIblFresnel=max(dielectricIblColoredFresnel.r,max(dielectricIblColoredFresnel.g,dielectricIblColoredFresnel.b));
#endif
vec3 conductorIblFresnel=computeConductorIblFresnel(baseConductorReflectance,baseGeoInfo.environmentBrdf);
#ifdef THIN_FILM
vec3 thinFilmConductorF0=evalIridescence(thin_film_outside_ior,thin_film_ior,1.0,thin_film_thickness,baseConductorReflectance.coloredF0);thinFilmConductorF0=mix(thinFilmConductorF0,vec3(dot(thinFilmConductorF0,vec3(0.3333))),thin_film_desaturation_scale);vec3 thinFilmConductorDir=evalIridescence(thin_film_outside_ior,thin_film_ior,thin_film_cos_theta,thin_film_thickness,baseConductorReflectance.coloredF0);thinFilmConductorDir=mix(thinFilmConductorDir,vec3(dot(thinFilmConductorDir,vec3(0.3333))),thin_film_desaturation_scale);float tf_f0c_avg =dot(thinFilmConductorF0, vec3(0.3333));float tf_dirc_avg=dot(thinFilmConductorDir,vec3(0.3333));vec3 thinFilmConductorRaw=thinFilmConductorDir*(tf_f0c_avg/max(tf_dirc_avg,1e-5));
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR) && defined(ENVIRONMENTBRDF)
vec3 tf_b=getF82B(baseConductorReflectance.coloredF0,baseConductorReflectance.coloredF90);float tf_brdf_z=baseGeoInfo.environmentBrdf.z/BRDF_Z_SCALE;vec3 tf_E_conductor=(vec3(1.0)-thinFilmConductorRaw)*vec3(tf_brdf_x)+thinFilmConductorRaw*vec3(tf_E_ss)-tf_b*vec3(tf_brdf_z);vec3 tf_F_avg_conductor=thinFilmConductorRaw+(vec3(1.0)-thinFilmConductorRaw)/21.0-tf_b/126.0;
#else
vec3 tf_E_conductor=(vec3(1.0)-thinFilmConductorRaw)*vec3(tf_brdf_x)+thinFilmConductorRaw*vec3(tf_E_ss);vec3 tf_F_avg_conductor=thinFilmConductorRaw+(vec3(1.0)-thinFilmConductorRaw)/21.0;
#endif
vec3 tf_ECF_conductor=vec3(1.0)+tf_F_avg_conductor*(vec3(1.0)/vec3(tf_E_ss)-vec3(1.0));vec3 thinFilmConductorFresnel=specular_weight*clamp(tf_E_conductor*tf_ECF_conductor,vec3(0.0),vec3(1.0));conductorIblFresnel=mix(conductorIblFresnel,thinFilmConductorFresnel,thin_film_weight*thin_film_ior_scale);
#endif
vec3 slab_diffuse_ibl=vec3(0.,0.,0.);vec3 slab_glossy_ibl=vec3(0.,0.,0.);vec3 slab_metal_ibl=vec3(0.,0.,0.);vec3 slab_coat_ibl=vec3(0.,0.,0.);slab_diffuse_ibl=baseDiffuseEnvironmentLight*vLightingIntensity.z;
#ifdef AMBIENT_OCCLUSION
specular_ambient_occlusion=compute_specular_occlusion(baseGeoInfo.NdotV,base_metalness,ambient_occlusion.x,specular_roughness);
#endif
slab_glossy_ibl=baseSpecularEnvironmentLight*vLightingIntensity.z;slab_metal_ibl=baseSpecularEnvironmentLight*conductorIblFresnel*vLightingIntensity.z;if (coat_weight>0.0) {slab_coat_ibl=coatEnvironmentLight*vLightingIntensity.z;
#ifdef AMBIENT_OCCLUSION
coat_specular_ambient_occlusion=compute_specular_occlusion(coatGeoInfo.NdotV,0.0,ambient_occlusion.x,coat_roughness);
#endif
}
#if defined(FUZZ) &&defined(FUZZENVIRONMENTBRDF)
vec3 slab_fuzz_ibl=fuzzEnvironmentLight*vLightingIntensity.z;
#endif
vec3 slab_translucent_base_ibl=vec3(0.0);vec3 slab_subsurface_ibl=vec3(0.,0.,0.);
#ifdef REFRACTED_ENVIRONMENT
#ifdef ANISOTROPIC_BASE
vec3 forwardScatteredEnvironmentLight=sampleRadianceAnisotropic(transmission_roughness_alpha,vReflectionMicrosurfaceInfos.rgb,vReflectionInfos
,baseGeoInfo
#ifdef GEOMETRY_THIN_WALLED
,viewDirectionW
#else
,normalW
#endif
,viewDirectionW
,vPositionW
,noise
,true
#ifdef GEOMETRY_THIN_WALLED
,1.05
#else
,specular_ior
#endif
,reflectionSampler
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
);
#else
vec3 forwardScatteredEnvironmentLight=vec3(0.,0.,0.);
#ifdef DISPERSION
for (int i=0; i<3; i++) {vec3 iblRefractionCoords=refractedViewVectors[i];
#else
vec3 iblRefractionCoords=refractedViewVector;
#endif
#ifdef REFRACTED_ENVIRONMENT_OPPOSITEZ
iblRefractionCoords.z*=-1.0;
#endif
#ifdef REFRACTED_ENVIRONMENT_LOCAL_CUBE
iblRefractionCoords=parallaxCorrectNormal(vPositionW,refractedViewVector,refractionSize,refractionPosition);
#endif
iblRefractionCoords=vec3(reflectionMatrix*vec4(iblRefractionCoords,0));
#ifdef DISPERSION
forwardScatteredEnvironmentLight[i]=sampleRadiance(transmission_roughness_alpha,vReflectionMicrosurfaceInfos.rgb,vReflectionInfos
,baseGeoInfo
,reflectionSampler
,iblRefractionCoords
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
)[i];
#else
forwardScatteredEnvironmentLight=sampleRadiance(transmission_roughness_alpha,vReflectionMicrosurfaceInfos.rgb,vReflectionInfos
,baseGeoInfo
,reflectionSampler
,iblRefractionCoords
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
);
#endif
#ifdef DISPERSION
}
#endif
#endif
#ifdef REFRACTED_BACKGROUND
#ifdef GEOMETRY_THIN_WALLED
forwardScatteredEnvironmentLight=mix(slab_translucent_background.rgb,forwardScatteredEnvironmentLight.rgb,0.2*transmission_roughness_alpha);
#else
forwardScatteredEnvironmentLight=max(slab_translucent_background.rgb,mix(slab_translucent_background.rgb,forwardScatteredEnvironmentLight,transmission_roughness_alpha));
#endif
#endif
#ifdef SCATTERING
#ifdef GEOMETRY_THIN_WALLED
vec3 scatterVector=normalW;
#else
#if defined(USEIRRADIANCEMAP) && defined(USE_IRRADIANCE_DOMINANT_DIRECTION)
vec3 scatterVector=mix(vReflectionDominantDirection,normalW,max3(iso_scatter_density));
#else
vec3 scatterVector=normalW;
#endif
scatterVector=mix(viewDirectionW,scatterVector,back_to_iso_scattering_blend);
#endif
#if defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING) && !defined(GEOMETRY_THIN_WALLED)
vec3 scatteredEnvironmentLight=scattered_light_from_irradiance_texture;
#else
vec3 scatteredEnvironmentLight=sampleIrradiance(
scatterVector
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,vEnvironmentIrradiance
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,reflectionMatrix
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
,vReflectionDominantDirection
#endif
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
#endif
#endif
,vReflectionInfos
,viewDirectionW
#if defined(GEOMETRY_THIN_WALLED)
,base_diffuse_roughness
,subsurface_color.rgb
#else
,1.0
,volumeParams.multi_scatter_color
#endif
);
#endif
#ifdef GEOMETRY_THIN_WALLED
vec3 forward_scattered_light=forwardScatteredEnvironmentLight*transmission_tint*volumeParams.multi_scatter_color;vec3 back_scattered_light=scatteredEnvironmentLight*volumeParams.multi_scatter_color;slab_translucent_base_ibl=mix(back_scattered_light,forward_scattered_light,0.5+0.5*volumeParams.anisotropy);
#else
vec3 forward_scattered_light=forwardScatteredEnvironmentLight*volume_absorption;vec3 back_scattered_light=mix(forward_scattered_light,scatteredEnvironmentLight*backscatter_color,iso_scatter_density);vec3 iso_scattered_light=mix(forward_scattered_light,scatteredEnvironmentLight*volumeParams.multi_scatter_color,iso_scatter_density);slab_translucent_base_ibl=mix(back_scattered_light,iso_scattered_light,back_to_iso_scattering_blend);slab_translucent_base_ibl=mix(slab_translucent_base_ibl,forward_scattered_light,iso_to_forward_scattering_blend)*transmission_tint;
#endif
#else
slab_translucent_base_ibl+=forwardScatteredEnvironmentLight*transmission_tint*volume_absorption;
#endif
#endif
#define CUSTOM_FRAGMENT_BEFORE_IBLLAYERCOMPOSITION
slab_diffuse_ibl*=ambient_occlusion;slab_metal_ibl*=specular_ambient_occlusion;slab_glossy_ibl*=specular_ambient_occlusion;slab_coat_ibl*=coat_specular_ambient_occlusion;vec3 material_dielectric_base_ibl=mix(slab_diffuse_ibl*base_color.rgb,slab_translucent_base_ibl,surface_translucency_weight);vec3 material_dielectric_gloss_ibl=material_dielectric_base_ibl*(1.0-dielectricIblFresnel)+slab_glossy_ibl*dielectricIblColoredFresnel;vec3 material_base_substrate_ibl=mix(material_dielectric_gloss_ibl,slab_metal_ibl,base_metalness);vec3 material_coated_base_ibl=layer(material_base_substrate_ibl,slab_coat_ibl,coatIblFresnel,coatAbsorption,vec3(1.0));
#if defined(FUZZ) && defined(FUZZENVIRONMENTBRDF)
slab_fuzz_ibl*=min(vec3(specular_ambient_occlusion),ambient_occlusion);material_surface_ibl=layer(material_coated_base_ibl,slab_fuzz_ibl,fuzzIblFresnel*fuzz_weight,vec3(1.0),fuzz_color);
#else
material_surface_ibl=material_coated_base_ibl;
#endif
#elif defined(REFRACTED_BACKGROUND)
vec3 black=vec3(0.0);vec3 slab_translucent_base_ibl=vec3(0.0);
#ifdef GEOMETRY_THIN_WALLED
#ifdef SCATTERING
vec3 forward_scattered_light=slab_translucent_background.rgb*transmission_tint*volumeParams.multi_scatter_color;slab_translucent_base_ibl=mix(black,forward_scattered_light,0.5+0.5*volumeParams.anisotropy);
#else
slab_translucent_base_ibl=slab_translucent_background.rgb*transmission_tint;
#endif
#else
#ifdef SCATTERING
vec3 forward_scattered_light=slab_translucent_background.rgb*volume_absorption;vec3 iso_scattered_light=(1.0-iso_scatter_density)*forward_scattered_light;slab_translucent_base_ibl=mix(black,iso_scattered_light,back_to_iso_scattering_blend);slab_translucent_base_ibl=mix(slab_translucent_base_ibl,forward_scattered_light,iso_to_forward_scattering_blend)*transmission_tint;
#else
slab_translucent_base_ibl=slab_translucent_background.rgb*volume_absorption*transmission_tint;
#endif
#endif
vec3 material_dielectric_base_ibl=mix(black,slab_translucent_base_ibl.rgb,surface_translucency_weight);vec3 material_dielectric_gloss_ibl=material_dielectric_base_ibl*(baseGeoInfo.NdotV);vec3 material_base_substrate_ibl=mix(material_dielectric_gloss_ibl,black,base_metalness);vec3 material_coated_base_ibl=layer(material_base_substrate_ibl,black,coatIblFresnel,coatAbsorption,vec3(1.0));material_surface_ibl=material_coated_base_ibl;
#endif
`;x.IncludesShadersStore[Nj]||(x.IncludesShadersStore[Nj]=rEe)});var Fj,nEe,Bj=y(()=>{k();Fj="openpbrDirectLightingInit",nEe=`#ifdef LIGHT{X}
preLightingInfo preInfo{X};preLightingInfo preInfoCoat{X};vec4 lightColor{X}=light{X}.vLightDiffuse;float shadow{X}=1.;
#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})
#else
#define CUSTOM_LIGHT{X}_COLOR
#ifdef SPOTLIGHT{X}
preInfo{X}=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,vPositionW);preInfoCoat{X}=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,coatNormalW,vPositionW);
#elif defined(POINTLIGHT{X})
preInfo{X}=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,vPositionW);preInfoCoat{X}=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,coatNormalW,vPositionW);
#elif defined(HEMILIGHT{X})
preInfo{X}=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);preInfoCoat{X}=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,coatNormalW);
#elif defined(DIRLIGHT{X})
preInfo{X}=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);preInfoCoat{X}=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,coatNormalW);
#elif defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
preInfo{X}=computeAreaPreLightingInfo(areaLightsLTC1Sampler,areaLightsLTC2Sampler,viewDirectionW,normalW,vPositionW,light{X}.vLightData,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,specular_roughness);preInfoCoat{X}=computeAreaPreLightingInfo(areaLightsLTC1Sampler,areaLightsLTC2Sampler,viewDirectionW,coatNormalW,vPositionW,light{X}.vLightData,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,coat_roughness);
#endif
preInfo{X}.NdotV=baseGeoInfo.NdotV;preInfoCoat{X}.NdotV=coatGeoInfo.NdotV;
#ifdef SPOTLIGHT{X}
#ifdef LIGHT_FALLOFF_GLTF{X}
preInfo{X}.attenuation=computeDistanceLightFalloff_GLTF(preInfo{X}.lightDistanceSquared,light{X}.vLightFalloff.y);
#ifdef IESLIGHTTEXTURE{X}
preInfo{X}.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo{X}.L,iesLightTexture{X});
#else
preInfo{X}.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo{X}.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
#endif
#elif defined(LIGHT_FALLOFF_PHYSICAL{X})
preInfo{X}.attenuation=computeDistanceLightFalloff_Physical(preInfo{X}.lightDistanceSquared);
#ifdef IESLIGHTTEXTURE{X}
preInfo{X}.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo{X}.L,iesLightTexture{X});
#else
preInfo{X}.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo{X}.L,light{X}.vLightDirection.w);
#endif
#elif defined(LIGHT_FALLOFF_STANDARD{X})
preInfo{X}.attenuation=computeDistanceLightFalloff_Standard(preInfo{X}.lightOffset,light{X}.vLightFalloff.x);
#ifdef IESLIGHTTEXTURE{X}
preInfo{X}.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo{X}.L,iesLightTexture{X});
#else
preInfo{X}.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo{X}.L,light{X}.vLightDirection.w,light{X}.vLightData.w);
#endif
#else
preInfo{X}.attenuation=computeDistanceLightFalloff(preInfo{X}.lightOffset,preInfo{X}.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);
#ifdef IESLIGHTTEXTURE{X}
preInfo{X}.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo{X}.L,iesLightTexture{X});
#else
preInfo{X}.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo{X}.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
#endif
#endif
#elif defined(POINTLIGHT{X})
#ifdef LIGHT_FALLOFF_GLTF{X}
preInfo{X}.attenuation=computeDistanceLightFalloff_GLTF(preInfo{X}.lightDistanceSquared,light{X}.vLightFalloff.y);
#elif defined(LIGHT_FALLOFF_PHYSICAL{X})
preInfo{X}.attenuation=computeDistanceLightFalloff_Physical(preInfo{X}.lightDistanceSquared);
#elif defined(LIGHT_FALLOFF_STANDARD{X})
preInfo{X}.attenuation=computeDistanceLightFalloff_Standard(preInfo{X}.lightOffset,light{X}.vLightFalloff.x);
#else
preInfo{X}.attenuation=computeDistanceLightFalloff(preInfo{X}.lightOffset,preInfo{X}.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);
#endif
#else
preInfo{X}.attenuation=1.0;
#endif
preInfoCoat{X}.attenuation=preInfo{X}.attenuation;
#if defined(HEMILIGHT{X})
preInfo{X}.roughness=specular_roughness;preInfoCoat{X}.roughness=coat_roughness;
#elif defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
preInfo{X}.roughness=specular_roughness;preInfoCoat{X}.roughness=coat_roughness;
#else
preInfo{X}.roughness=adjustRoughnessFromLightProperties(specular_roughness,light{X}.vLightSpecular.a,preInfo{X}.lightDistance);preInfoCoat{X}.roughness=adjustRoughnessFromLightProperties(coat_roughness,light{X}.vLightSpecular.a,preInfoCoat{X}.lightDistance);
#endif
preInfo{X}.diffuseRoughness=base_diffuse_roughness;preInfo{X}.surfaceAlbedo=base_color.rgb;
#endif
#endif
`;x.IncludesShadersStore[Fj]||(x.IncludesShadersStore[Fj]=nEe)});var Uj,sEe,Vj=y(()=>{k();Uj="openpbrDirectLighting",sEe=`#ifdef LIGHT{X}
{vec3 slab_diffuse=vec3(0.,0.,0.);vec3 slab_translucent=vec3(0.,0.,0.);vec3 slab_glossy=vec3(0.,0.,0.);float specularFresnel=0.0;vec3 specularColoredFresnel=vec3(0.,0.,0.);vec3 slab_metal=vec3(0.,0.,0.);vec3 slab_coat=vec3(0.,0.,0.);float coatFresnel=0.0;vec3 slab_fuzz=vec3(0.,0.,0.);float fuzzFresnel=0.0;
#ifdef HEMILIGHT{X}
slab_diffuse=computeHemisphericDiffuseLighting(preInfo{X},lightColor{X}.rgb,light{X}.vLightGround);
#elif defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
slab_diffuse=computeAreaDiffuseLighting(preInfo{X},lightColor{X}.rgb);
#else
slab_diffuse=computeDiffuseLighting(preInfo{X},lightColor{X}.rgb);
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
slab_diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},textureProjectionMatrix{X},vPositionW);
#endif
#ifdef FUZZ
float fuzzNdotH=max(dot(fuzzNormalW,preInfo{X}.H),0.0);vec3 fuzzBrdf=getFuzzBRDFLookup(fuzzNdotH,sqrt(fuzz_roughness));
#endif
#ifdef THIN_FILM
float thin_film_desaturation_scale=(thin_film_ior-1.0)*sqrt(thin_film_thickness*0.001);
#endif
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
slab_glossy=computeAreaSpecularLighting(preInfo{X},light{X}.vLightSpecular.rgb,baseConductorReflectance.F0,baseConductorReflectance.F90);
#else
{
#ifdef ANISOTROPIC_BASE
slab_glossy=computeAnisotropicSpecularLighting(preInfo{X},viewDirectionW,normalW,
baseGeoInfo.anisotropicTangent,baseGeoInfo.anisotropicBitangent,baseGeoInfo.anisotropy,
0.0,lightColor{X}.rgb);
#else
slab_glossy=computeSpecularLighting(preInfo{X},normalW,vec3(1.0),vec3(1.0),specular_roughness,lightColor{X}.rgb);
#endif
specularFresnel=fresnelSchlickGGX(preInfo{X}.VdotH,baseDielectricReflectance.F0,baseDielectricReflectance.F90);specularColoredFresnel=specularFresnel*specular_color;
#ifdef THIN_FILM
vec3 thinFilmDielectricFresnel=evalIridescence(thin_film_outside_ior,thin_film_ior,preInfo{X}.VdotH,thin_film_thickness,vec3(baseDielectricReflectance.F0));thinFilmDielectricFresnel=mix(thinFilmDielectricFresnel,vec3(dot(thinFilmDielectricFresnel,vec3(0.3333))),thin_film_desaturation_scale);specularColoredFresnel=mix(specularColoredFresnel,thinFilmDielectricFresnel*specular_color,thin_film_weight*thin_film_ior_scale);
#endif
}
#endif
#ifdef REFRACTED_LIGHTS
vec3 forwardScatteredLight=vec3(0.0);
#if AREALIGHT{X}
#else
{preLightingInfo preInfoTrans=preInfo{X};
#ifdef SCATTERING
preInfoTrans.roughness=sqrt(sqrt(max(transmission_roughness_alpha,0.05)));
#else
preInfoTrans.roughness=transmission_roughness;
#endif
if (preInfoTrans.NdotLUnclamped<=0.0) {specularFresnel=0.0;specularColoredFresnel=specularFresnel*specular_color;}
#ifdef GEOMETRY_THIN_WALLED
vec3 refractNormalW=viewDirectionW;
#else
vec3 refractNormalW=normalW;
#endif
preInfoTrans.NdotL=0.5*max(dot(-refractNormalW,preInfoTrans.L),0.0)+0.5;
#if defined(DISPERSION) && !defined(GEOMETRY_THIN_WALLED)
float diff=min(dispersion_iors[2]-dispersion_iors[0],max(dispersion_iors[0]-1.0,1.0));dispersion_iors[2]+=diff;dispersion_iors[0]-=diff;for (int i=0; i<3; i++) {float eta=1.0/dispersion_iors[i];
#elif defined(GEOMETRY_THIN_WALLED)
float eta=1.0;
#else
float eta=1.0/specular_ior;
#endif
preInfoTrans.H=preInfoTrans.L+min(eta,0.95)*viewDirectionW;float len2=dot(preInfoTrans.H,preInfoTrans.H);if (len2<1e-6) {preInfoTrans.H=preInfoTrans.L;} else {preInfoTrans.H=preInfoTrans.H*inversesqrt(len2);}
#ifdef ANISOTROPIC_BASE
preInfoTrans.H=-preInfoTrans.H;
#endif
preInfoTrans.VdotH=dot(viewDirectionW,preInfoTrans.H);
#if defined(DISPERSION) && !defined(GEOMETRY_THIN_WALLED)
forwardScatteredLight[i]+=
#else
forwardScatteredLight+=
#endif
#if defined(ANISOTROPIC_BASE)
computeAnisotropicSpecularLighting(preInfoTrans,viewDirectionW,refractNormalW,
baseGeoInfo.anisotropicTangent,baseGeoInfo.anisotropicBitangent,baseGeoInfo.anisotropy,
transmission_roughness_alpha,lightColor{X}.rgb
#else
computeSpecularLighting(preInfoTrans,-refractNormalW,vec3(1.0),vec3(1.0),transmission_roughness_alpha,lightColor{X}.rgb
#endif
#if defined(DISPERSION) && !defined(GEOMETRY_THIN_WALLED)
)[i];}
#else
);
#endif
#if !defined(GEOMETRY_THIN_WALLED)
forwardScatteredLight=mix(forwardScatteredLight,0.25*preInfoTrans.attenuation*lightColor{X}.rgb,clamp(1.0-pow(baseGeoInfo.NdotV,transmission_roughness_alpha),0.0,1.0));
#endif
#ifdef REFRACTED_BACKGROUND
#ifdef GEOMETRY_THIN_WALLED
forwardScatteredLight=mix(vec3(0.0),forwardScatteredLight.rgb,0.2*transmission_roughness_alpha);
#else
forwardScatteredLight=max(vec3(0.0),mix(vec3(0.0),forwardScatteredLight,transmission_roughness_alpha));
#endif
#endif
#ifdef SCATTERING
#if !defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING) || defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING_GBUFFER)
preInfoTrans.roughness=1.0;vec3 diffused_forward_scattered_light=computeSpecularLighting(preInfoTrans,normalW,vec3(1.0),vec3(1.0),1.0,lightColor{X}.rgb)*volume_absorption;
#endif
#ifdef GEOMETRY_THIN_WALLED
vec3 forward_scattered_light=forwardScatteredLight*transmission_tint*volumeParams.multi_scatter_color;vec3 back_scattered_light=slab_diffuse*volumeParams.multi_scatter_color;slab_translucent=mix(back_scattered_light,forward_scattered_light,0.5+0.5*volumeParams.anisotropy);
#else
vec3 back_scattered_normal=normalize(normalW+viewDirectionW);preInfoTrans.NdotL=max(dot(back_scattered_normal,preInfoTrans.L),0.0);preInfoTrans.NdotV=dot(back_scattered_normal,viewDirectionW);preInfoTrans.H=normalize(viewDirectionW+preInfoTrans.L);preInfoTrans.VdotH=clamp(dot(viewDirectionW,preInfoTrans.H),0.0,1.0);preInfoTrans.roughness=0.2;vec3 back_scattered_light=computeSpecularLighting(preInfoTrans,viewDirectionW,vec3(1.0),vec3(0.08),0.0,lightColor{X}.rgb);vec3 forward_scattered_light=(forwardScatteredLight*volume_absorption);vec3 iso_scattered_light=slab_diffuse;vec3 back_scattering=mix(forward_scattered_light,forward_scattered_light+back_scattered_light*backscatter_color,iso_scatter_density);
#if defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING) && !defined(USE_IRRADIANCE_TEXTURE_FOR_SCATTERING_GBUFFER)
vec3 iso_scattering=mix(forward_scattered_light,scattered_light_from_irradiance_texture*volumeParams.multi_scatter_color,iso_scatter_density);
#else
vec3 iso_scattering=mix(forward_scattered_light,(diffused_forward_scattered_light+iso_scattered_light)*volumeParams.multi_scatter_color,iso_scatter_density);
#endif
slab_translucent=mix(back_scattering,iso_scattering,back_to_iso_scattering_blend);slab_translucent=mix(slab_translucent,forward_scattered_light,iso_to_forward_scattering_blend)*transmission_tint;
#endif
#else
slab_translucent=forwardScatteredLight*transmission_tint*volume_absorption;
#endif
}
#endif
#endif
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
slab_metal=computeAreaSpecularLighting(preInfo{X},light{X}.vLightSpecular.rgb,baseConductorReflectance.F0,baseConductorReflectance.F90);
#else
{
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR)
vec3 coloredFresnel=getF82Specular(preInfo{X}.VdotH,baseConductorReflectance.coloredF0,baseConductorReflectance.coloredF90,specular_roughness);
#else
vec3 coloredFresnel=fresnelSchlickGGX(preInfo{X}.VdotH,baseConductorReflectance.coloredF0,baseConductorReflectance.coloredF90);
#endif
#ifdef THIN_FILM
float thinFilmConductorAngle=max(preInfo{X}.VdotH,specular_roughness);vec3 thinFilmConductorFresnel=evalIridescence(thin_film_outside_ior,thin_film_ior,thinFilmConductorAngle,thin_film_thickness,baseConductorReflectance.coloredF0);thinFilmConductorFresnel=mix(thinFilmConductorFresnel,vec3(dot(thinFilmConductorFresnel,vec3(0.3333))),thin_film_desaturation_scale);coloredFresnel=mix(coloredFresnel,specular_weight*thinFilmConductorFresnel,thin_film_weight*thin_film_ior_scale);
#endif
#ifdef ANISOTROPIC_BASE
slab_metal=computeAnisotropicSpecularLighting(preInfo{X},viewDirectionW,normalW,baseGeoInfo.anisotropicTangent,baseGeoInfo.anisotropicBitangent,baseGeoInfo.anisotropy,0.0,lightColor{X}.rgb);
#else
slab_metal=computeSpecularLighting(preInfo{X},normalW,vec3(1.0),coloredFresnel,specular_roughness,lightColor{X}.rgb);
#endif
}
#endif
#if defined(AREALIGHT{X}) && defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
slab_coat=computeAreaSpecularLighting(preInfoCoat{X},light{X}.vLightSpecular.rgb,coatReflectance.F0,coatReflectance.F90);
#else
{
#ifdef ANISOTROPIC_COAT
slab_coat=computeAnisotropicSpecularLighting(preInfoCoat{X},viewDirectionW,coatNormalW,
coatGeoInfo.anisotropicTangent,coatGeoInfo.anisotropicBitangent,coatGeoInfo.anisotropy,
0.0,lightColor{X}.rgb);
#else
slab_coat=computeSpecularLighting(preInfoCoat{X},coatNormalW,vec3(coatReflectance.F0),vec3(1.0),coat_roughness,lightColor{X}.rgb);
#endif
float NdotH=max(dot(coatNormalW,preInfoCoat{X}.H),0.0);coatFresnel=fresnelSchlickGGX(NdotH,coatReflectance.F0,coatReflectance.F90);}
#endif
vec3 coatAbsorption=vec3(1.0);if (coat_weight>0.0) {float cosTheta_view=max(preInfoCoat{X}.NdotV,0.001);float cosTheta_light=max(preInfoCoat{X}.NdotL,0.001);float fresnel_view=coatReflectance.F0+(1.0-coatReflectance.F0)*pow(1.0-cosTheta_view,5.0);float fresnel_light=coatReflectance.F0+(1.0-coatReflectance.F0)*pow(1.0-cosTheta_light,5.0);float averageReflectance=(fresnel_view+fresnel_light)*0.5;float darkened_transmission=(1.0-averageReflectance)/(1.0+averageReflectance);darkened_transmission=mix(1.0,darkened_transmission,coat_darkening);float sin2=1.0-cosTheta_view*cosTheta_view;sin2=sin2/(coat_ior*coat_ior);float cos_t=sqrt(1.0-sin2);float coatPathLength=1.0/cos_t;vec3 colored_transmission=pow(coat_color,vec3(coatPathLength));coatAbsorption=mix(vec3(1.0),colored_transmission*darkened_transmission,coat_weight);}
#ifdef FUZZ
fuzzFresnel=fuzzBrdf.z;vec3 fuzzNormalW=mix(normalW,coatNormalW,coat_weight);float fuzzNdotV=max(dot(fuzzNormalW,viewDirectionW.xyz),0.0);float fuzzNdotL=max(dot(fuzzNormalW,preInfo{X}.L),0.0);slab_fuzz=lightColor{X}.rgb*preInfo{X}.attenuation*evalFuzz(preInfo{X}.L,fuzzNdotL,fuzzNdotV,fuzzTangent,fuzzBitangent,fuzzBrdf);
#else
vec3 fuzz_color=vec3(0.0);
#endif
#ifdef PREPASS_IRRADIANCE
total_direct_diffuse+=slab_diffuse;
#endif
vec3 material_dielectric_base=mix(slab_diffuse*base_color.rgb,slab_translucent,surface_translucency_weight);vec3 material_dielectric_gloss=material_dielectric_base*(1.0-specularFresnel)+slab_glossy*specularColoredFresnel;vec3 material_base_substrate=mix(material_dielectric_gloss,slab_metal,base_metalness);vec3 material_coated_base=layer(material_base_substrate,slab_coat,coatFresnel,coatAbsorption,vec3(1.0));material_surface_direct+=layer(material_coated_base,slab_fuzz,fuzzFresnel*fuzz_weight,vec3(1.0),fuzz_color);}
#endif
`;x.IncludesShadersStore[Uj]||(x.IncludesShadersStore[Uj]=sEe)});var Gj,aEe,pF=y(()=>{k();Gj="pbrBlockImageProcessing",aEe=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)
#if !defined(SKIPFINALCOLORCLAMP)
finalColor.rgb=clamp(finalColor.rgb,0.,30.0);
#endif
#else
finalColor=applyImageProcessing(finalColor);
#endif
finalColor.a*=visibility;
#ifdef PREMULTIPLYALPHA
finalColor.rgb*=finalColor.a;
#endif
`;x.IncludesShadersStore[Gj]||(x.IncludesShadersStore[Gj]=aEe)});var kj,oEe,zj=y(()=>{k();kj="openpbrBlockPrePass",oEe=`#if SCENE_MRT_COUNT>0
float writeGeometryInfo=finalColor.a>ALPHATESTVALUE ? 1.0 : 0.0;
#ifdef PREPASS_POSITION
gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_LOCAL_POSITION
gl_FragData[PREPASS_LOCAL_POSITION_INDEX]=vec4(vPosition,writeGeometryInfo);
#endif
#if defined(PREPASS_VELOCITY)
vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#elif defined(PREPASS_VELOCITY_LINEAR)
vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w)-(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO
gl_FragData[PREPASS_ALBEDO_INDEX]=vec4(base_color,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
vec3 sqAlbedo=sqrt(base_color);
#endif
#ifdef PREPASS_IRRADIANCE
vec3 irradiance=total_direct_diffuse;
#ifndef UNLIT
#ifdef REFLECTION
irradiance+=slab_diffuse_ibl;
#endif
#endif
#ifdef SCATTERING
float scatter_mask=min(subsurface_weight+transmission_weight,1.0);
#else
float scatter_mask=0.0;
#endif
gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(irradiance,writeGeometryInfo*scatter_mask);
#endif
#if defined(PREPASS_COLOR)
gl_FragData[PREPASS_COLOR_INDEX]=vec4(finalColor.rgb,finalColor.a);
#endif
#ifdef PREPASS_DEPTH
gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_SCREENSPACE_DEPTH
gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
gl_FragData[PREPASS_NORMALIZED_VIEW_DEPTH_INDEX]=vec4(vNormViewDepth,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMAL
#ifdef PREPASS_NORMAL_WORLDSPACE
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo);
#else
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo);
#endif
#endif
#ifdef PREPASS_WORLD_NORMAL
gl_FragData[PREPASS_WORLD_NORMAL_INDEX]=vec4(normalW*0.5+0.5,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo);
#endif
#ifdef PREPASS_REFLECTIVITY
#ifndef UNLIT
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo;
#else
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo;
#endif
#endif
#endif
`;x.IncludesShadersStore[kj]||(x.IncludesShadersStore[kj]=oEe)});var Wj,lEe,gF=y(()=>{k();Wj="pbrDebug",lEe=`#if DEBUGMODE>0
if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) {
#if DEBUGMODE==1
gl_FragColor.rgb=vPositionW.rgb;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==2 && defined(NORMAL)
gl_FragColor.rgb=vNormalW.rgb;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC)
gl_FragColor.rgb=TBN[0];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC)
gl_FragColor.rgb=TBN[1];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==5
gl_FragColor.rgb=normalW;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==6 && defined(MAINUV1)
gl_FragColor.rgb=vec3(vMainUV1,0.0);
#elif DEBUGMODE==7 && defined(MAINUV2)
gl_FragColor.rgb=vec3(vMainUV2,0.0);
#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)
gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)
gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==10 && defined(CLEARCOAT)
gl_FragColor.rgb=clearcoatOut.clearCoatNormalW;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==11 && defined(ANISOTROPIC)
gl_FragColor.rgb=anisotropicOut.anisotropicNormal;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==12 && defined(ANISOTROPIC)
gl_FragColor.rgb=anisotropicOut.anisotropicTangent;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==13 && defined(ANISOTROPIC)
gl_FragColor.rgb=anisotropicOut.anisotropicBitangent;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==20 && defined(ALBEDO)
gl_FragColor.rgb=albedoTexture.rgb;
#ifndef GAMMAALBEDO
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==21 && defined(AMBIENT)
gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb;
#elif DEBUGMODE==22 && defined(OPACITY)
gl_FragColor.rgb=opacityMap.rgb;
#elif DEBUGMODE==23 && defined(EMISSIVE)
gl_FragColor.rgb=emissiveColorTex.rgb;
#ifndef GAMMAEMISSIVE
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==24 && defined(LIGHTMAP)
gl_FragColor.rgb=lightmapColor.rgb;
#ifndef GAMMALIGHTMAP
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)
gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb;
#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)
gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)
gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0);
#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb;
#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE)
gl_FragColor.rgb=sheenOut.sheenMapData.rgb;
#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)
gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb;
#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)
gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb;
#elif DEBUGMODE==32 && defined(BUMP)
gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb;
#elif DEBUGMODE==40 && defined(SS_REFRACTION)
gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==41 && defined(REFLECTION)
gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb;
#ifndef GAMMAREFLECTION
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION)
gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==50
gl_FragColor.rgb=diffuseBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==51 && defined(SPECULARTERM)
gl_FragColor.rgb=specularBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==52 && defined(CLEARCOAT)
gl_FragColor.rgb=clearCoatBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==53 && defined(SHEEN)
gl_FragColor.rgb=sheenBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==54 && defined(REFLECTION)
gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb;
#ifndef GAMMAREFLECTION
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==60
gl_FragColor.rgb=surfaceAlbedo.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==61
gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==62 && defined(METALLICWORKFLOW)
gl_FragColor.rgb=vec3(reflectivityOut.metallic);
#elif DEBUGMODE==71 && defined(METALLICWORKFLOW)
gl_FragColor.rgb=reflectivityOut.metallicF0;
#elif DEBUGMODE==63
gl_FragColor.rgb=vec3(roughness);
#elif DEBUGMODE==64
gl_FragColor.rgb=vec3(alphaG);
#elif DEBUGMODE==65
gl_FragColor.rgb=vec3(NdotV);
#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==67 && defined(CLEARCOAT)
gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness);
#elif DEBUGMODE==68 && defined(CLEARCOAT)
gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV);
#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)
gl_FragColor.rgb=subSurfaceOut.transmittance;
#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION)
gl_FragColor.rgb=subSurfaceOut.refractionTransmittance;
#elif DEBUGMODE==72
gl_FragColor.rgb=vec3(microSurface);
#elif DEBUGMODE==73
gl_FragColor.rgb=vAlbedoColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW)
gl_FragColor.rgb=vReflectivityColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==75
gl_FragColor.rgb=vEmissiveColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION)
gl_FragColor.rgb=vec3(seo);
#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
gl_FragColor.rgb=vec3(eho);
#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION)
gl_FragColor.rgb=vec3(energyConservationFactor);
#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
gl_FragColor.rgb=baseSpecularEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION)
gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==86 && defined(ALPHABLEND)
gl_FragColor.rgb=vec3(luminanceOverAlpha);
#elif DEBUGMODE==87
gl_FragColor.rgb=vec3(alpha);
#elif DEBUGMODE==88 && defined(ALBEDO)
gl_FragColor.rgb=vec3(albedoTexture.a);
#elif DEBUGMODE==89
gl_FragColor.rgb=aoOut.ambientOcclusionColor.rgb;
#else
float stripeWidth=30.;float stripePos=floor(gl_FragCoord.x/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor);
#endif
gl_FragColor.rgb*=vDebugMode.y;
#ifdef DEBUGMODE_NORMALIZE
gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5;
#endif
#ifdef DEBUGMODE_GAMMA
gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb);
#endif
gl_FragColor.a=1.0;
#ifdef PREPASS
gl_FragData[0]=toLinearSpace(gl_FragColor);
gl_FragData[1]=vec4(0.,0.,0.,0.);
#endif
#ifdef DEBUGMODE_FORCERETURN
return;
#endif
}
#endif
`;x.IncludesShadersStore[Wj]||(x.IncludesShadersStore[Wj]=lEe)});var Xj={};Be(Xj,{openpbrPixelShader:()=>cEe});var _F,Hj,cEe,Yj=y(()=>{k();gM();_M();qK();nF();aF();vM();EM();JK();TM();af();ch();lE();oo();oF();lF();cF();AM();SM();_g();fF();dF();gg();uF();hF();ty();lj();fj();vE();Mw();uj();mj();yw();Iw();gj();of();mF();Ej();Tj();xj();Pw();Cw();bj();yj();Cj();Lj();MM();Oj();wj();Bj();Vj();yM();cE();pF();zj();IM();gF();_F="openpbrPixelShader",Hj=`#define OPENPBR_FRAGMENT_SHADER
#define CUSTOM_FRAGMENT_EXTENSION
#if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)
#extension GL_OES_standard_derivatives : enable
#endif
#ifdef LODBASEDMICROSFURACE
#extension GL_EXT_shader_texture_lod : enable
#endif
#define CUSTOM_FRAGMENT_BEGIN
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
#include<prePassDeclaration>[SCENE_MRT_COUNT]
precision highp float;
#include<oitDeclaration>
#ifndef FROMLINEARSPACE
#define FROMLINEARSPACE
#endif
#include<__decl__openpbrFragment>
#include<pbrFragmentExtraDeclaration>
#include<__decl__lightFragment>[0..maxSimultaneousLights]
#include<openpbrFragmentSamplersDeclaration>
#include<imageProcessingDeclaration>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
#include<helperFunctions>
#include<subSurfaceScatteringFunctions>
#include<importanceSampling>
#include<pbrHelperFunctions>
#include<imageProcessingFunctions>
#include<shadowsFragmentFunctions>
#include<harmonicsFunctions>
#include<pbrDirectLightingSetupFunctions>
#include<pbrDirectLightingFalloffFunctions>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
#include<pbrDirectLightingFunctions>
#include<pbrIBLFunctions>
#include<openpbrNormalMapFragmentMainFunctions>
#include<openpbrNormalMapFragmentFunctions>
#ifdef REFLECTION
#include<reflectionFunction>
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
#include<openpbrDielectricReflectance>
#include<openpbrConductorReflectance>
#include<openpbrAmbientOcclusionFunctions>
#include<openpbrGeometryInfo>
#include<openpbrIblFunctions>
#include<openpbrVolumeFunctions>
vec3 layer(vec3 slab_bottom,vec3 slab_top,float lerp_factor,vec3 bottom_multiplier,vec3 top_multiplier) {return mix(slab_bottom*bottom_multiplier,slab_top*top_multiplier,lerp_factor);}
void main(void) {
#ifdef PREPASS_IRRADIANCE
vec3 total_direct_diffuse=vec3(0.0);
#endif
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#include<pbrBlockNormalGeometric>
vec3 coatNormalW=normalW;
#include<openpbrNormalMapFragment>
#include<openpbrBlockNormalFinal>
#include<openpbrBaseLayerData>
#include<openpbrTransmissionLayerData>
#include<openpbrSubsurfaceLayerData>
#include<openpbrCoatLayerData>
#include<openpbrThinFilmLayerData>
#include<openpbrFuzzLayerData>
#include<openpbrAmbientOcclusionData>
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
#include<depthPrePass>
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS
#ifdef ANISOTROPIC_COAT
geometryInfoAnisoOutParams coatGeoInfo=geometryInfoAniso(
coatNormalW,viewDirectionW.xyz,coat_roughness,geometricNormalW
,vec3(geometry_coat_tangent.x,geometry_coat_tangent.y,coat_roughness_anisotropy),TBN
);
#else
geometryInfoOutParams coatGeoInfo=geometryInfo(
coatNormalW,viewDirectionW.xyz,coat_roughness,geometricNormalW
);
#endif
specular_roughness=mix(specular_roughness,pow(min(1.0,pow(specular_roughness,4.0)+2.0*pow(coat_roughness,4.0)),0.25),coat_weight);
#ifdef ANISOTROPIC_BASE
geometryInfoAnisoOutParams baseGeoInfo=geometryInfoAniso(
normalW,viewDirectionW.xyz,specular_roughness,geometricNormalW
,vec3(geometry_tangent.x,geometry_tangent.y,specular_roughness_anisotropy),TBN
);
#else
geometryInfoOutParams baseGeoInfo=geometryInfo(
normalW,viewDirectionW.xyz,specular_roughness,geometricNormalW
);
#endif
#ifdef FUZZ
vec3 fuzzNormalW=normalize(mix(normalW,coatNormalW,coat_weight));vec3 fuzzTangent=normalize(TBN[0]);fuzzTangent=normalize(fuzzTangent-dot(fuzzTangent,fuzzNormalW)*fuzzNormalW);vec3 fuzzBitangent=cross(fuzzNormalW,fuzzTangent);geometryInfoOutParams fuzzGeoInfo=geometryInfo(
fuzzNormalW,viewDirectionW.xyz,fuzz_roughness,geometricNormalW
);
#endif
ReflectanceParams coatReflectance;coatReflectance=dielectricReflectance(
coat_ior
,1.0
,vec3(1.0)
,coat_weight
);
#ifdef THIN_FILM
float thin_film_outside_ior=mix(1.0,coat_ior,coat_weight);
#endif
ReflectanceParams baseDielectricReflectance;{float effectiveCoatIor=mix(1.0,coat_ior,coat_weight);baseDielectricReflectance=dielectricReflectance(
specular_ior
,effectiveCoatIor
,specular_color
,specular_weight
);}
ReflectanceParams baseConductorReflectance;baseConductorReflectance=conductorReflectance(base_color,specular_color,specular_weight);vec3 volume_absorption=vec3(1.0);vec3 transmission_tint=vec3(1.0);float surface_translucency_weight=0.0;
#if defined(REFRACTED_BACKGROUND) || defined(REFRACTED_ENVIRONMENT) || defined(REFRACTED_LIGHTS)
#if defined(GEOMETRY_THIN_WALLED)
vec3 refractedViewVector=-viewDirectionW;
#else
#ifdef DISPERSION
vec3 refractedViewVectors[3];float iorDispersionSpread=transmission_dispersion_scale/transmission_dispersion_abbe_number*(specular_ior-1.0);vec3 dispersion_iors=vec3(specular_ior-iorDispersionSpread,specular_ior,specular_ior+iorDispersionSpread);for (int i=0; i<3; i++) {refractedViewVectors[i]=double_refract(-viewDirectionW,normalW,dispersion_iors[i]); }
#else
vec3 refractedViewVector=double_refract(-viewDirectionW,normalW,specular_ior);
#endif
#endif
#ifdef GEOMETRY_THIN_WALLED
float transmission_roughness=specular_roughness;
#else
float transmission_roughness=specular_roughness*clamp(4.0*(specular_ior-1.0),0.001,1.0);
#endif
#if (defined(TRANSMISSION_SLAB) || defined(SUBSURFACE_SLAB))
OpenPBRHomogeneousVolume volumeParams;{
#if defined(TRANSMISSION_SLAB)
OpenPBRHomogeneousVolume transmissionVolumeParams=computeOpenPBRTransmissionVolume(
transmission_color.rgb,
transmission_depth,
transmission_scatter.rgb,
transmission_scatter_anisotropy
);
#endif
#if defined(SUBSURFACE_SLAB)
OpenPBRHomogeneousVolume subsurfaceVolumeParams=computeOpenPBRSubsurfaceVolume(
subsurface_color.rgb,
subsurface_radius,
subsurface_radius_scale.rgb,
subsurface_scatter_anisotropy
);
#endif
#if !defined(TRANSMISSION_SLAB)
volumeParams=subsurfaceVolumeParams;surface_translucency_weight=subsurface_weight;
#elif !defined(SUBSURFACE_SLAB)
volumeParams=transmissionVolumeParams;
#ifdef TRANSMISSION_SLAB_VOLUME
volumeParams.multi_scatter_color=singleScatterToMultiScatterAlbedo(volumeParams.ss_albedo);
#endif
surface_translucency_weight=transmission_weight;
#else
float subsurface_fraction_of_dielectric=(1.0f-transmission_weight)*subsurface_weight;float subsurface_and_transmission_fraction_of_dielectric=subsurface_fraction_of_dielectric+transmission_weight;float reciprocal_of_subsurface_and_transmission_fraction_of_dielectric =
1.0f/maxEps(subsurface_and_transmission_fraction_of_dielectric);float trans_weight=transmission_weight*reciprocal_of_subsurface_and_transmission_fraction_of_dielectric;float subsurf_weight=subsurface_fraction_of_dielectric*reciprocal_of_subsurface_and_transmission_fraction_of_dielectric;volumeParams.scatter_coeff=transmissionVolumeParams.scatter_coeff*trans_weight+subsurfaceVolumeParams.scatter_coeff*subsurf_weight;volumeParams.absorption_coeff=transmissionVolumeParams.absorption_coeff*trans_weight+subsurfaceVolumeParams.absorption_coeff*subsurf_weight;volumeParams.anisotropy=(transmissionVolumeParams.anisotropy*trans_weight+subsurfaceVolumeParams.anisotropy*subsurf_weight)/maxEps(trans_weight+subsurf_weight);volumeParams.extinction_coeff=volumeParams.absorption_coeff+volumeParams.scatter_coeff;volumeParams.ss_albedo=volumeParams.scatter_coeff/maxEps(volumeParams.extinction_coeff);volumeParams.multi_scatter_color=singleScatterToMultiScatterAlbedo(volumeParams.ss_albedo);surface_translucency_weight=subsurface_and_transmission_fraction_of_dielectric;
#endif
}
volume_absorption=exp(-volumeParams.absorption_coeff*geometry_thickness);vec3 backscatter_color=vec3(1.0);{vec3 reduced_scatter=volumeParams.scatter_coeff*vec3(1.0-volumeParams.anisotropy);vec3 reduced_albedo=reduced_scatter/(volumeParams.absorption_coeff+reduced_scatter);vec3 sqrt_term=max(sqrt(1.0-reduced_albedo),0.0001);backscatter_color=(1.0-sqrt_term)/(1.0+sqrt_term);}
#elif defined(TRANSMISSION_SLAB)
surface_translucency_weight=transmission_weight;
#endif
#ifdef SCATTERING
#ifdef GEOMETRY_THIN_WALLED
vec3 iso_scatter_density=vec3(1.0);
#else
#ifdef USE_IRRADIANCE_TEXTURE_FOR_SCATTERING
vec3 mfp=vec3(100.0)/volumeParams.extinction_coeff;vec3 scattered_light_from_irradiance_texture=sss_convolve(sceneIrradianceSampler,sceneDepthSampler,renderTargetSize,mfp,projection,inverseProjection,SSS_SAMPLE_COUNT,noise.xy);float numLights=float(LIGHTCOUNT);
#ifdef REFLECTION
numLights+=1.0;
#endif
scattered_light_from_irradiance_texture/=numLights;
#else
vec3 scattered_light_from_irradiance_texture=vec3(0.0);
#endif
float back_to_iso_scattering_blend=min(1.0+volumeParams.anisotropy,1.0);float iso_to_forward_scattering_blend=max(volumeParams.anisotropy,0.0);vec3 iso_scatter_transmittance=pow(exp(-volumeParams.scatter_coeff*geometry_thickness),vec3(0.2));vec3 iso_scatter_density=clamp(vec3(1.0)-iso_scatter_transmittance,0.0,1.0);transmission_roughness=min(transmission_roughness+pow((1.0-abs(volumeParams.anisotropy))*max3(iso_scatter_density*iso_scatter_density),3.0),1.0);
#endif
volumeParams.multi_scatter_color=mix(volumeParams.ss_albedo,volumeParams.multi_scatter_color,max3(iso_scatter_density));
#endif
#if defined(TRANSMISSION_SLAB) && (!defined(TRANSMISSION_SLAB_VOLUME) || defined(GEOMETRY_THIN_WALLED))
transmission_tint*=transmission_color.rgb;
#ifdef GEOMETRY_THIN_WALLED
float sin2=1.0-baseGeoInfo.NdotV*baseGeoInfo.NdotV;sin2=sin2/(specular_ior*specular_ior);float cos_t=sqrt(1.0-sin2);float pathLength=1.0/cos_t;transmission_tint=pow(transmission_tint,vec3(pathLength));
#else
transmission_tint*=transmission_color.rgb;
#endif
#endif
#if defined(SUBSURFACE_SLAB) && defined(GEOMETRY_THIN_WALLED)
float unweighted_translucency=mix(subsurface_weight,1.0f,transmission_weight);transmission_tint=mix(vec3(1.0),transmission_tint,transmission_weight/unweighted_translucency);transmission_roughness=mix(1.0,transmission_roughness,transmission_weight/unweighted_translucency);
#endif
float transmission_roughness_alpha=transmission_roughness*transmission_roughness;
#endif
#include<openpbrBackgroundTransmission>
vec3 material_surface_ibl=vec3(0.,0.,0.);
#include<openpbrEnvironmentLighting>
vec3 material_surface_direct=vec3(0.,0.,0.);
#if defined(LIGHT0)
float aggShadow=0.;
#include<openpbrDirectLightingInit>[0..maxSimultaneousLights]
#include<openpbrDirectLighting>[0..maxSimultaneousLights]
#endif
vec3 material_surface_emission=vEmissionColor;
#ifdef EMISSION_COLOR
vec3 emissionColorTex=texture2D(emissionColorSampler,vEmissionColorUV+uvOffset).rgb;
#ifdef EMISSION_COLOR_GAMMA
material_surface_emission*=toLinearSpace(emissionColorTex.rgb);
#else
material_surface_emission*=emissionColorTex.rgb;
#endif
material_surface_emission*= vEmissionColorInfos.y;
#endif
material_surface_emission*=vLightingIntensity.y;
#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION
vec4 finalColor=vec4(material_surface_ibl+material_surface_direct+material_surface_emission,alpha);
#define CUSTOM_FRAGMENT_BEFORE_FOG
finalColor=max(finalColor,0.0);
#include<logDepthFragment>
#include<fogFragment>(color,finalColor)
#include<pbrBlockImageProcessing>
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
#include<openpbrBlockPrePass>
#endif
#if !defined(PREPASS) || defined(WEBGL2)
gl_FragColor=finalColor;
#endif
#include<oitFragment>
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;}
#endif
#include<pbrDebug>
#define CUSTOM_FRAGMENT_MAIN_END
}
`;x.ShadersStore[_F]||(x.ShadersStore[_F]=Hj);cEe={name:_F,shader:Hj}});var Kj={};Be(Kj,{OpenPBRMaterial:()=>Ne,OpenPBRMaterialDefines:()=>LE});var Sg,ny,ui,Pi,vF,EF,LE,SF,Ne,jj=y(()=>{jt();Yt();$M();$t();Dv();Kr();ir();ls();Or();uo();Ib();Td();Hl();Jv();os();qi();Cb();yb();co();wt();Pb();Lb();Z9();He();Db();$v();Wo();Gi();O7();Sg={effect:null,subMesh:null},ny=class n{populateVectorFromLinkedProperties(e){let t=e.dimension[0];for(let i in this.linkedProperties){let r=this.linkedProperties[i],s=r.numComponents;if(t<s||r.targetUniformComponentOffset>t-s){s==1?te.Error(`Float property ${r.name} has an offset that is too large.`):te.Error(`Vector${s} property ${r.name} won't fit in Vector${t} or has an offset that is too large.`);return}typeof r.value=="number"?n._tmpArray[r.targetUniformComponentOffset]=r.value:r.value.toArray(n._tmpArray,r.targetUniformComponentOffset)}e.fromArray(n._tmpArray)}constructor(e,t){this.linkedProperties={},this.firstLinkedKey="",this.name=e,this.numComponents=t}};ny._tmpArray=[0,0,0,0];ui=class{constructor(e,t,i,r,s=0,a){this.targetUniformComponentNum=4,this.targetUniformComponentOffset=0,this.name=e,this.targetUniformName=i,this.defaultValue=t,this.value=t,this.targetUniformComponentNum=r,this.targetUniformComponentOffset=s,this.requiredDefine=a}get numComponents(){return typeof this.defaultValue=="number"?1:this.defaultValue.dimension[0]}},Pi=class{get samplerName(){return this.samplerPrefix+"Sampler"}get samplerInfoName(){return"v"+this.samplerPrefix.charAt(0).toUpperCase()+this.samplerPrefix.slice(1)+"Infos"}get samplerMatrixName(){return this.samplerPrefix+"Matrix"}constructor(e,t,i){this.value=null,this.samplerPrefix="",this.textureDefine="",this.name=e,this.samplerPrefix=t,this.textureDefine=i}},vF=class extends ag(sg(wr)){},EF=class extends j9(vF){},LE=class extends rg(EF){constructor(e){super(e),this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.IBL_CDF_FILTERING=!1,this.LIGHTCOUNT=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.VERTEXALPHA=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHA_FROM_BASE_COLOR_TEXTURE=!1,this.ALPHATESTVALUE="0.5",this.PREMULTIPLYALPHA=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.LODBASEDMICROSFURACE=!0,this.SPECULAR_ROUGHNESS_FROM_METALNESS_TEXTURE_GREEN=!1,this.BASE_METALNESS_FROM_METALNESS_TEXTURE_BLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.SPECULAR_WEIGHT_IN_ALPHA=!1,this.SPECULAR_WEIGHT_FROM_SPECULAR_COLOR_TEXTURE=!1,this.SPECULAR_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE=!1,this.COAT_ROUGHNESS_FROM_GREEN_CHANNEL=!1,this.COAT_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE=!1,this.USE_GLTF_STYLE_ANISOTROPY=!1,this.THIN_FILM_THICKNESS_FROM_THIN_FILM_TEXTURE=!1,this.FUZZ_ROUGHNESS_FROM_TEXTURE_ALPHA=!1,this.GEOMETRY_THICKNESS_FROM_GREEN_CHANNEL=!1,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.FUZZENVIRONMENTBRDF=!1,this.NORMAL=!1,this.TANGENT=!1,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.ANISOTROPIC=!1,this.ANISOTROPIC_OPENPBR=!0,this.ANISOTROPIC_BASE=!1,this.ANISOTROPIC_COAT=!1,this.FUZZ_IBL_SAMPLES=6,this.REFRACTION_HIGH_QUALITY_BLUR=!1,this.FUZZ=!1,this.THIN_FILM=!1,this.IRIDESCENCE=!1,this.DISPERSION=!1,this.SCATTERING=!1,this.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING=!1,this.SSS_SAMPLE_COUNT=16,this.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING_GBUFFER=!1,this.TRANSMISSION_SLAB=!1,this.TRANSMISSION_SLAB_VOLUME=!1,this.SUBSURFACE_SLAB=!1,this.GEOMETRY_THIN_WALLED=!1,this.REFRACTED_BACKGROUND=!1,this.REFRACTED_LIGHTS=!1,this.REFRACTED_ENVIRONMENT=!1,this.REFRACTED_ENVIRONMENT_OPPOSITEZ=!1,this.REFRACTED_ENVIRONMENT_LOCAL_CUBE=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_POSITION=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.MORPHTARGETS_UV2=!1,this.MORPHTARGETS_COLOR=!1,this.MORPHTARGETTEXTURE_HASPOSITIONS=!1,this.MORPHTARGETTEXTURE_HASNORMALS=!1,this.MORPHTARGETTEXTURE_HASTANGENTS=!1,this.MORPHTARGETTEXTURE_HASUVS=!1,this.MORPHTARGETTEXTURE_HASUV2S=!1,this.MORPHTARGETTEXTURE_HASCOLORS=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.MIRRORED=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.AREALIGHTSUPPORTED=!0,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.USE_VERTEX_PULLING=!1,this.VERTEX_PULLING_USE_INDEX_BUFFER=!1,this.VERTEX_PULLING_INDEX_BUFFER_32BITS=!1,this.RIGHT_HANDED=!1,this.CLUSTLIGHT_SLICES=0,this.CLUSTLIGHT_BATCH=0,this.BRDF_V_HEIGHT_CORRELATED=!0,this.MS_BRDF_ENERGY_CONSERVATION=!0,this.SPHERICAL_HARMONICS=!0,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!0,this.MIX_IBL_RADIANCE_WITH_IRRADIANCE=!0,this.LEGACY_SPECULAR_ENERGY_CONSERVATION=!1,this.BASE_DIFFUSE_MODEL=0,this.DIELECTRIC_SPECULAR_MODEL=1,this.CONDUCTOR_SPECULAR_MODEL=1,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.NORMALXYSCALE=!0}},SF=class extends og(jl){},Ne=class n extends SF{get geometryTangentAngle(){return Math.atan2(this.geometryTangent.y,this.geometryTangent.x)}set geometryTangentAngle(e){this.geometryTangent=new Fe(Math.cos(e),Math.sin(e))}get geometryCoatTangentAngle(){return Math.atan2(this.geometryCoatTangent.y,this.geometryCoatTangent.x)}set geometryCoatTangentAngle(e){this.geometryCoatTangent=new Fe(Math.cos(e),Math.sin(e))}get sssQuality(){return this._sssQuality}set sssQuality(e){this._sssQuality!==e&&(this._sssQuality=e,this.markAsDirty(1))}get sssIrradianceTexture(){return this._sssIrradianceTexture}set sssIrradianceTexture(e){this._sssIrradianceTexture!==e&&(this._sssIrradianceTexture=e,this._markAllSubMeshesAsTexturesDirty())}get sssDepthTexture(){return this._sssDepthTexture}set sssDepthTexture(e){this._sssDepthTexture!==e&&(this._sssDepthTexture=e,this._markAllSubMeshesAsTexturesDirty())}get hasTransparency(){return this.subsurfaceWeight>0||this.transmissionWeight>0}get hasScattering(){return this.transmissionWeight>0&&this.transmissionDepth>0&&!this.transmissionScatter.equals(he.BlackReadOnly)||this.subsurfaceWeight>0}get usePhysicalLightFalloff(){return this._lightFalloff===Ae.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Ae.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=Ae.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Ae.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Ae.LIGHTFALLOFF_GLTF:this._lightFalloff=Ae.LIGHTFALLOFF_STANDARD)}get backgroundRefractionTexture(){return this._backgroundRefractionTexture}set backgroundRefractionTexture(e){this._backgroundRefractionTexture=e,this._markAllSubMeshesAsTexturesDirty()}get refractionHighQualityBlur(){return this._refractionHighQualityBlur}set refractionHighQualityBlur(e){this._refractionHighQualityBlur!==e&&(this._refractionHighQualityBlur=e,this.markAsDirty(1))}get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get fuzzSampleNumber(){return this._fuzzSampleNumber}set fuzzSampleNumber(e){this._fuzzSampleNumber=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}constructor(e,t,i=!1){var s;super(e,t,void 0,i||n.ForceGLSL),this._baseWeight=new ui("base_weight",1,"vBaseWeight",1),this._baseWeightTexture=new Pi("base_weight","baseWeight","BASE_WEIGHT"),this._baseColor=new ui("base_color",he.White(),"vBaseColor",4),this._baseColorTexture=new Pi("base_color","baseColor","BASE_COLOR"),this._baseDiffuseRoughness=new ui("base_diffuse_roughness",0,"vBaseDiffuseRoughness",1),this._baseDiffuseRoughnessTexture=new Pi("base_diffuse_roughness","baseDiffuseRoughness","BASE_DIFFUSE_ROUGHNESS"),this._baseMetalness=new ui("base_metalness",0,"vReflectanceInfo",4,0),this._baseMetalnessTexture=new Pi("base_metalness","baseMetalness","BASE_METALNESS"),this._specularWeight=new ui("specular_weight",1,"vReflectanceInfo",4,3),this._specularWeightTexture=new Pi("specular_weight","specularWeight","SPECULAR_WEIGHT"),this._specularColor=new ui("specular_color",he.White(),"vSpecularColor",4),this._specularColorTexture=new Pi("specular_color","specularColor","SPECULAR_COLOR"),this._specularRoughness=new ui("specular_roughness",.3,"vReflectanceInfo",4,1),this._specularRoughnessTexture=new Pi("specular_roughness","specularRoughness","SPECULAR_ROUGHNESS"),this._specularRoughnessAnisotropy=new ui("specular_roughness_anisotropy",0,"vSpecularAnisotropy",3,2),this._specularRoughnessAnisotropyTexture=new Pi("specular_roughness_anisotropy","specularRoughnessAnisotropy","SPECULAR_ROUGHNESS_ANISOTROPY"),this._specularIor=new ui("specular_ior",1.5,"vReflectanceInfo",4,2),this._transmissionWeight=new ui("transmission_weight",0,"vTransmissionWeight",1),this._transmissionWeightTexture=new Pi("transmission_weight","transmissionWeight","TRANSMISSION_WEIGHT"),this._transmissionColor=new ui("transmission_color",he.White(),"vTransmissionColor",3,0),this._transmissionColorTexture=new Pi("transmission_color","transmissionColor","TRANSMISSION_COLOR"),this._transmissionDepth=new ui("transmission_depth",0,"vTransmissionDepth",1,0),this._transmissionDepthTexture=new Pi("transmission_depth","transmissionDepth","TRANSMISSION_DEPTH"),this._transmissionScatter=new ui("transmission_scatter",he.Black(),"vTransmissionScatter",3,0),this._transmissionScatterTexture=new Pi("transmission_scatter","transmissionScatter","TRANSMISSION_SCATTER"),this._transmissionScatterAnisotropy=new ui("transmission_scatter_anisotropy",0,"vTransmissionScatterAnisotropy",1,0),this._transmissionDispersionScale=new ui("transmission_dispersion_scale",0,"vTransmissionDispersionScale",1,0),this._transmissionDispersionScaleTexture=new Pi("transmission_dispersion_scale","transmissionDispersionScale","TRANSMISSION_DISPERSION_SCALE"),this._transmissionDispersionAbbeNumber=new ui("transmission_dispersion_abbe_number",20,"vTransmissionDispersionAbbeNumber",1,0),this._subsurfaceWeight=new ui("subsurface_weight",0,"vSubsurfaceWeight",1,0,"SUBSURFACE_SLAB"),this._subsurfaceWeightTexture=new Pi("subsurface_weight","subsurfaceWeight","SUBSURFACE_WEIGHT"),this._subsurfaceColor=new ui("subsurface_color",new he(.8,.8,.8),"vSubsurfaceColor",3,0,"SUBSURFACE_SLAB"),this._subsurfaceColorTexture=new Pi("subsurface_color","subsurfaceColor","SUBSURFACE_COLOR"),this._subsurfaceRadius=new ui("subsurface_radius",.1,"vSubsurfaceRadius",1,0,"SUBSURFACE_SLAB"),this._subsurfaceRadiusScale=new ui("subsurface_radius_scale",new he(1,.5,.25),"vSubsurfaceRadiusScale",3,0,"SUBSURFACE_SLAB"),this._subsurfaceRadiusScaleTexture=new Pi("subsurface_radius_scale","subsurfaceRadiusScale","SUBSURFACE_RADIUS_SCALE"),this._subsurfaceScatterAnisotropy=new ui("subsurface_scatter_anisotropy",0,"vSubsurfaceScatterAnisotropy",1,0,"SUBSURFACE_SLAB"),this._coatWeight=new ui("coat_weight",0,"vCoatWeight",1,0),this._coatWeightTexture=new Pi("coat_weight","coatWeight","COAT_WEIGHT"),this._coatColor=new ui("coat_color",he.White(),"vCoatColor",3,0),this._coatColorTexture=new Pi("coat_color","coatColor","COAT_COLOR"),this._coatRoughness=new ui("coat_roughness",0,"vCoatRoughness",1,0),this._coatRoughnessTexture=new Pi("coat_roughness","coatRoughness","COAT_ROUGHNESS"),this._coatRoughnessAnisotropy=new ui("coat_roughness_anisotropy",0,"vCoatRoughnessAnisotropy",1),this._coatRoughnessAnisotropyTexture=new Pi("coat_roughness_anisotropy","coatRoughnessAnisotropy","COAT_ROUGHNESS_ANISOTROPY"),this._coatIor=new ui("coat_ior",1.5,"vCoatIor",1,0),this._coatDarkening=new ui("coat_darkening",1,"vCoatDarkening",1,0),this._coatDarkeningTexture=new Pi("coat_darkening","coatDarkening","COAT_DARKENING"),this.useCoatRoughnessFromWeightTexture=!1,this._fuzzWeight=new ui("fuzz_weight",0,"vFuzzWeight",1,0),this._fuzzWeightTexture=new Pi("fuzz_weight","fuzzWeight","FUZZ_WEIGHT"),this._fuzzColor=new ui("fuzz_color",he.White(),"vFuzzColor",3,0),this._fuzzColorTexture=new Pi("fuzz_color","fuzzColor","FUZZ_COLOR"),this._fuzzRoughness=new ui("fuzz_roughness",.5,"vFuzzRoughness",1,0),this._fuzzRoughnessTexture=new Pi("fuzz_roughness","fuzzRoughness","FUZZ_ROUGHNESS"),this._geometryThinWalled=new ui("geometry_thin_walled",0,"vGeometryThinWalled",1,0),this._geometryNormalTexture=new Pi("geometry_normal","geometryNormal","GEOMETRY_NORMAL"),this._geometryTangent=new ui("geometry_tangent",new Fe(1,0),"vSpecularAnisotropy",3,0),this._geometryTangentTexture=new Pi("geometry_tangent","geometryTangent","GEOMETRY_TANGENT"),this._geometryCoatNormalTexture=new Pi("geometry_coat_normal","geometryCoatNormal","GEOMETRY_COAT_NORMAL"),this._geometryCoatTangent=new ui("geometry_coat_tangent",new Fe(1,0),"vGeometryCoatTangent",2,0),this._geometryCoatTangentTexture=new Pi("geometry_coat_tangent","geometryCoatTangent","GEOMETRY_COAT_TANGENT"),this._geometryOpacity=new ui("geometry_opacity",1,"vBaseColor",4,3),this._geometryOpacityTexture=new Pi("geometry_opacity","geometryOpacity","GEOMETRY_OPACITY"),this._geometryThickness=new ui("geometry_thickness",0,"vGeometryThickness",1,0),this._geometryThicknessTexture=new Pi("geometry_thickness","geometryThickness","GEOMETRY_THICKNESS"),this._emissionLuminance=new ui("emission_luminance",1,"vLightingIntensity",4,1),this._emissionColor=new ui("emission_color",he.Black(),"vEmissionColor",3),this._emissionColorTexture=new Pi("emission_color","emissionColor","EMISSION_COLOR"),this._thinFilmWeight=new ui("thin_film_weight",0,"vThinFilmWeight",1,0),this._thinFilmWeightTexture=new Pi("thin_film_weight","thinFilmWeight","THIN_FILM_WEIGHT"),this._thinFilmThickness=new ui("thin_film_thickness",.5,"vThinFilmThickness",2,0),this._thinFilmThicknessMin=new ui("thin_film_thickness_min",0,"vThinFilmThickness",2,1),this._thinFilmThicknessTexture=new Pi("thin_film_thickness","thinFilmThickness","THIN_FILM_THICKNESS"),this._thinFilmIor=new ui("thin_film_ior",1.4,"vThinFilmIor",1,0),this._ambientOcclusionTexture=new Pi("ambient_occlusion","ambientOcclusion","AMBIENT_OCCLUSION"),this._sssQuality=n.SSS_QUALITY_MEDIUM,this._sssIrradianceTexture=null,this._sssDepthTexture=null,this._uniformsList={},this._uniformsArray=[],this._samplersList={},this._samplerDefines={},this.directIntensity=1,this.environmentIntensity=1,this.useSpecularWeightFromTextureAlpha=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._lightingInfos=new Vi(this.directIntensity,1,this.environmentIntensity,1),this._radianceTexture=null,this._useSpecularWeightFromAlpha=!1,this._useSpecularWeightFromSpecularColorTexture=!1,this._useSpecularRoughnessAnisotropyFromTangentTexture=!1,this._useCoatRoughnessAnisotropyFromTangentTexture=!1,this._useCoatRoughnessFromGreenChannel=!1,this._useGltfStyleAnisotropy=!1,this._useFuzzRoughnessFromTextureAlpha=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromBaseColorTexture=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallicFromMetallicTextureBlue=!1,this._useThinFilmThicknessFromTextureGreen=!1,this._useGeometryThicknessFromGreenChannel=!1,this._lightFalloff=Ae.LIGHTFALLOFF_PHYSICAL,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._environmentFuzzBRDFTexture=null,this._backgroundRefractionTexture=null,this._refractionHighQualityBlur=!0,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._fuzzSampleNumber=4,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._renderTargets=new Qi(16),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this._shadersLoaded=!1,this._breakShaderLoadedCheck=!1,this._vertexPullingMetadata=null,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this._transparencyMode=Ae.MATERIAL_OPAQUE,this.getScene()&&!((s=this.getScene())!=null&&s.getEngine().isWebGPU)&&this.getScene().getEngine().webGLVersion<2&&te.Error("OpenPBRMaterial: WebGL 2.0 or above is required for this material."),n._noiseTextures[this.getScene().uniqueId]||(n._noiseTextures[this.getScene().uniqueId]=new _e(pe.GetAssetUrl("https://assets.babylonjs.com/core/blue_noise/blue_noise_rgb.png"),this.getScene(),!1,!0,1),this.getScene().onDisposeObservable.addOnce(()=>{var a;(a=n._noiseTextures[this.getScene().uniqueId])==null||a.dispose(),delete n._noiseTextures[this.getScene().uniqueId]})),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),fe.ReflectionTextureEnabled&&this._radianceTexture&&this._radianceTexture.isRenderTarget&&this._renderTargets.push(this._radianceTexture),fe.RefractionTextureEnabled&&this._backgroundRefractionTexture&&this._backgroundRefractionTexture.isRenderTarget&&this._renderTargets.push(this._backgroundRefractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=K9(this.getScene()),this._environmentFuzzBRDFTexture=xw(this.getScene()),this.prePassConfiguration=new fa,this._propertyList={};for(let a of Object.getOwnPropertyNames(this)){let o=this[a];o instanceof ui&&(this._propertyList[a]=o)}Object.keys(this._propertyList).forEach(a=>{let o=this._propertyList[a],l=this._uniformsList[o.targetUniformName];l?l.numComponents!==o.targetUniformComponentNum?te.Error(`Uniform ${o.targetUniformName} already exists of size ${l.numComponents}, but trying to set it to ${o.targetUniformComponentNum}.`):l.requiredDefine!==o.requiredDefine&&(l.requiredDefine=void 0):(l=new ny(o.targetUniformName,o.targetUniformComponentNum),l.requiredDefine=o.requiredDefine,this._uniformsList[o.targetUniformName]=l),l.firstLinkedKey===""&&(l.firstLinkedKey=o.name),l.linkedProperties[o.name]=o}),this._uniformsArray=Object.values(this._uniformsList),this._samplersList={};for(let a of Object.getOwnPropertyNames(this)){let o=this[a];o instanceof Pi&&(this._samplersList[a]=o)}for(let a in this._samplersList){let l=this._samplersList[a].textureDefine;this._samplerDefines[l]={type:"boolean",default:!1},this._samplerDefines[l+"DIRECTUV"]={type:"number",default:0},this._samplerDefines[l+"_GAMMA"]={type:"boolean",default:!1}}this._baseWeight,this._baseWeightTexture,this._baseColor,this._baseColorTexture,this._baseDiffuseRoughness,this._baseDiffuseRoughnessTexture,this._baseMetalness,this._baseMetalnessTexture,this._specularWeight,this._specularWeightTexture,this._specularColor,this._specularColorTexture,this._specularRoughness,this._specularIor,this._specularRoughnessTexture,this._specularRoughnessAnisotropy,this._specularRoughnessAnisotropyTexture,this._transmissionWeight,this._transmissionWeightTexture,this._transmissionColor,this._transmissionColorTexture,this._transmissionDepth,this._transmissionDepthTexture,this._transmissionScatter,this._transmissionScatterTexture,this._transmissionScatterAnisotropy,this._transmissionDispersionScale,this._transmissionDispersionScaleTexture,this._transmissionDispersionAbbeNumber,this._subsurfaceWeight,this._subsurfaceWeightTexture,this._subsurfaceColor,this._subsurfaceColorTexture,this._subsurfaceRadius,this._subsurfaceRadiusScale,this._subsurfaceRadiusScaleTexture,this._subsurfaceScatterAnisotropy,this._coatWeight,this._coatWeightTexture,this._coatColor,this._coatColorTexture,this._coatRoughness,this._coatRoughnessTexture,this._coatRoughnessAnisotropy,this._coatRoughnessAnisotropyTexture,this._coatIor,this._coatDarkening,this._coatDarkeningTexture,this._fuzzWeight,this._fuzzWeightTexture,this._fuzzColor,this._fuzzColorTexture,this._fuzzRoughness,this._fuzzRoughnessTexture,this._geometryThinWalled,this._geometryNormalTexture,this._geometryTangent,this._geometryTangentTexture,this._geometryCoatNormalTexture,this._geometryCoatTangent,this._geometryCoatTangentTexture,this._geometryOpacity,this._geometryOpacityTexture,this._geometryThickness,this._geometryThicknessTexture,this._thinFilmWeight,this._thinFilmWeightTexture,this._thinFilmThickness,this._thinFilmThicknessMin,this._thinFilmThicknessTexture,this._thinFilmIor,this._emissionLuminance,this._emissionColor,this._emissionColorTexture,this._ambientOcclusionTexture}get hasRenderTargetTextures(){return fe.ReflectionTextureEnabled&&this._radianceTexture&&this._radianceTexture.isRenderTarget||fe.RefractionTextureEnabled&&this._backgroundRefractionTexture&&this._backgroundRefractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"OpenPBRMaterial"}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._markAllSubMeshesAsTexturesAndMiscDirty())}_shouldUseAlphaFromBaseColorTexture(){return this._hasAlphaChannel()&&this._transparencyMode!==Ae.MATERIAL_OPAQUE&&!this.geometryOpacityTexture}_hasAlphaChannel(){return this.baseColorTexture!=null&&this.baseColorTexture.hasAlpha&&this._useAlphaFromBaseColorTexture||this.geometryOpacityTexture!=null}clone(e,t=!0,i=""){let r=at.Clone(()=>new n(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){let e=super.serialize();return e.customType="BABYLON.OpenPBRMaterial",e}static Parse(e,t,i){let r=at.Parse(()=>new n(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Ae._ParsePlugins(e,r,t,i),r}forceCompilation(e,t,i){let r={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(4,this._eventInfo),(()=>{if(this._breakShaderLoadedCheck)return;let a=new LE({...this._eventInfo.defineNames||{},...this._samplerDefines||{}}),o=this._prepareEffect(e,e,a,void 0,void 0,r.useInstances,r.clipPlane);this._onEffectCreatedObservable&&(Sg.effect=o,Sg.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Sg)),o.isReady()?t&&t(this):o.onCompileObservable.add(()=>{t&&t(this)})})()}isReadyForSubMesh(e,t,i){var u;this._uniformBufferLayoutBuilt||this.buildUniformLayout();let r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new LE({...this._eventInfo.defineNames||{},...this._samplerDefines||{}}));let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=this.getScene(),o=a.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a.texturesEnabled)){for(let m in this._samplersList){let g=this._samplersList[m];if(g.value&&!g.value.isReadyOrNotBlocking())return!1}let h=this._getRadianceTexture();if(h&&fe.ReflectionTextureEnabled){if(!h.isReadyOrNotBlocking())return!1;if(h.irradianceTexture){if(!h.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!h.sphericalPolynomial&&((u=h.getInternalTexture())!=null&&u._sphericalPolynomialPromise))return!1}if(this._environmentBRDFTexture&&fe.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady()||this._environmentFuzzBRDFTexture&&fe.ReflectionTextureEnabled&&!this._environmentFuzzBRDFTexture.isReady()||this._backgroundRefractionTexture&&fe.RefractionTextureEnabled&&!this._backgroundRefractionTexture.isReadyOrNotBlocking()||n._noiseTextures[a.uniqueId]&&!n._noiseTextures[a.uniqueId].isReady()||this._sssIrradianceTexture&&this._sssDepthTexture&&(!this._sssIrradianceTexture.isReady()||!this._sssDepthTexture.isReady()))return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;if(s.AREALIGHTUSED){for(let h=0;h<e.lightSources.length;h++)if(!e.lightSources[h]._isReady())return!1}if(!o.getCaps().standardDerivatives&&!e.isVerticesDataPresent(D.NormalKind)&&(e.createNormals(!0),te.Warn("OpenPBRMaterial: Normals have been created for the mesh: "+e.name)),!Vp(a,e,this._maxSimultaneousLights,this._disableLighting))return!1;let l=t.effect,c=s._areLightsDisposed,f=this._prepareEffect(e,t.getRenderingMesh(),s,this.onCompiled,this.onError,i,null),d=!1;if(f)if(this._onEffectCreatedObservable&&(Sg.effect=f,Sg.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Sg)),this.allowShaderHotSwapping&&l&&!f.isReady()){if(s.markAsUnprocessed(),d=this.isFrozen,c)return s._areLightsDisposed=!0,!1}else a.resetCachedMaterial(),t.setEffect(f,s,this._materialContext);return!t.effect||!t.effect.isReady()?!1:(s._renderId=a.getRenderId(),r._wasPreviouslyReady=!d,r._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){let e=this._uniformBuffer;e.addUniform("vTangentSpaceParams",2),e.addUniform("vLightingIntensity",4),e.addUniform("pointSize",1),e.addUniform("vDebugMode",2),e.addUniform("renderTargetSize",2),e.addUniform("cameraInfo",4),e.addUniform("backgroundRefractionMatrix",16),e.addUniform("vBackgroundRefractionInfos",3),Kp(e,!0,!0,!0,!0,!0),Object.values(this._uniformsList).forEach(t=>{e.addUniform(t.name,t.numComponents)}),Object.values(this._samplersList).forEach(t=>{e.addUniform(t.samplerInfoName,2),e.addUniform(t.samplerMatrixName,16)}),super.buildUniformLayout()}bindPropertiesForSubMesh(e,t,i,r){if(this.geometryThickness===0)e.updateFloat("vGeometryThickness",0);else{r.getRenderingMesh().getWorldMatrix().decompose(ee.Vector3[0]);let s=Math.max(Math.abs(ee.Vector3[0].x),Math.abs(ee.Vector3[0].y),Math.abs(ee.Vector3[0].z));e.updateFloat("vGeometryThickness",this.geometryThickness*s)}}bindForSubMesh(e,t,i){var d;let r=this.getScene(),s=i.materialDefines;if(!s)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e);let o=r.getEngine();this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),us.Bind(o.currentRenderPassId,this._activeEffect,t,e,this);let l=r.activeCamera;l?this._uniformBuffer.updateFloat4("cameraInfo",l.minZ,l.maxZ,0,0):this._uniformBuffer.updateFloat4("cameraInfo",0,0,0,0),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let c=this._mustRebind(r,a,i,t.visibility);aa(t,this._activeEffect,this.prePassConfiguration),this._vertexPullingMetadata&&xd(this._activeEffect,this._vertexPullingMetadata);let f=this._uniformBuffer;if(c){this.bindViewProjection(a);let u=this._getRadianceTexture();if(!f.useUbo||!this.isFrozen||!f.isSync||i._drawWrapper._forceRebindOnNextCall){if(r.texturesEnabled){for(let m in this._samplersList){let g=this._samplersList[m];g.value&&(f.updateFloat2(g.samplerInfoName,g.value.coordinatesIndex,g.value.level),di(g.value,f,g.samplerPrefix))}(this.geometryNormalTexture||this.geometryCoatNormalTexture)&&(r._mirroredCameraPosition?f.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):f.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),Dp(r,s,f,he.White(),u,this.realTimeFiltering,!0,!0,!0,!0,!0)}this.pointsCloud&&f.updateFloat("pointSize",this.pointSize);let h=this._uniformsArray;for(let m=0,g=h.length;m<g;m++){let p=h[m];p.requiredDefine!==void 0&&!s[p.requiredDefine]||(p.numComponents===4?(p.populateVectorFromLinkedProperties(ee.Vector4[0]),f.updateVector4(p.name,ee.Vector4[0])):p.numComponents===3?(p.populateVectorFromLinkedProperties(ee.Vector3[0]),f.updateVector3(p.name,ee.Vector3[0])):p.numComponents===2?(p.populateVectorFromLinkedProperties(ee.Vector2[0]),f.updateFloat2(p.name,ee.Vector2[0].x,ee.Vector2[0].y)):p.numComponents===1&&f.updateFloat(p.name,p.linkedProperties[p.firstLinkedKey].value))}this._lightingInfos.x=this.directIntensity,this._lightingInfos.y=this.emissionLuminance,this._lightingInfos.z=this.environmentIntensity*r.environmentIntensity,this._lightingInfos.w=1,f.updateVector4("vLightingIntensity",this._lightingInfos),f.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}if(r.texturesEnabled){for(let h in this._samplersList){let m=this._samplersList[h];m.value&&f.setTexture(m.samplerName,m.value)}if(db(r,s,f,u,this.realTimeFiltering),s.ENVIRONMENTBRDF&&f.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),s.FUZZENVIRONMENTBRDF&&f.setTexture("environmentFuzzBrdfSampler",this._environmentFuzzBRDFTexture),s.REFRACTED_BACKGROUND&&(f.setTexture("backgroundRefractionSampler",this._backgroundRefractionTexture),f.updateMatrix("backgroundRefractionMatrix",this._backgroundRefractionTexture.getReflectionTextureMatrix()),ee.Vector3[1].set(Math.log2(this._backgroundRefractionTexture.getSize().width),0,0),f.updateVector3("vBackgroundRefractionInfos",ee.Vector3[1])),(s.ANISOTROPIC||s.FUZZ||s.REFRACTED_BACKGROUND||s.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING)&&f.setTexture("blueNoiseSampler",n._noiseTextures[this.getScene().uniqueId]),s.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING&&this.sssIrradianceTexture&&this.sssDepthTexture){let h=this.sssIrradianceTexture.getSize().width,m=this.sssIrradianceTexture.getSize().height;f.setTexture("sceneIrradianceSampler",this.sssIrradianceTexture),f.setTexture("sceneDepthSampler",this.sssDepthTexture),f.updateFloat2("renderTargetSize",h,m)}}this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),ss(this._activeEffect,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);this.bindPropertiesForSubMesh(this._uniformBuffer,r,r.getEngine(),i),(c||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&Np(r,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(a),dd(r,t,this._activeEffect,!0),s.NUM_MORPH_INFLUENCERS&&as(t,this._activeEffect),s.BAKED_VERTEX_ANIMATION_TEXTURE&&((d=t.bakedVertexAnimationManager)==null||d.bind(a,s.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),fd(s,this._activeEffect,r)),this._afterBind(t,this._activeEffect,i),f.update()}getAnimatables(){let e=super.getAnimatables();for(let t in this._samplersList){let i=this._samplersList[t];i.value&&i.value.animations&&i.value.animations.length>0&&e.push(i.value)}return this._radianceTexture&&this._radianceTexture.animations&&this._radianceTexture.animations.length>0&&e.push(this._radianceTexture),e}getActiveTextures(){let e=super.getActiveTextures();for(let t in this._samplersList){let i=this._samplersList[t];i.value&&e.push(i.value)}return this._radianceTexture&&e.push(this._radianceTexture),e}hasTexture(e){if(super.hasTexture(e))return!0;for(let t in this._samplersList)if(this._samplersList[t].value===e)return!0;return this._radianceTexture===e}setPrePassRenderer(){return!1}dispose(e,t){var i,r;if(this._breakShaderLoadedCheck=!0,t){this._environmentBRDFTexture&&this.getScene().openPBREnvironmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._environmentFuzzBRDFTexture&&this.getScene().environmentFuzzBRDFTexture!==this._environmentFuzzBRDFTexture&&this._environmentFuzzBRDFTexture.dispose(),this._backgroundRefractionTexture=null;for(let s in this._samplersList)(i=this._samplersList[s].value)==null||i.dispose();(r=this._radianceTexture)==null||r.dispose()}this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}_getRadianceTexture(){return this._radianceTexture?this._radianceTexture:this.getScene().environmentTexture}_prepareEffect(e,t,i,r=null,s=null,a=null,o=null){if(this._prepareDefines(e,t,i,a,o),!i.isDirty)return null;i.markAsProcessed();let c=this.getScene().getEngine(),f=new ds,d=0;i.USESPHERICALINVERTEX&&f.addFallback(d++,"USESPHERICALINVERTEX"),i.FOG&&f.addFallback(d,"FOG"),i.SPECULARAA&&f.addFallback(d,"SPECULARAA"),i.POINTSIZE&&f.addFallback(d,"POINTSIZE"),i.LOGARITHMICDEPTH&&f.addFallback(d,"LOGARITHMICDEPTH"),i.PARALLAX&&f.addFallback(d,"PARALLAX"),i.PARALLAX_RHS&&f.addFallback(d,"PARALLAX_RHS"),i.PARALLAXOCCLUSION&&f.addFallback(d++,"PARALLAXOCCLUSION"),i.ENVIRONMENTBRDF&&f.addFallback(d++,"ENVIRONMENTBRDF"),i.TANGENT&&f.addFallback(d++,"TANGENT"),d=Bp(i,f,this._maxSimultaneousLights,d),i.SPECULARTERM&&f.addFallback(d++,"SPECULARTERM"),i.USESPHERICALFROMREFLECTIONMAP&&f.addFallback(d++,"USESPHERICALFROMREFLECTIONMAP"),i.USEIRRADIANCEMAP&&f.addFallback(d++,"USEIRRADIANCEMAP"),i.NORMAL&&f.addFallback(d++,"NORMAL"),i.VERTEXCOLOR&&f.addFallback(d++,"VERTEXCOLOR"),i.MORPHTARGETS&&f.addFallback(d++,"MORPHTARGETS"),i.MULTIVIEW&&f.addFallback(0,"MULTIVIEW");let u=[D.PositionKind];i.NORMAL&&u.push(D.NormalKind),i.TANGENT&&u.push(D.TangentKind);for(let T=1;T<=6;++T)i["UV"+T]&&u.push(`uv${T===1?"":T}`);i.VERTEXCOLOR&&u.push(D.ColorKind),wp(u,e,i,f),Fp(u,i),ih(u,e,i),Op(u,e,i);let h="openpbr",m=["world","view","viewProjection","projection","vEyePosition","inverseProjection","renderTargetSize","vLightsType","visibility","vFogInfos","vFogColor","pointSize","mBones","normalMatrix","vLightingIntensity","logarithmicDepthConstant","vTangentSpaceParams","boneTextureInfo","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices","cameraInfo","backgroundRefractionMatrix","vBackgroundRefractionInfos"];for(let T in this._uniformsList)m.push(T);let g=["environmentBrdfSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler","areaLightsLTC1Sampler","areaLightsLTC2Sampler"];i.FUZZENVIRONMENTBRDF&&g.push("environmentFuzzBrdfSampler"),i.REFRACTED_BACKGROUND&&g.push("backgroundRefractionSampler"),(i.ANISOTROPIC||i.FUZZ||i.REFRACTED_BACKGROUND||i.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING)&&g.push("blueNoiseSampler"),i.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING&&(g.push("sceneIrradianceSampler"),g.push("sceneDepthSampler"));for(let T in this._samplersList){let A=this._samplersList[T];g.push(A.samplerName),m.push(A.samplerInfoName),m.push(A.samplerMatrixName)}md(m,g,!0);let p=["Material","Scene","Mesh"],_={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:i.NUM_MORPH_INFLUENCERS};if(this._eventInfo.fallbacks=f,this._eventInfo.fallbackRank=d,this._eventInfo.defines=i,this._eventInfo.uniforms=m,this._eventInfo.attributes=u,this._eventInfo.samplers=g,this._eventInfo.uniformBuffersNames=p,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(128,this._eventInfo),us.AddUniformsAndSamplers(m,g),fa.AddUniforms(m),fa.AddSamplers(g),ns(m),this._useVertexPulling){let T=t==null?void 0:t.geometry;T&&(this._vertexPullingMetadata=Ad(T),this._vertexPullingMetadata&&this._vertexPullingMetadata.forEach((A,R)=>{m.push(`vp_${R}_info`)}))}else this._vertexPullingMetadata=null;Zt&&(Zt.PrepareUniforms(m,i),Zt.PrepareSamplers(g,i)),Yp({uniformsNames:m,uniformBuffersNames:p,samplers:g,defines:i,maxSimultaneousLights:this._maxSimultaneousLights,shaderLanguage:this._shaderLanguage});let v={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,m,p,g,i,u,v));let E=i.toString(),S=c.createEffect(h,{attributes:u,uniformsNames:m,uniformBuffersNames:p,samplers:g,defines:E,fallbacks:f,onCompiled:r,onError:s,indexParameters:_,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:i.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this.shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(k7(),G7)),Promise.resolve().then(()=>(UK(),BK))]):await Promise.all([Promise.resolve().then(()=>(jK(),KK)),Promise.resolve().then(()=>(Yj(),Xj))]),this._shadersLoaded=!0}},c);return this._eventInfo.customCode=void 0,S}_prepareDefines(e,t,i,r=null,s=null){var d;let a=t.hasThinInstances,o=this.getScene(),l=o.getEngine();Gp(o,e,i,!0,this._maxSimultaneousLights,this._disableLighting),i._needNormals=!0,Wp(o,i);let c=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Xp(o,i,this.canRenderToMRT&&!c),Hp(o,i,c),us.PrepareDefines(l.currentRenderPassId,e,i),i._areTexturesDirty){i._needUVs=!1;for(let u=1;u<=6;++u)i["MAINUV"+u]=!1;if(o.texturesEnabled){for(let m in this._samplersList){let g=this._samplersList[m];g.value?(fi(g.value,i,g.textureDefine),i[g.textureDefine+"_GAMMA"]=g.value.gammaSpace):i[g.textureDefine]=!1}let u=this._getRadianceTexture(),h=this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||l.getCaps().maxVaryingVectors<=8||this._baseDiffuseRoughnessTexture!=null;if(hd(o,u,i,this.realTimeFiltering,this.realTimeFilteringQuality,!h),this._baseMetalnessTexture&&(i.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed),i.SPECULAR_WEIGHT_IN_ALPHA=this._useSpecularWeightFromAlpha,i.SPECULAR_WEIGHT_FROM_SPECULAR_COLOR_TEXTURE=this._useSpecularWeightFromSpecularColorTexture,i.SPECULAR_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE=this._useSpecularRoughnessAnisotropyFromTangentTexture,i.COAT_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE=this._useCoatRoughnessAnisotropyFromTangentTexture,i.COAT_ROUGHNESS_FROM_GREEN_CHANNEL=this._useCoatRoughnessFromGreenChannel,i.SPECULAR_ROUGHNESS_FROM_METALNESS_TEXTURE_GREEN=this._useRoughnessFromMetallicTextureGreen,i.FUZZ_ROUGHNESS_FROM_TEXTURE_ALPHA=this._useFuzzRoughnessFromTextureAlpha,i.BASE_METALNESS_FROM_METALNESS_TEXTURE_BLUE=this._useMetallicFromMetallicTextureBlue,i.THIN_FILM_THICKNESS_FROM_THIN_FILM_TEXTURE=this._useThinFilmThicknessFromTextureGreen,i.GEOMETRY_THICKNESS_FROM_GREEN_CHANNEL=this._useGeometryThicknessFromGreenChannel,this.geometryNormalTexture?(this._useParallax&&this.baseColorTexture&&fe.DiffuseTextureEnabled?(i.PARALLAX=!0,i.PARALLAX_RHS=o.useRightHandedSystem,i.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):i.PARALLAX=!1,i.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(i.PARALLAX=!1,i.PARALLAX_RHS=!1,i.PARALLAXOCCLUSION=!1,i.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&fe.ReflectionTextureEnabled?(i.ENVIRONMENTBRDF=!0,i.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(i.ENVIRONMENTBRDF=!1,i.ENVIRONMENTBRDF_RGBD=!1),this._environmentFuzzBRDFTexture?i.FUZZENVIRONMENTBRDF=!0:i.FUZZENVIRONMENTBRDF=!1,this.hasTransparency){i.REFRACTED_BACKGROUND=!!this._backgroundRefractionTexture&&fe.RefractionTextureEnabled,i.REFRACTION_HIGH_QUALITY_BLUR=this._refractionHighQualityBlur,i.REFRACTED_LIGHTS=!0;let m=this._getRadianceTexture();m?(i.REFRACTED_ENVIRONMENT=fe.RefractionTextureEnabled,i.REFRACTED_ENVIRONMENT_OPPOSITEZ=this.getScene().useRightHandedSystem?!m.invertZ:m.invertZ,i.REFRACTED_ENVIRONMENT_LOCAL_CUBE=m.isCube&&m.boundingBoxSize):i.REFRACTED_ENVIRONMENT=!1}else i.REFRACTED_BACKGROUND=!1,i.REFRACTED_LIGHTS=!1,i.REFRACTED_ENVIRONMENT=!1;this._shouldUseAlphaFromBaseColorTexture()?i.ALPHA_FROM_BASE_COLOR_TEXTURE=!0:i.ALPHA_FROM_BASE_COLOR_TEXTURE=!1}this._lightFalloff===Ae.LIGHTFALLOFF_STANDARD?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Ae.LIGHTFALLOFF_GLTF?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!0):(i.USEPHYSICALLIGHTFALLOFF=!0,i.USEGLTFLIGHTFALLOFF=!1),!this.backFaceCulling&&this._twoSidedLighting?i.TWOSIDEDLIGHTING=!0:i.TWOSIDEDLIGHTING=!1,i.MIRRORED=!!o._mirroredCameraPosition,i.SPECULARAA=l.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(i._areTexturesDirty||i._areMiscDirty)&&(i.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1===0?".":""}`,i.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,i.ALPHABLEND=this.needAlphaBlendingForMesh(e)),i._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(i),i.FORCENORMALFORWARD=this._forceNormalForward,i.RADIANCEOCCLUSION=this._useRadianceOcclusion,i.HORIZONOCCLUSION=this._useHorizonOcclusion,(this.specularRoughnessAnisotropy>0||this.coatRoughnessAnisotropy>0)&&n._noiseTextures[o.uniqueId]&&fe.ReflectionTextureEnabled?(i.ANISOTROPIC=!0,e.isVerticesDataPresent(D.TangentKind)||(i._needUVs=!0,i.MAINUV1=!0),this._useGltfStyleAnisotropy&&(i.USE_GLTF_STYLE_ANISOTROPY=!0),i.ANISOTROPIC_BASE=this.specularRoughnessAnisotropy>0,i.ANISOTROPIC_COAT=this.coatRoughnessAnisotropy>0):(i.ANISOTROPIC=!1,i.USE_GLTF_STYLE_ANISOTROPY=!1,i.ANISOTROPIC_BASE=!1,i.ANISOTROPIC_COAT=!1),i.THIN_FILM=this.thinFilmWeight>0,i.IRIDESCENCE=this.thinFilmWeight>0,i.DISPERSION=this.transmissionDispersionScale>0,i.SCATTERING=this.hasScattering;let f=[8,16,32];if(i.SSS_SAMPLE_COUNT=(d=f[this._sssQuality])!=null?d:16,i.TRANSMISSION_SLAB=this.transmissionWeight>0,i.TRANSMISSION_SLAB_VOLUME=this.transmissionWeight>0&&this.transmissionDepth>0,i.SUBSURFACE_SLAB=this.subsurfaceWeight>0,!i.PREPASS&&(i.SUBSURFACE_SLAB||i.TRANSMISSION_SLAB_VOLUME)){let u=!1;if(!this.sssIrradianceTexture&&o.geometryBufferRenderer){let h=o.geometryBufferRenderer.getTextureIndex(ws.IRRADIANCE_TEXTURE_TYPE);this.sssIrradianceTexture=o.geometryBufferRenderer.getGBuffer().textures[h],u=!0}if(!this.sssDepthTexture&&o.geometryBufferRenderer){let h=o.geometryBufferRenderer.getTextureIndex(ws.SCREENSPACE_DEPTH_TEXTURE_TYPE);this.sssDepthTexture=o.geometryBufferRenderer.getGBuffer().textures[h],u=!0}this.sssIrradianceTexture&&this.sssDepthTexture&&(i.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING=!0,u&&(i.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING_GBUFFER=!0))}i.FUZZ=this.fuzzWeight>0&&fe.ReflectionTextureEnabled,i.GEOMETRY_THIN_WALLED=this.geometryThinWalled!=0,i.FUZZ?(e.isVerticesDataPresent(D.TangentKind)||(i._needUVs=!0,i.MAINUV1=!0),this._environmentFuzzBRDFTexture=xw(this.getScene()),i.FUZZ_IBL_SAMPLES=this.fuzzSampleNumber):(this._environmentFuzzBRDFTexture=null,i.FUZZENVIRONMENTBRDF=!1,i.FUZZ_IBL_SAMPLES=0),i._areMiscDirty&&(Up(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this.needAlphaTestingForMesh(e),i,this._applyDecalMapAfterDetailMap,this._useVertexPulling,t,this._isVertexOutputInvariant),i.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(D.NormalKind),i.DEBUGMODE=this._debugMode),kp(o,l,this,i,!!r,s,a),this._eventInfo.defines=i,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),zp(e,i,!0,!0,!0,this._transparencyMode!==Ae.MATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}};Ne.SSS_QUALITY_LOW=0;Ne.SSS_QUALITY_MEDIUM=1;Ne.SSS_QUALITY_HIGH=2;Ne._noiseTextures={};Ne.ForceGLSL=!1;P([vt("_markAllSubMeshesAsTexturesDirty","baseWeight")],Ne.prototype,"_baseWeight",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","baseWeightTexture")],Ne.prototype,"_baseWeightTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","baseColor")],Ne.prototype,"_baseColor",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","baseColorTexture")],Ne.prototype,"_baseColorTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","baseDiffuseRoughness")],Ne.prototype,"_baseDiffuseRoughness",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","baseDiffuseRoughnessTexture")],Ne.prototype,"_baseDiffuseRoughnessTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","baseMetalness")],Ne.prototype,"_baseMetalness",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","baseMetalnessTexture")],Ne.prototype,"_baseMetalnessTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","specularWeight")],Ne.prototype,"_specularWeight",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","specularWeightTexture")],Ne.prototype,"_specularWeightTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","specularColor")],Ne.prototype,"_specularColor",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","specularColorTexture")],Ne.prototype,"_specularColorTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","specularRoughness")],Ne.prototype,"_specularRoughness",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","specularRoughnessTexture")],Ne.prototype,"_specularRoughnessTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","specularRoughnessAnisotropy")],Ne.prototype,"_specularRoughnessAnisotropy",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","specularRoughnessAnisotropyTexture")],Ne.prototype,"_specularRoughnessAnisotropyTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","specularIor")],Ne.prototype,"_specularIor",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","transmissionWeight")],Ne.prototype,"_transmissionWeight",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","transmissionWeightTexture")],Ne.prototype,"_transmissionWeightTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","transmissionColor")],Ne.prototype,"_transmissionColor",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","transmissionColorTexture")],Ne.prototype,"_transmissionColorTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","transmissionDepth")],Ne.prototype,"_transmissionDepth",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","transmissionDepthTexture")],Ne.prototype,"_transmissionDepthTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","transmissionScatter")],Ne.prototype,"_transmissionScatter",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","transmissionScatterTexture")],Ne.prototype,"_transmissionScatterTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","transmissionScatterAnisotropy")],Ne.prototype,"_transmissionScatterAnisotropy",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","transmissionDispersionScale")],Ne.prototype,"_transmissionDispersionScale",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","transmissionDispersionScaleTexture")],Ne.prototype,"_transmissionDispersionScaleTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","transmissionDispersionAbbeNumber")],Ne.prototype,"_transmissionDispersionAbbeNumber",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","subsurfaceWeight")],Ne.prototype,"_subsurfaceWeight",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","subsurfaceWeightTexture")],Ne.prototype,"_subsurfaceWeightTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","subsurfaceColor")],Ne.prototype,"_subsurfaceColor",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","subsurfaceColorTexture")],Ne.prototype,"_subsurfaceColorTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","subsurfaceRadius")],Ne.prototype,"_subsurfaceRadius",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","subsurfaceRadiusScale")],Ne.prototype,"_subsurfaceRadiusScale",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","subsurfaceRadiusScaleTexture")],Ne.prototype,"_subsurfaceRadiusScaleTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","subsurfaceScatterAnisotropy")],Ne.prototype,"_subsurfaceScatterAnisotropy",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","coatWeight")],Ne.prototype,"_coatWeight",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","coatWeightTexture")],Ne.prototype,"_coatWeightTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","coatColor")],Ne.prototype,"_coatColor",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","coatColorTexture")],Ne.prototype,"_coatColorTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","coatRoughness")],Ne.prototype,"_coatRoughness",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","coatRoughnessTexture")],Ne.prototype,"_coatRoughnessTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","coatRoughnessAnisotropy")],Ne.prototype,"_coatRoughnessAnisotropy",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","coatRoughnessAnisotropyTexture")],Ne.prototype,"_coatRoughnessAnisotropyTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","coatIor")],Ne.prototype,"_coatIor",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","coatDarkening")],Ne.prototype,"_coatDarkening",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","coatDarkeningTexture")],Ne.prototype,"_coatDarkeningTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","fuzzWeight")],Ne.prototype,"_fuzzWeight",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","fuzzWeightTexture")],Ne.prototype,"_fuzzWeightTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","fuzzColor")],Ne.prototype,"_fuzzColor",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","fuzzColorTexture")],Ne.prototype,"_fuzzColorTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","fuzzRoughness")],Ne.prototype,"_fuzzRoughness",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","fuzzRoughnessTexture")],Ne.prototype,"_fuzzRoughnessTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","geometryThinWalled")],Ne.prototype,"_geometryThinWalled",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","geometryNormalTexture")],Ne.prototype,"_geometryNormalTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","geometryTangent")],Ne.prototype,"_geometryTangent",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","geometryTangentTexture")],Ne.prototype,"_geometryTangentTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","geometryCoatNormalTexture")],Ne.prototype,"_geometryCoatNormalTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","geometryCoatTangent")],Ne.prototype,"_geometryCoatTangent",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","geometryCoatTangentTexture")],Ne.prototype,"_geometryCoatTangentTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","geometryOpacity")],Ne.prototype,"_geometryOpacity",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","geometryOpacityTexture")],Ne.prototype,"_geometryOpacityTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","geometryThickness")],Ne.prototype,"_geometryThickness",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","geometryThicknessTexture")],Ne.prototype,"_geometryThicknessTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","emissionLuminance")],Ne.prototype,"_emissionLuminance",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","emissionColor")],Ne.prototype,"_emissionColor",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","emissionColorTexture")],Ne.prototype,"_emissionColorTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","thinFilmWeight")],Ne.prototype,"_thinFilmWeight",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","thinFilmWeightTexture")],Ne.prototype,"_thinFilmWeightTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","thinFilmThickness")],Ne.prototype,"_thinFilmThickness",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","thinFilmThicknessMin")],Ne.prototype,"_thinFilmThicknessMin",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","thinFilmThicknessTexture")],Ne.prototype,"_thinFilmThicknessTexture",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","thinFilmIor")],Ne.prototype,"_thinFilmIor",void 0);P([vt("_markAllSubMeshesAsTexturesDirty","ambientOcclusionTexture")],Ne.prototype,"_ambientOcclusionTexture",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"directIntensity",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"environmentIntensity",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useSpecularWeightFromTextureAlpha",void 0);P([F(),le("_markAllSubMeshesAsTexturesAndMiscDirty")],Ne.prototype,"forceAlphaTest",void 0);P([F(),le("_markAllSubMeshesAsTexturesAndMiscDirty")],Ne.prototype,"alphaCutOff",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useAmbientInGrayScale",void 0);P([F()],Ne.prototype,"usePhysicalLightFalloff",null);P([F()],Ne.prototype,"useGLTFLightFalloff",null);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useObjectSpaceNormalMap",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useParallax",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useParallaxOcclusion",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"parallaxScaleBias",void 0);P([F(),le("_markAllSubMeshesAsLightsDirty")],Ne.prototype,"disableLighting",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"forceIrradianceInFragment",void 0);P([F(),le("_markAllSubMeshesAsLightsDirty")],Ne.prototype,"maxSimultaneousLights",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"invertNormalMapX",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"invertNormalMapY",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"twoSidedLighting",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useAlphaFresnel",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useLinearAlphaFresnel",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"environmentBRDFTexture",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"forceNormalForward",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"enableSpecularAntiAliasing",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useHorizonOcclusion",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useRadianceOcclusion",void 0);P([F(),le("_markAllSubMeshesAsMiscDirty")],Ne.prototype,"unlit",void 0);P([F(),le("_markAllSubMeshesAsMiscDirty")],Ne.prototype,"applyDecalMapAfterDetailMap",void 0);P([le("_markAllSubMeshesAsMiscDirty")],Ne.prototype,"debugMode",void 0);P([F()],Ne.prototype,"transparencyMode",null);zt("BABYLON.OpenPBRMaterial",Ne)});var Zj={};Be(Zj,{OpenPBRMaterialLoadingAdapter:()=>TF});var TF,qj=y(()=>{$t();TF=class{constructor(e){this._diffuseTransmissionTint=he.White(),this._diffuseTransmissionTintTexture=null,this._material=e}get material(){return this._material}get isUnlit(){return this._material.unlit}set isUnlit(e){this._material.unlit=e}set backFaceCulling(e){this._material.backFaceCulling=e}get backFaceCulling(){return this._material.backFaceCulling}set twoSidedLighting(e){this._material.twoSidedLighting=e}get twoSidedLighting(){return this._material.twoSidedLighting}set alphaCutOff(e){}get alphaCutOff(){return .5}set useAlphaFromBaseColorTexture(e){this._material._useAlphaFromBaseColorTexture=e}get useAlphaFromBaseColorTexture(){return!1}get transparencyAsAlphaCoverage(){return!1}set transparencyAsAlphaCoverage(e){}set baseColor(e){this._material.baseColor=e}get baseColor(){return this._material.baseColor}set baseColorTexture(e){this._material.baseColorTexture=e}get baseColorTexture(){return this._material.baseColorTexture}set baseDiffuseRoughness(e){this._material.baseDiffuseRoughness=e}get baseDiffuseRoughness(){return this._material.baseDiffuseRoughness}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.baseMetalness=e}get baseMetalness(){return this._material.baseMetalness}set baseMetalnessTexture(e){this._material.baseMetalnessTexture=e}get baseMetalnessTexture(){return this._material.baseMetalnessTexture}set useRoughnessFromMetallicTextureGreen(e){this._material._useRoughnessFromMetallicTextureGreen=e}set useMetallicFromMetallicTextureBlue(e){this._material._useMetallicFromMetallicTextureBlue=e}enableSpecularEdgeColor(e=!1){}set specularWeight(e){this._material.specularWeight=e}get specularWeight(){return this._material.specularWeight}set specularWeightTexture(e){this._material.specularColorTexture===e?(this._material.specularWeightTexture=null,this._material._useSpecularWeightFromSpecularColorTexture=!0,this._material._useSpecularWeightFromAlpha=!0):this._material.specularWeightTexture=e}get specularWeightTexture(){return this._material.specularWeightTexture}set specularColor(e){this._material.specularColor=e}get specularColor(){return this._material.specularColor}set specularColorTexture(e){this._material.specularColorTexture=e,this._material.specularWeightTexture===this._material.specularColorTexture&&(this._material.specularWeightTexture=null,this._material._useSpecularWeightFromSpecularColorTexture=!0,this._material._useSpecularWeightFromAlpha=!0)}get specularColorTexture(){return this._material.specularColorTexture}set specularRoughness(e){this._material.specularRoughness=e}get specularRoughness(){return this._material.specularRoughness}set specularRoughnessTexture(e){this._material.specularRoughnessTexture=e}get specularRoughnessTexture(){return this._material.specularRoughnessTexture}set specularIor(e){this._material.specularIor=e}get specularIor(){return this._material.specularIor}set emissionColor(e){this._material.emissionColor=e}get emissionColor(){return this._material.emissionColor}set emissionLuminance(e){this._material.emissionLuminance=e}get emissionLuminance(){return this._material.emissionLuminance}set emissionColorTexture(e){this._material.emissionColorTexture=e}get emissionColorTexture(){return this._material.emissionColorTexture}set ambientOcclusionTexture(e){this._material.ambientOcclusionTexture=e}get ambientOcclusionTexture(){return this._material.ambientOcclusionTexture}set ambientOcclusionTextureStrength(e){let t=this._material.ambientOcclusionTexture;t&&(t.level=e)}get ambientOcclusionTextureStrength(){var t;let e=this._material.ambientOcclusionTexture;return(t=e==null?void 0:e.level)!=null?t:1}configureCoat(){}set coatWeight(e){this._material.coatWeight=e}get coatWeight(){return this._material.coatWeight}set coatWeightTexture(e){this._material.coatWeightTexture=e}get coatWeightTexture(){return this._material.coatWeightTexture}set coatColor(e){this._material.coatColor=e}set coatColorTexture(e){this._material.coatColorTexture=e}set coatRoughness(e){this._material.coatRoughness=e}get coatRoughness(){return this._material.coatRoughness}set coatRoughnessTexture(e){this._material.coatRoughnessTexture=e,e&&(this._material._useCoatRoughnessFromGreenChannel=!0)}get coatRoughnessTexture(){return this._material.coatRoughnessTexture}set coatIor(e){this._material.coatIor=e}set coatDarkening(e){this._material.coatDarkening=e}set coatDarkeningTexture(e){this._material.coatDarkeningTexture=e}set coatRoughnessAnisotropy(e){this._material.coatRoughnessAnisotropy=e}get coatRoughnessAnisotropy(){return this._material.coatRoughnessAnisotropy}set geometryCoatTangentAngle(e){this._material.geometryCoatTangentAngle=e}set geometryCoatTangentTexture(e){this._material.geometryCoatTangentTexture=e,e&&(this._material._useCoatRoughnessAnisotropyFromTangentTexture=!0)}get geometryCoatTangentTexture(){return this._material.geometryCoatTangentTexture}configureTransmission(){this._material.geometryThinWalled=1,this._material.transmissionDepth=0}set transmissionWeight(e){this._material.transmissionWeight=e}set transmissionWeightTexture(e){this._material.transmissionWeightTexture=e}get transmissionWeight(){return this._material.transmissionWeight}set transmissionScatter(e){this._material.transmissionScatter=e}get transmissionScatter(){return this._material.transmissionScatter}set transmissionScatterTexture(e){this._material.transmissionScatterTexture=e}get transmissionScatterTexture(){return this._material.transmissionScatterTexture}set transmissionScatterAnisotropy(e){this._material.transmissionScatterAnisotropy=e}set transmissionDispersionAbbeNumber(e){this._material.transmissionDispersionAbbeNumber=e}set transmissionDispersionScale(e){this._material.transmissionDispersionScale=e}set transmissionDepth(e){e!==Number.MAX_VALUE||this._material.transmissionDepth!==0?this._material.transmissionDepth=e:this._material.transmissionDepth=0}get transmissionDepth(){return this._material.transmissionDepth}set transmissionColor(e){e.equals(he.White())||(this._material.transmissionColor=e)}get transmissionColor(){return this._material.transmissionColor}get refractionBackgroundTexture(){return this._material.backgroundRefractionTexture}set refractionBackgroundTexture(e){this._material.backgroundRefractionTexture=e}configureVolume(){this._material.geometryThinWalled=0}set geometryThinWalled(e){this._material.geometryThinWalled=e?1:0}get geometryThinWalled(){return!!this._material.geometryThinWalled}set volumeThicknessTexture(e){this._material.geometryThicknessTexture=e,this._material._useGeometryThicknessFromGreenChannel=!0}set volumeThickness(e){this._material.geometryThickness=e}configureSubsurface(){this._material.geometryThinWalled=1,this._material.subsurfaceScatterAnisotropy=1}set subsurfaceWeight(e){this._material.subsurfaceWeight=e}get subsurfaceWeight(){return this._material.subsurfaceWeight}set subsurfaceWeightTexture(e){this._material.subsurfaceWeightTexture=e}set subsurfaceColor(e){this._material.subsurfaceColor=e}set subsurfaceColorTexture(e){this._material.subsurfaceColorTexture=e}set diffuseTransmissionTint(e){this._diffuseTransmissionTint=e}get diffuseTransmissionTint(){return this._diffuseTransmissionTint}set diffuseTransmissionTintTexture(e){this._diffuseTransmissionTintTexture=e}get subsurfaceRadius(){return this._material.subsurfaceRadius}set subsurfaceRadius(e){this._material.subsurfaceRadius=e}get subsurfaceRadiusScale(){return this._material.subsurfaceRadiusScale}set subsurfaceRadiusScale(e){this._material.subsurfaceRadiusScale=e}set subsurfaceScatterAnisotropy(e){this._material.subsurfaceScatterAnisotropy=e}isTranslucent(){return this.transmissionWeight>0||this.subsurfaceWeight>0}configureFuzz(){}set fuzzWeight(e){this._material.fuzzWeight=e}set fuzzWeightTexture(e){this._material.fuzzWeightTexture=e}set fuzzColor(e){this._material.fuzzColor=e}set fuzzColorTexture(e){this._material.fuzzColorTexture=e}set fuzzRoughness(e){this._material.fuzzRoughness=e}set fuzzRoughnessTexture(e){this._material.fuzzRoughnessTexture=e,this._material._useFuzzRoughnessFromTextureAlpha=!0}set specularRoughnessAnisotropy(e){this._material.specularRoughnessAnisotropy=e}get specularRoughnessAnisotropy(){return this._material.specularRoughnessAnisotropy}set geometryTangentAngle(e){this._material.geometryTangentAngle=e}set geometryTangentTexture(e){this._material.geometryTangentTexture=e,this._material._useSpecularRoughnessAnisotropyFromTangentTexture=!0}get geometryTangentTexture(){return this._material.geometryTangentTexture}configureGltfStyleAnisotropy(e=!0){this._material._useGltfStyleAnisotropy=e}set thinFilmWeight(e){this._material.thinFilmWeight=e}set thinFilmIor(e){this._material.thinFilmIor=e}set thinFilmThicknessMinimum(e){this._material.thinFilmThicknessMin=e/1e3}set thinFilmThicknessMaximum(e){this._material.thinFilmThickness=e/1e3}set thinFilmWeightTexture(e){this._material.thinFilmWeightTexture=e}set thinFilmThicknessTexture(e){this._material.thinFilmThicknessTexture=e,this._material._useThinFilmThicknessFromTextureGreen=!0}set unlit(e){this._material.unlit=e}set geometryOpacity(e){this._material.geometryOpacity=e}get geometryOpacity(){return this._material.geometryOpacity}set geometryNormalTexture(e){this._material.geometryNormalTexture=e}get geometryNormalTexture(){return this._material.geometryNormalTexture}setNormalMapInversions(e,t){}set geometryCoatNormalTexture(e){this._material.geometryCoatNormalTexture=e}get geometryCoatNormalTexture(){return this._material.geometryCoatNormalTexture}set geometryCoatNormalTextureScale(e){this._material.geometryCoatNormalTexture&&(this._material.geometryCoatNormalTexture.level=e)}finalize(){(this._diffuseTransmissionTint&&!this._diffuseTransmissionTint.equals(he.White())||this._diffuseTransmissionTintTexture)&&(this._material.geometryThinWalled?(this.subsurfaceColor=this._diffuseTransmissionTint,this.subsurfaceColorTexture=this._diffuseTransmissionTintTexture):this._material.coatWeight==0&&(!this.baseColor.equals(he.White())||this.baseColorTexture)&&(this._material.coatWeight=this.subsurfaceWeight,this._material.coatWeightTexture=this.subsurfaceWeightTexture,this._material.coatColor=this._diffuseTransmissionTint,this._material.coatColorTexture=this._diffuseTransmissionTintTexture,this._material.coatIor=this._material.specularIor,this._material.coatDarkening=0,this._material.coatRoughness=this._material.specularRoughness,this._material.coatRoughnessTexture=this._material.specularRoughnessTexture,this._material.specularRoughness=1,this._material.specularRoughnessTexture=null)),this.transmissionWeight>0&&(this._material.geometryThinWalled||this._material.transmissionDepth===0?(this._material.transmissionColor=this._material.baseColor,this._material.transmissionColorTexture=this._material.baseColorTexture):this._material.coatWeight==0&&(!this.baseColor.equals(he.White())||this.baseColorTexture!==null)&&(this._material.coatWeight=this.transmissionWeight,this._material.coatWeightTexture=this.transmissionWeightTexture,this._material.coatColor=this.baseColor,this._material.coatColorTexture=this.baseColorTexture,this._material.coatIor=this._material.specularIor,this._material.coatDarkening=0,this._material.coatRoughness=this._material.specularRoughness,this._material.coatRoughnessTexture=this._material.specularRoughnessTexture))}}});var AF,Vr,Qj=y(()=>{jt();Yt();uo();Md();AF=class extends wr{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1,this.MIX_IBL_RADIANCE_WITH_IRRADIANCE=!0,this.LEGACY_SPECULAR_ENERGY_CONSERVATION=!1,this.BASE_DIFFUSE_MODEL=0,this.DIELECTRIC_SPECULAR_MODEL=0,this.CONDUCTOR_SPECULAR_MODEL=0}},Vr=class n extends qr{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRBRDF",90,new AF,t),this._useEnergyConservation=n.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=n.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=n.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=n.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=n.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=n.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=n.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=n.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._mixIblRadianceWithIrradiance=n.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE,this.mixIblRadianceWithIrradiance=n.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE,this._useLegacySpecularEnergyConservation=n.DEFAULT_USE_LEGACY_SPECULAR_ENERGY_CONSERVATION,this.useLegacySpecularEnergyConservation=n.DEFAULT_USE_LEGACY_SPECULAR_ENERGY_CONSERVATION,this._baseDiffuseModel=n.DEFAULT_DIFFUSE_MODEL,this.baseDiffuseModel=n.DEFAULT_DIFFUSE_MODEL,this._dielectricSpecularModel=n.DEFAULT_DIELECTRIC_SPECULAR_MODEL,this.dielectricSpecularModel=n.DEFAULT_DIELECTRIC_SPECULAR_MODEL,this._conductorSpecularModel=n.DEFAULT_CONDUCTOR_SPECULAR_MODEL,this.conductorSpecularModel=n.DEFAULT_CONDUCTOR_SPECULAR_MODEL,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation,e.MIX_IBL_RADIANCE_WITH_IRRADIANCE=this._mixIblRadianceWithIrradiance&&!this._material._disableLighting,e.LEGACY_SPECULAR_ENERGY_CONSERVATION=this._useLegacySpecularEnergyConservation,e.BASE_DIFFUSE_MODEL=this._baseDiffuseModel,e.DIELECTRIC_SPECULAR_MODEL=this._dielectricSpecularModel,e.CONDUCTOR_SPECULAR_MODEL=this._conductorSpecularModel}getClassName(){return"PBRBRDFConfiguration"}};Vr.DEFAULT_USE_ENERGY_CONSERVATION=!0;Vr.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0;Vr.DEFAULT_USE_SPHERICAL_HARMONICS=!0;Vr.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0;Vr.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE=!0;Vr.DEFAULT_USE_LEGACY_SPECULAR_ENERGY_CONSERVATION=!0;Vr.DEFAULT_DIFFUSE_MODEL=0;Vr.DEFAULT_DIELECTRIC_SPECULAR_MODEL=0;Vr.DEFAULT_CONDUCTOR_SPECULAR_MODEL=0;P([F(),le("_markAllSubMeshesAsMiscDirty")],Vr.prototype,"useEnergyConservation",void 0);P([F(),le("_markAllSubMeshesAsMiscDirty")],Vr.prototype,"useSmithVisibilityHeightCorrelated",void 0);P([F(),le("_markAllSubMeshesAsMiscDirty")],Vr.prototype,"useSphericalHarmonics",void 0);P([F(),le("_markAllSubMeshesAsMiscDirty")],Vr.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);P([F(),le("_markAllSubMeshesAsMiscDirty")],Vr.prototype,"mixIblRadianceWithIrradiance",void 0);P([F(),le("_markAllSubMeshesAsMiscDirty")],Vr.prototype,"useLegacySpecularEnergyConservation",void 0);P([F("baseDiffuseModel"),le("_markAllSubMeshesAsMiscDirty")],Vr.prototype,"baseDiffuseModel",void 0);P([F("dielectricSpecularModel"),le("_markAllSubMeshesAsMiscDirty")],Vr.prototype,"dielectricSpecularModel",void 0);P([F("conductorSpecularModel"),le("_markAllSubMeshesAsMiscDirty")],Vr.prototype,"conductorSpecularModel",void 0)});var xF,An,$j=y(()=>{jt();Yt();$t();co();Md();uo();os();xF=class extends wr{constructor(){super(...arguments),this.CLEARCOAT=!1,this.CLEARCOAT_DEFAULTIOR=!1,this.CLEARCOAT_TEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this.CLEARCOAT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,this.CLEARCOAT_BUMP=!1,this.CLEARCOAT_BUMPDIRECTUV=0,this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,this.CLEARCOAT_REMAP_F0=!1,this.CLEARCOAT_TINT=!1,this.CLEARCOAT_TINT_TEXTURE=!1,this.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TINT_GAMMATEXTURE=!1}},An=class n extends qr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRClearCoat",100,new xF,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=n._DefaultIndexOfRefraction,this.indexOfRefraction=n._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._textureRoughness=null,this.textureRoughness=null,this._remapF0OnInterfaceChange=!0,this.remapF0OnInterfaceChange=!0,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=he.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;let r=this._material._disableBumpMap;return!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&fe.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&fe.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking()||i.getCaps().standardDerivatives&&this._bumpTexture&&fe.ClearCoatBumpTextureEnabled&&!r&&!this._bumpTexture.isReady()||this._isTintEnabled&&this._tintTexture&&fe.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking()))}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&fe.ClearCoatTextureEnabled?fi(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&fe.ClearCoatTextureEnabled?fi(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&fe.ClearCoatBumpTextureEnabled?fi(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===n._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&fe.ClearCoatTintTextureEnabled?(fi(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,i,r){var f,d,u,h,m,g,p,_;if(!this._isEnabled)return;let s=r.materialDefines,a=this._material.isFrozen,o=this._material._disableBumpMap,l=this._material._invertNormalMapX,c=this._material._invertNormalMapY;if(!e.useUbo||!a||!e.isSync){(this._texture||this._textureRoughness)&&fe.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",(d=(f=this._texture)==null?void 0:f.coordinatesIndex)!=null?d:0,(h=(u=this._texture)==null?void 0:u.level)!=null?h:0,(g=(m=this._textureRoughness)==null?void 0:m.coordinatesIndex)!=null?g:0,(_=(p=this._textureRoughness)==null?void 0:p.level)!=null?_:0),this._texture&&di(this._texture,e,"clearCoat"),this._textureRoughness&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&di(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&fe.ClearCoatTextureEnabled&&!o&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),di(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",l?1:-1,c?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",l?-1:1,c?-1:1)),this._tintTexture&&fe.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),di(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);let v=1-this._indexOfRefraction,E=1+this._indexOfRefraction,S=Math.pow(-v/E,2),T=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",S,T,v,E),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&fe.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&fe.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&fe.ClearCoatBumpTextureEnabled&&!o&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&fe.ClearCoatTintTextureEnabled&&e.setTexture("clearCoatTintSampler",this._tintTexture))}hasTexture(e){return this._texture===e||this._textureRoughness===e||this._bumpTexture===e||this._tintTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness),this._bumpTexture&&e.push(this._bumpTexture),this._tintTexture&&e.push(this._tintTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){var t,i,r,s;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose(),(r=this._bumpTexture)==null||r.dispose(),(s=this._tintTexture)==null||s.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}};An._DefaultIndexOfRefraction=1.5;P([F(),le("_markAllSubMeshesAsTexturesDirty")],An.prototype,"isEnabled",void 0);P([F()],An.prototype,"intensity",void 0);P([F()],An.prototype,"roughness",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],An.prototype,"indexOfRefraction",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],An.prototype,"texture",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],An.prototype,"useRoughnessFromMainTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],An.prototype,"textureRoughness",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],An.prototype,"remapF0OnInterfaceChange",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],An.prototype,"bumpTexture",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],An.prototype,"isTintEnabled",void 0);P([yr()],An.prototype,"tintColor",void 0);P([F()],An.prototype,"tintColorAtDistance",void 0);P([F()],An.prototype,"tintThickness",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],An.prototype,"tintTexture",void 0)});var RF,ua,Jj=y(()=>{jt();Yt();co();Md();uo();os();RF=class extends wr{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0}},ua=class n extends qr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRIridescence",110,new RF,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=n._DefaultMinimumThickness,this.maximumThickness=n._DefaultMaximumThickness,this.indexOfRefraction=n._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&fe.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._thicknessTexture&&fe.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&fe.IridescenceTextureEnabled?fi(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&fe.IridescenceTextureEnabled?fi(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t){var r,s,a,o,l,c,f,d;if(!this._isEnabled)return;let i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&((this._texture||this._thicknessTexture)&&fe.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",(s=(r=this._texture)==null?void 0:r.coordinatesIndex)!=null?s:0,(o=(a=this._texture)==null?void 0:a.level)!=null?o:0,(c=(l=this._thicknessTexture)==null?void 0:l.coordinatesIndex)!=null?c:0,(d=(f=this._thicknessTexture)==null?void 0:f.level)!=null?d:0),this._texture&&di(this._texture,e,"iridescence"),this._thicknessTexture&&di(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&fe.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&fe.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){var t,i;e&&((t=this._texture)==null||t.dispose(),(i=this._thicknessTexture)==null||i.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}};ua._DefaultMinimumThickness=100;ua._DefaultMaximumThickness=400;ua._DefaultIndexOfRefraction=1.3;P([F(),le("_markAllSubMeshesAsTexturesDirty")],ua.prototype,"isEnabled",void 0);P([F()],ua.prototype,"intensity",void 0);P([F()],ua.prototype,"minimumThickness",void 0);P([F()],ua.prototype,"maximumThickness",void 0);P([F()],ua.prototype,"indexOfRefraction",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],ua.prototype,"texture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],ua.prototype,"thicknessTexture",void 0)});var bF,df,eZ=y(()=>{jt();Yt();qi();He();co();Md();uo();os();bF=class extends wr{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}},df=class extends qr{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new bF,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new Fe(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&fe.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking()):!0}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(D.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&fe.AnisotropicTextureEnabled?fi(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;let i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&(this._texture&&fe.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),di(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&fe.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),e.legacy===void 0&&(this.legacy=!0)}};P([F(),le("_markAllSubMeshesAsTexturesDirty")],df.prototype,"isEnabled",void 0);P([F()],df.prototype,"intensity",void 0);P([mp()],df.prototype,"direction",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],df.prototype,"texture",void 0);P([F(),le("_markAllSubMeshesAsMiscDirty")],df.prototype,"legacy",void 0)});var MF,Ba,tZ=y(()=>{jt();Yt();$t();co();Md();uo();os();MF=class extends wr{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1}},Ba=class extends qr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"Sheen",120,new MF,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=he.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&fe.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&fe.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=this._roughness!==null,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&fe.SheenTextureEnabled?(fi(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&fe.SheenTextureEnabled?fi(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,r){var o,l,c,f,d,u,h,m;if(!this._isEnabled)return;let s=r.materialDefines,a=this._material.isFrozen;(!e.useUbo||!a||!e.isSync)&&((this._texture||this._textureRoughness)&&fe.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",(l=(o=this._texture)==null?void 0:o.coordinatesIndex)!=null?l:0,(f=(c=this._texture)==null?void 0:c.level)!=null?f:0,(u=(d=this._textureRoughness)==null?void 0:d.coordinatesIndex)!=null?u:0,(m=(h=this._textureRoughness)==null?void 0:h.level)!=null?m:0),this._texture&&di(this._texture,e,"sheen"),this._textureRoughness&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&di(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),this._roughness!==null&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&fe.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&fe.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){var t,i;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}};P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ba.prototype,"isEnabled",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ba.prototype,"linkSheenWithAlbedo",void 0);P([F()],Ba.prototype,"intensity",void 0);P([yr()],Ba.prototype,"color",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],Ba.prototype,"texture",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ba.prototype,"useRoughnessFromMainTexture",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ba.prototype,"roughness",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],Ba.prototype,"textureRoughness",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Ba.prototype,"albedoScaling",void 0)});var yF,Li,iZ=y(()=>{jt();Yt();$t();co();He();Md();uo();os();yF=class extends wr{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,this.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA=!1,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_USE_GLTF_TEXTURES=!1,this.SS_APPLY_ALBEDO_AFTER_SUBSURFACE=!1,this.SS_TRANSLUCENCY_LEGACY=!1}},Li=class n extends qr{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){e>=1?this._volumeIndexOfRefraction=e:this._volumeIndexOfRefraction=-1}get legacyTransluceny(){return this.legacyTranslucency}set legacyTransluceny(e){this.legacyTranslucency=e}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRSubSurface",130,new yF,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this._useAlbedoToTintRefraction=!1,this.useAlbedoToTintRefraction=!1,this._useAlbedoToTintTranslucency=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=he.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=he.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this.translucencyColor=null,this._translucencyColorTexture=null,this.translucencyColorTexture=null,this._useGltfStyleTextures=!0,this.useGltfStyleTextures=!0,this.applyAlbedoAfterSubSurface=n.DEFAULT_APPLY_ALBEDO_AFTERSUBSURFACE,this.legacyTranslucency=n.DEFAULT_LEGACY_TRANSLUCENCY,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&fe.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking()||this._refractionIntensityTexture&&fe.RefractionIntensityTextureEnabled&&!this._refractionIntensityTexture.isReadyOrNotBlocking()||this._translucencyColorTexture&&fe.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking()||this._translucencyIntensityTexture&&fe.TranslucencyIntensityTextureEnabled&&!this._translucencyIntensityTexture.isReadyOrNotBlocking())return!1;let i=this._getRefractionTexture(t);if(i&&fe.RefractionTextureEnabled&&!i.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA=!1,e.SS_APPLY_ALBEDO_AFTER_SUBSURFACE=!1;return}if(e._areTexturesDirty){if(e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_LEGACY=this.legacyTranslucency,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e.SS_APPLY_ALBEDO_AFTER_SUBSURFACE=this.applyAlbedoAfterSubSurface,e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&fe.ThicknessTextureEnabled&&fi(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&fe.RefractionIntensityTextureEnabled&&fi(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&fe.TranslucencyIntensityTextureEnabled&&fi(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&fe.TranslucencyColorTextureEnabled&&(fi(this._translucencyColorTexture,e,"SS_TRANSLUCENCYCOLOR_TEXTURE"),e.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA=this._translucencyColorTexture.gammaSpace)),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!==0,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._refractionIntensityTexture,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._translucencyIntensityTexture,this._isRefractionEnabled&&t.texturesEnabled){let i=this._getRefractionTexture(t);i&&fe.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this._useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this._useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(!(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled))if(this.maximumThickness===0&&this.minimumThickness===0)e.updateFloat2("vThicknessParam",0,0);else{r.getRenderingMesh().getWorldMatrix().decompose(ee.Vector3[0]);let s=Math.max(Math.abs(ee.Vector3[0].x),Math.abs(ee.Vector3[0].y),Math.abs(ee.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}}bindForSubMesh(e,t,i,r){var f;if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;let s=r.materialDefines,a=this._material.isFrozen,o=this._material.realTimeFiltering,l=s.LODBASEDMICROSFURACE,c=this._getRefractionTexture(t);if(!e.useUbo||!a||!e.isSync){if(this._thicknessTexture&&fe.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),di(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&fe.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),di(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&fe.TranslucencyColorTextureEnabled&&s.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),di(this._translucencyColorTexture,e,"translucencyColor")),this._translucencyIntensityTexture&&fe.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),di(this._translucencyIntensityTexture,e,"translucencyIntensity")),c&&fe.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",c.getRefractionTextureMatrix());let d=1;c.isCube||c.depth&&(d=c.depth);let u=c.getSize().width,h=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",c.level,1/h,d,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",u,c.lodGenerationScale,c.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",u,Math.log2(u)),c.boundingBoxSize){let m=c;e.updateVector3("vRefractionPosition",m.boundingBoxPosition),e.updateVector3("vRefractionSize",m.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateColor4("vTranslucencyColor",(f=this.translucencyColor)!=null?f:this.tintColor,0),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&fe.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&fe.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&fe.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&fe.TranslucencyColorTextureEnabled&&s.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),c&&fe.RefractionTextureEnabled&&(l?e.setTexture("refractionSampler",c):(e.setTexture("refractionSampler",c._lodTextureMid||c),e.setTexture("refractionSamplerLow",c._lodTextureLow||c),e.setTexture("refractionSamplerHigh",c._lodTextureHigh||c))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){fe.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e||this._refractionIntensityTexture===e||this._translucencyIntensityTexture===e||this._translucencyColorTexture===e}hasRenderTargetTextures(){return!!(fe.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture),this._refractionIntensityTexture&&e.push(this._refractionIntensityTexture),this._translucencyColorTexture&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&e.push(this._translucencyIntensityTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this._refractionIntensityTexture&&this._refractionIntensityTexture.animations&&this._refractionIntensityTexture.animations.length>0&&e.push(this._refractionIntensityTexture),this._translucencyColorTexture&&this._translucencyColorTexture.animations&&this._translucencyColorTexture.animations.length>0&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.animations&&this._translucencyIntensityTexture.animations.length>0&&e.push(this._translucencyIntensityTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._refractionIntensityTexture&&this._refractionIntensityTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.dispose(),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","translucencyColorSampler")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"},{name:"vTranslucencyColor",size:4,type:"vec4"},{name:"vTranslucencyColorInfos",size:2,type:"vec2"},{name:"translucencyColorMatrix",size:16,type:"mat4"}]}}};Li.DEFAULT_APPLY_ALBEDO_AFTERSUBSURFACE=!1;Li.DEFAULT_LEGACY_TRANSLUCENCY=!1;P([F(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"isRefractionEnabled",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"isTranslucencyEnabled",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"isDispersionEnabled",void 0);P([F(),le("_markScenePrePassDirty")],Li.prototype,"isScatteringEnabled",void 0);P([F()],Li.prototype,"_scatteringDiffusionProfileIndex",void 0);P([F()],Li.prototype,"refractionIntensity",void 0);P([F()],Li.prototype,"translucencyIntensity",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"useAlbedoToTintRefraction",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"useAlbedoToTintTranslucency",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"thicknessTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"refractionTexture",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"indexOfRefraction",void 0);P([F()],Li.prototype,"_volumeIndexOfRefraction",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"volumeIndexOfRefraction",null);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"invertRefractionY",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"linkRefractionWithTransparency",void 0);P([F()],Li.prototype,"minimumThickness",void 0);P([F()],Li.prototype,"maximumThickness",void 0);P([F()],Li.prototype,"useThicknessAsDepth",void 0);P([yr()],Li.prototype,"tintColor",void 0);P([F()],Li.prototype,"tintColorAtDistance",void 0);P([F()],Li.prototype,"dispersion",void 0);P([yr()],Li.prototype,"diffusionDistance",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"useMaskFromThicknessTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"refractionIntensityTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"translucencyIntensityTexture",void 0);P([yr()],Li.prototype,"translucencyColor",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"translucencyColorTexture",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],Li.prototype,"useGltfStyleTextures",void 0);P([F()],Li.prototype,"applyAlbedoAfterSubSurface",void 0);P([F()],Li.prototype,"legacyTranslucency",void 0)});var rZ,fEe,IF=y(()=>{k();sh();pE();rZ="pbrUboDeclaration",fEe=`uniform vAlbedoInfos: vec2f;uniform vBaseWeightInfos: vec2f;uniform vBaseDiffuseRoughnessInfos: vec2f;uniform vAmbientInfos: vec4f;uniform vOpacityInfos: vec2f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vReflectivityInfos: vec3f;uniform vMicroSurfaceSamplerInfos: vec2f;uniform vBumpInfos: vec3f;uniform albedoMatrix: mat4x4f;uniform baseWeightMatrix: mat4x4f;uniform baseDiffuseRoughnessMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform reflectivityMatrix: mat4x4f;uniform microSurfaceSamplerMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform vAlbedoColor: vec4f;uniform baseWeight: f32;uniform baseDiffuseRoughness: f32;uniform vLightingIntensity: vec4f;uniform pointSize: f32;uniform vReflectivityColor: vec4f;uniform vEmissiveColor: vec3f;uniform vAmbientColor: vec3f;uniform vDebugMode: vec2f;uniform vMetallicReflectanceFactors: vec4f;uniform vMetallicReflectanceInfos: vec2f;uniform metallicReflectanceMatrix: mat4x4f;uniform vReflectanceInfos: vec2f;uniform reflectanceMatrix: mat4x4f;uniform cameraInfo: vec4f;uniform vReflectionInfos: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vReflectionFilteringInfo: vec2f;uniform vReflectionDominantDirection: vec3f;uniform vReflectionColor: vec3f;uniform vSphericalL00: vec3f;uniform vSphericalL1_1: vec3f;uniform vSphericalL10: vec3f;uniform vSphericalL11: vec3f;uniform vSphericalL2_2: vec3f;uniform vSphericalL2_1: vec3f;uniform vSphericalL20: vec3f;uniform vSphericalL21: vec3f;uniform vSphericalL22: vec3f;uniform vSphericalX: vec3f;uniform vSphericalY: vec3f;uniform vSphericalZ: vec3f;uniform vSphericalXX_ZZ: vec3f;uniform vSphericalYY_ZZ: vec3f;uniform vSphericalZZ: vec3f;uniform vSphericalXY: vec3f;uniform vSphericalYZ: vec3f;uniform vSphericalZX: vec3f;
#define ADDITIONAL_UBO_DECLARATION
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;x.IncludesShadersStoreWGSL[rZ]||(x.IncludesShadersStoreWGSL[rZ]=fEe)});var sZ={};Be(sZ,{pbrVertexShaderWGSL:()=>dEe});var CF,nZ,dEe,aZ=y(()=>{k();IF();Ob();lg();ao();Eg();Wc();Hc();Rd();Nb();wb();vg();tN();Xc();eE();Fb();yd();Id();ah();Bb();Ub();Cd();Pd();Yc();Kc();jc();Vb();Gb();kb();zb();Zc();tE();Wb();iE();Hb();CF="pbrVertexShader",nZ=`#define PBR_VERTEX_SHADER
#include<pbrUboDeclaration>
#define CUSTOM_VERTEX_BEGIN
#ifndef USE_VERTEX_PULLING
attribute position: vec3f;
#ifdef NORMAL
attribute normal: vec3f;
#endif
#ifdef TANGENT
attribute tangent: vec4f;
#endif
#ifdef UV1
attribute uv: vec2f;
#endif
#include<uvAttributeDeclaration>[2..7]
#ifdef VERTEXCOLOR
attribute color: vec4f;
#endif
#endif
#include<mainUVVaryingDeclaration>[1..7]
#include<helperFunctions>
#include<pbrBRDFFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)
#include<samplerVertexDeclaration>(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)
#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)
#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)
#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)
#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)
#ifdef CLEARCOAT
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)
#endif
#ifdef IRIDESCENCE
#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)
#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)
#endif
#ifdef SHEEN
#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)
#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
#endif
#ifdef ANISOTROPIC
#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)
#endif
#ifdef SUBSURFACE
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor)
#endif
varying vPositionW: vec3f;
#if DEBUGMODE>0
varying vClipSpacePosition: vec4f;
#endif
#ifdef NORMAL
varying vNormalW: vec3f;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vEnvironmentIrradiance: vec3f;
#include<harmonicsFunctions>
#endif
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vColor: vec4f;
#endif
#include<bumpVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<lightVxUboDeclaration>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vPositionUVW: vec3f;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vDirectionW: vec3f;
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
varying vViewDepth: f32;
#endif
#include<logDepthDeclaration>
#include<vertexPullingDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef USE_VERTEX_PULLING
var positionUpdated: vec3f=vec3f(0.0);
#ifdef NORMAL
var normalUpdated: vec3f=vec3f(0.0);
#endif
#ifdef TANGENT
var tangentUpdated: vec4f=vec4f(0.0);
#endif
#ifdef UV1
var uvUpdated: vec2f=vec2f(0.0);
#endif
#ifdef UV2
var uv2Updated: vec2f=vec2f(0.0);
#endif
#ifdef VERTEXCOLOR
var colorUpdated: vec4f=vec4f(0.0);
#endif
#else
var positionUpdated: vec3f=vertexInputs.position;
#ifdef NORMAL
var normalUpdated: vec3f=vertexInputs.normal;
#endif
#ifdef TANGENT
var tangentUpdated: vec4f=vertexInputs.tangent;
#endif
#ifdef UV1
var uvUpdated: vec2f=vertexInputs.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=vertexInputs.uv2;
#endif
#ifdef VERTEXCOLOR
var colorUpdated: vec4f=vertexInputs.color;
#endif
#endif
#include<vertexPullingVertex>
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vertexOutputs.vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)
vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*vec4f(positionUpdated,1.0);
#endif
#ifdef USE_VERTEX_PULLING
#include<bonesVertex>(vertexInputs.matricesIndices,vp_matricesIndices,vertexInputs.matricesWeights,vp_matricesWeights,vertexInputs.matricesIndicesExtra,vp_matricesIndicesExtra,vertexInputs.matricesWeightsExtra,vp_matricesWeightsExtra)
#include<bakedVertexAnimation>(vertexInputs.matricesIndices,vp_matricesIndices,vertexInputs.matricesWeights,vp_matricesWeights,vertexInputs.matricesIndicesExtra,vp_matricesIndicesExtra,vertexInputs.matricesWeightsExtra,vp_matricesWeightsExtra)
#else
#include<bonesVertex>
#include<bakedVertexAnimation>
#endif
var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);vertexOutputs.vPositionW= worldPos.xyz;
#ifdef PREPASS
#include<prePassVertex>
#endif
#ifdef NORMAL
var normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated);
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
#if BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LAMBERT && BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LEGACY
var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-vertexOutputs.vPositionW);var NdotV: f32=max(dot(vertexOutputs.vNormalW,viewDirectionW),0.0);var roughNormal: vec3f=mix(vertexOutputs.vNormalW,viewDirectionW,(0.5*(1.0-NdotV))*uniforms.baseDiffuseRoughness);var reflectionVector: vec3f= (uniforms.reflectionMatrix* vec4f(roughNormal,0)).xyz;
#else
var reflectionVector: vec3f= (uniforms.reflectionMatrix* vec4f(vertexOutputs.vNormalW,0)).xyz;
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
vertexOutputs.vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;}
#else
vertexOutputs.position=scene.viewProjection*worldPos;
#endif
#if DEBUGMODE>0
vertexOutputs.vClipSpacePosition=vertexOutputs.position;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vertexOutputs.vDirectionW=normalize((finalWorld*vec4f(positionUpdated,0.0)).xyz);
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
#ifdef RIGHT_HANDED
vertexOutputs.vViewDepth=-(scene.view*worldPos).z;
#else
vertexOutputs.vViewDepth=(scene.view*worldPos).z;
#endif
#endif
#ifndef UV1
var uvUpdated: vec2f= vec2f(0.,0.);
#endif
#ifdef MAINUV1
vertexOutputs.vMainUV1=uvUpdated;
#endif
#ifndef UV2
var uv2Updated: vec2f= vec2f(0.,0.);
#endif
#ifdef MAINUV2
vertexOutputs.vMainUV2=uv2Updated;
#endif
#include<uvVariableDeclaration>[3..7]
#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight,_MATRIXNAME_,baseWeight,_INFONAME_,BaseWeightInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness,_MATRIXNAME_,baseDiffuseRoughness,_INFONAME_,BaseDiffuseRoughnessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)
#ifdef CLEARCOAT
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)
#endif
#ifdef IRIDESCENCE
#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)
#endif
#ifdef SHEEN
#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z)
#endif
#ifdef ANISOTROPIC
#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)
#endif
#ifdef SUBSURFACE
#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x)
#endif
#include<bumpVertex>
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#include<vertexColorMixing>
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`;x.ShadersStoreWGSL[CF]||(x.ShadersStoreWGSL[CF]=nZ);dEe={name:CF,shader:nZ}});var oZ,uEe,lZ=y(()=>{k();oZ="samplerFragmentAlternateDeclaration",uEe=`#ifdef _DEFINENAME_
#if _DEFINENAME_DIRECTUV==1
#define v_VARYINGNAME_UV vMainUV1
#elif _DEFINENAME_DIRECTUV==2
#define v_VARYINGNAME_UV vMainUV2
#elif _DEFINENAME_DIRECTUV==3
#define v_VARYINGNAME_UV vMainUV3
#elif _DEFINENAME_DIRECTUV==4
#define v_VARYINGNAME_UV vMainUV4
#elif _DEFINENAME_DIRECTUV==5
#define v_VARYINGNAME_UV vMainUV5
#elif _DEFINENAME_DIRECTUV==6
#define v_VARYINGNAME_UV vMainUV6
#else
varying v_VARYINGNAME_UV: vec2f;
#endif
#endif
`;x.IncludesShadersStoreWGSL[oZ]||(x.IncludesShadersStoreWGSL[oZ]=uEe)});var cZ,hEe,fZ=y(()=>{k();oh();lZ();iy();cZ="pbrFragmentSamplersDeclaration",hEe=`#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight,_SAMPLERNAME_,baseWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness,_SAMPLERNAME_,baseDiffuseRoughness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)
#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)
#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)
#ifdef CLEARCOAT
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)
#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)
var clearCoatRoughnessSamplerSampler: sampler;var clearCoatRoughnessSampler: texture_2d<f32>;
#endif
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)
#endif
#ifdef IRIDESCENCE
#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)
#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)
#endif
#ifdef SHEEN
#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)
#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)
var sheenRoughnessSamplerSampler: sampler;var sheenRoughnessSampler: texture_2d<f32>;
#endif
#endif
#ifdef ANISOTROPIC
#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)
#endif
#include<pbrFragmentReflectionDeclaration>
#ifdef ENVIRONMENTBRDF
var environmentBrdfSamplerSampler: sampler;var environmentBrdfSampler: texture_2d<f32>;
#endif
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
#ifdef SS_REFRACTIONMAP_3D
var refractionSamplerSampler: sampler;var refractionSampler: texture_cube<f32>;
#ifdef LODBASEDMICROSFURACE
#else
var refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_cube<f32>;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_cube<f32>;
#endif
#else
var refractionSamplerSampler: sampler;var refractionSampler: texture_2d<f32>;
#ifdef LODBASEDMICROSFURACE
#else
var refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_2d<f32>;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_2d<f32>;
#endif
#endif
#endif
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)
#endif
#ifdef IBL_CDF_FILTERING
var icdfSamplerSampler: sampler;var icdfSampler: texture_2d<f32>;
#endif
`;x.IncludesShadersStoreWGSL[cZ]||(x.IncludesShadersStoreWGSL[cZ]=hEe)});var dZ,mEe,uZ=y(()=>{k();sN();dZ="pbrBlockAlbedoOpacity",mEe=`struct albedoOpacityOutParams
{surfaceAlbedo: vec3f,
alpha: f32};
#define pbr_inline
fn albedoOpacityBlock(
vAlbedoColor: vec4f
#ifdef ALBEDO
,albedoTexture: vec4f
,albedoInfos: vec2f
#endif
,baseWeight: f32
#ifdef BASE_WEIGHT
,baseWeightTexture: vec4f
,vBaseWeightInfos: vec2f
#endif
#ifdef OPACITY
,opacityMap: vec4f
,vOpacityInfos: vec2f
#endif
#ifdef DETAIL
,detailColor: vec4f
,vDetailInfos: vec4f
#endif
#ifdef DECAL
,decalColor: vec4f
,vDecalInfos: vec4f
#endif
)->albedoOpacityOutParams
{var outParams: albedoOpacityOutParams;var surfaceAlbedo: vec3f=vAlbedoColor.rgb;var alpha: f32=vAlbedoColor.a;
#ifdef ALBEDO
#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)
alpha*=albedoTexture.a;
#endif
#ifdef GAMMAALBEDO
surfaceAlbedo*=toLinearSpaceVec3(albedoTexture.rgb);
#else
surfaceAlbedo*=albedoTexture.rgb;
#endif
surfaceAlbedo*=albedoInfos.y;
#endif
#ifndef DECAL_AFTER_DETAIL
#include<decalFragment>
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
surfaceAlbedo*=fragmentInputs.vColor.rgb;
#endif
#ifdef DETAIL
var detailAlbedo: f32=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo;
#endif
#ifdef DECAL_AFTER_DETAIL
#include<decalFragment>
#endif
#define CUSTOM_FRAGMENT_UPDATE_ALBEDO
surfaceAlbedo*=baseWeight;
#ifdef BASE_WEIGHT
surfaceAlbedo*=baseWeightTexture.r;
#endif
#ifdef OPACITY
#ifdef OPACITYRGB
alpha=getLuminance(opacityMap.rgb);
#else
alpha*=opacityMap.a;
#endif
alpha*=vOpacityInfos.y;
#endif
#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)
alpha*=fragmentInputs.vColor.a;
#endif
#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)
#ifdef ALPHATEST
#if DEBUGMODE != 88
if (alpha<ALPHATESTVALUE) {discard;}
#endif
#ifndef ALPHABLEND
alpha=1.0;
#endif
#endif
#endif
outParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;return outParams;}
`;x.IncludesShadersStoreWGSL[dZ]||(x.IncludesShadersStoreWGSL[dZ]=mEe)});var hZ,pEe,mZ=y(()=>{k();hZ="pbrBlockReflectivity",pEe=`struct reflectivityOutParams
{microSurface: f32,
roughness: f32,
diffuseRoughness: f32,
reflectanceF0: f32,
reflectanceF90: vec3f,
colorReflectanceF0: vec3f,
colorReflectanceF90: vec3f,
#ifdef METALLICWORKFLOW
surfaceAlbedo: vec3f,
metallic: f32,
specularWeight: f32,
dielectricColorF0: vec3f,
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
ambientOcclusionColor: vec3f,
#endif
#if DEBUGMODE>0
#ifdef METALLICWORKFLOW
#ifdef REFLECTIVITY
surfaceMetallicColorMap: vec4f,
#endif
metallicF0: vec3f,
#else
#ifdef REFLECTIVITY
surfaceReflectivityColorMap: vec4f,
#endif
#endif
#endif
};
#define pbr_inline
fn reflectivityBlock(
reflectivityColor: vec4f
#ifdef METALLICWORKFLOW
,surfaceAlbedo: vec3f
,metallicReflectanceFactors: vec4f
#endif
,baseDiffuseRoughness: f32
#ifdef BASE_DIFFUSE_ROUGHNESS
,baseDiffuseRoughnessTexture: f32
,baseDiffuseRoughnessInfos: vec2f
#endif
#ifdef REFLECTIVITY
,reflectivityInfos: vec3f
,surfaceMetallicOrReflectivityColorMap: vec4f
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
,ambientOcclusionColorIn: vec3f
#endif
#ifdef MICROSURFACEMAP
,microSurfaceTexel: vec4f
#endif
#ifdef DETAIL
,detailColor: vec4f
,vDetailInfos: vec4f
#endif
)->reflectivityOutParams
{var outParams: reflectivityOutParams;var microSurface: f32=reflectivityColor.a;var surfaceReflectivityColor: vec3f=reflectivityColor.rgb;
#ifdef METALLICWORKFLOW
var metallicRoughness: vec2f=surfaceReflectivityColor.rg;var ior: f32=surfaceReflectivityColor.b;
#ifdef REFLECTIVITY
#if DEBUGMODE>0
outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;
#endif
#ifdef AOSTOREINMETALMAPRED
var aoStoreInMetalMap: vec3f= vec3f(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);
#endif
#ifdef METALLNESSSTOREINMETALMAPBLUE
metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;
#else
metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;
#endif
#ifdef ROUGHNESSSTOREINMETALMAPALPHA
metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;
#else
#ifdef ROUGHNESSSTOREINMETALMAPGREEN
metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;
#endif
#endif
#endif
#ifdef DETAIL
var detailRoughness: f32=mix(0.5,detailColor.b,vDetailInfos.w);var loLerp: f32=mix(0.,metallicRoughness.g,detailRoughness*2.);var hiLerp: f32=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));
#endif
#ifdef MICROSURFACEMAP
metallicRoughness.g*=microSurfaceTexel.r;
#endif
#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS
microSurface=1.0-metallicRoughness.g;var baseColor: vec3f=surfaceAlbedo;outParams.metallic=metallicRoughness.r;outParams.specularWeight=metallicReflectanceFactors.a;var dielectricF0 : f32=reflectivityColor.a*outParams.specularWeight;surfaceReflectivityColor=metallicReflectanceFactors.rgb;
#if DEBUGMODE>0
outParams.metallicF0=dielectricF0*surfaceReflectivityColor;
#endif
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
outParams.surfaceAlbedo=baseColor.rgb*(vec3f(1.0)-vec3f(dielectricF0)*surfaceReflectivityColor)*(1.0-outParams.metallic);
#else
outParams.surfaceAlbedo=baseColor.rgb;
#endif
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
{let reflectivityColor: vec3f=mix(dielectricF0*surfaceReflectivityColor,baseColor.rgb,outParams.metallic);outParams.reflectanceF0=max(reflectivityColor.r,max(reflectivityColor.g,reflectivityColor.b));}
#else
#if DIELECTRIC_SPECULAR_MODEL==DIELECTRIC_SPECULAR_MODEL_GLTF
let maxF0: f32=max(surfaceReflectivityColor.r,max(surfaceReflectivityColor.g,surfaceReflectivityColor.b));outParams.reflectanceF0=mix(dielectricF0*maxF0,1.0f,outParams.metallic);
#else
outParams.reflectanceF0=mix(dielectricF0,1.0,outParams.metallic);
#endif
#endif
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
outParams.reflectanceF90=vec3(outParams.specularWeight);var f90Scale: f32=1.0;
#else
var f90Scale: f32=clamp(2.0*(ior-1.0),0.0,1.0);outParams.reflectanceF90=vec3(mix(
outParams.specularWeight*f90Scale,1.0,outParams.metallic));
#endif
outParams.dielectricColorF0=vec3f(dielectricF0*surfaceReflectivityColor);var metallicColorF0: vec3f=baseColor.rgb;outParams.colorReflectanceF0=mix(outParams.dielectricColorF0,metallicColorF0,outParams.metallic);
#if (DIELECTRIC_SPECULAR_MODEL==DIELECTRIC_SPECULAR_MODEL_OPENPBR)
let dielectricColorF90
: vec3f=surfaceReflectivityColor *
vec3f(outParams.specularWeight*f90Scale);
#else
let dielectricColorF90
: vec3f=vec3f(outParams.specularWeight*f90Scale);
#endif
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR)
let conductorColorF90: vec3f=surfaceReflectivityColor;
#else
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
let conductorColorF90: vec3f=outParams.reflectanceF90;
#else
let conductorColorF90: vec3f=vec3f(1.0f);
#endif
#endif
outParams.colorReflectanceF90=mix(dielectricColorF90,conductorColorF90,outParams.metallic);
#else
#ifdef REFLECTIVITY
surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;
#if DEBUGMODE>0
outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;
#endif
#ifdef MICROSURFACEFROMREFLECTIVITYMAP
microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z;
#else
#ifdef MICROSURFACEAUTOMATIC
microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);
#endif
#ifdef MICROSURFACEMAP
microSurface*=microSurfaceTexel.r;
#endif
#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE
#endif
#endif
outParams.colorReflectanceF0=surfaceReflectivityColor;outParams.reflectanceF0=max(surfaceReflectivityColor.r,max(surfaceReflectivityColor.g,surfaceReflectivityColor.b));outParams.reflectanceF90=vec3f(1.0);
#if (DIELECTRIC_SPECULAR_MODEL==DIELECTRIC_SPECULAR_MODEL_OPENPBR)
outParams.colorReflectanceF90=surfaceReflectivityColor;
#else
outParams.colorReflectanceF90=vec3(1.0);
#endif
#endif
microSurface=saturate(microSurface);var roughness: f32=1.-microSurface;var diffuseRoughness: f32=baseDiffuseRoughness;
#ifdef BASE_DIFFUSE_ROUGHNESS
diffuseRoughness*=baseDiffuseRoughnessTexture*baseDiffuseRoughnessInfos.y;
#endif
outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.diffuseRoughness=diffuseRoughness;return outParams;}
`;x.IncludesShadersStoreWGSL[hZ]||(x.IncludesShadersStoreWGSL[hZ]=pEe)});var pZ,gEe,gZ=y(()=>{k();pZ="pbrBlockAmbientOcclusion",gEe=`struct ambientOcclusionOutParams
{ambientOcclusionColor: vec3f,
#if DEBUGMODE>0 && defined(AMBIENT)
ambientOcclusionColorMap: vec3f
#endif
};
#define pbr_inline
fn ambientOcclusionBlock(
#ifdef AMBIENT
ambientOcclusionColorMap_: vec3f,
vAmbientInfos: vec4f
#endif
)->ambientOcclusionOutParams
{
var outParams: ambientOcclusionOutParams;var ambientOcclusionColor: vec3f= vec3f(1.,1.,1.);
#ifdef AMBIENT
var ambientOcclusionColorMap: vec3f=ambientOcclusionColorMap_*vAmbientInfos.y;
#ifdef AMBIENTINGRAYSCALE
ambientOcclusionColorMap= vec3f(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);
#endif
ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);
#if DEBUGMODE>0
outParams.ambientOcclusionColorMap=ambientOcclusionColorMap;
#endif
#endif
outParams.ambientOcclusionColor=ambientOcclusionColor;return outParams;}
`;x.IncludesShadersStoreWGSL[pZ]||(x.IncludesShadersStoreWGSL[pZ]=gEe)});var _Z,_Ee,vZ=y(()=>{k();_Z="pbrBlockAlphaFresnel",_Ee=`#ifdef ALPHAFRESNEL
#if defined(ALPHATEST) || defined(ALPHABLEND)
struct alphaFresnelOutParams
{alpha: f32};fn faceforward(N: vec3<f32>,I: vec3<f32>,Nref: vec3<f32>)->vec3<f32> {return select(N,-N,dot(Nref,I)>0.0);}
#define pbr_inline
fn alphaFresnelBlock(
normalW: vec3f,
viewDirectionW: vec3f,
alpha: f32,
microSurface: f32
)->alphaFresnelOutParams
{var outParams: alphaFresnelOutParams;var opacityPerceptual: f32=alpha;
#ifdef LINEARALPHAFRESNEL
var opacity0: f32=opacityPerceptual;
#else
var opacity0: f32=opacityPerceptual*opacityPerceptual;
#endif
var opacity90: f32=fresnelGrazingReflectance(opacity0);var normalForward: vec3f=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)), vec3f(opacity0), vec3f(opacity90),sqrt(microSurface)).x;
#ifdef ALPHATEST
if (outParams.alpha<ALPHATESTVALUE) {discard;}
#ifndef ALPHABLEND
outParams.alpha=1.0;
#endif
#endif
return outParams;}
#endif
#endif
`;x.IncludesShadersStoreWGSL[_Z]||(x.IncludesShadersStoreWGSL[_Z]=_Ee)});var EZ,vEe,SZ=y(()=>{k();EZ="pbrBlockAnisotropic",vEe=`#ifdef ANISOTROPIC
struct anisotropicOutParams
{anisotropy: f32,
anisotropicTangent: vec3f,
anisotropicBitangent: vec3f,
anisotropicNormal: vec3f,
#if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE)
anisotropyMapData: vec3f
#endif
};
#define pbr_inline
fn anisotropicBlock(
vAnisotropy: vec3f,
roughness: f32,
#ifdef ANISOTROPIC_TEXTURE
anisotropyMapData: vec3f,
#endif
TBN: mat3x3f,
normalW: vec3f,
viewDirectionW: vec3f
)->anisotropicOutParams
{
var outParams: anisotropicOutParams;var anisotropy: f32=vAnisotropy.b;var anisotropyDirection: vec3f= vec3f(vAnisotropy.xy,0.);
#ifdef ANISOTROPIC_TEXTURE
var amd=anisotropyMapData.rg;anisotropy*=anisotropyMapData.b;
#if DEBUGMODE>0
outParams.anisotropyMapData=anisotropyMapData;
#endif
amd=amd*2.0-1.0;
#ifdef ANISOTROPIC_LEGACY
anisotropyDirection=vec3f(anisotropyDirection.xy*amd,anisotropyDirection.z);
#else
anisotropyDirection=vec3f(mat2x2f(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(amd),anisotropyDirection.z);
#endif
#endif
var anisoTBN: mat3x3f= mat3x3f(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));var anisotropicTangent: vec3f=normalize(anisoTBN*anisotropyDirection);var anisotropicBitangent: vec3f=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);return outParams;}
#endif
`;x.IncludesShadersStoreWGSL[EZ]||(x.IncludesShadersStoreWGSL[EZ]=vEe)});var TZ,EEe,AZ=y(()=>{k();TZ="pbrBlockReflection",EEe=`#ifdef REFLECTION
struct reflectionOutParams
{environmentRadiance: vec4f
,environmentIrradiance: vec3f
#ifdef REFLECTIONMAP_3D
,reflectionCoords: vec3f
#else
,reflectionCoords: vec2f
#endif
#ifdef SS_TRANSLUCENCY
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
,irradianceVector: vec3f
#endif
#endif
#endif
};
#define pbr_inline
#ifdef REFLECTIONMAP_3D
fn createReflectionCoords(
vPositionW: vec3f,
normalW: vec3f,
#ifdef ANISOTROPIC
anisotropicOut: anisotropicOutParams,
#endif
)->vec3f
{var reflectionCoords: vec3f;
#else
fn createReflectionCoords(
vPositionW: vec3f,
normalW: vec3f,
#ifdef ANISOTROPIC
anisotropicOut: anisotropicOutParams,
#endif
)->vec2f
{
var reflectionCoords: vec2f;
#endif
#ifdef ANISOTROPIC
var reflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),anisotropicOut.anisotropicNormal);
#else
var reflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),normalW);
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
reflectionCoords=reflectionVector;
#else
reflectionCoords=reflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
reflectionCoords/=reflectionVector.z;
#endif
reflectionCoords.y=1.0-reflectionCoords.y;
#endif
return reflectionCoords;}
#define pbr_inline
fn sampleReflectionTexture(
alphaG: f32
,vReflectionMicrosurfaceInfos: vec3f
,vReflectionInfos: vec2f
,vReflectionColor: vec3f
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,NdotVUnclamped: f32
#endif
#ifdef LINEARSPECULARREFLECTION
,roughness: f32
#endif
#ifdef REFLECTIONMAP_3D
,reflectionSampler: texture_cube<f32>
,reflectionSamplerSampler: sampler
,reflectionCoords: vec3f
#else
,reflectionSampler: texture_2d<f32>
,reflectionSamplerSampler: sampler
,reflectionCoords: vec2f
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,reflectionLowSampler: texture_cube<f32>
,reflectionLowSamplerSampler: sampler
,reflectionHighSampler: texture_cube<f32>
,reflectionHighSamplerSampler: sampler
#else
,reflectionLowSampler: texture_2d<f32>
,reflectionLowSamplerSampler: sampler
,reflectionHighSampler: texture_2d<f32>
,reflectionHighSamplerSampler: sampler
#endif
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo: vec2f
#endif
)->vec4f
{var environmentRadiance: vec4f;
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
var reflectionLOD: f32=getLodFromAlphaGNdotV(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);
#elif defined(LINEARSPECULARREFLECTION)
var reflectionLOD: f32=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);
#else
var reflectionLOD: f32=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);
#endif
#ifdef LODBASEDMICROSFURACE
reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;
#ifdef LODINREFLECTIONALPHA
var automaticReflectionLOD: f32=UNPACK_LOD(textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords).a);var requestedReflectionLOD: f32=max(automaticReflectionLOD,reflectionLOD);
#else
var requestedReflectionLOD: f32=reflectionLOD;
#endif
#ifdef REALTIME_FILTERING
environmentRadiance= vec4f(radiance(alphaG,reflectionSampler,reflectionSamplerSampler,reflectionCoords,vReflectionFilteringInfo),1.0);
#else
environmentRadiance=textureSampleLevel(reflectionSampler,reflectionSamplerSampler,reflectionCoords,reflectionLOD);
#endif
#else
var lodReflectionNormalized: f32=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));var lodReflectionNormalizedDoubled: f32=lodReflectionNormalized*2.0;var environmentMid: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix(
textureSample(reflectionHighSampler,reflectionHighSamplerSampler,reflectionCoords),
environmentMid,
lodReflectionNormalizedDoubled
);} else {environmentRadiance=mix(
environmentMid,
textureSample(reflectionLowSampler,reflectionLowSamplerSampler,reflectionCoords),
lodReflectionNormalizedDoubled-1.0
);}
#endif
var envRadiance=environmentRadiance.rgb;
#ifdef RGBDREFLECTION
envRadiance=fromRGBD(environmentRadiance);
#endif
#ifdef GAMMAREFLECTION
envRadiance=toLinearSpaceVec3(environmentRadiance.rgb);
#endif
envRadiance*=vReflectionInfos.x;envRadiance*=vReflectionColor.rgb;return vec4f(envRadiance,environmentRadiance.a);}
#define pbr_inline
fn reflectionBlock(
vPositionW: vec3f
,normalW: vec3f
,alphaG: f32
,vReflectionMicrosurfaceInfos: vec3f
,vReflectionInfos: vec2f
,vReflectionColor: vec3f
#ifdef ANISOTROPIC
,anisotropicOut: anisotropicOutParams
#endif
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,NdotVUnclamped: f32
#endif
#ifdef LINEARSPECULARREFLECTION
,roughness: f32
#endif
#ifdef REFLECTIONMAP_3D
,reflectionSampler: texture_cube<f32>
,reflectionSamplerSampler: sampler
#else
,reflectionSampler: texture_2d<f32>
,reflectionSamplerSampler: sampler
#endif
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,vEnvironmentIrradiance: vec3f
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,reflectionMatrix: mat4x4f
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
,irradianceSampler: texture_cube<f32>
,irradianceSamplerSampler: sampler
#else
,irradianceSampler: texture_2d<f32>
,irradianceSamplerSampler: sampler
#endif
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
,reflectionDominantDirection: vec3f
#endif
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,reflectionLowSampler: texture_cube<f32>
,reflectionLowSamplerSampler: sampler
,reflectionHighSampler: texture_cube<f32>
,reflectionHighSamplerSampler: sampler
#else
,reflectionLowSampler: texture_2d<f32>
,reflectionLowSamplerSampler: sampler
,reflectionHighSampler: texture_2d<f32>
,reflectionHighSamplerSampler: sampler
#endif
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo: vec2f
#ifdef IBL_CDF_FILTERING
,icdfSampler: texture_2d<f32>
,icdfSamplerSampler: sampler
#endif
#endif
,viewDirectionW: vec3f
,diffuseRoughness: f32
,surfaceAlbedo: vec3f
)->reflectionOutParams
{var outParams: reflectionOutParams;var environmentRadiance: vec4f= vec4f(0.,0.,0.,0.);
#ifdef REFLECTIONMAP_3D
var reflectionCoords: vec3f= vec3f(0.);
#else
var reflectionCoords: vec2f= vec2f(0.);
#endif
reflectionCoords=createReflectionCoords(
vPositionW,
normalW,
#ifdef ANISOTROPIC
anisotropicOut,
#endif
);environmentRadiance=sampleReflectionTexture(
alphaG
,vReflectionMicrosurfaceInfos
,vReflectionInfos
,vReflectionColor
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,NdotVUnclamped
#endif
#ifdef LINEARSPECULARREFLECTION
,roughness
#endif
#ifdef REFLECTIONMAP_3D
,reflectionSampler
,reflectionSamplerSampler
,reflectionCoords
#else
,reflectionSampler
,reflectionSamplerSampler
,reflectionCoords
#endif
#ifndef LODBASEDMICROSFURACE
,reflectionLowSampler
,reflectionLowSamplerSampler
,reflectionHighSampler
,reflectionHighSamplerSampler
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
);var environmentIrradiance: vec3f= vec3f(0.,0.,0.);
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
#ifdef ANISOTROPIC
var irradianceVector: vec3f= (reflectionMatrix* vec4f(anisotropicOut.anisotropicNormal,0)).xyz;
#else
var irradianceVector: vec3f= (reflectionMatrix* vec4f(normalW,0)).xyz;
#endif
var irradianceView: vec3f= (reflectionMatrix* vec4f(viewDirectionW,0)).xyz;
#if !defined(USE_IRRADIANCE_DOMINANT_DIRECTION) && !defined(REALTIME_FILTERING)
#if BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LAMBERT && BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LEGACY
var NdotV: f32=max(dot(normalW,viewDirectionW),0.0);irradianceVector=mix(irradianceVector,irradianceView,(0.5*(1.0-NdotV))*diffuseRoughness);
#endif
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;irradianceView.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;irradianceView.y*=-1.0;
#endif
#endif
#ifdef USESPHERICALFROMREFLECTIONMAP
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
environmentIrradiance=vEnvironmentIrradiance;
#else
#if defined(REALTIME_FILTERING)
environmentIrradiance=irradiance(reflectionSampler,reflectionSamplerSampler,irradianceVector,vReflectionFilteringInfo,diffuseRoughness,surfaceAlbedo,irradianceView
#ifdef IBL_CDF_FILTERING
,icdfSampler
,icdfSamplerSampler
#endif
);
#else
environmentIrradiance=computeEnvironmentIrradiance(irradianceVector);
#endif
#ifdef SS_TRANSLUCENCY
outParams.irradianceVector=irradianceVector;
#endif
#endif
#elif defined(USEIRRADIANCEMAP)
#ifdef REFLECTIONMAP_3D
var environmentIrradiance4: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,irradianceVector);
#else
var environmentIrradiance4: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,reflectionCoords);
#endif
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
var Ls: vec3f=normalize(reflectionDominantDirection);var NoL: f32=dot(irradianceVector,Ls);var NoV: f32=dot(irradianceVector,irradianceView);var diffuseRoughnessTerm: vec3f=vec3f(1.0);
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
var LoV: f32=dot(Ls,irradianceView);var mag: f32=length(reflectionDominantDirection)*2.0f;var clampedAlbedo: vec3f=clamp(surfaceAlbedo,vec3f(0.1),vec3f(1.0));diffuseRoughnessTerm=diffuseBRDF_EON(clampedAlbedo,diffuseRoughness,NoL,NoV,LoV)*PI;diffuseRoughnessTerm=diffuseRoughnessTerm/clampedAlbedo;diffuseRoughnessTerm=mix(vec3f(1.0),diffuseRoughnessTerm,sqrt(clamp(mag*NoV,0.0,1.0f)));
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
var H: vec3f=(irradianceView+Ls)*0.5f;var VoH: f32=dot(irradianceView,H);diffuseRoughnessTerm=vec3f(diffuseBRDF_Burley(NoL,NoV,VoH,diffuseRoughness)*PI);
#endif
environmentIrradiance=environmentIrradiance4.rgb*diffuseRoughnessTerm;
#else
environmentIrradiance=environmentIrradiance4.rgb;
#endif
#ifdef RGBDREFLECTION
environmentIrradiance=fromRGBD(environmentIrradiance4);
#endif
#ifdef GAMMAREFLECTION
environmentIrradiance=toLinearSpaceVec3(environmentIrradiance.rgb);
#endif
#endif
environmentIrradiance*=vReflectionColor.rgb*vReflectionInfos.x;
#ifdef MIX_IBL_RADIANCE_WITH_IRRADIANCE
outParams.environmentRadiance=vec4f(mix(environmentRadiance.rgb,environmentIrradiance,alphaG),environmentRadiance.a);
#else
outParams.environmentRadiance=environmentRadiance;
#endif
outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;return outParams;}
#endif
`;x.IncludesShadersStoreWGSL[TZ]||(x.IncludesShadersStoreWGSL[TZ]=EEe)});var xZ,SEe,RZ=y(()=>{k();xZ="pbrBlockSheen",SEe=`#ifdef SHEEN
struct sheenOutParams
{sheenIntensity: f32
,sheenColor: vec3f
,sheenRoughness: f32
#ifdef SHEEN_LINKWITHALBEDO
,surfaceAlbedo: vec3f
#endif
#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
,sheenAlbedoScaling: f32
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
,finalSheenRadianceScaled: vec3f
#endif
#if DEBUGMODE>0
#ifdef SHEEN_TEXTURE
,sheenMapData: vec4f
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
,sheenEnvironmentReflectance: vec3f
#endif
#endif
};
#define pbr_inline
fn sheenBlock(
vSheenColor: vec4f
#ifdef SHEEN_ROUGHNESS
,vSheenRoughness: f32
#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
,sheenMapRoughnessData: vec4f
#endif
#endif
,roughness: f32
#ifdef SHEEN_TEXTURE
,sheenMapData: vec4f
,sheenMapLevel: f32
#endif
,reflectance: f32
#ifdef SHEEN_LINKWITHALBEDO
,baseColor: vec3f
,surfaceAlbedo: vec3f
#endif
#ifdef ENVIRONMENTBRDF
,NdotV: f32
,environmentBrdf: vec3f
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
,AARoughnessFactors: vec2f
,vReflectionMicrosurfaceInfos: vec3f
,vReflectionInfos: vec2f
,vReflectionColor: vec3f
,vLightingIntensity: vec4f
#ifdef REFLECTIONMAP_3D
,reflectionSampler: texture_cube<f32>
,reflectionSamplerSampler: sampler
,reflectionCoords: vec3f
#else
,reflectionSampler: texture_2d<f32>
,reflectionSamplerSampler: sampler
,reflectionCoords: vec2f
#endif
,NdotVUnclamped: f32
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,reflectionLowSampler: texture_cube<f32>
,reflectionLowSamplerSampler: sampler
,reflectionHighSampler: texture_cube<f32>
,reflectionHighSamplerSampler: sampler
#else
,reflectionLowSampler: texture_2d<f32>
,reflectionLowSamplerSampler: sampler
,reflectionHighSampler: texture_2d<f32>
,reflectionHighSamplerSampler: sampler
#endif
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo: vec2f
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
,seo: f32
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
,eho: f32
#endif
#endif
)->sheenOutParams
{var outParams: sheenOutParams;var sheenIntensity: f32=vSheenColor.a;
#ifdef SHEEN_TEXTURE
#if DEBUGMODE>0
outParams.sheenMapData=sheenMapData;
#endif
#endif
#ifdef SHEEN_LINKWITHALBEDO
var sheenFactor: f32=pow5(1.0-sheenIntensity);var sheenColor: vec3f=baseColor.rgb*(1.0-sheenFactor);var sheenRoughness: f32=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;
#ifdef SHEEN_TEXTURE
sheenIntensity*=sheenMapData.a;
#endif
#else
var sheenColor: vec3f=vSheenColor.rgb;
#ifdef SHEEN_TEXTURE
#ifdef SHEEN_GAMMATEXTURE
sheenColor*=toLinearSpaceVec3(sheenMapData.rgb);
#else
sheenColor*=sheenMapData.rgb;
#endif
sheenColor*=sheenMapLevel;
#endif
#ifdef SHEEN_ROUGHNESS
var sheenRoughness: f32=vSheenRoughness;
#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE
#if defined(SHEEN_TEXTURE)
sheenRoughness*=sheenMapData.a;
#endif
#elif defined(SHEEN_TEXTURE_ROUGHNESS)
sheenRoughness*=sheenMapRoughnessData.a;
#endif
#else
var sheenRoughness: f32=roughness;
#ifdef SHEEN_TEXTURE
sheenIntensity*=sheenMapData.a;
#endif
#endif
#if !defined(SHEEN_ALBEDOSCALING)
sheenIntensity*=(1.-reflectance);
#endif
sheenColor*=sheenIntensity;
#endif
#ifdef ENVIRONMENTBRDF
/*#ifdef SHEEN_SOFTER
var environmentSheenBrdf: vec3f= vec3f(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness));
#else*/
#ifdef SHEEN_ROUGHNESS
var environmentSheenBrdf: vec3f=getBRDFLookup(NdotV,sheenRoughness);
#else
var environmentSheenBrdf: vec3f=environmentBrdf;
#endif
/*#endif*/
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
var sheenAlphaG: f32=convertRoughnessToAverageSlope(sheenRoughness);
#ifdef SPECULARAA
sheenAlphaG+=AARoughnessFactors.y;
#endif
var environmentSheenRadiance: vec4f= vec4f(0.,0.,0.,0.);environmentSheenRadiance=sampleReflectionTexture(
sheenAlphaG
,vReflectionMicrosurfaceInfos
,vReflectionInfos
,vReflectionColor
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,NdotVUnclamped
#endif
#ifdef LINEARSPECULARREFLECTION
,sheenRoughness
#endif
,reflectionSampler
,reflectionSamplerSampler
,reflectionCoords
#ifndef LODBASEDMICROSFURACE
,reflectionLowSampler
,reflectionLowSamplerSampler
,reflectionHighSampler
,reflectionHighSamplerSampler
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
);var sheenEnvironmentReflectance: vec3f=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
sheenEnvironmentReflectance*=seo;
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
sheenEnvironmentReflectance*=eho;
#endif
#if DEBUGMODE>0
outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;
#endif
outParams.finalSheenRadianceScaled=
environmentSheenRadiance.rgb *
sheenEnvironmentReflectance *
vLightingIntensity.z;
#endif
#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;
#endif
outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;return outParams;}
#endif
`;x.IncludesShadersStoreWGSL[xZ]||(x.IncludesShadersStoreWGSL[xZ]=SEe)});var bZ,TEe,MZ=y(()=>{k();bZ="pbrBlockClearcoat",TEe=`struct clearcoatOutParams
{specularEnvironmentR0: vec3f,
conservationFactor: f32,
clearCoatNormalW: vec3f,
clearCoatAARoughnessFactors: vec2f,
clearCoatIntensity: f32,
clearCoatRoughness: f32,
#ifdef REFLECTION
finalClearCoatRadianceScaled: vec3f,
#endif
#ifdef CLEARCOAT_TINT
absorption: vec3f,
clearCoatNdotVRefract: f32,
clearCoatColor: vec3f,
clearCoatThickness: f32,
#endif
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
energyConservationFactorClearCoat: vec3f,
#endif
#if DEBUGMODE>0
#ifdef CLEARCOAT_BUMP
TBNClearCoat: mat3x3f,
#endif
#ifdef CLEARCOAT_TEXTURE
clearCoatMapData: vec2f,
#endif
#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
clearCoatTintMapData: vec4f,
#endif
#ifdef REFLECTION
environmentClearCoatRadiance: vec4f,
clearCoatEnvironmentReflectance: vec3f,
#endif
clearCoatNdotV: f32
#endif
};
#ifdef CLEARCOAT
#define pbr_inline
fn clearcoatBlock(
vPositionW: vec3f
,geometricNormalW: vec3f
,viewDirectionW: vec3f
,vClearCoatParams: vec2f
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
,clearCoatMapRoughnessData: vec4f
#endif
,specularEnvironmentR0: vec3f
#ifdef CLEARCOAT_TEXTURE
,clearCoatMapData: vec2f
#endif
#ifdef CLEARCOAT_TINT
,vClearCoatTintParams: vec4f
,clearCoatColorAtDistance: f32
,vClearCoatRefractionParams: vec4f
#ifdef CLEARCOAT_TINT_TEXTURE
,clearCoatTintMapData: vec4f
#endif
#endif
#ifdef CLEARCOAT_BUMP
,vClearCoatBumpInfos: vec2f
,clearCoatBumpMapData: vec4f
,vClearCoatBumpUV: vec2f
#if defined(TANGENT) && defined(NORMAL)
,vTBN: mat3x3f
#else
,vClearCoatTangentSpaceParams: vec2f
#endif
#ifdef OBJECTSPACE_NORMALMAP
,normalMatrix: mat4x4f
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
,faceNormal: vec3f
#endif
#ifdef REFLECTION
,vReflectionMicrosurfaceInfos: vec3f
,vReflectionInfos: vec2f
,vReflectionColor: vec3f
,vLightingIntensity: vec4f
#ifdef REFLECTIONMAP_3D
,reflectionSampler: texture_cube<f32>
,reflectionSamplerSampler: sampler
#else
,reflectionSampler: texture_2d<f32>
,reflectionSamplerSampler: sampler
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,reflectionLowSampler: texture_cube<f32>
,reflectionLowSamplerSampler: sampler
,reflectionHighSampler: texture_cube<f32>
,reflectionHighSamplerSampler: sampler
#else
,reflectionLowSampler: texture_2d<f32>
,reflectionLowSamplerSampler: sampler
,reflectionHighSampler: texture_2d<f32>
,reflectionHighSamplerSampler: sampler
#endif
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo: vec2f
#endif
#endif
#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
,frontFacingMultiplier: f32
#endif
)->clearcoatOutParams
{var outParams: clearcoatOutParams;var clearCoatIntensity: f32=vClearCoatParams.x;var clearCoatRoughness: f32=vClearCoatParams.y;
#ifdef CLEARCOAT_TEXTURE
clearCoatIntensity*=clearCoatMapData.x;
#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE
clearCoatRoughness*=clearCoatMapData.y;
#endif
#if DEBUGMODE>0
outParams.clearCoatMapData=clearCoatMapData;
#endif
#endif
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
clearCoatRoughness*=clearCoatMapRoughnessData.y;
#endif
outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness;
#ifdef CLEARCOAT_TINT
var clearCoatColor: vec3f=vClearCoatTintParams.rgb;var clearCoatThickness: f32=vClearCoatTintParams.a;
#ifdef CLEARCOAT_TINT_TEXTURE
#ifdef CLEARCOAT_TINT_GAMMATEXTURE
clearCoatColor*=toLinearSpaceVec3(clearCoatTintMapData.rgb);
#else
clearCoatColor*=clearCoatTintMapData.rgb;
#endif
clearCoatThickness*=clearCoatTintMapData.a;
#if DEBUGMODE>0
outParams.clearCoatTintMapData=clearCoatTintMapData;
#endif
#endif
outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness;
#endif
#ifdef CLEARCOAT_REMAP_F0
var specularEnvironmentR0Updated: vec3f=getR0RemappedForClearCoat(specularEnvironmentR0);
#else
var specularEnvironmentR0Updated: vec3f=specularEnvironmentR0;
#endif
outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);var clearCoatNormalW: vec3f=geometricNormalW;
#ifdef CLEARCOAT_BUMP
#ifdef NORMALXYSCALE
var clearCoatNormalScale: f32=1.0;
#else
var clearCoatNormalScale: f32=vClearCoatBumpInfos.y;
#endif
#if defined(TANGENT) && defined(NORMAL)
var TBNClearCoat: mat3x3f=vTBN;
#else
var TBNClearCoatUV: vec2f=vClearCoatBumpUV*frontFacingMultiplier;var TBNClearCoat: mat3x3f=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);
#endif
#if DEBUGMODE>0
outParams.TBNClearCoat=TBNClearCoat;
#endif
#ifdef OBJECTSPACE_NORMALMAP
clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize( mat3x3f(normalMatrix[0].xyz,normalMatrix[1].xyz,normalMatrix[2].xyz)*clearCoatNormalW);
#else
clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;
#endif
outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);var clearCoatNdotVUnclamped: f32=dot(clearCoatNormalW,viewDirectionW);var clearCoatNdotV: f32=absEps(clearCoatNdotVUnclamped);
#if DEBUGMODE>0
outParams.clearCoatNdotV=clearCoatNdotV;
#endif
#ifdef CLEARCOAT_TINT
var clearCoatVRefract: vec3f=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));
#endif
#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))
var environmentClearCoatBrdf: vec3f=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);
#endif
#if defined(REFLECTION)
var clearCoatAlphaG: f32=convertRoughnessToAverageSlope(clearCoatRoughness);
#ifdef SPECULARAA
clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;
#endif
var environmentClearCoatRadiance: vec4f= vec4f(0.,0.,0.,0.);var clearCoatReflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),clearCoatNormalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
clearCoatReflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
var clearCoatReflectionCoords: vec3f=clearCoatReflectionVector;
#else
var clearCoatReflectionCoords: vec2f=clearCoatReflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
clearCoatReflectionCoords/=clearCoatReflectionVector.z;
#endif
clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;
#endif
environmentClearCoatRadiance=sampleReflectionTexture(
clearCoatAlphaG
,vReflectionMicrosurfaceInfos
,vReflectionInfos
,vReflectionColor
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,clearCoatNdotVUnclamped
#endif
#ifdef LINEARSPECULARREFLECTION
,clearCoatRoughness
#endif
,reflectionSampler
,reflectionSamplerSampler
,clearCoatReflectionCoords
#ifndef LODBASEDMICROSFURACE
,reflectionLowSampler
,reflectionLowSamplerSampler
,reflectionHighSampler
,reflectionHighSamplerSampler
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
);
#if DEBUGMODE>0
outParams.environmentClearCoatRadiance=environmentClearCoatRadiance;
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
var clearCoatEnvironmentReflectance: vec3f=getReflectanceFromBRDFLookup(vec3f(uniforms.vClearCoatRefractionParams.x),environmentClearCoatBrdf);
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
var clearCoatEho: f32=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho;
#endif
#endif
#endif
#else
var clearCoatEnvironmentReflectance: vec3f=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV, vec3f(1.), vec3f(1.),sqrt(1.-clearCoatRoughness));
#endif
clearCoatEnvironmentReflectance*=clearCoatIntensity;
#if DEBUGMODE>0
outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;
#endif
outParams.finalClearCoatRadianceScaled=
environmentClearCoatRadiance.rgb *
clearCoatEnvironmentReflectance *
vLightingIntensity.z;
#endif
#if defined(CLEARCOAT_TINT)
outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);
#endif
var fresnelIBLClearCoat: f32=fresnelSchlickGGX(clearCoatNdotV,uniforms.vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat);
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);
#endif
return outParams;}
#endif
`;x.IncludesShadersStoreWGSL[bZ]||(x.IncludesShadersStoreWGSL[bZ]=TEe)});var yZ,AEe,IZ=y(()=>{k();yZ="pbrBlockIridescence",AEe=`struct iridescenceOutParams
{iridescenceIntensity: f32,
iridescenceIOR: f32,
iridescenceThickness: f32,
specularEnvironmentR0: vec3f};
#ifdef IRIDESCENCE
fn iridescenceBlock(
vIridescenceParams: vec4f
,viewAngle_: f32
,specularEnvironmentR0: vec3f
#ifdef IRIDESCENCE_TEXTURE
,iridescenceMapData: vec2f
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
,iridescenceThicknessMapData: vec2f
#endif
#ifdef CLEARCOAT
,NdotVUnclamped: f32
,vClearCoatParams: vec2f
#ifdef CLEARCOAT_TEXTURE
,clearCoatMapData: vec2f
#endif
#endif
)->iridescenceOutParams
{var outParams: iridescenceOutParams;var iridescenceIntensity: f32=vIridescenceParams.x;var iridescenceIOR: f32=vIridescenceParams.y;var iridescenceThicknessMin: f32=vIridescenceParams.z;var iridescenceThicknessMax: f32=vIridescenceParams.w;var iridescenceThicknessWeight: f32=1.;var viewAngle=viewAngle_;
#ifdef IRIDESCENCE_TEXTURE
iridescenceIntensity*=iridescenceMapData.x;
#endif
#if defined(IRIDESCENCE_THICKNESS_TEXTURE)
iridescenceThicknessWeight=iridescenceThicknessMapData.g;
#endif
var iridescenceThickness: f32=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);var topIor: f32=1.;
#ifdef CLEARCOAT
var clearCoatIntensity: f32=vClearCoatParams.x;
#ifdef CLEARCOAT_TEXTURE
clearCoatIntensity*=clearCoatMapData.x;
#endif
topIor=mix(1.0,uniforms.vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+((1.0/topIor)*(1.0/topIor))*((NdotVUnclamped*NdotVUnclamped)-1.0));
#endif
var iridescenceFresnel: vec3f=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;return outParams;}
#endif
`;x.IncludesShadersStoreWGSL[yZ]||(x.IncludesShadersStoreWGSL[yZ]=AEe)});var CZ,xEe,PZ=y(()=>{k();CZ="pbrBlockSubSurface",xEe=`struct subSurfaceOutParams
{specularEnvironmentReflectance: vec3f,
#ifdef SS_REFRACTION
finalRefraction: vec3f,
surfaceAlbedo: vec3f,
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
alpha: f32,
#endif
refractionOpacity: f32,
#endif
#ifdef SS_TRANSLUCENCY
transmittance: vec3f,
translucencyIntensity: f32,
#ifdef REFLECTION
refractionIrradiance: vec3f,
#endif
#endif
#if DEBUGMODE>0
#ifdef SS_THICKNESSANDMASK_TEXTURE
thicknessMap: vec4f,
#endif
#ifdef SS_REFRACTION
environmentRefraction: vec4f,
refractionTransmittance: vec3f
#endif
#endif
};
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
#define pbr_inline
fn sampleEnvironmentRefraction(
ior: f32
,thickness: f32
,refractionLOD: f32
,normalW: vec3f
,vPositionW: vec3f
,viewDirectionW: vec3f
,view: mat4x4f
,vRefractionInfos: vec4f
,refractionMatrix: mat4x4f
,vRefractionMicrosurfaceInfos: vec4f
,alphaG: f32
#ifdef SS_REFRACTIONMAP_3D
,refractionSampler: texture_cube<f32>
,refractionSamplerSampler: sampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler: texture_cube<f32>
,refractionLowSamplerSampler: sampler
,refractionHighSampler: texture_cube<f32>
,refractionHighSamplerSampler: sampler
#endif
#else
,refractionSampler: texture_2d<f32>
,refractionSamplerSampler: sampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler: texture_2d<f32>
,refractionLowSamplerSampler: sampler
,refractionHighSampler: texture_2d<f32>
,refractionHighSamplerSampler: sampler
#endif
#endif
#ifdef ANISOTROPIC
,anisotropicOut: anisotropicOutParams
#endif
#ifdef REALTIME_FILTERING
,vRefractionFilteringInfo: vec2f
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,refractionPosition: vec3f
,refractionSize: vec3f
#endif
)->vec4f {var environmentRefraction: vec4f= vec4f(0.,0.,0.,0.);
#ifdef ANISOTROPIC
var refractionVector: vec3f=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior);
#else
var refractionVector: vec3f=refract(-viewDirectionW,normalW,ior);
#endif
#ifdef SS_REFRACTIONMAP_OPPOSITEZ
refractionVector.z*=-1.0;
#endif
#ifdef SS_REFRACTIONMAP_3D
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);
#endif
refractionVector.y=refractionVector.y*vRefractionInfos.w;var refractionCoords: vec3f=refractionVector;refractionCoords= (refractionMatrix* vec4f(refractionCoords,0)).xyz;
#else
#ifdef SS_USE_THICKNESS_AS_DEPTH
var vRefractionUVW: vec3f= (refractionMatrix*(view* vec4f(vPositionW+refractionVector*thickness,1.0))).xyz;
#else
var vRefractionUVW: vec3f= (refractionMatrix*(view* vec4f(vPositionW+refractionVector*vRefractionInfos.z,1.0))).xyz;
#endif
var refractionCoords: vec2f=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;
#endif
#ifdef LODBASEDMICROSFURACE
var lod=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;
#ifdef SS_LODINREFRACTIONALPHA
var automaticRefractionLOD: f32=UNPACK_LOD(textureSample(refractionSampler,refractionSamplerSampler,refractionCoords).a);var requestedRefractionLOD: f32=max(automaticRefractionLOD,lod);
#else
var requestedRefractionLOD: f32=lod;
#endif
#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D)
environmentRefraction= vec4f(radiance(alphaG,refractionSampler,refractionSamplerSampler,refractionCoords,vRefractionFilteringInfo),1.0);
#else
environmentRefraction=textureSampleLevel(refractionSampler,refractionSamplerSampler,refractionCoords,requestedRefractionLOD);
#endif
#else
var lodRefractionNormalized: f32=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));var lodRefractionNormalizedDoubled: f32=lodRefractionNormalized*2.0;var environmentRefractionMid: vec4f=textureSample(refractionSampler,refractionSamplerSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix(
textureSample(refractionHighSampler,refractionHighSamplerSampler,refractionCoords),
environmentRefractionMid,
lodRefractionNormalizedDoubled
);} else {environmentRefraction=mix(
environmentRefractionMid,
textureSample(refractionLowSampler,refractionLowSamplerSampler,refractionCoords),
lodRefractionNormalizedDoubled-1.0
);}
#endif
var refraction=environmentRefraction.rgb;
#ifdef SS_RGBDREFRACTION
refraction=fromRGBD(environmentRefraction);
#endif
#ifdef SS_GAMMAREFRACTION
refraction=toLinearSpaceVec3(environmentRefraction.rgb);
#endif
return vec4f(refraction,environmentRefraction.a);}
#endif
#define pbr_inline
fn subSurfaceBlock(
vSubSurfaceIntensity: vec3f
,vThicknessParam: vec2f
,vTintColor: vec4f
,normalW: vec3f
,specularEnvironmentReflectance: vec3f
#ifdef SS_THICKNESSANDMASK_TEXTURE
,thicknessMap: vec4f
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
,refractionIntensityMap: vec4f
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
,translucencyIntensityMap: vec4f
#endif
#ifdef REFLECTION
#ifdef SS_TRANSLUCENCY
,reflectionMatrix: mat4x4f
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
,irradianceVector_: vec3f
#endif
#if defined(REALTIME_FILTERING)
,reflectionSampler: texture_cube<f32>
,reflectionSamplerSampler: sampler
,vReflectionFilteringInfo: vec2f
#ifdef IBL_CDF_FILTERING
,icdfSampler: texture_2d<f32>
,icdfSamplerSampler: sampler
#endif
#endif
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
,irradianceSampler: texture_cube<f32>
,irradianceSamplerSampler: sampler
#else
,irradianceSampler: texture_2d<f32>
,irradianceSamplerSampler: sampler
#endif
#endif
#endif
#endif
#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
,surfaceAlbedo: vec3f
#endif
#ifdef SS_REFRACTION
,vPositionW: vec3f
,viewDirectionW: vec3f
,view: mat4x4f
,vRefractionInfos: vec4f
,refractionMatrix: mat4x4f
,vRefractionMicrosurfaceInfos: vec4f
,vLightingIntensity: vec4f
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
,alpha: f32
#endif
#ifdef SS_LODINREFRACTIONALPHA
,NdotVUnclamped: f32
#endif
#ifdef SS_LINEARSPECULARREFRACTION
,roughness: f32
#endif
,alphaG: f32
#ifdef SS_REFRACTIONMAP_3D
,refractionSampler: texture_cube<f32>
,refractionSamplerSampler: sampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler: texture_cube<f32>
,refractionLowSamplerSampler: sampler
,refractionHighSampler: texture_cube<f32>
,refractionHighSamplerSampler: sampler
#endif
#else
,refractionSampler: texture_2d<f32>
,refractionSamplerSampler: sampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler: texture_2d<f32>
,refractionLowSamplerSampler: sampler
,refractionHighSampler: texture_2d<f32>
,refractionHighSamplerSampler: sampler
#endif
#endif
#ifdef ANISOTROPIC
,anisotropicOut: anisotropicOutParams
#endif
#ifdef REALTIME_FILTERING
,vRefractionFilteringInfo: vec2f
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,refractionPosition: vec3f
,refractionSize: vec3f
#endif
#ifdef SS_DISPERSION
,dispersion: f32
#endif
#endif
#ifdef SS_TRANSLUCENCY
,vDiffusionDistance: vec3f
,vTranslucencyColor: vec4f
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
,translucencyColorMap: vec4f
#endif
#endif
)->subSurfaceOutParams
{var outParams: subSurfaceOutParams;outParams.specularEnvironmentReflectance=specularEnvironmentReflectance;
#ifdef SS_REFRACTION
var refractionIntensity: f32=vSubSurfaceIntensity.x;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
refractionIntensity*=(1.0-alpha);outParams.alpha=1.0;
#endif
#endif
#ifdef SS_TRANSLUCENCY
var translucencyIntensity: f32=vSubSurfaceIntensity.y;
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
#ifdef SS_USE_GLTF_TEXTURES
var thickness: f32=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;
#else
var thickness: f32=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;
#endif
#if DEBUGMODE>0
outParams.thicknessMap=thicknessMap;
#endif
#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS)
#ifdef SS_USE_GLTF_TEXTURES
refractionIntensity*=thicknessMap.r;
#else
refractionIntensity*=thicknessMap.g;
#endif
#endif
#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS)
#ifdef SS_USE_GLTF_TEXTURES
translucencyIntensity*=thicknessMap.a;
#else
translucencyIntensity*=thicknessMap.b;
#endif
#endif
#else
var thickness: f32=vThicknessParam.y;
#endif
#if defined(SS_REFRACTION) && defined(SS_REFRACTIONINTENSITY_TEXTURE)
#ifdef SS_USE_GLTF_TEXTURES
refractionIntensity*=refractionIntensityMap.r;
#else
refractionIntensity*=refractionIntensityMap.g;
#endif
#endif
#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCYINTENSITY_TEXTURE)
#ifdef SS_USE_GLTF_TEXTURES
translucencyIntensity*=translucencyIntensityMap.a;
#else
translucencyIntensity*=translucencyIntensityMap.b;
#endif
#endif
#ifdef SS_TRANSLUCENCY
thickness=maxEps(thickness);var translucencyColor: vec4f=vTranslucencyColor;
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
translucencyColor*=translucencyColorMap;
#endif
var transmittance: vec3f=transmittanceBRDF_Burley(translucencyColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity;
#endif
#ifdef SS_REFRACTION
var environmentRefraction: vec4f= vec4f(0.,0.,0.,0.);
#ifdef SS_HAS_THICKNESS
var ior: f32=vRefractionInfos.y;
#else
var ior: f32=vRefractionMicrosurfaceInfos.w;
#endif
#ifdef SS_LODINREFRACTIONALPHA
var refractionAlphaG: f32=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLodFromAlphaGNdotV(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);
#elif defined(SS_LINEARSPECULARREFRACTION)
var refractionRoughness: f32=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);
#else
var refractionAlphaG: f32=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);
#endif
var refraction_ior: f32=vRefractionInfos.y;
#ifdef SS_DISPERSION
var realIOR: f32=1.0/refraction_ior;var iorDispersionSpread: f32=0.04*dispersion*(realIOR-1.0);var iors: vec3f= vec3f(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (var i: i32=0; i<3; i++) {refraction_ior=iors[i];
#endif
var envSample: vec4f=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG
#ifdef SS_REFRACTIONMAP_3D
,refractionSampler
,refractionSamplerSampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler
,refractionLowSamplerSampler
,refractionHighSampler
,refractionHighSamplerSampler
#endif
#else
,refractionSampler
,refractionSamplerSampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler
,refractionLowSamplerSampler
,refractionHighSampler
,refractionHighSamplerSampler
#endif
#endif
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,refractionPosition
,refractionSize
#endif
);
#ifdef SS_DISPERSION
environmentRefraction[i]=envSample[i];}
#else
environmentRefraction=envSample;
#endif
environmentRefraction=vec4f(environmentRefraction.rgb*vRefractionInfos.x,environmentRefraction.a);
#endif
#ifdef SS_REFRACTION
var refractionTransmittance: vec3f= vec3f(refractionIntensity);
#ifdef SS_THICKNESSANDMASK_TEXTURE
var volumeAlbedo: vec3f=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambertVec3(volumeAlbedo,thickness);
#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)
var maxChannel: f32=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);var volumeAlbedo: vec3f=saturateVec3(maxChannel*surfaceAlbedo);environmentRefraction=vec4f(environmentRefraction.rgb*volumeAlbedo,environmentRefraction.a);
#else
var volumeAlbedo: vec3f=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambertVec3(volumeAlbedo,vThicknessParam.y);
#endif
#ifdef SS_ALBEDOFORREFRACTIONTINT
environmentRefraction=vec4f(environmentRefraction.rgb*surfaceAlbedo.rgb,environmentRefraction.a);
#endif
outParams.surfaceAlbedo=surfaceAlbedo;outParams.refractionOpacity=1.-refractionIntensity;
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
outParams.surfaceAlbedo*=outParams.refractionOpacity;
#endif
#ifdef UNUSED_MULTIPLEBOUNCES
var bounceSpecularEnvironmentReflectance: vec3f=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);
#endif
#if DEBUGMODE>0
outParams.refractionTransmittance=refractionTransmittance;
#endif
outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;outParams.finalRefraction*=vec3f(1.0)-specularEnvironmentReflectance;
#if DEBUGMODE>0
outParams.environmentRefraction=environmentRefraction;
#endif
#endif
#if defined(REFLECTION) && defined(SS_TRANSLUCENCY)
#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP)
var irradianceVector: vec3f= (reflectionMatrix* vec4f(normalW,0)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;
#endif
#else
var irradianceVector: vec3f=irradianceVector_;
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP)
#if defined(REALTIME_FILTERING)
var refractionIrradiance: vec3f=irradiance(reflectionSampler,reflectionSamplerSampler,-irradianceVector,vReflectionFilteringInfo,0.0,surfaceAlbedo,irradianceVector
#ifdef IBL_CDF_FILTERING
,icdfSampler
,icdfSamplerSampler
#endif
);
#else
var refractionIrradiance: vec3f=computeEnvironmentIrradiance(-irradianceVector);
#endif
#elif defined(USEIRRADIANCEMAP)
#ifdef REFLECTIONMAP_3D
var irradianceCoords: vec3f=irradianceVector;
#else
var irradianceCoords: vec2f=irradianceVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
irradianceCoords/=irradianceVector.z;
#endif
irradianceCoords.y=1.0-irradianceCoords.y;
#endif
var temp: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,-irradianceCoords);var refractionIrradiance=temp.rgb;
#ifdef RGBDREFLECTION
refractionIrradiance=fromRGBD(temp).rgb;
#endif
#ifdef GAMMAREFLECTION
refractionIrradiance=toLinearSpaceVec3(refractionIrradiance);
#endif
#else
var refractionIrradiance: vec3f= vec3f(0.);
#endif
refractionIrradiance*=transmittance;
#ifdef SS_ALBEDOFORTRANSLUCENCYTINT
refractionIrradiance*=surfaceAlbedo.rgb;
#endif
outParams.refractionIrradiance=refractionIrradiance;
#endif
return outParams;}
#endif
`;x.IncludesShadersStoreWGSL[CZ]||(x.IncludesShadersStoreWGSL[CZ]=xEe)});var LZ,REe,DZ=y(()=>{k();LZ="pbrBlockNormalFinal",REe=`#if defined(FORCENORMALFORWARD) && defined(NORMAL)
var faceNormal: vec3f=normalize(cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW)))*scene.vEyePosition.w;
#if defined(TWOSIDEDLIGHTING)
faceNormal=select(-faceNormal,faceNormal,fragmentInputs.frontFacing);
#endif
normalW*=sign(dot(normalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
#if defined(MIRRORED)
normalW=select(normalW,-normalW,fragmentInputs.frontFacing);
#else
normalW=select(-normalW,normalW,fragmentInputs.frontFacing);
#endif
#endif
`;x.IncludesShadersStoreWGSL[LZ]||(x.IncludesShadersStoreWGSL[LZ]=REe)});var OZ,bEe,NZ=y(()=>{k();OZ="pbrBlockLightmapInit",bEe=`#ifdef LIGHTMAP
var lightmapColor: vec4f=textureSample(lightmapSampler,lightmapSamplerSampler,fragmentInputs.vLightmapUV+uvOffset);
#ifdef RGBDLIGHTMAP
lightmapColor=vec4f(fromRGBD(lightmapColor),lightmapColor.a);
#endif
#ifdef GAMMALIGHTMAP
lightmapColor=vec4f(toLinearSpaceVec3(lightmapColor.rgb),lightmapColor.a);
#endif
lightmapColor=vec4f(lightmapColor.rgb*uniforms.vLightmapInfos.y,lightmapColor.a);
#endif
`;x.IncludesShadersStoreWGSL[OZ]||(x.IncludesShadersStoreWGSL[OZ]=bEe)});var wZ,MEe,FZ=y(()=>{k();wZ="pbrBlockGeometryInfo",MEe=`var NdotVUnclamped: f32=dot(normalW,viewDirectionW);var NdotV: f32=absEps(NdotVUnclamped);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var AARoughnessFactors: vec2f=getAARoughnessFactors(normalW.xyz);
#ifdef SPECULARAA
alphaG+=AARoughnessFactors.y;
#endif
#if defined(ENVIRONMENTBRDF)
var environmentBrdf: vec3f=getBRDFLookup(NdotV,roughness);
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
#ifdef RADIANCEOCCLUSION
#ifdef AMBIENTINGRAYSCALE
var ambientMonochrome: f32=aoOut.ambientOcclusionColor.r;
#else
var ambientMonochrome: f32=getLuminance(aoOut.ambientOcclusionColor);
#endif
var seo: f32=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);
#endif
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
var eho: f32=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);
#endif
#endif
#endif
#endif
`;x.IncludesShadersStoreWGSL[wZ]||(x.IncludesShadersStoreWGSL[wZ]=MEe)});var BZ,yEe,UZ=y(()=>{k();BZ="pbrBlockReflectance",yEe=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
var baseSpecularEnvironmentReflectance: vec3f=getReflectanceFromBRDFWithEnvLookup(vec3f(reflectanceF0),vec3f(reflectivityOut.reflectanceF90),environmentBrdf);
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR)
let metalEnvironmentReflectance: vec3f=vec3f(reflectivityOut.specularWeight)*getF82Specular(NdotV,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90,reflectivityOut.roughness);let dielectricEnvironmentReflectance=getReflectanceFromBRDFWithEnvLookup(reflectivityOut.dielectricColorF0,reflectivityOut.colorReflectanceF90,environmentBrdf);var colorSpecularEnvironmentReflectance: vec3f=mix(dielectricEnvironmentReflectance,metalEnvironmentReflectance,reflectivityOut.metallic);
#else
var colorSpecularEnvironmentReflectance=getReflectanceFromBRDFWithEnvLookup(clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90,environmentBrdf);
#endif
#ifdef RADIANCEOCCLUSION
colorSpecularEnvironmentReflectance*=seo;
#endif
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
colorSpecularEnvironmentReflectance*=eho;
#endif
#endif
#endif
#else
var colorSpecularEnvironmentReflectance: vec3f=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));var baseSpecularEnvironmentReflectance: vec3f=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,vec3f(reflectanceF0),vec3f(reflectivityOut.reflectanceF90),sqrt(microSurface));
#endif
#ifdef CLEARCOAT
colorSpecularEnvironmentReflectance*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
colorSpecularEnvironmentReflectance*=clearcoatOut.absorption;
#endif
#endif
`;x.IncludesShadersStoreWGSL[BZ]||(x.IncludesShadersStoreWGSL[BZ]=yEe)});var VZ,IEe,GZ=y(()=>{k();VZ="pbrBlockDirectLighting",IEe=`var diffuseBase: vec3f=vec3f(0.,0.,0.);
#ifdef SS_TRANSLUCENCY
var diffuseTransmissionBase: vec3f=vec3f(0.,0.,0.);
#endif
#ifdef SPECULARTERM
var specularBase: vec3f=vec3f(0.,0.,0.);
#endif
#ifdef CLEARCOAT
var clearCoatBase: vec3f=vec3f(0.,0.,0.);
#endif
#ifdef SHEEN
var sheenBase: vec3f=vec3f(0.,0.,0.);
#endif
#if defined(SPECULARTERM) && defined(LIGHT0)
var coloredFresnel: vec3f=vec3f(0.,0.,0.);
#endif
var preInfo: preLightingInfo;var info: lightingInfo;var shadow: f32=1.;
var aggShadow: f32=0.;var numLights: f32=0.;
#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
var absorption: vec3f=vec3f(0.);
#endif
`;x.IncludesShadersStoreWGSL[VZ]||(x.IncludesShadersStoreWGSL[VZ]=IEe)});var kZ,CEe,zZ=y(()=>{k();kZ="pbrBlockFinalLitComponents",CEe=`aggShadow=aggShadow/numLights;
#if defined(ENVIRONMENTBRDF)
#ifdef MS_BRDF_ENERGY_CONSERVATION
var baseSpecularEnergyConservationFactor: vec3f=getEnergyConservationFactor(vec3f(reflectanceF0),environmentBrdf);var coloredEnergyConservationFactor: vec3f=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);
#endif
#endif
#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)
surfaceAlbedo=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;
#endif
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
#ifndef METALLICWORKFLOW
#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION
surfaceAlbedo=vec3f(1.-reflectanceF0)*surfaceAlbedo.rgb;
#endif
#endif
#endif
#ifdef REFLECTION
var finalIrradiance: vec3f=reflectionOut.environmentIrradiance;
#ifndef LEGACY_SPECULAR_ENERGY_CONSERVATION
#if defined(METALLICWORKFLOW) || defined(SPECULAR_GLOSSINESS_ENERGY_CONSERVATION)
var baseSpecularEnergy: vec3f=vec3f(baseSpecularEnvironmentReflectance);
#if defined(ENVIRONMENTBRDF)
#ifdef MS_BRDF_ENERGY_CONSERVATION
baseSpecularEnergy*=baseSpecularEnergyConservationFactor;
#endif
#endif
finalIrradiance*=clamp(vec3f(1.0)-baseSpecularEnergy,vec3f(0.0),vec3f(1.0));
#endif
#endif
#if defined(CLEARCOAT)
finalIrradiance*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
finalIrradiance*=clearcoatOut.absorption;
#endif
#endif
#ifndef SS_APPLY_ALBEDO_AFTER_SUBSURFACE
finalIrradiance*=surfaceAlbedo.rgb;
#endif
#if defined(SS_REFRACTION)
finalIrradiance*=subSurfaceOut.refractionOpacity;
#endif
#if defined(SS_TRANSLUCENCY)
finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance;
#endif
#ifdef SS_APPLY_ALBEDO_AFTER_SUBSURFACE
finalIrradiance*=surfaceAlbedo.rgb;
#endif
finalIrradiance*=uniforms.vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor;
#endif
#ifdef SPECULARTERM
var finalSpecular: vec3f=specularBase;finalSpecular=max(finalSpecular,vec3f(0.0));var finalSpecularScaled: vec3f=finalSpecular*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalSpecularScaled*=coloredEnergyConservationFactor;
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
finalSpecularScaled*=sheenOut.sheenAlbedoScaling;
#endif
#endif
#ifdef REFLECTION
var finalRadiance: vec3f=reflectionOut.environmentRadiance.rgb;finalRadiance*=colorSpecularEnvironmentReflectance;;var finalRadianceScaled: vec3f=finalRadiance*uniforms.vLightingIntensity.z;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalRadianceScaled*=coloredEnergyConservationFactor;
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
finalRadianceScaled*=sheenOut.sheenAlbedoScaling;
#endif
#endif
#ifdef SHEEN
var finalSheen: vec3f=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,vec3f(0.0));var finalSheenScaled: vec3f=finalSheen*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w;
#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)
sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;
#endif
#endif
#endif
#ifdef CLEARCOAT
var finalClearCoat: vec3f=clearCoatBase;finalClearCoat=max(finalClearCoat,vec3f(0.0));var finalClearCoatScaled: vec3f=finalClearCoat*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;
#endif
#ifdef SS_REFRACTION
subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;
#ifdef CLEARCOAT_TINT
subSurfaceOut.finalRefraction*=clearcoatOut.absorption;
#endif
#endif
#endif
#ifdef ALPHABLEND
var luminanceOverAlpha: f32=0.0;
#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)
luminanceOverAlpha+=getLuminance(finalRadianceScaled);
#if defined(CLEARCOAT)
luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);
#endif
#endif
#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)
luminanceOverAlpha+=getLuminance(finalSpecularScaled);
#endif
#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)
luminanceOverAlpha+=getLuminance(finalClearCoatScaled);
#endif
#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)
alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);
#endif
#endif
`;x.IncludesShadersStoreWGSL[kZ]||(x.IncludesShadersStoreWGSL[kZ]=CEe)});var WZ,PEe,HZ=y(()=>{k();WZ="pbrBlockFinalUnlitComponents",PEe=`var finalDiffuse: vec3f=diffuseBase;finalDiffuse*=surfaceAlbedo;
#if defined(SS_REFRACTION) && !defined(UNLIT) && !defined(LEGACY_SPECULAR_ENERGY_CONSERVATION)
finalDiffuse*=subSurfaceOut.refractionOpacity;
#endif
#if defined(SS_TRANSLUCENCY) && !defined(UNLIT)
finalDiffuse+=diffuseTransmissionBase;
#endif
finalDiffuse=max(finalDiffuse,vec3f(0.0));finalDiffuse*=uniforms.vLightingIntensity.x;var finalAmbient: vec3f=uniforms.vAmbientColor;finalAmbient=finalAmbient*surfaceAlbedo.rgb;var finalEmissive: vec3f=uniforms.vEmissiveColor;
#ifdef EMISSIVE
var emissiveColorTex: vec3f=textureSample(emissiveSampler,emissiveSamplerSampler,fragmentInputs.vEmissiveUV+uvOffset).rgb;
#ifdef GAMMAEMISSIVE
finalEmissive*=toLinearSpaceVec3(emissiveColorTex.rgb);
#else
finalEmissive*=emissiveColorTex.rgb;
#endif
finalEmissive*= uniforms.vEmissiveInfos.y;
#endif
finalEmissive*=uniforms.vLightingIntensity.y;
#ifdef AMBIENT
var ambientOcclusionForDirectDiffuse: vec3f=mix( vec3f(1.),aoOut.ambientOcclusionColor,uniforms.vAmbientInfos.w);
#else
var ambientOcclusionForDirectDiffuse: vec3f=aoOut.ambientOcclusionColor;
#endif
finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse;
`;x.IncludesShadersStoreWGSL[WZ]||(x.IncludesShadersStoreWGSL[WZ]=PEe)});var XZ,LEe,YZ=y(()=>{k();XZ="pbrBlockFinalColorComposition",LEe=`var finalColor: vec4f= vec4f(
#ifndef UNLIT
#ifdef REFLECTION
finalIrradiance +
#endif
#ifdef SPECULARTERM
finalSpecularScaled +
#endif
#ifdef SHEEN
finalSheenScaled +
#endif
#ifdef CLEARCOAT
finalClearCoatScaled +
#endif
#ifdef REFLECTION
finalRadianceScaled +
#if defined(SHEEN) && defined(ENVIRONMENTBRDF)
sheenOut.finalSheenRadianceScaled +
#endif
#ifdef CLEARCOAT
clearcoatOut.finalClearCoatRadianceScaled +
#endif
#endif
#ifdef SS_REFRACTION
subSurfaceOut.finalRefraction +
#endif
#endif
finalAmbient +
finalDiffuse,
alpha);
#ifdef LIGHTMAP
#ifndef LIGHTMAPEXCLUDED
#ifdef USELIGHTMAPASSHADOWMAP
finalColor=vec4f(finalColor.rgb*lightmapColor.rgb,finalColor.a);
#else
finalColor=vec4f(finalColor.rgb+lightmapColor.rgb,finalColor.a);
#endif
#endif
#endif
finalColor=vec4f(finalColor.rgb+finalEmissive,finalColor.a);
#define CUSTOM_FRAGMENT_BEFORE_FOG
finalColor=max(finalColor,vec4f(0.0));
`;x.IncludesShadersStoreWGSL[XZ]||(x.IncludesShadersStoreWGSL[XZ]=LEe)});var KZ,DEe,jZ=y(()=>{k();KZ="pbrBlockPrePass",DEe=`#if SCENE_MRT_COUNT>0
var writeGeometryInfo: f32=select(0.0,1.0,finalColor.a>ALPHATESTVALUE);var fragData: array<vec4<f32>,SCENE_MRT_COUNT>;
#ifdef PREPASS_POSITION
fragData[PREPASS_POSITION_INDEX]= vec4f(fragmentInputs.vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_LOCAL_POSITION
fragData[PREPASS_LOCAL_POSITION_INDEX]=vec4f(fragmentInputs.vPosition,writeGeometryInfo);
#endif
#ifdef PREPASS_VELOCITY
var a: vec2f=(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[PREPASS_VELOCITY_INDEX]= vec4f(velocity,0.0,writeGeometryInfo);
#elif defined(PREPASS_VELOCITY_LINEAR)
var velocity : vec2f=vec2f(0.5)*((fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w) -
(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w));fragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO
fragData[PREPASS_ALBEDO_INDEX]=vec4f(surfaceAlbedo,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
var sqAlbedo : vec3f=sqrt(surfaceAlbedo);
#endif
#ifdef PREPASS_IRRADIANCE_LEGACY
var irradiance : vec3f=finalDiffuse;
#ifndef UNLIT
#ifdef REFLECTION
irradiance+=finalIrradiance;
#endif
#endif
#ifdef SS_SCATTERING
#ifdef PREPASS_COLOR
fragData[PREPASS_COLOR_INDEX]=vec4f(finalColor.rgb-irradiance,finalColor.a);
#endif
irradiance/=sqAlbedo;fragData[PREPASS_IRRADIANCE_LEGACY_INDEX]=vec4f(clamp(irradiance,vec3f(0.),vec3f(1.)),writeGeometryInfo*uniforms.scatteringDiffusionProfile/255.);
#else
#ifdef PREPASS_COLOR
fragData[PREPASS_COLOR_INDEX]=finalColor;
#endif
fragData[PREPASS_IRRADIANCE_LEGACY_INDEX]=vec4f(clamp(irradiance,vec3f(0.),vec3f(1.)),writeGeometryInfo);
#endif
#else
#ifdef PREPASS_IRRADIANCE
var irradiance : vec3f=finalDiffuse;
#ifndef UNLIT
#ifdef REFLECTION
irradiance+=finalIrradiance;
#endif
#endif
fragData[PREPASS_IRRADIANCE_INDEX]=vec4f(irradiance,writeGeometryInfo);
#endif
#ifdef PREPASS_COLOR
fragData[PREPASS_COLOR_INDEX]=vec4f(finalColor.rgb,finalColor.a);
#endif
#endif
#ifdef PREPASS_DEPTH
fragData[PREPASS_DEPTH_INDEX]=vec4f(fragmentInputs.vViewPos.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_SCREENSPACE_DEPTH
fragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
fragData[PREPASS_NORMALIZED_VIEW_DEPTH_INDEX]=vec4f(fragmentInputs.vNormViewDepth,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMAL
#ifdef PREPASS_NORMAL_WORLDSPACE
fragData[PREPASS_NORMAL_INDEX]=vec4f(normalW,writeGeometryInfo);
#else
fragData[PREPASS_NORMAL_INDEX]=vec4f(normalize((scene.view*vec4f(normalW,0.0)).rgb),writeGeometryInfo);
#endif
#endif
#ifdef PREPASS_WORLD_NORMAL
fragData[PREPASS_WORLD_NORMAL_INDEX]=vec4f(normalW*0.5+0.5,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
fragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4f(sqAlbedo,writeGeometryInfo);
#endif
#ifdef PREPASS_REFLECTIVITY
#ifndef UNLIT
fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(specularEnvironmentR0,microSurface)*writeGeometryInfo;
#else
fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(0.0,0.0,0.0,1.0)*writeGeometryInfo;
#endif
#endif
#if SCENE_MRT_COUNT>0
fragmentOutputs.fragData0=fragData[0];
#endif
#if SCENE_MRT_COUNT>1
fragmentOutputs.fragData1=fragData[1];
#endif
#if SCENE_MRT_COUNT>2
fragmentOutputs.fragData2=fragData[2];
#endif
#if SCENE_MRT_COUNT>3
fragmentOutputs.fragData3=fragData[3];
#endif
#if SCENE_MRT_COUNT>4
fragmentOutputs.fragData4=fragData[4];
#endif
#if SCENE_MRT_COUNT>5
fragmentOutputs.fragData5=fragData[5];
#endif
#if SCENE_MRT_COUNT>6
fragmentOutputs.fragData6=fragData[6];
#endif
#if SCENE_MRT_COUNT>7
fragmentOutputs.fragData7=fragData[7];
#endif
#endif
`;x.IncludesShadersStoreWGSL[KZ]||(x.IncludesShadersStoreWGSL[KZ]=DEe)});var qZ={};Be(qZ,{pbrPixelShaderWGSL:()=>OEe});var PF,ZZ,OEe,QZ=y(()=>{k();Xb();Yb();IF();Xw();Kb();fZ();Zb();qc();ah();rE();ao();Yw();Kw();jw();qb();jb();vg();Zw();qw();Eg();Qw();Jw();ry();Qb();$b();gE();uZ();mZ();gZ();vZ();SZ();AZ();RZ();MZ();IZ();PZ();Qc();eF();Jb();DZ();eM();NZ();FZ();$w();UZ();GZ();aN();zZ();HZ();YZ();tM();nE();tF();jZ();iM();iF();PF="pbrPixelShader",ZZ=`#define PBR_FRAGMENT_SHADER
#define CUSTOM_FRAGMENT_BEGIN
#include<prePassDeclaration>[SCENE_MRT_COUNT]
#include<oitDeclaration>
#ifndef FROMLINEARSPACE
#define FROMLINEARSPACE
#endif
#include<pbrUboDeclaration>
#include<pbrFragmentExtraDeclaration>
#include<lightUboDeclaration>[0..maxSimultaneousLights]
#include<pbrFragmentSamplersDeclaration>
#include<imageProcessingDeclaration>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
#include<helperFunctions>
#include<subSurfaceScatteringFunctions>
#include<importanceSampling>
#include<pbrHelperFunctions>
#include<imageProcessingFunctions>
#include<shadowsFragmentFunctions>
#include<harmonicsFunctions>
#include<pbrDirectLightingSetupFunctions>
#include<pbrDirectLightingFalloffFunctions>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
#include<pbrDirectLightingFunctions>
#include<pbrIBLFunctions>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#ifdef REFLECTION
#include<reflectionFunction>
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
#include<pbrBlockAlbedoOpacity>
#include<pbrBlockReflectivity>
#include<pbrBlockAmbientOcclusion>
#include<pbrBlockAlphaFresnel>
#include<pbrBlockAnisotropic>
#include<pbrBlockReflection>
#include<pbrBlockSheen>
#include<pbrBlockClearcoat>
#include<pbrBlockIridescence>
#include<pbrBlockSubSurface>
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#include<pbrBlockNormalGeometric>
#include<bumpFragment>
#include<pbrBlockNormalFinal>
var albedoOpacityOut: albedoOpacityOutParams;
#ifdef ALBEDO
var albedoTexture: vec4f=textureSample(albedoSampler,albedoSamplerSampler,fragmentInputs.vAlbedoUV+uvOffset);
#endif
#ifdef BASE_WEIGHT
var baseWeightTexture: vec4f=textureSample(baseWeightSampler,baseWeightSamplerSampler,fragmentInputs.vBaseWeightUV+uvOffset);
#endif
#ifdef OPACITY
var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vOpacityUV+uvOffset);
#endif
#ifdef DECAL
var decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset);
#endif
albedoOpacityOut=albedoOpacityBlock(
uniforms.vAlbedoColor
#ifdef ALBEDO
,albedoTexture
,uniforms.vAlbedoInfos
#endif
,uniforms.baseWeight
#ifdef BASE_WEIGHT
,baseWeightTexture
,uniforms.vBaseWeightInfos
#endif
#ifdef OPACITY
,opacityMap
,uniforms.vOpacityInfos
#endif
#ifdef DETAIL
,detailColor
,uniforms.vDetailInfos
#endif
#ifdef DECAL
,decalColor
,uniforms.vDecalInfos
#endif
);var surfaceAlbedo: vec3f=albedoOpacityOut.surfaceAlbedo;var alpha: f32=albedoOpacityOut.alpha;
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
#include<depthPrePass>
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS
var aoOut: ambientOcclusionOutParams;
#ifdef AMBIENT
var ambientOcclusionColorMap: vec3f=textureSample(ambientSampler,ambientSamplerSampler,fragmentInputs.vAmbientUV+uvOffset).rgb;
#endif
aoOut=ambientOcclusionBlock(
#ifdef AMBIENT
ambientOcclusionColorMap,
uniforms.vAmbientInfos
#endif
);
#include<pbrBlockLightmapInit>
#ifdef UNLIT
var diffuseBase: vec3f= vec3f(1.,1.,1.);
#else
var baseColor: vec3f=surfaceAlbedo;var reflectivityOut: reflectivityOutParams;
#if defined(REFLECTIVITY)
var surfaceMetallicOrReflectivityColorMap: vec4f=textureSample(reflectivitySampler,reflectivitySamplerSampler,fragmentInputs.vReflectivityUV+uvOffset);var baseReflectivity: vec4f=surfaceMetallicOrReflectivityColorMap;
#ifndef METALLICWORKFLOW
#ifdef REFLECTIVITY_GAMMA
surfaceMetallicOrReflectivityColorMap=toLinearSpaceVec4(surfaceMetallicOrReflectivityColorMap);
#endif
surfaceMetallicOrReflectivityColorMap=vec4f(surfaceMetallicOrReflectivityColorMap.rgb*uniforms.vReflectivityInfos.y,surfaceMetallicOrReflectivityColorMap.a);
#endif
#endif
#if defined(MICROSURFACEMAP)
var microSurfaceTexel: vec4f=textureSample(microSurfaceSampler,microSurfaceSamplerSampler,fragmentInputs.vMicroSurfaceSamplerUV+uvOffset)*uniforms.vMicroSurfaceSamplerInfos.y;
#endif
#ifdef BASE_DIFFUSE_ROUGHNESS
var baseDiffuseRoughnessTexture: f32=textureSample(baseDiffuseRoughnessSampler,baseDiffuseRoughnessSamplerSampler,fragmentInputs.vBaseDiffuseRoughnessUV+uvOffset).x;
#endif
#ifdef METALLICWORKFLOW
var metallicReflectanceFactors: vec4f=uniforms.vMetallicReflectanceFactors;
#ifdef REFLECTANCE
var reflectanceFactorsMap: vec4f=textureSample(reflectanceSampler,reflectanceSamplerSampler,fragmentInputs.vReflectanceUV+uvOffset);
#ifdef REFLECTANCE_GAMMA
reflectanceFactorsMap=toLinearSpaceVec4(reflectanceFactorsMap);
#endif
metallicReflectanceFactors=vec4f(metallicReflectanceFactors.rgb*reflectanceFactorsMap.rgb,metallicReflectanceFactors.a);
#endif
#ifdef METALLIC_REFLECTANCE
var metallicReflectanceFactorsMap: vec4f=textureSample(metallicReflectanceSampler,metallicReflectanceSamplerSampler,fragmentInputs.vMetallicReflectanceUV+uvOffset);
#ifdef METALLIC_REFLECTANCE_GAMMA
metallicReflectanceFactorsMap=toLinearSpaceVec4(metallicReflectanceFactorsMap);
#endif
#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY
metallicReflectanceFactors=vec4f(metallicReflectanceFactors.rgb*metallicReflectanceFactorsMap.rgb,metallicReflectanceFactors.a);
#endif
metallicReflectanceFactors.a*=metallicReflectanceFactorsMap.a;
#endif
#endif
reflectivityOut=reflectivityBlock(
uniforms.vReflectivityColor
#ifdef METALLICWORKFLOW
,surfaceAlbedo
,metallicReflectanceFactors
#endif
,uniforms.baseDiffuseRoughness
#ifdef BASE_DIFFUSE_ROUGHNESS
,baseDiffuseRoughnessTexture
,uniforms.vBaseDiffuseRoughnessInfos
#endif
#ifdef REFLECTIVITY
,uniforms.vReflectivityInfos
,surfaceMetallicOrReflectivityColorMap
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
,aoOut.ambientOcclusionColor
#endif
#ifdef MICROSURFACEMAP
,microSurfaceTexel
#endif
#ifdef DETAIL
,detailColor
,uniforms.vDetailInfos
#endif
);var microSurface: f32=reflectivityOut.microSurface;var roughness: f32=reflectivityOut.roughness;var diffuseRoughness: f32=reflectivityOut.diffuseRoughness;
#ifdef METALLICWORKFLOW
surfaceAlbedo=reflectivityOut.surfaceAlbedo;
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;
#endif
#ifdef ALPHAFRESNEL
#if defined(ALPHATEST) || defined(ALPHABLEND)
var alphaFresnelOut: alphaFresnelOutParams;alphaFresnelOut=alphaFresnelBlock(
normalW,
viewDirectionW,
alpha,
microSurface
);alpha=alphaFresnelOut.alpha;
#endif
#endif
#include<pbrBlockGeometryInfo>
#ifdef ANISOTROPIC
var anisotropicOut: anisotropicOutParams;
#ifdef ANISOTROPIC_TEXTURE
var anisotropyMapData: vec3f=textureSample(anisotropySampler,anisotropySamplerSampler,fragmentInputs.vAnisotropyUV+uvOffset).rgb*uniforms.vAnisotropyInfos.y;
#endif
anisotropicOut=anisotropicBlock(
uniforms.vAnisotropy,
roughness,
#ifdef ANISOTROPIC_TEXTURE
anisotropyMapData,
#endif
TBN,
normalW,
viewDirectionW
);
#endif
#ifdef REFLECTION
var reflectionOut: reflectionOutParams;
#ifndef USE_CUSTOM_REFLECTION
reflectionOut=reflectionBlock(
fragmentInputs.vPositionW
,normalW
,alphaG
,uniforms.vReflectionMicrosurfaceInfos
,uniforms.vReflectionInfos
,uniforms.vReflectionColor
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,NdotVUnclamped
#endif
#ifdef LINEARSPECULARREFLECTION
,roughness
#endif
,reflectionSampler
,reflectionSamplerSampler
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,fragmentInputs.vEnvironmentIrradiance
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,uniforms.reflectionMatrix
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
,irradianceSamplerSampler
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
,uniforms.vReflectionDominantDirection
#endif
#endif
#ifndef LODBASEDMICROSFURACE
,reflectionLowSampler
,reflectionLowSamplerSampler
,reflectionHighSampler
,reflectionHighSamplerSampler
#endif
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
,icdfSamplerSampler
#endif
#endif
,viewDirectionW
,diffuseRoughness
,surfaceAlbedo
);
#else
#define CUSTOM_REFLECTION
#endif
#endif
#include<pbrBlockReflectance0>
#ifdef SHEEN
var sheenOut: sheenOutParams;
#ifdef SHEEN_TEXTURE
var sheenMapData: vec4f=textureSample(sheenSampler,sheenSamplerSampler,fragmentInputs.vSheenUV+uvOffset);
#endif
#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
var sheenMapRoughnessData: vec4f=textureSample(sheenRoughnessSampler,sheenRoughnessSamplerSampler,fragmentInputs.vSheenRoughnessUV+uvOffset)*uniforms.vSheenInfos.w;
#endif
sheenOut=sheenBlock(
uniforms.vSheenColor
#ifdef SHEEN_ROUGHNESS
,uniforms.vSheenRoughness
#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
,sheenMapRoughnessData
#endif
#endif
,roughness
#ifdef SHEEN_TEXTURE
,sheenMapData
,uniforms.vSheenInfos.y
#endif
,reflectanceF0
#ifdef SHEEN_LINKWITHALBEDO
,baseColor
,surfaceAlbedo
#endif
#ifdef ENVIRONMENTBRDF
,NdotV
,environmentBrdf
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
,AARoughnessFactors
,uniforms.vReflectionMicrosurfaceInfos
,uniforms.vReflectionInfos
,uniforms.vReflectionColor
,uniforms.vLightingIntensity
,reflectionSampler
,reflectionSamplerSampler
,reflectionOut.reflectionCoords
,NdotVUnclamped
#ifndef LODBASEDMICROSFURACE
,reflectionLowSampler
,reflectionLowSamplerSampler
,reflectionHighSampler
,reflectionHighSamplerSampler
#endif
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
,seo
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
,eho
#endif
#endif
);
#ifdef SHEEN_LINKWITHALBEDO
surfaceAlbedo=sheenOut.surfaceAlbedo;
#endif
#endif
#ifdef CLEARCOAT
#ifdef CLEARCOAT_TEXTURE
var clearCoatMapData: vec2f=textureSample(clearCoatSampler,clearCoatSamplerSampler,fragmentInputs.vClearCoatUV+uvOffset).rg*uniforms.vClearCoatInfos.y;
#endif
#endif
#ifdef IRIDESCENCE
var iridescenceOut: iridescenceOutParams;
#ifdef IRIDESCENCE_TEXTURE
var iridescenceMapData: vec2f=textureSample(iridescenceSampler,iridescenceSamplerSampler,fragmentInputs.vIridescenceUV+uvOffset).rg*uniforms.vIridescenceInfos.y;
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
var iridescenceThicknessMapData: vec2f=textureSample(iridescenceThicknessSampler,iridescenceThicknessSamplerSampler,fragmentInputs.vIridescenceThicknessUV+uvOffset).rg*uniforms.vIridescenceInfos.w;
#endif
iridescenceOut=iridescenceBlock(
uniforms.vIridescenceParams
,NdotV
,specularEnvironmentR0
#ifdef IRIDESCENCE_TEXTURE
,iridescenceMapData
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
,iridescenceThicknessMapData
#endif
#ifdef CLEARCOAT
,NdotVUnclamped
,uniforms.vClearCoatParams
#ifdef CLEARCOAT_TEXTURE
,clearCoatMapData
#endif
#endif
);var iridescenceIntensity: f32=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0;
#endif
var clearcoatOut: clearcoatOutParams;
#ifdef CLEARCOAT
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
var clearCoatMapRoughnessData: vec4f=textureSample(clearCoatRoughnessSampler,clearCoatRoughnessSamplerSampler,fragmentInputs.vClearCoatRoughnessUV+uvOffset)*uniforms.vClearCoatInfos.w;
#endif
#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
var clearCoatTintMapData: vec4f=textureSample(clearCoatTintSampler,clearCoatTintSamplerSampler,fragmentInputs.vClearCoatTintUV+uvOffset);
#endif
#ifdef CLEARCOAT_BUMP
var clearCoatBumpMapData: vec4f=textureSample(clearCoatBumpSampler,clearCoatBumpSamplerSampler,fragmentInputs.vClearCoatBumpUV+uvOffset);
#endif
clearcoatOut=clearcoatBlock(
fragmentInputs.vPositionW
,geometricNormalW
,viewDirectionW
,uniforms.vClearCoatParams
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
,clearCoatMapRoughnessData
#endif
,specularEnvironmentR0
#ifdef CLEARCOAT_TEXTURE
,clearCoatMapData
#endif
#ifdef CLEARCOAT_TINT
,uniforms.vClearCoatTintParams
,uniforms.clearCoatColorAtDistance
,uniforms.vClearCoatRefractionParams
#ifdef CLEARCOAT_TINT_TEXTURE
,clearCoatTintMapData
#endif
#endif
#ifdef CLEARCOAT_BUMP
,uniforms.vClearCoatBumpInfos
,clearCoatBumpMapData
,fragmentInputs.vClearCoatBumpUV
#if defined(TANGENT) && defined(NORMAL)
,mat3x3<f32>(input.vTBN0,input.vTBN1,input.vTBN2)
#else
,uniforms.vClearCoatTangentSpaceParams
#endif
#ifdef OBJECTSPACE_NORMALMAP
,uniforms.normalMatrix
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
,faceNormal
#endif
#ifdef REFLECTION
,uniforms.vReflectionMicrosurfaceInfos
,uniforms.vReflectionInfos
,uniforms.vReflectionColor
,uniforms.vLightingIntensity
,reflectionSampler
,reflectionSamplerSampler
#ifndef LODBASEDMICROSFURACE
,reflectionLowSampler
,reflectionLowSamplerSampler
,reflectionHighSampler
,reflectionHighSamplerSampler
#endif
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#endif
#endif
#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
,select(-1.,1.,fragmentInputs.frontFacing)
#endif
);
#else
clearcoatOut.specularEnvironmentR0=specularEnvironmentR0;
#endif
#include<pbrBlockReflectance>
var subSurfaceOut: subSurfaceOutParams;
#ifdef SUBSURFACE
#ifdef SS_THICKNESSANDMASK_TEXTURE
var thicknessMap: vec4f=textureSample(thicknessSampler,thicknessSamplerSampler,fragmentInputs.vThicknessUV+uvOffset);
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
var refractionIntensityMap: vec4f=textureSample(refractionIntensitySampler,refractionIntensitySamplerSampler,fragmentInputs.vRefractionIntensityUV+uvOffset);
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
var translucencyIntensityMap: vec4f=textureSample(translucencyIntensitySampler,translucencyIntensitySamplerSampler,fragmentInputs.vTranslucencyIntensityUV+uvOffset);
#endif
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
var translucencyColorMap: vec4f=textureSample(translucencyColorSampler,translucencyColorSamplerSampler,fragmentInputs.vTranslucencyColorUV+uvOffset);
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA
translucencyColorMap=toLinearSpaceVec4(translucencyColorMap);
#endif
#endif
subSurfaceOut=subSurfaceBlock(
uniforms.vSubSurfaceIntensity
,uniforms.vThicknessParam
,uniforms.vTintColor
,normalW
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
,vec3f(max(colorSpecularEnvironmentReflectance.r,max(colorSpecularEnvironmentReflectance.g,colorSpecularEnvironmentReflectance.b)))
#else
,baseSpecularEnvironmentReflectance
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
,thicknessMap
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
,refractionIntensityMap
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
,translucencyIntensityMap
#endif
#ifdef REFLECTION
#ifdef SS_TRANSLUCENCY
,uniforms.reflectionMatrix
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
,reflectionOut.irradianceVector
#endif
#if defined(REALTIME_FILTERING)
,reflectionSampler
,reflectionSamplerSampler
,uniforms.vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
,icdfSamplerSampler
#endif
#endif
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
,irradianceSamplerSampler
#endif
#endif
#endif
#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
,surfaceAlbedo
#endif
#ifdef SS_REFRACTION
,fragmentInputs.vPositionW
,viewDirectionW
,scene.view
,uniforms.vRefractionInfos
,uniforms.refractionMatrix
,uniforms.vRefractionMicrosurfaceInfos
,uniforms.vLightingIntensity
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
,alpha
#endif
#ifdef SS_LODINREFRACTIONALPHA
,NdotVUnclamped
#endif
#ifdef SS_LINEARSPECULARREFRACTION
,roughness
#endif
,alphaG
,refractionSampler
,refractionSamplerSampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler
,refractionLowSamplerSampler
,refractionHighSampler
,refractionHighSamplerSampler
#endif
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,uniforms.vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,uniforms.vRefractionPosition
,uniforms.vRefractionSize
#endif
#ifdef SS_DISPERSION
,uniforms.dispersion
#endif
#endif
#ifdef SS_TRANSLUCENCY
,uniforms.vDiffusionDistance
,uniforms.vTranslucencyColor
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
,translucencyColorMap
#endif
#endif
);
#ifdef SS_REFRACTION
surfaceAlbedo=subSurfaceOut.surfaceAlbedo;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
alpha=subSurfaceOut.alpha;
#endif
#endif
#else
subSurfaceOut.specularEnvironmentReflectance=colorSpecularEnvironmentReflectance;
#endif
#include<pbrBlockDirectLighting>
#include<lightFragment>[0..maxSimultaneousLights]
#include<pbrBlockFinalLitComponents>
#endif
#include<pbrBlockFinalUnlitComponents>
#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION
#include<pbrBlockFinalColorComposition>
#include<logDepthFragment>
#include<fogFragment>(color,finalColor)
#include<pbrBlockImageProcessing>
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
#include<pbrBlockPrePass>
#endif
#if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY)
fragmentOutputs.color=finalColor;
#endif
#include<oitFragment>
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+finalColor.rgb*finalColor.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-finalColor.a));} else {fragmentOutputs.backColor+=finalColor;}
#endif
#include<pbrDebug>
#define CUSTOM_FRAGMENT_MAIN_END
}
`;x.ShadersStoreWGSL[PF]||(x.ShadersStoreWGSL[PF]=ZZ);OEe={name:PF,shader:ZZ}});var $Z,NEe,JZ=y(()=>{k();rM();$Z="pbrVertexDeclaration",NEe=`uniform mat4 view;uniform mat4 viewProjection;uniform vec4 vEyePosition;
#ifdef MULTIVIEW
mat4 viewProjectionR;
#endif
#ifdef ALBEDO
uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos;
#endif
#ifdef BASE_WEIGHT
uniform mat4 baseWeightMatrix;uniform vec2 vBaseWeightInfos;
#endif
uniform float baseDiffuseRoughness;
#ifdef BASE_DIFFUSE_ROUGHNESS
uniform mat4 baseDiffuseRoughnessMatrix;uniform vec2 vBaseDiffuseRoughnessInfos;
#endif
#ifdef AMBIENT
uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos;
#endif
#ifdef OPACITY
uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;
#endif
#ifdef REFLECTIVITY
uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix;
#endif
#ifdef METALLIC_REFLECTANCE
uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix;
#endif
#ifdef REFLECTANCE
uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix;
#endif
#ifdef MICROSURFACEMAP
uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform mat4 bumpMatrix;
#endif
#ifdef POINTSIZE
uniform float pointSize;
#endif
uniform vec4 cameraInfo;
#ifdef REFLECTION
uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;
#endif
#ifdef CLEARCOAT
#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)
uniform vec4 vClearCoatInfos;
#endif
#ifdef CLEARCOAT_TEXTURE
uniform mat4 clearCoatMatrix;
#endif
#ifdef CLEARCOAT_TEXTURE_ROUGHNESS
uniform mat4 clearCoatRoughnessMatrix;
#endif
#ifdef CLEARCOAT_BUMP
uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix;
#endif
#ifdef CLEARCOAT_TINT_TEXTURE
uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;
#endif
#endif
#ifdef IRIDESCENCE
#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)
uniform vec4 vIridescenceInfos;
#endif
#ifdef IRIDESCENCE_TEXTURE
uniform mat4 iridescenceMatrix;
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
uniform mat4 iridescenceThicknessMatrix;
#endif
#endif
#ifdef ANISOTROPIC
#ifdef ANISOTROPIC_TEXTURE
uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;
#endif
#endif
#ifdef SHEEN
#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)
uniform vec4 vSheenInfos;
#endif
#ifdef SHEEN_TEXTURE
uniform mat4 sheenMatrix;
#endif
#ifdef SHEEN_TEXTURE_ROUGHNESS
uniform mat4 sheenRoughnessMatrix;
#endif
#endif
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;
#endif
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
uniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;
#endif
#endif
#ifdef NORMAL
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;
#else
uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;
#endif
#endif
#endif
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;uniform mat4 detailMatrix;
#endif
#include<decalVertexDeclaration>
#define ADDITIONAL_VERTEX_DECLARATION
`;x.IncludesShadersStore[$Z]||(x.IncludesShadersStore[$Z]=NEe)});var eq,wEe,LF=y(()=>{k();lh();_E();eq="pbrUboDeclaration",wEe=`layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec2 vBaseWeightInfos;vec2 vBaseDiffuseRoughnessInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec3 vBumpInfos;mat4 albedoMatrix;mat4 baseWeightMatrix;mat4 baseDiffuseRoughnessMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;vec4 vAlbedoColor;float baseWeight;float baseDiffuseRoughness;vec4 vLightingIntensity;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec4 cameraInfo;vec2 vReflectionInfos;mat4 reflectionMatrix;vec3 vReflectionMicrosurfaceInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vReflectionFilteringInfo;vec3 vReflectionDominantDirection;vec3 vReflectionColor;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;
#define ADDITIONAL_UBO_DECLARATION
};
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;x.IncludesShadersStore[eq]||(x.IncludesShadersStore[eq]=wEe)});var iq={};Be(iq,{pbrVertexShader:()=>FEe});var DF,tq,FEe,rq=y(()=>{k();JZ();LF();nM();cg();oo();gg();$c();Jc();bd();sM();aM();_g();cN();ef();sE();oM();lM();Ld();Dd();ch();Od();Nd();tf();rf();nf();cM();fM();dM();uM();sf();aE();hM();oE();mM();DF="pbrVertexShader",tq=`#define PBR_VERTEX_SHADER
#define CUSTOM_VERTEX_EXTENSION
precision highp float;
#include<__decl__pbrVertex>
#define CUSTOM_VERTEX_BEGIN
attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#ifdef TANGENT
attribute vec4 tangent;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#include<uvAttributeDeclaration>[2..7]
#include<mainUVVaryingDeclaration>[1..7]
#ifdef VERTEXCOLOR
attribute vec4 color;
#endif
#include<helperFunctions>
#include<pbrBRDFFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)
#include<samplerVertexDeclaration>(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)
#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)
#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)
#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)
#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)
#ifdef CLEARCOAT
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)
#endif
#ifdef IRIDESCENCE
#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)
#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)
#endif
#ifdef SHEEN
#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)
#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
#endif
#ifdef ANISOTROPIC
#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)
#endif
#ifdef SUBSURFACE
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor)
#endif
varying vec3 vPositionW;
#if DEBUGMODE>0
varying vec4 vClipSpacePosition;
#endif
#ifdef NORMAL
varying vec3 vNormalW;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vec3 vEnvironmentIrradiance;
#include<harmonicsFunctions>
#endif
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#include<bumpVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
varying float vViewDepth;
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec3 positionUpdated=position;
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#ifdef TANGENT
vec4 tangentUpdated=tangent;
#endif
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#ifdef VERTEXCOLOR
vec4 colorUpdated=color;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos);
#ifdef PREPASS
#include<prePassVertex>
#endif
#ifdef NORMAL
mat3 normalWorld=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vNormalW=normalize(normalWorld*normalUpdated);
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
#if BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LAMBERT && BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LEGACY
vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);float NdotV=max(dot(vNormalW,viewDirectionW),0.0);vec3 roughNormal=mix(vNormalW,viewDirectionW,(0.5*(1.0-NdotV))*baseDiffuseRoughness);vec3 reflectionVector=vec3(reflectionMatrix*vec4(roughNormal,0)).xyz;
#else
vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}
#else
gl_Position=viewProjection*worldPos;
#endif
#if DEBUGMODE>0
vClipSpacePosition=gl_Position;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
#ifdef RIGHT_HANDED
vViewDepth=-(view*worldPos).z;
#else
vViewDepth=(view*worldPos).z;
#endif
#endif
#ifndef UV1
vec2 uvUpdated=vec2(0.,0.);
#endif
#ifndef UV2
vec2 uv2Updated=vec2(0.,0.);
#endif
#ifdef MAINUV1
vMainUV1=uvUpdated;
#endif
#ifdef MAINUV2
vMainUV2=uv2Updated;
#endif
#include<uvVariableDeclaration>[3..7]
#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight,_MATRIXNAME_,baseWeight,_INFONAME_,BaseWeightInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness,_MATRIXNAME_,baseDiffuseRoughness,_INFONAME_,BaseDiffuseRoughnessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)
#ifdef CLEARCOAT
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)
#endif
#ifdef IRIDESCENCE
#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)
#endif
#ifdef SHEEN
#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z)
#endif
#ifdef ANISOTROPIC
#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)
#endif
#ifdef SUBSURFACE
#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x)
#endif
#include<bumpVertex>
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#include<vertexColorMixing>
#if defined(POINTSIZE) && !defined(WEBGPU)
gl_PointSize=pointSize;
#endif
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}
`;x.ShadersStore[DF]||(x.ShadersStore[DF]=tq);FEe={name:DF,shader:tq}});var nq,BEe,sq=y(()=>{k();pM();nq="pbrFragmentDeclaration",BEe=`uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform float baseWeight;uniform float baseDiffuseRoughness;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor;
#ifdef ALBEDO
uniform vec2 vAlbedoInfos;
#endif
#ifdef BASE_WEIGHT
uniform vec2 vBaseWeightInfos;
#endif
#ifdef BASE_DIFFUSE_ROUGHNESS
uniform vec2 vBaseDiffuseRoughnessInfos;
#endif
#ifdef AMBIENT
uniform vec4 vAmbientInfos;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;
#endif
#ifdef OPACITY
uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;
#endif
#ifdef REFLECTIVITY
uniform vec3 vReflectivityInfos;
#endif
#ifdef MICROSURFACEMAP
uniform vec2 vMicroSurfaceSamplerInfos;
#endif
#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)
uniform mat4 view;
#endif
#ifdef REFLECTION
uniform vec2 vReflectionInfos;
#ifdef REALTIME_FILTERING
uniform vec2 vReflectionFilteringInfo;
#endif
uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;
#if defined(USEIRRADIANCEMAP) && defined(USE_IRRADIANCE_DOMINANT_DIRECTION)
uniform vec3 vReflectionDominantDirection;
#endif
#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)
uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;
#endif
#endif
#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)
uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize;
#endif
#ifdef CLEARCOAT
uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams;
#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)
uniform vec4 vClearCoatInfos;
#endif
#ifdef CLEARCOAT_TEXTURE
uniform mat4 clearCoatMatrix;
#endif
#ifdef CLEARCOAT_TEXTURE_ROUGHNESS
uniform mat4 clearCoatRoughnessMatrix;
#endif
#ifdef CLEARCOAT_BUMP
uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix;
#endif
#ifdef CLEARCOAT_TINT
uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance;
#ifdef CLEARCOAT_TINT_TEXTURE
uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;
#endif
#endif
#endif
#ifdef IRIDESCENCE
uniform vec4 vIridescenceParams;
#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)
uniform vec4 vIridescenceInfos;
#endif
#ifdef IRIDESCENCE_TEXTURE
uniform mat4 iridescenceMatrix;
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
uniform mat4 iridescenceThicknessMatrix;
#endif
#endif
#ifdef ANISOTROPIC
uniform vec3 vAnisotropy;
#ifdef ANISOTROPIC_TEXTURE
uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;
#endif
#endif
#ifdef SHEEN
uniform vec4 vSheenColor;
#ifdef SHEEN_ROUGHNESS
uniform float vSheenRoughness;
#endif
#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)
uniform vec4 vSheenInfos;
#endif
#ifdef SHEEN_TEXTURE
uniform mat4 sheenMatrix;
#endif
#ifdef SHEEN_TEXTURE_ROUGHNESS
uniform mat4 sheenRoughnessMatrix;
#endif
#endif
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;
#ifdef REALTIME_FILTERING
uniform vec2 vRefractionFilteringInfo;
#endif
#ifdef SS_DISPERSION
uniform float dispersion;
#endif
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;
#endif
uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;uniform vec4 vTranslucencyColor;
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
uniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;
#endif
#endif
#ifdef PREPASS
#ifdef SS_SCATTERING
uniform float scatteringDiffusionProfile;
#endif
#endif
#if DEBUGMODE>0
uniform vec2 vDebugMode;
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;
#endif
#include<decalFragmentDeclaration>
#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;
#else
uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;
#endif
#endif
#define ADDITIONAL_FRAGMENT_DECLARATION
`;x.IncludesShadersStore[nq]||(x.IncludesShadersStore[nq]=BEe)});var aq,UEe,oq=y(()=>{k();aq="samplerFragmentAlternateDeclaration",UEe=`#ifdef _DEFINENAME_
#if _DEFINENAME_DIRECTUV==1
#define v_VARYINGNAME_UV vMainUV1
#elif _DEFINENAME_DIRECTUV==2
#define v_VARYINGNAME_UV vMainUV2
#elif _DEFINENAME_DIRECTUV==3
#define v_VARYINGNAME_UV vMainUV3
#elif _DEFINENAME_DIRECTUV==4
#define v_VARYINGNAME_UV vMainUV4
#elif _DEFINENAME_DIRECTUV==5
#define v_VARYINGNAME_UV vMainUV5
#elif _DEFINENAME_DIRECTUV==6
#define v_VARYINGNAME_UV vMainUV6
#else
varying vec2 v_VARYINGNAME_UV;
#endif
#endif
`;x.IncludesShadersStore[aq]||(x.IncludesShadersStore[aq]=UEe)});var lq,VEe,cq=y(()=>{k();fh();oq();ey();lq="pbrFragmentSamplersDeclaration",VEe=`#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight,_SAMPLERNAME_,baseWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness,_SAMPLERNAME_,baseDiffuseRoughness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)
#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)
#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)
#ifdef CLEARCOAT
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)
#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)
uniform sampler2D clearCoatRoughnessSampler;
#endif
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)
#endif
#ifdef IRIDESCENCE
#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)
#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)
#endif
#ifdef SHEEN
#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)
#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)
uniform sampler2D sheenRoughnessSampler;
#endif
#endif
#ifdef ANISOTROPIC
#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)
#endif
#include<pbrFragmentReflectionDeclaration>
#ifdef ENVIRONMENTBRDF
uniform sampler2D environmentBrdfSampler;
#endif
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
#ifdef SS_REFRACTIONMAP_3D
#define sampleRefraction(s,c) textureCube(s,c)
uniform samplerCube refractionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)
#else
uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh;
#endif
#else
#define sampleRefraction(s,c) texture2D(s,c)
uniform sampler2D refractionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)
#else
uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh;
#endif
#endif
#endif
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)
#endif
#ifdef IBL_CDF_FILTERING
uniform sampler2D icdfSampler;
#endif
`;x.IncludesShadersStore[lq]||(x.IncludesShadersStore[lq]=VEe)});var fq,GEe,dq=y(()=>{k();mN();fq="pbrBlockAlbedoOpacity",GEe=`struct albedoOpacityOutParams
{vec3 surfaceAlbedo;float alpha;};
#define pbr_inline
albedoOpacityOutParams albedoOpacityBlock(
in vec4 vAlbedoColor
#ifdef ALBEDO
,in vec4 albedoTexture
,in vec2 albedoInfos
#endif
,in float baseWeight
#ifdef BASE_WEIGHT
,in vec4 baseWeightTexture
,in vec2 vBaseWeightInfos
#endif
#ifdef OPACITY
,in vec4 opacityMap
,in vec2 vOpacityInfos
#endif
#ifdef DETAIL
,in vec4 detailColor
,in vec4 vDetailInfos
#endif
#ifdef DECAL
,in vec4 decalColor
,in vec4 vDecalInfos
#endif
)
{albedoOpacityOutParams outParams;vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a;
#ifdef ALBEDO
#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)
alpha*=albedoTexture.a;
#endif
#ifdef GAMMAALBEDO
surfaceAlbedo*=toLinearSpace(albedoTexture.rgb);
#else
surfaceAlbedo*=albedoTexture.rgb;
#endif
surfaceAlbedo*=albedoInfos.y;
#endif
#ifndef DECAL_AFTER_DETAIL
#include<decalFragment>
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
surfaceAlbedo*=vColor.rgb;
#endif
#ifdef DETAIL
float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo;
#endif
#ifdef DECAL_AFTER_DETAIL
#include<decalFragment>
#endif
#define CUSTOM_FRAGMENT_UPDATE_ALBEDO
surfaceAlbedo*=baseWeight;
#ifdef BASE_WEIGHT
surfaceAlbedo*=baseWeightTexture.r;
#endif
#ifdef OPACITY
#ifdef OPACITYRGB
alpha=getLuminance(opacityMap.rgb);
#else
alpha*=opacityMap.a;
#endif
alpha*=vOpacityInfos.y;
#endif
#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)
alpha*=vColor.a;
#endif
#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)
#ifdef ALPHATEST
#if DEBUGMODE != 88
if (alpha<ALPHATESTVALUE)
discard;
#endif
#ifndef ALPHABLEND
alpha=1.0;
#endif
#endif
#endif
outParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;return outParams;}
`;x.IncludesShadersStore[fq]||(x.IncludesShadersStore[fq]=GEe)});var uq,kEe,hq=y(()=>{k();uq="pbrBlockReflectivity",kEe=`struct reflectivityOutParams
{float microSurface;float roughness;float diffuseRoughness;float reflectanceF0;vec3 reflectanceF90;vec3 colorReflectanceF0;vec3 colorReflectanceF90;
#ifdef METALLICWORKFLOW
vec3 surfaceAlbedo;float metallic;float specularWeight;vec3 dielectricColorF0;
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
vec3 ambientOcclusionColor;
#endif
#if DEBUGMODE>0
#ifdef METALLICWORKFLOW
#ifdef REFLECTIVITY
vec4 surfaceMetallicColorMap;
#endif
vec3 metallicF0;
#else
#ifdef REFLECTIVITY
vec4 surfaceReflectivityColorMap;
#endif
#endif
#endif
};
#define pbr_inline
reflectivityOutParams reflectivityBlock(
in vec4 reflectivityColor
#ifdef METALLICWORKFLOW
,in vec3 surfaceAlbedo
,in vec4 metallicReflectanceFactors
#endif
,in float baseDiffuseRoughness
#ifdef BASE_DIFFUSE_ROUGHNESS
,in float baseDiffuseRoughnessTexture
,in vec2 baseDiffuseRoughnessInfos
#endif
#ifdef REFLECTIVITY
,in vec3 reflectivityInfos
,in vec4 surfaceMetallicOrReflectivityColorMap
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
,in vec3 ambientOcclusionColorIn
#endif
#ifdef MICROSURFACEMAP
,in vec4 microSurfaceTexel
#endif
#ifdef DETAIL
,in vec4 detailColor
,in vec4 vDetailInfos
#endif
)
{reflectivityOutParams outParams;float microSurface=reflectivityColor.a;vec3 surfaceReflectivityColor=reflectivityColor.rgb;
#ifdef METALLICWORKFLOW
vec2 metallicRoughness=surfaceReflectivityColor.rg;float ior=surfaceReflectivityColor.b;
#ifdef REFLECTIVITY
#if DEBUGMODE>0
outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;
#endif
#ifdef AOSTOREINMETALMAPRED
vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);
#endif
#ifdef METALLNESSSTOREINMETALMAPBLUE
metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;
#else
metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;
#endif
#ifdef ROUGHNESSSTOREINMETALMAPALPHA
metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;
#else
#ifdef ROUGHNESSSTOREINMETALMAPGREEN
metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;
#endif
#endif
#endif
#ifdef DETAIL
float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));
#endif
#ifdef MICROSURFACEMAP
metallicRoughness.g*=microSurfaceTexel.r;
#endif
#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS
microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo;outParams.metallic=metallicRoughness.r;outParams.specularWeight=metallicReflectanceFactors.a;float dielectricF0=reflectivityColor.a*outParams.specularWeight;surfaceReflectivityColor=metallicReflectanceFactors.rgb;
#if DEBUGMODE>0
outParams.metallicF0=vec3(dielectricF0)*surfaceReflectivityColor;
#endif
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
outParams.surfaceAlbedo=baseColor.rgb*(vec3(1.0)-vec3(dielectricF0)*surfaceReflectivityColor)*(1.0-outParams.metallic);
#else
outParams.surfaceAlbedo=baseColor.rgb;
#endif
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
{vec3 reflectivityColor=mix(dielectricF0*surfaceReflectivityColor,baseColor.rgb,outParams.metallic);outParams.reflectanceF0=max(reflectivityColor.r,max(reflectivityColor.g,reflectivityColor.b));}
#else
#if DIELECTRIC_SPECULAR_MODEL==DIELECTRIC_SPECULAR_MODEL_GLTF
float maxF0=max(surfaceReflectivityColor.r,max(surfaceReflectivityColor.g,surfaceReflectivityColor.b));outParams.reflectanceF0=mix(dielectricF0*maxF0,1.0,outParams.metallic);
#else
outParams.reflectanceF0=mix(dielectricF0,1.0,outParams.metallic);
#endif
#endif
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
outParams.reflectanceF90=vec3(outParams.specularWeight);float f90Scale=1.0;
#else
float f90Scale=clamp(2.0*(ior-1.0),0.0,1.0);outParams.reflectanceF90=vec3(mix(outParams.specularWeight*f90Scale,1.0,outParams.metallic));
#endif
outParams.dielectricColorF0=vec3(dielectricF0*surfaceReflectivityColor);vec3 metallicColorF0=baseColor.rgb;outParams.colorReflectanceF0=mix(outParams.dielectricColorF0,metallicColorF0,outParams.metallic);
#if (DIELECTRIC_SPECULAR_MODEL==DIELECTRIC_SPECULAR_MODEL_OPENPBR)
vec3 dielectricColorF90=surfaceReflectivityColor*vec3(outParams.specularWeight)*vec3(f90Scale);
#else
vec3 dielectricColorF90=vec3(outParams.specularWeight*f90Scale);
#endif
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR)
vec3 conductorColorF90=surfaceReflectivityColor;
#else
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
vec3 conductorColorF90=outParams.reflectanceF90;
#else
vec3 conductorColorF90=vec3(1.0);
#endif
#endif
outParams.colorReflectanceF90=mix(dielectricColorF90,conductorColorF90,outParams.metallic);
#else
#ifdef REFLECTIVITY
surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;
#if DEBUGMODE>0
outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;
#endif
#ifdef MICROSURFACEFROMREFLECTIVITYMAP
microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z;
#else
#ifdef MICROSURFACEAUTOMATIC
microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);
#endif
#ifdef MICROSURFACEMAP
microSurface*=microSurfaceTexel.r;
#endif
#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE
#endif
#endif
outParams.colorReflectanceF0=surfaceReflectivityColor;outParams.reflectanceF0=max(surfaceReflectivityColor.r,max(surfaceReflectivityColor.g,surfaceReflectivityColor.b));outParams.reflectanceF90=vec3(1.0);
#if (DIELECTRIC_SPECULAR_MODEL==DIELECTRIC_SPECULAR_MODEL_OPENPBR)
outParams.colorReflectanceF90=surfaceReflectivityColor;
#else
outParams.colorReflectanceF90=vec3(1.0);
#endif
#endif
microSurface=saturate(microSurface);float roughness=1.-microSurface;float diffuseRoughness=baseDiffuseRoughness;
#ifdef BASE_DIFFUSE_ROUGHNESS
diffuseRoughness*=baseDiffuseRoughnessTexture*baseDiffuseRoughnessInfos.y;
#endif
outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.diffuseRoughness=diffuseRoughness;return outParams;}
`;x.IncludesShadersStore[uq]||(x.IncludesShadersStore[uq]=kEe)});var mq,zEe,pq=y(()=>{k();mq="pbrBlockAmbientOcclusion",zEe=`struct ambientOcclusionOutParams
{vec3 ambientOcclusionColor;
#if DEBUGMODE>0 && defined(AMBIENT)
vec3 ambientOcclusionColorMap;
#endif
};ambientOcclusionOutParams ambientOcclusionBlock(
#ifdef AMBIENT
in vec3 ambientOcclusionColorMap_,
in vec4 vAmbientInfos
#endif
)
{ambientOcclusionOutParams outParams;vec3 ambientOcclusionColor=vec3(1.,1.,1.);
#ifdef AMBIENT
vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y;
#ifdef AMBIENTINGRAYSCALE
ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);
#endif
ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);
#if DEBUGMODE>0
outParams.ambientOcclusionColorMap=ambientOcclusionColorMap;
#endif
#endif
outParams.ambientOcclusionColor=ambientOcclusionColor;return outParams;}
`;x.IncludesShadersStore[mq]||(x.IncludesShadersStore[mq]=zEe)});var gq,WEe,_q=y(()=>{k();gq="pbrBlockAlphaFresnel",WEe=`#ifdef ALPHAFRESNEL
#if defined(ALPHATEST) || defined(ALPHABLEND)
struct alphaFresnelOutParams
{float alpha;};
#define pbr_inline
alphaFresnelOutParams alphaFresnelBlock(
in vec3 normalW,
in vec3 viewDirectionW,
in float alpha,
in float microSurface
)
{alphaFresnelOutParams outParams;float opacityPerceptual=alpha;
#ifdef LINEARALPHAFRESNEL
float opacity0=opacityPerceptual;
#else
float opacity0=opacityPerceptual*opacityPerceptual;
#endif
float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;
#ifdef ALPHATEST
if (outParams.alpha<ALPHATESTVALUE)
discard;
#ifndef ALPHABLEND
outParams.alpha=1.0;
#endif
#endif
return outParams;}
#endif
#endif
`;x.IncludesShadersStore[gq]||(x.IncludesShadersStore[gq]=WEe)});var vq,HEe,Eq=y(()=>{k();vq="pbrBlockAnisotropic",HEe=`#ifdef ANISOTROPIC
struct anisotropicOutParams
{float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;vec3 anisotropicNormal;
#if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE)
vec3 anisotropyMapData;
#endif
};
#define pbr_inline
anisotropicOutParams anisotropicBlock(
in vec3 vAnisotropy,
in float roughness,
#ifdef ANISOTROPIC_TEXTURE
in vec3 anisotropyMapData,
#endif
in mat3 TBN,
in vec3 normalW,
in vec3 viewDirectionW
)
{anisotropicOutParams outParams;float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);
#ifdef ANISOTROPIC_TEXTURE
anisotropy*=anisotropyMapData.b;
#if DEBUGMODE>0
outParams.anisotropyMapData=anisotropyMapData;
#endif
anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0;
#ifdef ANISOTROPIC_LEGACY
anisotropyDirection.rg*=anisotropyMapData.rg;
#else
anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg);
#endif
#endif
mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);return outParams;}
#endif
`;x.IncludesShadersStore[vq]||(x.IncludesShadersStore[vq]=HEe)});var Sq,XEe,Tq=y(()=>{k();Sq="pbrBlockReflection",XEe=`#ifdef REFLECTION
struct reflectionOutParams
{vec4 environmentRadiance;vec3 environmentIrradiance;
#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords;
#else
vec2 reflectionCoords;
#endif
#ifdef SS_TRANSLUCENCY
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
vec3 irradianceVector;
#endif
#endif
#endif
};
#define pbr_inline
void createReflectionCoords(
in vec3 vPositionW,
in vec3 normalW,
#ifdef ANISOTROPIC
in anisotropicOutParams anisotropicOut,
#endif
#ifdef REFLECTIONMAP_3D
out vec3 reflectionCoords
#else
out vec2 reflectionCoords
#endif
)
{
#ifdef ANISOTROPIC
vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal);
#else
vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
reflectionCoords=reflectionVector;
#else
reflectionCoords=reflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
reflectionCoords/=reflectionVector.z;
#endif
reflectionCoords.y=1.0-reflectionCoords.y;
#endif
}
#define pbr_inline
#define inline
void sampleReflectionTexture(
in float alphaG,
in vec3 vReflectionMicrosurfaceInfos,
in vec2 vReflectionInfos,
in vec3 vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
in float NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
in float roughness,
#endif
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSampler,
const vec3 reflectionCoords,
#else
in sampler2D reflectionSampler,
const vec2 reflectionCoords,
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSamplerLow,
in samplerCube reflectionSamplerHigh,
#else
in sampler2D reflectionSamplerLow,
in sampler2D reflectionSamplerHigh,
#endif
#endif
#ifdef REALTIME_FILTERING
in vec2 vReflectionFilteringInfo,
#endif
out vec4 environmentRadiance
)
{
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);
#elif defined(LINEARSPECULARREFLECTION)
float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);
#else
float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);
#endif
#ifdef LODBASEDMICROSFURACE
reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;
#ifdef LODINREFLECTIONALPHA
float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);
#else
float requestedReflectionLOD=reflectionLOD;
#endif
#ifdef REALTIME_FILTERING
environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0);
#else
environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);
#endif
#else
float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix(
sampleReflection(reflectionSamplerHigh,reflectionCoords),
environmentMid,
lodReflectionNormalizedDoubled
);} else {environmentRadiance=mix(
environmentMid,
sampleReflection(reflectionSamplerLow,reflectionCoords),
lodReflectionNormalizedDoubled-1.0
);}
#endif
#ifdef RGBDREFLECTION
environmentRadiance.rgb=fromRGBD(environmentRadiance);
#endif
#ifdef GAMMAREFLECTION
environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);
#endif
environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;}
#define pbr_inline
#define inline
reflectionOutParams reflectionBlock(
in vec3 vPositionW
,in vec3 normalW
,in float alphaG
,in vec3 vReflectionMicrosurfaceInfos
,in vec2 vReflectionInfos
,in vec3 vReflectionColor
#ifdef ANISOTROPIC
,in anisotropicOutParams anisotropicOut
#endif
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,in float NdotVUnclamped
#endif
#ifdef LINEARSPECULARREFLECTION
,in float roughness
#endif
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSampler
#else
,in sampler2D reflectionSampler
#endif
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,in vec3 vEnvironmentIrradiance
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,in mat4 reflectionMatrix
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
,in samplerCube irradianceSampler
#else
,in sampler2D irradianceSampler
#endif
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
,in vec3 reflectionDominantDirection
#endif
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSamplerLow
,in samplerCube reflectionSamplerHigh
#else
,in sampler2D reflectionSamplerLow
,in sampler2D reflectionSamplerHigh
#endif
#endif
#ifdef REALTIME_FILTERING
,in vec2 vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,in sampler2D icdfSampler
#endif
#endif
,in vec3 viewDirectionW
,in float diffuseRoughness
,in vec3 surfaceAlbedo
)
{reflectionOutParams outParams;vec4 environmentRadiance=vec4(0.,0.,0.,0.);
#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords=vec3(0.);
#else
vec2 reflectionCoords=vec2(0.);
#endif
createReflectionCoords(
vPositionW,
normalW,
#ifdef ANISOTROPIC
anisotropicOut,
#endif
reflectionCoords
);sampleReflectionTexture(
alphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
roughness,
#endif
#ifdef REFLECTIONMAP_3D
reflectionSampler,
reflectionCoords,
#else
reflectionSampler,
reflectionCoords,
#endif
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
environmentRadiance
);vec3 environmentIrradiance=vec3(0.,0.,0.);
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
#ifdef ANISOTROPIC
vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz;
#else
vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;
#endif
vec3 irradianceView=vec3(reflectionMatrix*vec4(viewDirectionW,0)).xyz;
#if !defined(USE_IRRADIANCE_DOMINANT_DIRECTION) && !defined(REALTIME_FILTERING)
#if BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LAMBERT && BASE_DIFFUSE_MODEL != BRDF_DIFFUSE_MODEL_LEGACY
float NdotV=max(dot(normalW,viewDirectionW),0.0);irradianceVector=mix(irradianceVector,irradianceView,(0.5*(1.0-NdotV))*diffuseRoughness);
#endif
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;irradianceView.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;irradianceView.y*=-1.0;
#endif
#endif
#ifdef USESPHERICALFROMREFLECTIONMAP
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
environmentIrradiance=vEnvironmentIrradiance;
#else
#if defined(REALTIME_FILTERING)
environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo,diffuseRoughness,surfaceAlbedo,irradianceView
#ifdef IBL_CDF_FILTERING
,icdfSampler
#endif
);
#else
environmentIrradiance=computeEnvironmentIrradiance(irradianceVector);
#endif
#ifdef SS_TRANSLUCENCY
outParams.irradianceVector=irradianceVector;
#endif
#endif
#elif defined(USEIRRADIANCEMAP)
#ifdef REFLECTIONMAP_3D
vec4 environmentIrradiance4=sampleReflection(irradianceSampler,irradianceVector);
#else
vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);
#endif
environmentIrradiance=environmentIrradiance4.rgb;
#ifdef RGBDREFLECTION
environmentIrradiance.rgb=fromRGBD(environmentIrradiance4);
#endif
#ifdef GAMMAREFLECTION
environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);
#endif
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
vec3 Ls=normalize(reflectionDominantDirection);float NoL=dot(irradianceVector,Ls);float NoV=dot(irradianceVector,irradianceView);vec3 diffuseRoughnessTerm=vec3(1.0);
#if BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_EON
float LoV=dot (Ls,irradianceView);float mag=length(reflectionDominantDirection)*2.0;vec3 clampedAlbedo=clamp(surfaceAlbedo,vec3(0.1),vec3(1.0));diffuseRoughnessTerm=diffuseBRDF_EON(clampedAlbedo,diffuseRoughness,NoL,NoV,LoV)*PI;diffuseRoughnessTerm=diffuseRoughnessTerm/clampedAlbedo;diffuseRoughnessTerm=mix(vec3(1.0),diffuseRoughnessTerm,sqrt(clamp(mag*NoV,0.0,1.0)));
#elif BASE_DIFFUSE_MODEL==BRDF_DIFFUSE_MODEL_BURLEY
vec3 H=(irradianceView+Ls)*0.5;float VoH=dot(irradianceView,H);diffuseRoughnessTerm=vec3(diffuseBRDF_Burley(NoL,NoV,VoH,diffuseRoughness)*PI);
#endif
environmentIrradiance=environmentIrradiance.rgb*diffuseRoughnessTerm;
#endif
#endif
environmentIrradiance*=vReflectionColor.rgb*vReflectionInfos.x;
#ifdef MIX_IBL_RADIANCE_WITH_IRRADIANCE
outParams.environmentRadiance=vec4(mix(environmentRadiance.rgb,environmentIrradiance,alphaG),environmentRadiance.a);
#else
outParams.environmentRadiance=environmentRadiance;
#endif
outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;return outParams;}
#endif
`;x.IncludesShadersStore[Sq]||(x.IncludesShadersStore[Sq]=XEe)});var Aq,YEe,xq=y(()=>{k();Aq="pbrBlockSheen",YEe=`#ifdef SHEEN
struct sheenOutParams
{float sheenIntensity;vec3 sheenColor;float sheenRoughness;
#ifdef SHEEN_LINKWITHALBEDO
vec3 surfaceAlbedo;
#endif
#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
float sheenAlbedoScaling;
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
vec3 finalSheenRadianceScaled;
#endif
#if DEBUGMODE>0
#ifdef SHEEN_TEXTURE
vec4 sheenMapData;
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
vec3 sheenEnvironmentReflectance;
#endif
#endif
};
#define pbr_inline
#define inline
sheenOutParams sheenBlock(
in vec4 vSheenColor
#ifdef SHEEN_ROUGHNESS
,in float vSheenRoughness
#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
,in vec4 sheenMapRoughnessData
#endif
#endif
,in float roughness
#ifdef SHEEN_TEXTURE
,in vec4 sheenMapData
,in float sheenMapLevel
#endif
,in float reflectance
#ifdef SHEEN_LINKWITHALBEDO
,in vec3 baseColor
,in vec3 surfaceAlbedo
#endif
#ifdef ENVIRONMENTBRDF
,in float NdotV
,in vec3 environmentBrdf
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
,in vec2 AARoughnessFactors
,in vec3 vReflectionMicrosurfaceInfos
,in vec2 vReflectionInfos
,in vec3 vReflectionColor
,in vec4 vLightingIntensity
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSampler
,in vec3 reflectionCoords
#else
,in sampler2D reflectionSampler
,in vec2 reflectionCoords
#endif
,in float NdotVUnclamped
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSamplerLow
,in samplerCube reflectionSamplerHigh
#else
,in sampler2D reflectionSamplerLow
,in sampler2D reflectionSamplerHigh
#endif
#endif
#ifdef REALTIME_FILTERING
,in vec2 vReflectionFilteringInfo
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
,in float seo
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
,in float eho
#endif
#endif
)
{sheenOutParams outParams;float sheenIntensity=vSheenColor.a;
#ifdef SHEEN_TEXTURE
#if DEBUGMODE>0
outParams.sheenMapData=sheenMapData;
#endif
#endif
#ifdef SHEEN_LINKWITHALBEDO
float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;
#ifdef SHEEN_TEXTURE
sheenIntensity*=sheenMapData.a;
#endif
#else
vec3 sheenColor=vSheenColor.rgb;
#ifdef SHEEN_TEXTURE
#ifdef SHEEN_GAMMATEXTURE
sheenColor.rgb*=toLinearSpace(sheenMapData.rgb);
#else
sheenColor.rgb*=sheenMapData.rgb;
#endif
sheenColor.rgb*=sheenMapLevel;
#endif
#ifdef SHEEN_ROUGHNESS
float sheenRoughness=vSheenRoughness;
#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE
#if defined(SHEEN_TEXTURE)
sheenRoughness*=sheenMapData.a;
#endif
#elif defined(SHEEN_TEXTURE_ROUGHNESS)
sheenRoughness*=sheenMapRoughnessData.a;
#endif
#else
float sheenRoughness=roughness;
#ifdef SHEEN_TEXTURE
sheenIntensity*=sheenMapData.a;
#endif
#endif
#if !defined(SHEEN_ALBEDOSCALING)
sheenIntensity*=(1.-reflectance);
#endif
sheenColor*=sheenIntensity;
#endif
#ifdef ENVIRONMENTBRDF
/*#ifdef SHEEN_SOFTER
vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness));
#else*/
#ifdef SHEEN_ROUGHNESS
vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness);
#else
vec3 environmentSheenBrdf=environmentBrdf;
#endif
/*#endif*/
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness);
#ifdef SPECULARAA
sheenAlphaG+=AARoughnessFactors.y;
#endif
vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture(
sheenAlphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
sheenRoughness,
#endif
reflectionSampler,
reflectionCoords,
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
environmentSheenRadiance
);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
sheenEnvironmentReflectance*=seo;
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
sheenEnvironmentReflectance*=eho;
#endif
#if DEBUGMODE>0
outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;
#endif
outParams.finalSheenRadianceScaled=
environmentSheenRadiance.rgb *
sheenEnvironmentReflectance *
vLightingIntensity.z;
#endif
#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;
#endif
outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;return outParams;}
#endif
`;x.IncludesShadersStore[Aq]||(x.IncludesShadersStore[Aq]=YEe)});var Rq,KEe,bq=y(()=>{k();Rq="pbrBlockClearcoat",KEe=`struct clearcoatOutParams
{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness;
#ifdef REFLECTION
vec3 finalClearCoatRadianceScaled;
#endif
#ifdef CLEARCOAT_TINT
vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness;
#endif
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
vec3 energyConservationFactorClearCoat;
#endif
#if DEBUGMODE>0
#ifdef CLEARCOAT_BUMP
mat3 TBNClearCoat;
#endif
#ifdef CLEARCOAT_TEXTURE
vec2 clearCoatMapData;
#endif
#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
vec4 clearCoatTintMapData;
#endif
#ifdef REFLECTION
vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance;
#endif
float clearCoatNdotV;
#endif
};
#ifdef CLEARCOAT
#define pbr_inline
#define inline
clearcoatOutParams clearcoatBlock(
in vec3 vPositionW
,in vec3 geometricNormalW
,in vec3 viewDirectionW
,in vec2 vClearCoatParams
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
,in vec4 clearCoatMapRoughnessData
#endif
,in vec3 specularEnvironmentR0
#ifdef CLEARCOAT_TEXTURE
,in vec2 clearCoatMapData
#endif
#ifdef CLEARCOAT_TINT
,in vec4 vClearCoatTintParams
,in float clearCoatColorAtDistance
,in vec4 vClearCoatRefractionParams
#ifdef CLEARCOAT_TINT_TEXTURE
,in vec4 clearCoatTintMapData
#endif
#endif
#ifdef CLEARCOAT_BUMP
,in vec2 vClearCoatBumpInfos
,in vec4 clearCoatBumpMapData
,in vec2 vClearCoatBumpUV
#if defined(TANGENT) && defined(NORMAL)
,in mat3 vTBN
#else
,in vec2 vClearCoatTangentSpaceParams
#endif
#ifdef OBJECTSPACE_NORMALMAP
,in mat4 normalMatrix
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
,in vec3 faceNormal
#endif
#ifdef REFLECTION
,in vec3 vReflectionMicrosurfaceInfos
,in vec2 vReflectionInfos
,in vec3 vReflectionColor
,in vec4 vLightingIntensity
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSampler
#else
,in sampler2D reflectionSampler
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSamplerLow
,in samplerCube reflectionSamplerHigh
#else
,in sampler2D reflectionSamplerLow
,in sampler2D reflectionSamplerHigh
#endif
#endif
#ifdef REALTIME_FILTERING
,in vec2 vReflectionFilteringInfo
#endif
#endif
#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
,in float frontFacingMultiplier
#endif
)
{clearcoatOutParams outParams;float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y;
#ifdef CLEARCOAT_TEXTURE
clearCoatIntensity*=clearCoatMapData.x;
#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE
clearCoatRoughness*=clearCoatMapData.y;
#endif
#if DEBUGMODE>0
outParams.clearCoatMapData=clearCoatMapData;
#endif
#endif
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
clearCoatRoughness*=clearCoatMapRoughnessData.y;
#endif
outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness;
#ifdef CLEARCOAT_TINT
vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a;
#ifdef CLEARCOAT_TINT_TEXTURE
#ifdef CLEARCOAT_TINT_GAMMATEXTURE
clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb);
#else
clearCoatColor*=clearCoatTintMapData.rgb;
#endif
clearCoatThickness*=clearCoatTintMapData.a;
#if DEBUGMODE>0
outParams.clearCoatTintMapData=clearCoatTintMapData;
#endif
#endif
outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness;
#endif
#ifdef CLEARCOAT_REMAP_F0
vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0);
#else
vec3 specularEnvironmentR0Updated=specularEnvironmentR0;
#endif
outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW;
#ifdef CLEARCOAT_BUMP
#ifdef NORMALXYSCALE
float clearCoatNormalScale=1.0;
#else
float clearCoatNormalScale=vClearCoatBumpInfos.y;
#endif
#if defined(TANGENT) && defined(NORMAL)
mat3 TBNClearCoat=vTBN;
#else
vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);
#endif
#if DEBUGMODE>0
outParams.TBNClearCoat=TBNClearCoat;
#endif
#ifdef OBJECTSPACE_NORMALMAP
clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW);
#else
clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;
#endif
outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped);
#if DEBUGMODE>0
outParams.clearCoatNdotV=clearCoatNdotV;
#endif
#ifdef CLEARCOAT_TINT
vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));
#endif
#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))
vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);
#endif
#if defined(REFLECTION)
float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness);
#ifdef SPECULARAA
clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;
#endif
vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
clearCoatReflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
vec3 clearCoatReflectionCoords=clearCoatReflectionVector;
#else
vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
clearCoatReflectionCoords/=clearCoatReflectionVector.z;
#endif
clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;
#endif
sampleReflectionTexture(
clearCoatAlphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
clearCoatNdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
clearCoatRoughness,
#endif
reflectionSampler,
clearCoatReflectionCoords,
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
environmentClearCoatRadiance
);
#if DEBUGMODE>0
outParams.environmentClearCoatRadiance=environmentClearCoatRadiance;
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf);
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho;
#endif
#endif
#endif
#else
vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness));
#endif
clearCoatEnvironmentReflectance*=clearCoatIntensity;
#if DEBUGMODE>0
outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;
#endif
outParams.finalClearCoatRadianceScaled=
environmentClearCoatRadiance.rgb *
clearCoatEnvironmentReflectance *
vLightingIntensity.z;
#endif
#if defined(CLEARCOAT_TINT)
outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);
#endif
float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat);
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);
#endif
return outParams;}
#endif
`;x.IncludesShadersStore[Rq]||(x.IncludesShadersStore[Rq]=KEe)});var Mq,jEe,yq=y(()=>{k();Mq="pbrBlockIridescence",jEe=`struct iridescenceOutParams
{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;};
#ifdef IRIDESCENCE
#define pbr_inline
#define inline
iridescenceOutParams iridescenceBlock(
in vec4 vIridescenceParams
,in float viewAngle
,in vec3 specularEnvironmentR0
#ifdef IRIDESCENCE_TEXTURE
,in vec2 iridescenceMapData
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
,in vec2 iridescenceThicknessMapData
#endif
#ifdef CLEARCOAT
,in float NdotVUnclamped
,in vec2 vClearCoatParams
#ifdef CLEARCOAT_TEXTURE
,in vec2 clearCoatMapData
#endif
#endif
)
{iridescenceOutParams outParams;float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.;
#ifdef IRIDESCENCE_TEXTURE
iridescenceIntensity*=iridescenceMapData.x;
#endif
#if defined(IRIDESCENCE_THICKNESS_TEXTURE)
iridescenceThicknessWeight=iridescenceThicknessMapData.g;
#endif
float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.;
#ifdef CLEARCOAT
float clearCoatIntensity=vClearCoatParams.x;
#ifdef CLEARCOAT_TEXTURE
clearCoatIntensity*=clearCoatMapData.x;
#endif
topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0));
#endif
vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;return outParams;}
#endif
`;x.IncludesShadersStore[Mq]||(x.IncludesShadersStore[Mq]=jEe)});var Iq,ZEe,Cq=y(()=>{k();Iq="pbrBlockSubSurface",ZEe=`struct subSurfaceOutParams
{vec3 specularEnvironmentReflectance;
#ifdef SS_REFRACTION
vec3 finalRefraction;vec3 surfaceAlbedo;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
float alpha;
#endif
float refractionOpacity;
#endif
#ifdef SS_TRANSLUCENCY
vec3 transmittance;float translucencyIntensity;
#ifdef REFLECTION
vec3 refractionIrradiance;
#endif
#endif
#if DEBUGMODE>0
#ifdef SS_THICKNESSANDMASK_TEXTURE
vec4 thicknessMap;
#endif
#ifdef SS_REFRACTION
vec4 environmentRefraction;vec3 refractionTransmittance;
#endif
#endif
};
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
#define pbr_inline
#define inline
vec4 sampleEnvironmentRefraction(
in float ior
,in float thickness
,in float refractionLOD
,in vec3 normalW
,in vec3 vPositionW
,in vec3 viewDirectionW
,in mat4 view
,in vec4 vRefractionInfos
,in mat4 refractionMatrix
,in vec4 vRefractionMicrosurfaceInfos
,in float alphaG
#ifdef SS_REFRACTIONMAP_3D
,in samplerCube refractionSampler
#ifndef LODBASEDMICROSFURACE
,in samplerCube refractionSamplerLow
,in samplerCube refractionSamplerHigh
#endif
#else
,in sampler2D refractionSampler
#ifndef LODBASEDMICROSFURACE
,in sampler2D refractionSamplerLow
,in sampler2D refractionSamplerHigh
#endif
#endif
#ifdef ANISOTROPIC
,in anisotropicOutParams anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,in vec2 vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,in vec3 refractionPosition
,in vec3 refractionSize
#endif
) {vec4 environmentRefraction=vec4(0.,0.,0.,0.);
#ifdef ANISOTROPIC
vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior);
#else
vec3 refractionVector=refract(-viewDirectionW,normalW,ior);
#endif
#ifdef SS_REFRACTIONMAP_OPPOSITEZ
refractionVector.z*=-1.0;
#endif
#ifdef SS_REFRACTIONMAP_3D
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);
#endif
refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));
#else
#ifdef SS_USE_THICKNESS_AS_DEPTH
vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0)));
#else
vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));
#endif
vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;
#endif
#ifdef LODBASEDMICROSFURACE
refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;
#ifdef SS_LODINREFRACTIONALPHA
float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);
#else
float requestedRefractionLOD=refractionLOD;
#endif
#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D)
environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0);
#else
environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);
#endif
#else
float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix(
sampleRefraction(refractionSamplerHigh,refractionCoords),
environmentRefractionMid,
lodRefractionNormalizedDoubled
);} else {environmentRefraction=mix(
environmentRefractionMid,
sampleRefraction(refractionSamplerLow,refractionCoords),
lodRefractionNormalizedDoubled-1.0
);}
#endif
#ifdef SS_RGBDREFRACTION
environmentRefraction.rgb=fromRGBD(environmentRefraction);
#endif
#ifdef SS_GAMMAREFRACTION
environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);
#endif
return environmentRefraction;}
#endif
#define pbr_inline
#define inline
subSurfaceOutParams subSurfaceBlock(
in vec3 vSubSurfaceIntensity
,in vec2 vThicknessParam
,in vec4 vTintColor
,in vec3 normalW
,in vec3 vSpecularEnvironmentReflectance
#ifdef SS_THICKNESSANDMASK_TEXTURE
,in vec4 thicknessMap
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
,in vec4 refractionIntensityMap
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
,in vec4 translucencyIntensityMap
#endif
#ifdef REFLECTION
#ifdef SS_TRANSLUCENCY
,in mat4 reflectionMatrix
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
,in vec3 irradianceVector_
#endif
#if defined(REALTIME_FILTERING)
,in samplerCube reflectionSampler
,in vec2 vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,in sampler2D icdfSampler
#endif
#endif
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
,in samplerCube irradianceSampler
#else
,in sampler2D irradianceSampler
#endif
#endif
#endif
#endif
#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
,in vec3 surfaceAlbedo
#endif
#ifdef SS_REFRACTION
,in vec3 vPositionW
,in vec3 viewDirectionW
,in mat4 view
,in vec4 vRefractionInfos
,in mat4 refractionMatrix
,in vec4 vRefractionMicrosurfaceInfos
,in vec4 vLightingIntensity
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
,in float alpha
#endif
#ifdef SS_LODINREFRACTIONALPHA
,in float NdotVUnclamped
#endif
#ifdef SS_LINEARSPECULARREFRACTION
,in float roughness
#endif
,in float alphaG
#ifdef SS_REFRACTIONMAP_3D
,in samplerCube refractionSampler
#ifndef LODBASEDMICROSFURACE
,in samplerCube refractionSamplerLow
,in samplerCube refractionSamplerHigh
#endif
#else
,in sampler2D refractionSampler
#ifndef LODBASEDMICROSFURACE
,in sampler2D refractionSamplerLow
,in sampler2D refractionSamplerHigh
#endif
#endif
#ifdef ANISOTROPIC
,in anisotropicOutParams anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,in vec2 vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,in vec3 refractionPosition
,in vec3 refractionSize
#endif
#ifdef SS_DISPERSION
,in float dispersion
#endif
#endif
#ifdef SS_TRANSLUCENCY
,in vec3 vDiffusionDistance
,in vec4 vTranslucencyColor
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
,in vec4 translucencyColorMap
#endif
#endif
)
{subSurfaceOutParams outParams;outParams.specularEnvironmentReflectance=vSpecularEnvironmentReflectance;
#ifdef SS_REFRACTION
float refractionIntensity=vSubSurfaceIntensity.x;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
refractionIntensity*=(1.0-alpha);outParams.alpha=1.0;
#endif
#endif
#ifdef SS_TRANSLUCENCY
float translucencyIntensity=vSubSurfaceIntensity.y;
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
#ifdef SS_USE_GLTF_TEXTURES
float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;
#else
float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;
#endif
#if DEBUGMODE>0
outParams.thicknessMap=thicknessMap;
#endif
#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS)
#ifdef SS_USE_GLTF_TEXTURES
refractionIntensity*=thicknessMap.r;
#else
refractionIntensity*=thicknessMap.g;
#endif
#endif
#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS)
#ifdef SS_USE_GLTF_TEXTURES
translucencyIntensity*=thicknessMap.a;
#else
translucencyIntensity*=thicknessMap.b;
#endif
#endif
#else
float thickness=vThicknessParam.y;
#endif
#if defined(SS_REFRACTION) && defined(SS_REFRACTIONINTENSITY_TEXTURE)
#ifdef SS_USE_GLTF_TEXTURES
refractionIntensity*=refractionIntensityMap.r;
#else
refractionIntensity*=refractionIntensityMap.g;
#endif
#endif
#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCYINTENSITY_TEXTURE)
#ifdef SS_USE_GLTF_TEXTURES
translucencyIntensity*=translucencyIntensityMap.a;
#else
translucencyIntensity*=translucencyIntensityMap.b;
#endif
#endif
#ifdef SS_TRANSLUCENCY
thickness=maxEps(thickness);vec4 translucencyColor=vTranslucencyColor;
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
translucencyColor*=translucencyColorMap;
#endif
vec3 transmittance=transmittanceBRDF_Burley(translucencyColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity;
#endif
#ifdef SS_REFRACTION
vec4 environmentRefraction=vec4(0.,0.,0.,0.);
#ifdef SS_HAS_THICKNESS
float ior=vRefractionInfos.y;
#else
float ior=vRefractionMicrosurfaceInfos.w;
#endif
#ifdef SS_LODINREFRACTIONALPHA
float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);
#elif defined(SS_LINEARSPECULARREFRACTION)
float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);
#else
float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);
#endif
float refraction_ior=vRefractionInfos.y;
#ifdef SS_DISPERSION
float realIOR=1.0/refraction_ior;float iorDispersionSpread=0.04*dispersion*(realIOR-1.0);vec3 iors=vec3(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (int i=0; i<3; i++) {refraction_ior=iors[i];
#endif
vec4 envSample=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG
#ifdef SS_REFRACTIONMAP_3D
,refractionSampler
#ifndef LODBASEDMICROSFURACE
,refractionSamplerLow
,refractionSamplerHigh
#endif
#else
,refractionSampler
#ifndef LODBASEDMICROSFURACE
,refractionSamplerLow
,refractionSamplerHigh
#endif
#endif
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,refractionPosition
,refractionSize
#endif
);
#ifdef SS_DISPERSION
environmentRefraction[i]=envSample[i];}
#else
environmentRefraction=envSample;
#endif
environmentRefraction.rgb*=vRefractionInfos.x;
#endif
#ifdef SS_REFRACTION
vec3 refractionTransmittance=vec3(refractionIntensity);
#ifdef SS_THICKNESSANDMASK_TEXTURE
vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness);
#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)
float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo;
#else
vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y);
#endif
#ifdef SS_ALBEDOFORREFRACTIONTINT
environmentRefraction.rgb*=surfaceAlbedo.rgb;
#endif
outParams.surfaceAlbedo=surfaceAlbedo;outParams.refractionOpacity=1.-refractionIntensity;
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
outParams.surfaceAlbedo*=outParams.refractionOpacity;
#endif
#ifdef UNUSED_MULTIPLEBOUNCES
vec3 bounceSpecularEnvironmentReflectance=(2.0*vSpecularEnvironmentReflectance)/(1.0+vSpecularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,vSpecularEnvironmentReflectance,refractionIntensity);
#endif
#if DEBUGMODE>0
outParams.refractionTransmittance=refractionTransmittance;
#endif
outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;outParams.finalRefraction*=vec3(1.0)-vSpecularEnvironmentReflectance;
#if DEBUGMODE>0
outParams.environmentRefraction=environmentRefraction;
#endif
#endif
#if defined(REFLECTION) && defined(SS_TRANSLUCENCY)
#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP)
vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;
#endif
#else
vec3 irradianceVector=irradianceVector_;
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP)
#if defined(REALTIME_FILTERING)
vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo,0.0,surfaceAlbedo,irradianceVector
#ifdef IBL_CDF_FILTERING
,icdfSampler
#endif
);
#else
vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector);
#endif
#elif defined(USEIRRADIANCEMAP)
#ifdef REFLECTIONMAP_3D
vec3 irradianceCoords=irradianceVector;
#else
vec2 irradianceCoords=irradianceVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
irradianceCoords/=irradianceVector.z;
#endif
irradianceCoords.y=1.0-irradianceCoords.y;
#endif
vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords);
#ifdef RGBDREFLECTION
refractionIrradiance.rgb=fromRGBD(refractionIrradiance);
#endif
#ifdef GAMMAREFLECTION
refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb);
#endif
#else
vec4 refractionIrradiance=vec4(0.);
#endif
refractionIrradiance.rgb*=transmittance;
#ifdef SS_ALBEDOFORTRANSLUCENCYTINT
refractionIrradiance.rgb*=surfaceAlbedo.rgb;
#endif
outParams.refractionIrradiance=refractionIrradiance.rgb;
#endif
return outParams;}
#endif
`;x.IncludesShadersStore[Iq]||(x.IncludesShadersStore[Iq]=ZEe)});var Pq,qEe,OF=y(()=>{k();Pq="pbrBlockReflectance0",qEe=`float reflectanceF0=reflectivityOut.reflectanceF0;vec3 specularEnvironmentR0=reflectivityOut.colorReflectanceF0;vec3 specularEnvironmentR90=reflectivityOut.colorReflectanceF90;
#ifdef ALPHAFRESNEL
float reflectance90=fresnelGrazingReflectance(reflectanceF0);specularEnvironmentR90=specularEnvironmentR90*reflectance90;
#endif
`;x.IncludesShadersStore[Pq]||(x.IncludesShadersStore[Pq]=qEe)});var Lq,QEe,Dq=y(()=>{k();hN();OF();Lq="pbrClusteredLightingFunctions",QEe=`#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
#include<clusteredLightingFunctions>
#define inline
lightingInfo computeClusteredLighting(
sampler2D lightDataTexture,
sampler2D tileMaskTexture,
vec4 lightData,
ivec2 sliceRange,
vec3 V,
vec3 N,
vec3 posW,
vec3 surfaceAlbedo,
reflectivityOutParams reflectivityOut
#ifdef IRIDESCENCE
,float iridescenceIntensity
#endif
#ifdef SS_TRANSLUCENCY
,subSurfaceOutParams subSurfaceOut
#endif
#ifdef SPECULARTERM
,float AARoughnessFactor
#endif
#ifdef ANISOTROPIC
,anisotropicOutParams anisotropicOut
#endif
#ifdef SHEEN
,sheenOutParams sheenOut
#endif
#ifdef CLEARCOAT
,clearcoatOutParams clearcoatOut
#endif
) {float NdotV=absEps(dot(N,V));
#include<pbrBlockReflectance0>
#ifdef CLEARCOAT
specularEnvironmentR0=clearcoatOut.specularEnvironmentR0;
#endif
lightingInfo result;ivec2 tilePosition=ivec2(gl_FragCoord.xy*lightData.xy);int maskHeight=int(lightData.z);tilePosition.y=min(tilePosition.y,maskHeight-1);ivec2 batchRange=sliceRange/CLUSTLIGHT_BATCH;int batchOffset=batchRange.x*CLUSTLIGHT_BATCH;tilePosition.y+=maskHeight*batchRange.x;for (int i=batchRange.x; i<=batchRange.y; i+=1) {uint mask=uint(texelFetch(tileMaskTexture,tilePosition,0).r);tilePosition.y+=maskHeight;int maskOffset=max(sliceRange.x-batchOffset,0);int maskWidth=min(sliceRange.y-batchOffset+1,CLUSTLIGHT_BATCH);mask=extractBits(mask,maskOffset,maskWidth);while (mask != 0u) {uint bit=mask & -mask;mask ^= bit;int position=onlyBitPosition(bit);ClusteredLight light=getClusteredLight(lightDataTexture,batchOffset+maskOffset+position);preLightingInfo preInfo=computePointAndSpotPreLightingInfo(light.vLightData,V,N,posW);preInfo.NdotV=NdotV;preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light.vLightFalloff.x,light.vLightFalloff.y);if (light.vLightDirection.w>=0.0) {preInfo.attenuation*=computeDirectionalLightFalloff(light.vLightDirection.xyz,preInfo.L,light.vLightDirection.w,light.vLightData.w,light.vLightFalloff.z,light.vLightFalloff.w);}
preInfo.roughness=adjustRoughnessFromLightProperties(reflectivityOut.roughness,light.vLightSpecular.a,preInfo.lightDistance);preInfo.diffuseRoughness=reflectivityOut.diffuseRoughness;preInfo.surfaceAlbedo=surfaceAlbedo;
#ifdef IRIDESCENCE
preInfo.iridescenceIntensity=iridescenceIntensity;
#endif
lightingInfo info;
#ifdef SS_TRANSLUCENCY
#ifdef SS_TRANSLUCENCY_LEGACY
info.diffuse=computeDiffuseTransmittedLighting(preInfo,light.vLightDiffuse.rgb,subSurfaceOut.transmittance);info.diffuseTransmission=vec3(0);
#else
info.diffuse=computeDiffuseLighting(preInfo,light.vLightDiffuse.rgb)*(1.0-subSurfaceOut.translucencyIntensity);info.diffuseTransmission=computeDiffuseTransmittedLighting(preInfo,light.vLightDiffuse.rgb,subSurfaceOut.transmittance);
#endif
#else
info.diffuse=computeDiffuseLighting(preInfo,light.vLightDiffuse.rgb);
#endif
#ifdef SPECULARTERM
#if CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR
vec3 metalFresnel=reflectivityOut.specularWeight*getF82Specular(preInfo.VdotH,specularEnvironmentR0,reflectivityOut.colorReflectanceF90,reflectivityOut.roughness);vec3 dielectricFresnel=fresnelSchlickGGX(preInfo.VdotH,reflectivityOut.dielectricColorF0,reflectivityOut.colorReflectanceF90);vec3 coloredFresnel=mix(dielectricFresnel,metalFresnel,reflectivityOut.metallic);
#else
vec3 coloredFresnel=fresnelSchlickGGX(preInfo.VdotH,specularEnvironmentR0,reflectivityOut.colorReflectanceF90);
#endif
#ifndef LEGACY_SPECULAR_ENERGY_CONSERVATION
float NdotH=dot(N,preInfo.H);vec3 fresnel=fresnelSchlickGGX(NdotH,vec3(reflectanceF0),specularEnvironmentR90);info.diffuse*=(vec3(1.0)-fresnel);
#endif
#ifdef ANISOTROPIC
info.specular=computeAnisotropicSpecularLighting(preInfo,V,N,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactor,light.vLightDiffuse.rgb);
#else
info.specular=computeSpecularLighting(preInfo,N,specularEnvironmentR0,coloredFresnel,AARoughnessFactor,light.vLightDiffuse.rgb);
#endif
#endif
#ifdef SHEEN
#ifdef SHEEN_LINKWITHALBEDO
preInfo.roughness=sheenOut.sheenIntensity;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light.vLightSpecular.a,preInfo.lightDistance);
#endif
info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactor,light.vLightDiffuse.rgb);
#endif
#ifdef CLEARCOAT
preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light.vLightSpecular.a,preInfo.lightDistance);info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light.vLightDiffuse.rgb);
#ifdef CLEARCOAT_TINT
float absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;
#ifdef SS_TRANSLUCENCY
info.diffuseTransmission*=absorption;
#endif
#ifdef SPECULARTERM
info.specular*=absorption;
#endif
#endif
info.diffuse*=info.clearCoat.w;
#ifdef SS_TRANSLUCENCY
info.diffuseTransmission*=info.clearCoat.w;
#endif
#ifdef SPECULARTERM
info.specular*=info.clearCoat.w;
#endif
#ifdef SHEEN
info.sheen*=info.clearCoat.w;
#endif
#endif
result.diffuse+=info.diffuse;
#ifdef SS_TRANSLUCENCY
result.diffuseTransmission+=info.diffuseTransmission;
#endif
#ifdef SPECULARTERM
result.specular+=info.specular;
#endif
#ifdef CLEARCOAT
result.clearCoat+=info.clearCoat;
#endif
#ifdef SHEEN
result.sheen+=info.sheen;
#endif
}
batchOffset+=CLUSTLIGHT_BATCH;}
return result;}
#endif
`;x.IncludesShadersStore[Lq]||(x.IncludesShadersStore[Lq]=QEe)});var Oq,$Ee,Nq=y(()=>{k();Oq="pbrBlockNormalFinal",$Ee=`#if defined(FORCENORMALFORWARD) && defined(NORMAL)
vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;
#if defined(TWOSIDEDLIGHTING)
faceNormal=gl_FrontFacing ? faceNormal : -faceNormal;
#endif
normalW*=sign(dot(normalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
#if defined(MIRRORED)
normalW=gl_FrontFacing ? -normalW : normalW;
#else
normalW=gl_FrontFacing ? normalW : -normalW;
#endif
#endif
`;x.IncludesShadersStore[Oq]||(x.IncludesShadersStore[Oq]=$Ee)});var wq,JEe,Fq=y(()=>{k();wq="pbrBlockLightmapInit",JEe=`#ifdef LIGHTMAP
vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);
#ifdef RGBDLIGHTMAP
lightmapColor.rgb=fromRGBD(lightmapColor);
#endif
#ifdef GAMMALIGHTMAP
lightmapColor.rgb=toLinearSpace(lightmapColor.rgb);
#endif
lightmapColor.rgb*=vLightmapInfos.y;
#endif
`;x.IncludesShadersStore[wq]||(x.IncludesShadersStore[wq]=JEe)});var Bq,eSe,Uq=y(()=>{k();Bq="pbrBlockGeometryInfo",eSe=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz);
#ifdef SPECULARAA
alphaG+=AARoughnessFactors.y;
#endif
#if defined(ENVIRONMENTBRDF)
vec3 environmentBrdf=getBRDFLookup(NdotV,roughness);
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
#ifdef RADIANCEOCCLUSION
#ifdef AMBIENTINGRAYSCALE
float ambientMonochrome=aoOut.ambientOcclusionColor.r;
#else
float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor);
#endif
float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);
#endif
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);
#endif
#endif
#endif
#endif
`;x.IncludesShadersStore[Bq]||(x.IncludesShadersStore[Bq]=eSe)});var Vq,tSe,Gq=y(()=>{k();Vq="pbrBlockReflectance",tSe=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
vec3 baseSpecularEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(reflectanceF0),reflectivityOut.reflectanceF90,environmentBrdf);
#if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR)
vec3 metalEnvironmentReflectance=reflectivityOut.specularWeight*getF82Specular(NdotV,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90,reflectivityOut.roughness);vec3 dielectricEnvironmentReflectance=getReflectanceFromBRDFLookup(reflectivityOut.dielectricColorF0,reflectivityOut.colorReflectanceF90,environmentBrdf);vec3 colorSpecularEnvironmentReflectance=mix(dielectricEnvironmentReflectance,metalEnvironmentReflectance,reflectivityOut.metallic);
#else
vec3 colorSpecularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90,environmentBrdf);
#endif
#ifdef RADIANCEOCCLUSION
colorSpecularEnvironmentReflectance*=seo;
#endif
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
colorSpecularEnvironmentReflectance*=eho;
#endif
#endif
#endif
#else
vec3 colorSpecularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));vec3 baseSpecularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,vec3(reflectanceF0),reflectivityOut.reflectanceF90,sqrt(microSurface));
#endif
#ifdef CLEARCOAT
colorSpecularEnvironmentReflectance*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
colorSpecularEnvironmentReflectance*=clearcoatOut.absorption;
#endif
#endif
`;x.IncludesShadersStore[Vq]||(x.IncludesShadersStore[Vq]=tSe)});var kq,iSe,zq=y(()=>{k();kq="pbrBlockDirectLighting",iSe=`vec3 diffuseBase=vec3(0.,0.,0.);
#ifdef SS_TRANSLUCENCY
vec3 diffuseTransmissionBase=vec3(0.,0.,0.);
#endif
#ifdef SPECULARTERM
vec3 specularBase=vec3(0.,0.,0.);
#endif
#ifdef CLEARCOAT
vec3 clearCoatBase=vec3(0.,0.,0.);
#endif
#ifdef SHEEN
vec3 sheenBase=vec3(0.,0.,0.);
#endif
#if defined(SPECULARTERM) && defined(LIGHT0)
vec3 coloredFresnel;
#endif
preLightingInfo preInfo;lightingInfo info;float shadow=1.;
float aggShadow=0.;float numLights=0.;
#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
vec3 absorption=vec3(0.);
#endif
`;x.IncludesShadersStore[kq]||(x.IncludesShadersStore[kq]=iSe)});var Wq,rSe,Hq=y(()=>{k();Wq="pbrBlockFinalLitComponents",rSe=`aggShadow=aggShadow/numLights;
#if defined(ENVIRONMENTBRDF)
#ifdef MS_BRDF_ENERGY_CONSERVATION
vec3 baseSpecularEnergyConservationFactor=getEnergyConservationFactor(vec3(reflectanceF0),environmentBrdf);vec3 coloredEnergyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);
#endif
#endif
#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)
surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;
#endif
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
#ifndef METALLICWORKFLOW
#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION
surfaceAlbedo.rgb=(1.-reflectanceF0)*surfaceAlbedo.rgb;
#endif
#endif
#endif
#ifdef REFLECTION
vec3 finalIrradiance=reflectionOut.environmentIrradiance;
#ifndef LEGACY_SPECULAR_ENERGY_CONSERVATION
#if defined(METALLICWORKFLOW) || defined(SPECULAR_GLOSSINESS_ENERGY_CONSERVATION)
vec3 baseSpecularEnergy=vec3(baseSpecularEnvironmentReflectance);
#if defined(ENVIRONMENTBRDF)
#ifdef MS_BRDF_ENERGY_CONSERVATION
baseSpecularEnergy*=baseSpecularEnergyConservationFactor;
#endif
#endif
finalIrradiance*=clamp(vec3(1.0)-baseSpecularEnergy,0.0,1.0);
#endif
#endif
#if defined(CLEARCOAT)
finalIrradiance*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
finalIrradiance*=clearcoatOut.absorption;
#endif
#endif
#ifndef SS_APPLY_ALBEDO_AFTER_SUBSURFACE
finalIrradiance*=surfaceAlbedo.rgb;
#endif
#if defined(SS_REFRACTION)
finalIrradiance*=subSurfaceOut.refractionOpacity;
#endif
#if defined(SS_TRANSLUCENCY)
finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance;
#endif
#ifdef SS_APPLY_ALBEDO_AFTER_SUBSURFACE
finalIrradiance*=surfaceAlbedo.rgb;
#endif
finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor;
#endif
#ifdef SPECULARTERM
vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalSpecularScaled*=coloredEnergyConservationFactor;
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
finalSpecularScaled*=sheenOut.sheenAlbedoScaling;
#endif
#endif
#ifdef REFLECTION
vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=colorSpecularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalRadianceScaled*=coloredEnergyConservationFactor;
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
finalRadianceScaled*=sheenOut.sheenAlbedoScaling;
#endif
#endif
#ifdef SHEEN
vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w;
#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)
sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;
#endif
#endif
#endif
#ifdef CLEARCOAT
vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;
#endif
#ifdef SS_REFRACTION
subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;
#ifdef CLEARCOAT_TINT
subSurfaceOut.finalRefraction*=clearcoatOut.absorption;
#endif
#endif
#endif
#ifdef ALPHABLEND
float luminanceOverAlpha=0.0;
#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)
luminanceOverAlpha+=getLuminance(finalRadianceScaled);
#if defined(CLEARCOAT)
luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);
#endif
#endif
#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)
luminanceOverAlpha+=getLuminance(finalSpecularScaled);
#endif
#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)
luminanceOverAlpha+=getLuminance(finalClearCoatScaled);
#endif
#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)
alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);
#endif
#endif
`;x.IncludesShadersStore[Wq]||(x.IncludesShadersStore[Wq]=rSe)});var Xq,nSe,Yq=y(()=>{k();Xq="pbrBlockFinalUnlitComponents",nSe=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo;
#if defined(SS_REFRACTION) && !defined(UNLIT) && !defined(LEGACY_SPECULAR_ENERGY_CONSERVATION)
finalDiffuse*=subSurfaceOut.refractionOpacity;
#endif
#if defined(SS_TRANSLUCENCY) && !defined(UNLIT)
finalDiffuse+=diffuseTransmissionBase;
#endif
finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor;
#ifdef EMISSIVE
vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;
#ifdef GAMMAEMISSIVE
finalEmissive*=toLinearSpace(emissiveColorTex.rgb);
#else
finalEmissive*=emissiveColorTex.rgb;
#endif
finalEmissive*= vEmissiveInfos.y;
#endif
finalEmissive*=vLightingIntensity.y;
#ifdef AMBIENT
vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w);
#else
vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor;
#endif
finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse;
`;x.IncludesShadersStore[Xq]||(x.IncludesShadersStore[Xq]=nSe)});var Kq,sSe,jq=y(()=>{k();Kq="pbrBlockFinalColorComposition",sSe=`vec4 finalColor=vec4(
#ifndef UNLIT
#ifdef REFLECTION
finalIrradiance +
#endif
#ifdef SPECULARTERM
finalSpecularScaled +
#endif
#ifdef SHEEN
finalSheenScaled +
#endif
#ifdef CLEARCOAT
finalClearCoatScaled +
#endif
#ifdef REFLECTION
finalRadianceScaled +
#if defined(SHEEN) && defined(ENVIRONMENTBRDF)
sheenOut.finalSheenRadianceScaled +
#endif
#ifdef CLEARCOAT
clearcoatOut.finalClearCoatRadianceScaled +
#endif
#endif
#ifdef SS_REFRACTION
subSurfaceOut.finalRefraction +
#endif
#endif
finalAmbient +
finalDiffuse,
alpha);
#ifdef LIGHTMAP
#ifndef LIGHTMAPEXCLUDED
#ifdef USELIGHTMAPASSHADOWMAP
finalColor.rgb*=lightmapColor.rgb;
#else
finalColor.rgb+=lightmapColor.rgb;
#endif
#endif
#endif
finalColor.rgb+=finalEmissive;
#define CUSTOM_FRAGMENT_BEFORE_FOG
finalColor=max(finalColor,0.0);
`;x.IncludesShadersStore[Kq]||(x.IncludesShadersStore[Kq]=sSe)});var Zq,aSe,qq=y(()=>{k();Zq="pbrBlockPrePass",aSe=`#if SCENE_MRT_COUNT>0
float writeGeometryInfo=finalColor.a>ALPHATESTVALUE ? 1.0 : 0.0;
#ifdef PREPASS_POSITION
gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_LOCAL_POSITION
gl_FragData[PREPASS_LOCAL_POSITION_INDEX]=vec4(vPosition,writeGeometryInfo);
#endif
#if defined(PREPASS_VELOCITY)
vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#elif defined(PREPASS_VELOCITY_LINEAR)
vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w)-(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO
gl_FragData[PREPASS_ALBEDO_INDEX]=vec4(surfaceAlbedo,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
vec3 sqAlbedo=sqrt(surfaceAlbedo);
#endif
#ifdef PREPASS_IRRADIANCE_LEGACY
vec3 irradiance=finalDiffuse;
#ifndef UNLIT
#ifdef REFLECTION
irradiance+=finalIrradiance;
#endif
#endif
#ifdef SS_SCATTERING
#ifdef PREPASS_COLOR
gl_FragData[PREPASS_COLOR_INDEX]=vec4(finalColor.rgb-irradiance,finalColor.a);
#endif
irradiance/=sqAlbedo;
#else
#ifdef PREPASS_COLOR
gl_FragData[PREPASS_COLOR_INDEX]=finalColor;
#endif
float scatteringDiffusionProfile=255.;
#endif
gl_FragData[PREPASS_IRRADIANCE_LEGACY_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.);
#else
#ifdef PREPASS_IRRADIANCE
vec3 irradiance=finalDiffuse;
#ifndef UNLIT
#ifdef REFLECTION
irradiance+=finalIrradiance;
#endif
#endif
gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(irradiance,writeGeometryInfo);
#endif
#if defined(PREPASS_COLOR)
gl_FragData[PREPASS_COLOR_INDEX]=vec4(finalColor.rgb,finalColor.a);
#endif
#endif
#ifdef PREPASS_DEPTH
gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_SCREENSPACE_DEPTH
gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
gl_FragData[PREPASS_NORMALIZED_VIEW_DEPTH_INDEX]=vec4(vNormViewDepth,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMAL
#ifdef PREPASS_NORMAL_WORLDSPACE
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo);
#else
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo);
#endif
#endif
#ifdef PREPASS_WORLD_NORMAL
gl_FragData[PREPASS_WORLD_NORMAL_INDEX]=vec4(normalW*0.5+0.5,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo);
#endif
#ifdef PREPASS_REFLECTIVITY
#ifndef UNLIT
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo;
#else
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo;
#endif
#endif
#endif
`;x.IncludesShadersStore[Zq]||(x.IncludesShadersStore[Zq]=aSe)});var $q={};Be($q,{pbrPixelShader:()=>oSe});var NF,Qq,oSe,Jq=y(()=>{k();gM();_M();sq();LF();aF();vM();EM();cq();TM();af();ch();lE();oo();oF();lF();cF();AM();SM();_g();fF();dF();gg();uF();hF();ty();xM();RM();vE();dq();hq();pq();_q();Eq();Tq();xq();bq();yq();Cq();Dq();of();mF();bM();Nq();MM();Fq();Uq();OF();Gq();zq();pN();Hq();Yq();jq();yM();cE();pF();qq();IM();gF();NF="pbrPixelShader",Qq=`#define PBR_FRAGMENT_SHADER
#define CUSTOM_FRAGMENT_EXTENSION
#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#extension GL_OES_standard_derivatives : enable
#endif
#ifdef LODBASEDMICROSFURACE
#extension GL_EXT_shader_texture_lod : enable
#endif
#define CUSTOM_FRAGMENT_BEGIN
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
#if SCENE_MRT_COUNT>0
#include<prePassDeclaration>[SCENE_MRT_COUNT]
#endif
precision highp float;
#include<oitDeclaration>
#ifndef FROMLINEARSPACE
#define FROMLINEARSPACE
#endif
#include<__decl__pbrFragment>
#include<pbrFragmentExtraDeclaration>
#include<__decl__lightFragment>[0..maxSimultaneousLights]
#include<pbrFragmentSamplersDeclaration>
#include<imageProcessingDeclaration>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
#include<helperFunctions>
#include<subSurfaceScatteringFunctions>
#include<importanceSampling>
#include<pbrHelperFunctions>
#include<imageProcessingFunctions>
#include<shadowsFragmentFunctions>
#include<harmonicsFunctions>
#include<pbrDirectLightingSetupFunctions>
#include<pbrDirectLightingFalloffFunctions>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
#include<pbrDirectLightingFunctions>
#include<pbrIBLFunctions>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#ifdef REFLECTION
#include<reflectionFunction>
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
#include<pbrBlockAlbedoOpacity>
#include<pbrBlockReflectivity>
#include<pbrBlockAmbientOcclusion>
#include<pbrBlockAlphaFresnel>
#include<pbrBlockAnisotropic>
#include<pbrBlockReflection>
#include<pbrBlockSheen>
#include<pbrBlockClearcoat>
#include<pbrBlockIridescence>
#include<pbrBlockSubSurface>
#include<pbrClusteredLightingFunctions>
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#include<pbrBlockNormalGeometric>
#include<bumpFragment>
#include<pbrBlockNormalFinal>
albedoOpacityOutParams albedoOpacityOut;
#ifdef ALBEDO
vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);
#endif
#ifdef BASE_WEIGHT
vec4 baseWeightTexture=texture2D(baseWeightSampler,vBaseWeightUV+uvOffset);
#endif
#ifdef OPACITY
vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);
#endif
#ifdef DECAL
vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);
#endif
albedoOpacityOut=albedoOpacityBlock(
vAlbedoColor
#ifdef ALBEDO
,albedoTexture
,vAlbedoInfos
#endif
,baseWeight
#ifdef BASE_WEIGHT
,baseWeightTexture
,vBaseWeightInfos
#endif
#ifdef OPACITY
,opacityMap
,vOpacityInfos
#endif
#ifdef DETAIL
,detailColor
,vDetailInfos
#endif
#ifdef DECAL
,decalColor
,vDecalInfos
#endif
);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha;
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
#include<depthPrePass>
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS
ambientOcclusionOutParams aoOut;
#ifdef AMBIENT
vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb;
#endif
aoOut=ambientOcclusionBlock(
#ifdef AMBIENT
ambientOcclusionColorMap,
vAmbientInfos
#endif
);
#include<pbrBlockLightmapInit>
#ifdef UNLIT
vec3 diffuseBase=vec3(1.,1.,1.);
#else
vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut;
#if defined(REFLECTIVITY)
vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap;
#ifndef METALLICWORKFLOW
#ifdef REFLECTIVITY_GAMMA
surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap);
#endif
surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y;
#endif
#endif
#if defined(MICROSURFACEMAP)
vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;
#endif
#ifdef METALLICWORKFLOW
vec4 metallicReflectanceFactors=vMetallicReflectanceFactors;
#ifdef REFLECTANCE
vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset);
#ifdef REFLECTANCE_GAMMA
reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap);
#endif
metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb;
#endif
#ifdef METALLIC_REFLECTANCE
vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset);
#ifdef METALLIC_REFLECTANCE_GAMMA
metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap);
#endif
#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY
metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb;
#endif
metallicReflectanceFactors.a*=metallicReflectanceFactorsMap.a;
#endif
#endif
#ifdef BASE_DIFFUSE_ROUGHNESS
float baseDiffuseRoughnessTexture=texture2D(baseDiffuseRoughnessSampler,vBaseDiffuseRoughnessUV+uvOffset).r;
#endif
reflectivityOut=reflectivityBlock(
vReflectivityColor
#ifdef METALLICWORKFLOW
,surfaceAlbedo
,metallicReflectanceFactors
#endif
,baseDiffuseRoughness
#ifdef BASE_DIFFUSE_ROUGHNESS
,baseDiffuseRoughnessTexture
,vBaseDiffuseRoughnessInfos
#endif
#ifdef REFLECTIVITY
,vReflectivityInfos
,surfaceMetallicOrReflectivityColorMap
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
,aoOut.ambientOcclusionColor
#endif
#ifdef MICROSURFACEMAP
,microSurfaceTexel
#endif
#ifdef DETAIL
,detailColor
,vDetailInfos
#endif
);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness;float diffuseRoughness=reflectivityOut.diffuseRoughness;
#ifdef METALLICWORKFLOW
surfaceAlbedo=reflectivityOut.surfaceAlbedo;
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;
#endif
#ifdef ALPHAFRESNEL
#if defined(ALPHATEST) || defined(ALPHABLEND)
alphaFresnelOutParams alphaFresnelOut;alphaFresnelOut=alphaFresnelBlock(
normalW,
viewDirectionW,
alpha,
microSurface
);alpha=alphaFresnelOut.alpha;
#endif
#endif
#include<pbrBlockGeometryInfo>
#ifdef ANISOTROPIC
anisotropicOutParams anisotropicOut;
#ifdef ANISOTROPIC_TEXTURE
vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y;
#endif
anisotropicOut=anisotropicBlock(
vAnisotropy,
roughness,
#ifdef ANISOTROPIC_TEXTURE
anisotropyMapData,
#endif
TBN,
normalW,
viewDirectionW
);
#endif
#ifdef REFLECTION
reflectionOutParams reflectionOut;
#ifndef USE_CUSTOM_REFLECTION
reflectionOut=reflectionBlock(
vPositionW
,normalW
,alphaG
,vReflectionMicrosurfaceInfos
,vReflectionInfos
,vReflectionColor
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,NdotVUnclamped
#endif
#ifdef LINEARSPECULARREFLECTION
,roughness
#endif
,reflectionSampler
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,vEnvironmentIrradiance
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,reflectionMatrix
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
#ifdef USE_IRRADIANCE_DOMINANT_DIRECTION
,vReflectionDominantDirection
#endif
#endif
#ifndef LODBASEDMICROSFURACE
,reflectionSamplerLow
,reflectionSamplerHigh
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
#endif
#endif
,viewDirectionW
,diffuseRoughness
,baseColor
);
#else
#define CUSTOM_REFLECTION
#endif
#endif
#include<pbrBlockReflectance0>
#ifdef SHEEN
sheenOutParams sheenOut;
#ifdef SHEEN_TEXTURE
vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset);
#endif
#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w;
#endif
sheenOut=sheenBlock(
vSheenColor
#ifdef SHEEN_ROUGHNESS
,vSheenRoughness
#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
,sheenMapRoughnessData
#endif
#endif
,roughness
#ifdef SHEEN_TEXTURE
,sheenMapData
,vSheenInfos.y
#endif
,reflectanceF0
#ifdef SHEEN_LINKWITHALBEDO
,baseColor
,surfaceAlbedo
#endif
#ifdef ENVIRONMENTBRDF
,NdotV
,environmentBrdf
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
,AARoughnessFactors
,vReflectionMicrosurfaceInfos
,vReflectionInfos
,vReflectionColor
,vLightingIntensity
,reflectionSampler
,reflectionOut.reflectionCoords
,NdotVUnclamped
#ifndef LODBASEDMICROSFURACE
,reflectionSamplerLow
,reflectionSamplerHigh
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
,seo
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
,eho
#endif
#endif
);
#ifdef SHEEN_LINKWITHALBEDO
surfaceAlbedo=sheenOut.surfaceAlbedo;
#endif
#endif
#ifdef CLEARCOAT
#ifdef CLEARCOAT_TEXTURE
vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y;
#endif
#endif
#ifdef IRIDESCENCE
iridescenceOutParams iridescenceOut;
#ifdef IRIDESCENCE_TEXTURE
vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y;
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w;
#endif
iridescenceOut=iridescenceBlock(
vIridescenceParams
,NdotV
,specularEnvironmentR0
#ifdef IRIDESCENCE_TEXTURE
,iridescenceMapData
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
,iridescenceThicknessMapData
#endif
#ifdef CLEARCOAT
,NdotVUnclamped
,vClearCoatParams
#ifdef CLEARCOAT_TEXTURE
,clearCoatMapData
#endif
#endif
);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0;
#endif
clearcoatOutParams clearcoatOut;
#ifdef CLEARCOAT
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w;
#endif
#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset);
#endif
#ifdef CLEARCOAT_BUMP
vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset);
#endif
clearcoatOut=clearcoatBlock(
vPositionW
,geometricNormalW
,viewDirectionW
,vClearCoatParams
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
,clearCoatMapRoughnessData
#endif
,specularEnvironmentR0
#ifdef CLEARCOAT_TEXTURE
,clearCoatMapData
#endif
#ifdef CLEARCOAT_TINT
,vClearCoatTintParams
,clearCoatColorAtDistance
,vClearCoatRefractionParams
#ifdef CLEARCOAT_TINT_TEXTURE
,clearCoatTintMapData
#endif
#endif
#ifdef CLEARCOAT_BUMP
,vClearCoatBumpInfos
,clearCoatBumpMapData
,vClearCoatBumpUV
#if defined(TANGENT) && defined(NORMAL)
,vTBN
#else
,vClearCoatTangentSpaceParams
#endif
#ifdef OBJECTSPACE_NORMALMAP
,normalMatrix
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
,faceNormal
#endif
#ifdef REFLECTION
,vReflectionMicrosurfaceInfos
,vReflectionInfos
,vReflectionColor
,vLightingIntensity
,reflectionSampler
#ifndef LODBASEDMICROSFURACE
,reflectionSamplerLow
,reflectionSamplerHigh
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
#endif
#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
,(gl_FrontFacing ? 1. : -1.)
#endif
);
#else
clearcoatOut.specularEnvironmentR0=specularEnvironmentR0;
#endif
#include<pbrBlockReflectance>
subSurfaceOutParams subSurfaceOut;
#ifdef SUBSURFACE
#ifdef SS_THICKNESSANDMASK_TEXTURE
vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset);
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset);
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset);
#endif
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
vec4 translucencyColorMap=texture2D(translucencyColorSampler,vTranslucencyColorUV+uvOffset);
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA
translucencyColorMap=toLinearSpace(translucencyColorMap);
#endif
#endif
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
vec3 vSpecularEnvironmentReflectance=vec3(max(colorSpecularEnvironmentReflectance.r,max(colorSpecularEnvironmentReflectance.g,colorSpecularEnvironmentReflectance.b)));
#endif
subSurfaceOut=subSurfaceBlock(
vSubSurfaceIntensity
,vThicknessParam
,vTintColor
,normalW
#ifdef LEGACY_SPECULAR_ENERGY_CONSERVATION
,vSpecularEnvironmentReflectance
#else
,baseSpecularEnvironmentReflectance
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
,thicknessMap
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
,refractionIntensityMap
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
,translucencyIntensityMap
#endif
#ifdef REFLECTION
#ifdef SS_TRANSLUCENCY
,reflectionMatrix
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
,reflectionOut.irradianceVector
#endif
#if defined(REALTIME_FILTERING)
,reflectionSampler
,vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
#endif
#endif
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
#endif
#endif
#endif
#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
,surfaceAlbedo
#endif
#ifdef SS_REFRACTION
,vPositionW
,viewDirectionW
,view
,vRefractionInfos
,refractionMatrix
,vRefractionMicrosurfaceInfos
,vLightingIntensity
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
,alpha
#endif
#ifdef SS_LODINREFRACTIONALPHA
,NdotVUnclamped
#endif
#ifdef SS_LINEARSPECULARREFRACTION
,roughness
#endif
,alphaG
,refractionSampler
#ifndef LODBASEDMICROSFURACE
,refractionSamplerLow
,refractionSamplerHigh
#endif
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,vRefractionPosition
,vRefractionSize
#endif
#ifdef SS_DISPERSION
,dispersion
#endif
#endif
#ifdef SS_TRANSLUCENCY
,vDiffusionDistance
,vTranslucencyColor
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
,translucencyColorMap
#endif
#endif
);
#ifdef SS_REFRACTION
surfaceAlbedo=subSurfaceOut.surfaceAlbedo;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
alpha=subSurfaceOut.alpha;
#endif
#endif
#else
subSurfaceOut.specularEnvironmentReflectance=colorSpecularEnvironmentReflectance;
#endif
#include<pbrBlockDirectLighting>
#include<lightFragment>[0..maxSimultaneousLights]
#include<pbrBlockFinalLitComponents>
#endif
#include<pbrBlockFinalUnlitComponents>
#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION
#include<pbrBlockFinalColorComposition>
#include<logDepthFragment>
#include<fogFragment>(color,finalColor)
#include<pbrBlockImageProcessing>
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
#include<pbrBlockPrePass>
#endif
#if !defined(PREPASS) || defined(WEBGL2)
gl_FragColor=finalColor;
#endif
#include<oitFragment>
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;}
#endif
#include<pbrDebug>
#define CUSTOM_FRAGMENT_MAIN_END
}
`;x.ShadersStore[NF]||(x.ShadersStore[NF]=Qq);oSe={name:NF,shader:Qq}});var Tg,wF,sy,FF,Cr,eQ=y(()=>{jt();Yt();wt();Wo();$M();na();He();qi();Qj();yb();$t();Ib();Dv();ls();uo();$v();co();fD();Td();$j();Jj();eZ();tZ();iZ();JO();Hl();Jv();os();Cb();Pb();Lb();Db();Tg={effect:null,subMesh:null},wF=class extends ag(sg(wr)){},sy=class extends rg(wF){constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.IBL_CDF_FILTERING=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BASE_WEIGHT=!1,this.BASE_WEIGHTDIRECTUV=0,this.BASE_DIFFUSE_ROUGHNESS=!1,this.BASE_DIFFUSE_ROUGHNESSDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_POSITION=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.MORPHTARGETS_UV2=!1,this.MORPHTARGETS_COLOR=!1,this.MORPHTARGETTEXTURE_HASPOSITIONS=!1,this.MORPHTARGETTEXTURE_HASNORMALS=!1,this.MORPHTARGETTEXTURE_HASTANGENTS=!1,this.MORPHTARGETTEXTURE_HASUVS=!1,this.MORPHTARGETTEXTURE_HASUV2S=!1,this.MORPHTARGETTEXTURE_HASCOLORS=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.MIRRORED=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.AREALIGHTSUPPORTED=!0,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.USE_VERTEX_PULLING=!1,this.VERTEX_PULLING_USE_INDEX_BUFFER=!1,this.VERTEX_PULLING_INDEX_BUFFER_32BITS=!1,this.RIGHT_HANDED=!1,this.CLUSTLIGHT_SLICES=0,this.CLUSTLIGHT_BATCH=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}},FF=class extends og(jl){},Cr=class n extends FF{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}constructor(e,t,i=!1){super(e,t,void 0,i||n.ForceGLSL),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new Vi(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._baseWeightTexture=null,this._baseDiffuseRoughnessTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=n.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=he.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new he(0,0,0),this._albedoColor=new he(1,1,1),this._baseWeight=1,this._baseDiffuseRoughness=null,this._reflectivityColor=new he(1,1,1),this._reflectionColor=new he(1,1,1),this._emissiveColor=new he(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=n.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._renderTargets=new Qi(16),this._globalAmbientColor=new he(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this._shadersLoaded=!1,this._breakShaderLoadedCheck=!1,this._vertexPullingMetadata=null,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Vr(this),this.clearCoat=new An(this),this.iridescence=new ua(this),this.anisotropy=new df(this),this.sheen=new Ba(this),this.subSurface=new Li(this),this.detailMap=new ho(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),fe.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=QM(this.getScene()),this.prePassConfiguration=new fa}get hasRenderTargetTextures(){return fe.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){var e;return this._transparencyMode===n.PBRMATERIAL_OPAQUE||this._transparencyMode===n.PBRMATERIAL_ALPHATEST||((e=this.subSurface)==null?void 0:e.disableAlphaBlending)}needAlphaBlending(){return this._hasTransparencyMode?this._transparencyModeIsBlend:this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromAlbedoTexture()}needAlphaTesting(){var e;return this._hasTransparencyMode?this._transparencyModeIsTest:(e=this.subSurface)!=null&&e.disableAlphaBlending?!1:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===n.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==n.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var u;this._uniformBufferLayoutBuilt||this.buildUniformLayout();let r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new sy(this._eventInfo.defineNames));let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=this.getScene(),o=a.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a.texturesEnabled)){if(this._albedoTexture&&fe.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._baseWeightTexture&&fe.BaseWeightTextureEnabled&&!this._baseWeightTexture.isReadyOrNotBlocking()||this._baseDiffuseRoughnessTexture&&fe.BaseDiffuseRoughnessTextureEnabled&&!this._baseDiffuseRoughnessTexture.isReadyOrNotBlocking()||this._ambientTexture&&fe.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&fe.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;let h=this._getReflectionTexture();if(h&&fe.ReflectionTextureEnabled){if(!h.isReadyOrNotBlocking())return!1;if(h.irradianceTexture){if(!h.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!h.sphericalPolynomial&&((u=h.getInternalTexture())!=null&&u._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&fe.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&fe.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(fe.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&fe.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&fe.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;if(s.AREALIGHTUSED||s.CLUSTLIGHT_BATCH){for(let h=0;h<e.lightSources.length;h++)if(!e.lightSources[h]._isReady())return!1}if(!o.getCaps().standardDerivatives&&!e.isVerticesDataPresent(D.NormalKind)&&(e.createNormals(!0),te.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name)),!Vp(a,e,this._maxSimultaneousLights,this._disableLighting))return!1;let l=t.effect,c=s._areLightsDisposed,f=this._prepareEffect(e,t.getRenderingMesh(),s,this.onCompiled,this.onError,i,null),d=!1;if(f)if(this._onEffectCreatedObservable&&(Tg.effect=f,Tg.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Tg)),this.allowShaderHotSwapping&&l&&!f.isReady()){if(s.markAsUnprocessed(),d=this.isFrozen,c)return s._areLightsDisposed=!0,!1}else a.resetCachedMaterial(),t.setEffect(f,s,this._materialContext);return!t.effect||!t.effect.isReady()?!1:(s._renderId=a.getRenderId(),r._wasPreviouslyReady=!d,r._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return!!(this._metallic!=null||this._roughness!=null||this._metallicTexture)}_prepareEffect(e,t,i,r=null,s=null,a=null,o=null){if(this._prepareDefines(e,t,i,a,o),!i.isDirty)return null;i.markAsProcessed();let c=this.getScene().getEngine(),f=new ds,d=0;i.USESPHERICALINVERTEX&&f.addFallback(d++,"USESPHERICALINVERTEX"),i.FOG&&f.addFallback(d,"FOG"),i.SPECULARAA&&f.addFallback(d,"SPECULARAA"),i.POINTSIZE&&f.addFallback(d,"POINTSIZE"),i.LOGARITHMICDEPTH&&f.addFallback(d,"LOGARITHMICDEPTH"),i.PARALLAX&&f.addFallback(d,"PARALLAX"),i.PARALLAX_RHS&&f.addFallback(d,"PARALLAX_RHS"),i.PARALLAXOCCLUSION&&f.addFallback(d++,"PARALLAXOCCLUSION"),i.ENVIRONMENTBRDF&&f.addFallback(d++,"ENVIRONMENTBRDF"),i.TANGENT&&f.addFallback(d++,"TANGENT"),i.BUMP&&f.addFallback(d++,"BUMP"),d=Bp(i,f,this._maxSimultaneousLights,d),i.SPECULARTERM&&f.addFallback(d++,"SPECULARTERM"),i.USESPHERICALFROMREFLECTIONMAP&&f.addFallback(d++,"USESPHERICALFROMREFLECTIONMAP"),i.USEIRRADIANCEMAP&&f.addFallback(d++,"USEIRRADIANCEMAP"),i.LIGHTMAP&&f.addFallback(d++,"LIGHTMAP"),i.NORMAL&&f.addFallback(d++,"NORMAL"),i.AMBIENT&&f.addFallback(d++,"AMBIENT"),i.EMISSIVE&&f.addFallback(d++,"EMISSIVE"),i.VERTEXCOLOR&&f.addFallback(d++,"VERTEXCOLOR"),i.MORPHTARGETS&&f.addFallback(d++,"MORPHTARGETS"),i.MULTIVIEW&&f.addFallback(0,"MULTIVIEW");let u=[D.PositionKind];i.NORMAL&&u.push(D.NormalKind),i.TANGENT&&u.push(D.TangentKind);for(let T=1;T<=6;++T)i["UV"+T]&&u.push(`uv${T===1?"":T}`);i.VERTEXCOLOR&&u.push(D.ColorKind),wp(u,e,i,f),Fp(u,i),ih(u,e,i),Op(u,e,i);let h="pbr",m=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","baseWeight","baseDiffuseRoughness","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vBaseWeightInfos","vBaseDiffuseRoughnessInfos","vAmbientInfos","vOpacityInfos","vEmissiveInfos","vReflectivityInfos","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","baseWeightMatrix","baseDiffuseRoughnessMatrix","ambientMatrix","opacityMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vTangentSpaceParams","boneTextureInfo","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices","cameraInfo"],g=["albedoSampler","baseWeightSampler","baseDiffuseRoughnessSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler","areaLightsLTC1Sampler","areaLightsLTC2Sampler"];md(m,g,!0);let p=["Material","Scene","Mesh"],_={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:i.NUM_MORPH_INFLUENCERS};if(this._eventInfo.fallbacks=f,this._eventInfo.fallbackRank=d,this._eventInfo.defines=i,this._eventInfo.uniforms=m,this._eventInfo.attributes=u,this._eventInfo.samplers=g,this._eventInfo.uniformBuffersNames=p,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(128,this._eventInfo),us.AddUniformsAndSamplers(m,g),fa.AddUniforms(m),fa.AddSamplers(g),ns(m),this._useVertexPulling){let T=t==null?void 0:t.geometry;T&&(this._vertexPullingMetadata=Ad(T),this._vertexPullingMetadata&&this._vertexPullingMetadata.forEach((A,R)=>{m.push(`vp_${R}_info`)}))}else this._vertexPullingMetadata=null;Zt&&(Zt.PrepareUniforms(m,i),Zt.PrepareSamplers(g,i)),Yp({uniformsNames:m,uniformBuffersNames:p,samplers:g,defines:i,maxSimultaneousLights:this._maxSimultaneousLights,shaderLanguage:this._shaderLanguage});let v={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,m,p,g,i,u,v));let E=i.toString(),S=c.createEffect(h,{attributes:u,uniformsNames:m,uniformBuffersNames:p,samplers:g,defines:E,fallbacks:f,onCompiled:r,onError:s,indexParameters:_,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:i.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this.shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(aZ(),sZ)),Promise.resolve().then(()=>(QZ(),qZ))]):await Promise.all([Promise.resolve().then(()=>(rq(),iq)),Promise.resolve().then(()=>(Jq(),$q))]),this._shadersLoaded=!0}},c);return this._eventInfo.customCode=void 0,S}_prepareDefines(e,t,i,r=null,s=null){let a=t.hasThinInstances,o=this.getScene(),l=o.getEngine();Gp(o,e,i,!0,this._maxSimultaneousLights,this._disableLighting),i._needNormals=!0,Wp(o,i);let c=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Xp(o,i,this.canRenderToMRT&&!c),Hp(o,i,c),us.PrepareDefines(l.currentRenderPassId,e,i),i.METALLICWORKFLOW=this.isMetallicWorkflow(),i._areTexturesDirty){i._needUVs=!1;for(let f=1;f<=6;++f)i["MAINUV"+f]=!1;if(o.texturesEnabled){i.ALBEDODIRECTUV=0,i.BASE_WEIGHTDIRECTUV=0,i.BASE_DIFFUSE_ROUGHNESSDIRECTUV=0,i.AMBIENTDIRECTUV=0,i.OPACITYDIRECTUV=0,i.EMISSIVEDIRECTUV=0,i.REFLECTIVITYDIRECTUV=0,i.MICROSURFACEMAPDIRECTUV=0,i.METALLIC_REFLECTANCEDIRECTUV=0,i.REFLECTANCEDIRECTUV=0,i.BUMPDIRECTUV=0,i.LIGHTMAPDIRECTUV=0,l.getCaps().textureLOD&&(i.LODBASEDMICROSFURACE=!0),this._albedoTexture&&fe.DiffuseTextureEnabled?(fi(this._albedoTexture,i,"ALBEDO"),i.GAMMAALBEDO=this._albedoTexture.gammaSpace):i.ALBEDO=!1,this._baseWeightTexture&&fe.BaseWeightTextureEnabled?fi(this._baseWeightTexture,i,"BASE_WEIGHT"):i.BASE_WEIGHT=!1,this._baseDiffuseRoughnessTexture&&fe.BaseDiffuseRoughnessTextureEnabled?fi(this._baseDiffuseRoughnessTexture,i,"BASE_DIFFUSE_ROUGHNESS"):i.BASE_DIFFUSE_ROUGHNESS=!1,this._ambientTexture&&fe.AmbientTextureEnabled?(fi(this._ambientTexture,i,"AMBIENT"),i.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):i.AMBIENT=!1,this._opacityTexture&&fe.OpacityTextureEnabled?(fi(this._opacityTexture,i,"OPACITY"),i.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):i.OPACITY=!1;let f=this._getReflectionTexture(),d=this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||l.getCaps().maxVaryingVectors<=8||this._baseDiffuseRoughnessTexture!=null;hd(o,f,i,this.realTimeFiltering,this.realTimeFilteringQuality,!d),this._lightmapTexture&&fe.LightmapTextureEnabled?(fi(this._lightmapTexture,i,"LIGHTMAP"),i.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,i.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,i.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):i.LIGHTMAP=!1,this._emissiveTexture&&fe.EmissiveTextureEnabled?(fi(this._emissiveTexture,i,"EMISSIVE"),i.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):i.EMISSIVE=!1,fe.SpecularTextureEnabled?(this._metallicTexture?(fi(this._metallicTexture,i,"REFLECTIVITY"),i.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,i.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,i.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,i.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,i.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(fi(this._reflectivityTexture,i,"REFLECTIVITY"),i.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,i.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,i.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):i.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture?(i.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture,this._metallicReflectanceTexture?(fi(this._metallicReflectanceTexture,i,"METALLIC_REFLECTANCE"),i.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):i.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(fi(this._reflectanceTexture,i,"REFLECTANCE"),i.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):i.REFLECTANCE=!1):(i.METALLIC_REFLECTANCE=!1,i.REFLECTANCE=!1),this._microSurfaceTexture?fi(this._microSurfaceTexture,i,"MICROSURFACEMAP"):i.MICROSURFACEMAP=!1):(i.REFLECTIVITY=!1,i.MICROSURFACEMAP=!1),l.getCaps().standardDerivatives&&this._bumpTexture&&fe.BumpTextureEnabled&&!this._disableBumpMap?(fi(this._bumpTexture,i,"BUMP"),this._useParallax&&this._albedoTexture&&fe.DiffuseTextureEnabled?(i.PARALLAX=!0,i.PARALLAX_RHS=o.useRightHandedSystem,i.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):i.PARALLAX=!1,i.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(i.BUMP=!1,i.PARALLAX=!1,i.PARALLAX_RHS=!1,i.PARALLAXOCCLUSION=!1,i.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&fe.ReflectionTextureEnabled?(i.ENVIRONMENTBRDF=!0,i.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(i.ENVIRONMENTBRDF=!1,i.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?i.ALPHAFROMALBEDO=!0:i.ALPHAFROMALBEDO=!1}i.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===n.LIGHTFALLOFF_STANDARD?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===n.LIGHTFALLOFF_GLTF?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!0):(i.USEPHYSICALLIGHTFALLOFF=!0,i.USEGLTFLIGHTFALLOFF=!1),i.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?i.TWOSIDEDLIGHTING=!0:i.TWOSIDEDLIGHTING=!1,i.MIRRORED=!!o._mirroredCameraPosition,i.SPECULARAA=l.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(i._areTexturesDirty||i._areMiscDirty)&&(i.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1===0?".":""}`,i.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,i.ALPHABLEND=this.needAlphaBlendingForMesh(e),i.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,i.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),i._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(i),i.FORCENORMALFORWARD=this._forceNormalForward,i.RADIANCEOCCLUSION=this._useRadianceOcclusion,i.HORIZONOCCLUSION=this._useHorizonOcclusion,i._areMiscDirty&&(Up(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this.needAlphaTestingForMesh(e),i,this._applyDecalMapAfterDetailMap,this._useVertexPulling,t,this._isVertexOutputInvariant),i.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(D.NormalKind),i.DEBUGMODE=this._debugMode),kp(o,l,this,i,!!r,s,a),this._eventInfo.defines=i,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),zp(e,i,!0,!0,!0,this._transparencyMode!==n.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){let r={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(4,this._eventInfo),(()=>{if(this._breakShaderLoadedCheck)return;let a=new sy(this._eventInfo.defineNames),o=this._prepareEffect(e,e,a,void 0,void 0,r.useInstances,r.clipPlane);this._onEffectCreatedObservable&&(Tg.effect=o,Tg.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Tg)),o.isReady()?t&&t(this):o.onCompileObservable.add(()=>{t&&t(this)})})()}buildUniformLayout(){let e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vBaseWeightInfos",2),e.addUniform("vBaseDiffuseRoughnessInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("baseWeightMatrix",16),e.addUniform("baseDiffuseRoughnessMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("vAlbedoColor",4),e.addUniform("baseWeight",1),e.addUniform("baseDiffuseRoughness",1),e.addUniform("vLightingIntensity",4),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("cameraInfo",4),Kp(e,!0,!0,!0,!0,!0),super.buildUniformLayout()}bindForSubMesh(e,t,i){var u,h,m,g;let r=this.getScene(),s=i.materialDefines;if(!s)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e);let o=r.getEngine();this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),us.Bind(o.currentRenderPassId,this._activeEffect,t,e,this);let l=r.activeCamera;l?this._uniformBuffer.updateFloat4("cameraInfo",l.minZ,l.maxZ,0,0):this._uniformBuffer.updateFloat4("cameraInfo",0,0,0,0),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let c=this._mustRebind(r,a,i,t.visibility);aa(t,this._activeEffect,this.prePassConfiguration),this._vertexPullingMetadata&&xd(this._activeEffect,this._vertexPullingMetadata);let f=null,d=this._uniformBuffer;if(c){if(this.bindViewProjection(a),f=this._getReflectionTexture(),!d.useUbo||!this.isFrozen||!d.isSync||i._drawWrapper._forceRebindOnNextCall){if(r.texturesEnabled&&(this._albedoTexture&&fe.DiffuseTextureEnabled&&(d.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),di(this._albedoTexture,d,"albedo")),this._baseWeightTexture&&fe.BaseWeightTextureEnabled&&(d.updateFloat2("vBaseWeightInfos",this._baseWeightTexture.coordinatesIndex,this._baseWeightTexture.level),di(this._baseWeightTexture,d,"baseWeight")),this._baseDiffuseRoughnessTexture&&fe.BaseDiffuseRoughnessTextureEnabled&&(d.updateFloat2("vBaseDiffuseRoughnessInfos",this._baseDiffuseRoughnessTexture.coordinatesIndex,this._baseDiffuseRoughnessTexture.level),di(this._baseDiffuseRoughnessTexture,d,"baseDiffuseRoughness")),this._ambientTexture&&fe.AmbientTextureEnabled&&(d.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),di(this._ambientTexture,d,"ambient")),this._opacityTexture&&fe.OpacityTextureEnabled&&(d.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),di(this._opacityTexture,d,"opacity")),this._emissiveTexture&&fe.EmissiveTextureEnabled&&(d.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),di(this._emissiveTexture,d,"emissive")),this._lightmapTexture&&fe.LightmapTextureEnabled&&(d.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),di(this._lightmapTexture,d,"lightmap")),fe.SpecularTextureEnabled&&(this._metallicTexture?(d.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),di(this._metallicTexture,d,"reflectivity")):this._reflectivityTexture&&(d.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),di(this._reflectivityTexture,d,"reflectivity")),this._metallicReflectanceTexture&&(d.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),di(this._metallicReflectanceTexture,d,"metallicReflectance")),this._reflectanceTexture&&s.REFLECTANCE&&(d.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),di(this._reflectanceTexture,d,"reflectance")),this._microSurfaceTexture&&(d.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),di(this._microSurfaceTexture,d,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&fe.BumpTextureEnabled&&!this._disableBumpMap&&(d.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),di(this._bumpTexture,d,"bump"),r._mirroredCameraPosition?d.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):d.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),Dp(r,s,d,this._reflectionColor,f,this.realTimeFiltering,!0,!0,!0,!0,!0)),this.pointsCloud&&d.updateFloat("pointSize",this.pointSize),s.METALLICWORKFLOW){Gn.Color4[0].r=this._metallic===void 0||this._metallic===null?1:this._metallic,Gn.Color4[0].g=this._roughness===void 0||this._roughness===null?1:this._roughness;let p=(h=(u=this.subSurface)==null?void 0:u._indexOfRefraction)!=null?h:1.5,_=1;Gn.Color4[0].b=p;let v=Math.pow((p-_)/(p+_),2);Gn.Color4[0].a=v,d.updateDirectColor4("vReflectivityColor",Gn.Color4[0]),d.updateColor4("vMetallicReflectanceFactors",this._metallicReflectanceColor,this._metallicF0Factor)}else d.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);d.updateColor3("vEmissiveColor",fe.EmissiveTextureEnabled?this._emissiveColor:he.BlackReadOnly),!s.SS_REFRACTION&&((m=this.subSurface)!=null&&m._linkRefractionWithTransparency)?d.updateColor4("vAlbedoColor",this._albedoColor,1):d.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),d.updateFloat("baseWeight",this._baseWeight),d.updateFloat("baseDiffuseRoughness",this._baseDiffuseRoughness||0),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*r.environmentIntensity,this._lightingInfos.w=this._specularIntensity,d.updateVector4("vLightingIntensity",this._lightingInfos),r.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),d.updateColor3("vAmbientColor",this._globalAmbientColor),d.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}r.texturesEnabled&&(this._albedoTexture&&fe.DiffuseTextureEnabled&&d.setTexture("albedoSampler",this._albedoTexture),this._baseWeightTexture&&fe.BaseWeightTextureEnabled&&d.setTexture("baseWeightSampler",this._baseWeightTexture),this._baseDiffuseRoughnessTexture&&fe.BaseDiffuseRoughnessTextureEnabled&&d.setTexture("baseDiffuseRoughnessSampler",this._baseDiffuseRoughnessTexture),this._ambientTexture&&fe.AmbientTextureEnabled&&d.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&fe.OpacityTextureEnabled&&d.setTexture("opacitySampler",this._opacityTexture),db(r,s,d,f,this.realTimeFiltering),s.ENVIRONMENTBRDF&&d.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&fe.EmissiveTextureEnabled&&d.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&fe.LightmapTextureEnabled&&d.setTexture("lightmapSampler",this._lightmapTexture),fe.SpecularTextureEnabled&&(this._metallicTexture?d.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&d.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&d.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&s.REFLECTANCE&&d.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&d.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&fe.BumpTextureEnabled&&!this._disableBumpMap&&d.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),ss(this._activeEffect,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(c||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&Np(r,t,this._activeEffect,s,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==ai.FOGMODE_NONE||f||this.subSurface.refractionTexture||t.receiveShadows||s.PREPASS||s.CLUSTLIGHT_BATCH)&&this.bindView(a),dd(r,t,this._activeEffect,!0),s.NUM_MORPH_INFLUENCERS&&as(t,this._activeEffect),s.BAKED_VERTEX_ANIMATION_TEXTURE&&((g=t.bakedVertexAnimationManager)==null||g.bind(a,s.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),fd(s,this._activeEffect,r)),this._afterBind(t,this._activeEffect,i),d.update()}getAnimatables(){let e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._baseWeightTexture&&this._baseWeightTexture.animations&&this._baseWeightTexture.animations.length>0&&e.push(this._baseWeightTexture),this._baseDiffuseRoughnessTexture&&this._baseDiffuseRoughnessTexture.animations&&this._baseDiffuseRoughnessTexture.animations.length>0&&e.push(this._baseDiffuseRoughnessTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){let e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._baseWeightTexture&&e.push(this._baseWeightTexture),this._baseDiffuseRoughnessTexture&&e.push(this._baseDiffuseRoughnessTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._albedoTexture===e||this._baseWeightTexture===e||this._baseDiffuseRoughnessTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e)}setPrePassRenderer(){var t;if(!((t=this.subSurface)!=null&&t.isScatteringEnabled))return!1;let e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){var i,r,s,a,o,l,c,f,d,u,h,m,g,p;this._breakShaderLoadedCheck=!0,t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),(i=this._albedoTexture)==null||i.dispose(),(r=this._baseWeightTexture)==null||r.dispose(),(s=this._baseDiffuseRoughnessTexture)==null||s.dispose(),(a=this._ambientTexture)==null||a.dispose(),(o=this._opacityTexture)==null||o.dispose(),(l=this._reflectionTexture)==null||l.dispose(),(c=this._emissiveTexture)==null||c.dispose(),(f=this._metallicTexture)==null||f.dispose(),(d=this._reflectivityTexture)==null||d.dispose(),(u=this._bumpTexture)==null||u.dispose(),(h=this._lightmapTexture)==null||h.dispose(),(m=this._metallicReflectanceTexture)==null||m.dispose(),(g=this._reflectanceTexture)==null||g.dispose(),(p=this._microSurfaceTexture)==null||p.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}};Cr.PBRMATERIAL_OPAQUE=Ae.MATERIAL_OPAQUE;Cr.PBRMATERIAL_ALPHATEST=Ae.MATERIAL_ALPHATEST;Cr.PBRMATERIAL_ALPHABLEND=Ae.MATERIAL_ALPHABLEND;Cr.PBRMATERIAL_ALPHATESTANDBLEND=Ae.MATERIAL_ALPHATESTANDBLEND;Cr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0;Cr.LIGHTFALLOFF_PHYSICAL=0;Cr.LIGHTFALLOFF_GLTF=1;Cr.LIGHTFALLOFF_STANDARD=2;Cr.ForceGLSL=!1;P([le("_markAllSubMeshesAsMiscDirty")],Cr.prototype,"debugMode",void 0)});var tQ={};Be(tQ,{PBRMaterial:()=>_t});var _t,iQ=y(()=>{jt();Yt();$M();$t();eQ();ir();ls();Or();_t=class n extends Cr{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===Cr.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Cr.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=Cr.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Cr.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Cr.LIGHTFALLOFF_GLTF:this._lightFalloff=Cr.LIGHTFALLOFF_STANDARD)}constructor(e,t,i=!1){super(e,t,i),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=n.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=he.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new he(0,0,0),this.albedoColor=new he(1,1,1),this.baseWeight=1,this.reflectivityColor=new he(1,1,1),this.reflectionColor=new he(1,1,1),this.emissiveColor=new he(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=QM(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){let r=at.Clone(()=>new n(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){let e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){let r=at.Parse(()=>new n(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Ae._ParsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};_t.PBRMATERIAL_OPAQUE=Cr.PBRMATERIAL_OPAQUE;_t.PBRMATERIAL_ALPHATEST=Cr.PBRMATERIAL_ALPHATEST;_t.PBRMATERIAL_ALPHABLEND=Cr.PBRMATERIAL_ALPHABLEND;_t.PBRMATERIAL_ALPHATESTANDBLEND=Cr.PBRMATERIAL_ALPHATESTANDBLEND;_t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Cr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"directIntensity",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"emissiveIntensity",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"environmentIntensity",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"specularIntensity",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"disableBumpMap",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"albedoTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"baseWeightTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"baseDiffuseRoughnessTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"ambientTexture",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"ambientTextureStrength",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"ambientTextureImpactOnAnalyticalLights",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesAndMiscDirty")],_t.prototype,"opacityTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"reflectionTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"emissiveTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"reflectivityTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"metallicTexture",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"metallic",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"roughness",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"metallicF0Factor",void 0);P([yr(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"metallicReflectanceColor",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"metallicReflectanceTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"reflectanceTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"microSurfaceTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"bumpTexture",void 0);P([Xt(),le("_markAllSubMeshesAsTexturesDirty",null)],_t.prototype,"lightmapTexture",void 0);P([yr("ambient"),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"ambientColor",void 0);P([yr("albedo"),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"albedoColor",void 0);P([F("baseWeight"),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"baseWeight",void 0);P([F("baseDiffuseRoughness"),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"baseDiffuseRoughness",void 0);P([yr("reflectivity"),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"reflectivityColor",void 0);P([yr("reflection"),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"reflectionColor",void 0);P([yr("emissive"),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"emissiveColor",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"microSurface",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useLightmapAsShadowmap",void 0);P([F(),le("_markAllSubMeshesAsTexturesAndMiscDirty")],_t.prototype,"useAlphaFromAlbedoTexture",void 0);P([F(),le("_markAllSubMeshesAsTexturesAndMiscDirty")],_t.prototype,"forceAlphaTest",void 0);P([F(),le("_markAllSubMeshesAsTexturesAndMiscDirty")],_t.prototype,"alphaCutOff",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useSpecularOverAlpha",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useRoughnessFromMetallicTextureAlpha",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useRoughnessFromMetallicTextureGreen",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useMetallnessFromMetallicTextureBlue",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useAmbientInGrayScale",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0);P([F()],_t.prototype,"usePhysicalLightFalloff",null);P([F()],_t.prototype,"useGLTFLightFalloff",null);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useRadianceOverAlpha",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useObjectSpaceNormalMap",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useParallax",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useParallaxOcclusion",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"parallaxScaleBias",void 0);P([F(),le("_markAllSubMeshesAsLightsDirty")],_t.prototype,"disableLighting",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"forceIrradianceInFragment",void 0);P([F(),le("_markAllSubMeshesAsLightsDirty")],_t.prototype,"maxSimultaneousLights",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"invertNormalMapX",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"invertNormalMapY",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"twoSidedLighting",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useAlphaFresnel",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useLinearAlphaFresnel",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"environmentBRDFTexture",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"forceNormalForward",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"enableSpecularAntiAliasing",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useHorizonOcclusion",void 0);P([F(),le("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"useRadianceOcclusion",void 0);P([F(),le("_markAllSubMeshesAsMiscDirty")],_t.prototype,"unlit",void 0);P([F(),le("_markAllSubMeshesAsMiscDirty")],_t.prototype,"applyDecalMapAfterDetailMap",void 0);zt("BABYLON.PBRMaterial",_t)});var rQ={};Be(rQ,{PBRMaterialLoadingAdapter:()=>BF});var BF,nQ=y(()=>{$t();gw();He();BF=class{constructor(e){this._material=e,this._material.enableSpecularAntiAliasing=!0}get material(){return this._material}get isUnlit(){return this._material.unlit}set isUnlit(e){this._material.unlit=e}set backFaceCulling(e){this._material.backFaceCulling=e}get backFaceCulling(){return this._material.backFaceCulling}set twoSidedLighting(e){this._material.twoSidedLighting=e}get twoSidedLighting(){return this._material.twoSidedLighting}set alphaCutOff(e){this._material.alphaCutOff=e}get alphaCutOff(){return this._material.alphaCutOff}set useAlphaFromBaseColorTexture(e){this._material.useAlphaFromAlbedoTexture=e}get useAlphaFromBaseColorTexture(){return this._material.useAlphaFromAlbedoTexture}get transparencyAsAlphaCoverage(){return this._material.useRadianceOverAlpha||this._material.useSpecularOverAlpha}set transparencyAsAlphaCoverage(e){this._material.useRadianceOverAlpha=!e,this._material.useSpecularOverAlpha=!e}set baseColor(e){this._material.albedoColor=e}get baseColor(){return this._material.albedoColor}set baseColorTexture(e){this._material.albedoTexture=e}get baseColorTexture(){return this._material.albedoTexture}set baseDiffuseRoughness(e){this._material.baseDiffuseRoughness=e,e>0&&(this._material.brdf.baseDiffuseModel=z.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR)}get baseDiffuseRoughness(){var e;return(e=this._material.baseDiffuseRoughness)!=null?e:0}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.metallic=e}get baseMetalness(){var e;return(e=this._material.metallic)!=null?e:1}set baseMetalnessTexture(e){this._material.metallicTexture=e}get baseMetalnessTexture(){return this._material.metallicTexture}set useRoughnessFromMetallicTextureGreen(e){this._material.useRoughnessFromMetallicTextureGreen=e,this._material.useRoughnessFromMetallicTextureAlpha=!e}set useMetallicFromMetallicTextureBlue(e){this._material.useMetallnessFromMetallicTextureBlue=e}enableSpecularEdgeColor(e=!1){e&&(this._material.brdf.dielectricSpecularModel=z.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR,this._material.brdf.conductorSpecularModel=z.MATERIAL_CONDUCTOR_SPECULAR_MODEL_OPENPBR)}set specularWeight(e){this._material.metallicF0Factor=e}get specularWeight(){var e;return(e=this._material.metallicF0Factor)!=null?e:1}set specularWeightTexture(e){e?(this._material.metallicReflectanceTexture=e,this._material.useOnlyMetallicFromMetallicReflectanceTexture=!0):(this._material.metallicReflectanceTexture=null,this._material.useOnlyMetallicFromMetallicReflectanceTexture=!1)}get specularWeightTexture(){return this._material.metallicReflectanceTexture}set specularColor(e){this._material.metallicReflectanceColor=e}get specularColor(){return this._material.metallicReflectanceColor}set specularColorTexture(e){this._material.reflectanceTexture=e}get specularColorTexture(){return this._material.reflectanceTexture}set specularRoughness(e){this._material.roughness=e}get specularRoughness(){var e;return(e=this._material.roughness)!=null?e:1}set specularRoughnessTexture(e){this.baseMetalnessTexture||(this._material.metallicTexture=e)}get specularRoughnessTexture(){return this._material.metallicTexture}set specularIor(e){this._material.indexOfRefraction=e}get specularIor(){return this._material.indexOfRefraction}set emissionColor(e){this._material.emissiveColor=e}get emissionColor(){return this._material.emissiveColor}set emissionLuminance(e){this._material.emissiveIntensity=e}get emissionLuminance(){return this._material.emissiveIntensity}set emissionColorTexture(e){this._material.emissiveTexture=e}get emissionColorTexture(){return this._material.emissiveTexture}set ambientOcclusionTexture(e){this._material.ambientTexture=e,e&&(this._material.useAmbientInGrayScale=!0)}get ambientOcclusionTexture(){return this._material.ambientTexture}set ambientOcclusionTextureStrength(e){this._material.ambientTextureStrength=e}get ambientOcclusionTextureStrength(){var e;return(e=this._material.ambientTextureStrength)!=null?e:1}configureCoat(){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.useRoughnessFromMainTexture=!1,this._material.clearCoat.remapF0OnInterfaceChange=!1}set coatWeight(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.intensity=e}get coatWeight(){return this._material.clearCoat.intensity}set coatWeightTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.texture=e}get coatWeightTexture(){return this._material.clearCoat.texture}set coatColor(e){this._material.clearCoat.isTintEnabled=e!=he.White(),this._material.clearCoat.tintColor=e}set coatColorTexture(e){this._material.clearCoat.tintTexture=e}set coatRoughness(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.roughness=e}get coatRoughness(){var e;return(e=this._material.clearCoat.roughness)!=null?e:0}set coatRoughnessTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.useRoughnessFromMainTexture=!1,this._material.clearCoat.textureRoughness=e}get coatRoughnessTexture(){return this._material.clearCoat.textureRoughness}set coatIor(e){this._material.clearCoat.indexOfRefraction=e}set coatDarkening(e){}set coatDarkeningTexture(e){}set coatRoughnessAnisotropy(e){}get coatRoughnessAnisotropy(){return 0}set geometryCoatTangentAngle(e){}set geometryCoatTangentTexture(e){}get geometryCoatTangentTexture(){return null}set transmissionWeight(e){this._material.subSurface.isRefractionEnabled=e>0,this._material.subSurface.refractionIntensity=e}get transmissionWeight(){return this._material.subSurface.isRefractionEnabled?this._material.subSurface.refractionIntensity:0}set transmissionWeightTexture(e){this._material.subSurface.isRefractionEnabled=!0,this._material.subSurface.refractionIntensityTexture=e,this._material.subSurface.useGltfStyleTextures=!0}set transmissionDepth(e){this.transmissionWeight>0?this._material.subSurface.tintColorAtDistance=e:this.subsurfaceWeight>0&&this._material.subSurface.diffusionDistance.multiplyInPlace(new he(e,e,e))}get transmissionDepth(){return this.transmissionWeight>0?this._material.subSurface.tintColorAtDistance:0}set transmissionColor(e){this.transmissionWeight>0?this._material.subSurface.tintColor=e:this.subsurfaceWeight>0&&this._material.subSurface.diffusionDistance.multiplyInPlace(e)}get transmissionColor(){return this.transmissionWeight>0?this._material.subSurface.tintColor:this.subsurfaceWeight>0?this._material.subSurface.diffusionDistance:new he(0,0,0)}set transmissionScatter(e){this._material.subSurface.diffusionDistance=e}get transmissionScatter(){return this._material.subSurface.diffusionDistance}set transmissionScatterTexture(e){}set transmissionScatterAnisotropy(e){}set transmissionDispersionAbbeNumber(e){}set transmissionDispersionScale(e){e>0?(this._material.subSurface.isDispersionEnabled=!0,this._material.subSurface.dispersion=20/e):(this._material.subSurface.isDispersionEnabled=!1,this._material.subSurface.dispersion=0)}get refractionBackgroundTexture(){return this._material.subSurface.refractionTexture}set refractionBackgroundTexture(e){this._material.subSurface.refractionTexture=e}configureTransmission(){this._material.subSurface.volumeIndexOfRefraction=1,this._material.subSurface.useAlbedoToTintRefraction=!0,this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=0}configureVolume(){}set geometryThinWalled(e){}get geometryThinWalled(){return!0}set volumeThicknessTexture(e){this._material.subSurface.thicknessTexture=e,this._material.subSurface.useGltfStyleTextures=!0}set volumeThickness(e){this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=e,this._material.subSurface.useThicknessAsDepth=!0,e>0&&(this._material.subSurface.volumeIndexOfRefraction=this._material.indexOfRefraction)}configureSubsurface(){this._material.subSurface.useGltfStyleTextures=!0,this._material.subSurface.volumeIndexOfRefraction=1,this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=0,this._material.subSurface.useAlbedoToTintTranslucency=!1}set subsurfaceWeight(e){this._material.subSurface.isTranslucencyEnabled=e>0,this._material.subSurface.translucencyIntensity=e}get subsurfaceWeight(){return this._material.subSurface.isTranslucencyEnabled?this._material.subSurface.translucencyIntensity:0}set subsurfaceWeightTexture(e){this._material.subSurface.translucencyIntensityTexture=e}set subsurfaceColor(e){let t=new b(-Math.log(this.transmissionColor.r),-Math.log(this.transmissionColor.g),-Math.log(this.transmissionColor.b));t.scaleInPlace(1/Math.max(this.transmissionDepth,.001));let i=t,r=Math.max(i.x,Math.max(i.y,i.z)),s=r>0?1/r:1;this._material.subSurface.diffusionDistance=new he(Math.exp(-i.x*s),Math.exp(-i.y*s),Math.exp(-i.z*s))}set subsurfaceColorTexture(e){}set diffuseTransmissionTint(e){this._material.subSurface.tintColor=e}get diffuseTransmissionTint(){return this._material.subSurface.tintColor}set diffuseTransmissionTintTexture(e){this._material.subSurface.translucencyColorTexture=e}get subsurfaceRadius(){return 1}set subsurfaceRadius(e){}get subsurfaceRadiusScale(){var e;return(e=this._material.subSurface.scatteringDiffusionProfile)!=null?e:he.White()}set subsurfaceRadiusScale(e){this._material.subSurface.scatteringDiffusionProfile=e}set subsurfaceScatterAnisotropy(e){}isTranslucent(){return this.transmissionWeight>0||this.subsurfaceWeight>0}configureFuzz(){this._material.sheen.isEnabled=!0,this._material.sheen.useRoughnessFromMainTexture=!1,this._material.sheen.albedoScaling=!0}set fuzzWeight(e){this._material.sheen.isEnabled=!0,this._material.sheen.intensity=e}set fuzzWeightTexture(e){this._material.sheen.texture||(this._material.sheen.texture=e)}set fuzzColor(e){this._material.sheen.isEnabled=!0,this._material.sheen.color=e}set fuzzColorTexture(e){this._material.sheen.texture=e}set fuzzRoughness(e){this._material.sheen.isEnabled=!0,this._material.sheen.roughness=e}set fuzzRoughnessTexture(e){this._material.sheen.isEnabled=!0,this._material.sheen.textureRoughness=e}set specularRoughnessAnisotropy(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.intensity=e}get specularRoughnessAnisotropy(){return this._material.anisotropy.intensity}set geometryTangentAngle(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.angle=e}set geometryTangentTexture(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.texture=e}get geometryTangentTexture(){return this._material.anisotropy.texture}configureGltfStyleAnisotropy(e=!0){}set thinFilmWeight(e){this._material.iridescence.isEnabled=e>0,this._material.iridescence.intensity=e}set thinFilmIor(e){this._material.iridescence.indexOfRefraction=e}set thinFilmThicknessMinimum(e){this._material.iridescence.minimumThickness=e}set thinFilmThicknessMaximum(e){this._material.iridescence.maximumThickness=e}set thinFilmWeightTexture(e){this._material.iridescence.texture=e}set thinFilmThicknessTexture(e){this._material.iridescence.thicknessTexture=e}set unlit(e){this._material.unlit=e}set geometryOpacity(e){this._material.alpha=e}get geometryOpacity(){return this._material.alpha}set geometryNormalTexture(e){this._material.bumpTexture=e,this._material.forceIrradianceInFragment=!0}get geometryNormalTexture(){return this._material.bumpTexture}setNormalMapInversions(e,t){this._material.invertNormalMapX=e,this._material.invertNormalMapY=t}set geometryCoatNormalTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.bumpTexture=e}get geometryCoatNormalTexture(){return this._material.clearCoat.bumpTexture}set geometryCoatNormalTextureScale(e){this._material.clearCoat.bumpTexture&&(this._material.clearCoat.bumpTexture.level=e)}}});function fSe(n){if(n.min&&n.max){let e=n.min,t=n.max,i=ee.Vector3[0].copyFromFloats(e[0],e[1],e[2]),r=ee.Vector3[1].copyFromFloats(t[0],t[1],t[2]);if(n.normalized&&n.componentType!==5126){let s=1;switch(n.componentType){case 5120:s=127;break;case 5121:s=255;break;case 5122:s=32767;break;case 5123:s=65535;break}let a=1/s;i.scaleInPlace(a),r.scaleInPlace(a)}return new In(i,r)}return null}var lSe,cSe,ri,ay,sQ=y(()=>{T9();He();$t();Gi();zl();I9();HM();P9();ls();Kr();cd();qi();lb();Pp();ki();hw();D9();uw();Cc();wt();Ip();pw();_w();F9();_p();B9();lSe=new IE(()=>Promise.resolve().then(()=>(z9(),k9))),cSe=new IE(()=>Promise.resolve().then(()=>(Y9(),X9))),ri=class{static Get(e,t,i){if(!t||i==null||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return!e||t==null||!e[t]?null:e[t]}static Assign(e){if(e)for(let t=0;t<e.length;t++)e[t].index=t}};ay=class n{isMatchingMaterialType(e){return e&&this._pbrMaterialImpl?e instanceof this._pbrMaterialImpl.materialClass:!1}static RegisterExtension(e,t){KM(e,!1,t)}static UnregisterExtension(e){return bE(e)}get gltf(){if(!this._gltf)throw new Error("glTF JSON is not available");return this._gltf}get bin(){return this._bin}get parent(){return this._parent}get babylonScene(){if(!this._babylonScene)throw new Error("Scene is not available");return this._babylonScene}get rootBabylonMesh(){return this._rootBabylonMesh}get rootUrl(){return this._rootUrl}constructor(e){this._completePromises=new Array,this._assetContainer=null,this._babylonLights=[],this._disableInstancedMesh=0,this._allMaterialsDirtyRequired=!1,this._skipStartAnimationStep=!1,this._extensions=new Array,this._disposed=!1,this._rootUrl=null,this._fileName=null,this._uniqueRootUrl=null,this._bin=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions=new Array,this._materialAdapterCache=new WeakMap,this._materialAdapters=new Set,this._pbrMaterialImpl=null,this._parent=e}_getOrCreateMaterialAdapter(e){let t=this._materialAdapterCache.get(e);if(!t){if(this._pbrMaterialImpl)t=new this._pbrMaterialImpl.adapterClass(e);else throw new Error("Appropriate material adapter class not found");let i=t;this._materialAdapterCache.set(e,i),this._materialAdapters.add(i)}return t}dispose(){var e;if(!this._disposed){this._disposed=!0,this._completePromises.length=0,this._extensions.forEach(t=>t.dispose&&t.dispose()),this._extensions.length=0;for(let t of Array.from(this._materialAdapters))(e=t.finalize)==null||e.call(t);this._materialAdapters.clear(),this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose()}}async importMeshAsync(e,t,i,r,s,a,o=""){return await Promise.resolve().then(async()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(r);let l=null;if(e){let c={};if(this._gltf.nodes)for(let d of this._gltf.nodes)d.name&&(c[d.name]=d.index);l=(e instanceof Array?e:[e]).map(d=>{let u=c[d];if(u===void 0)throw new Error(`Failed to find node '${d}'`);return u})}return await this._loadAsync(s,o,l,()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]}))})}async loadAsync(e,t,i,r,s=""){return this._babylonScene=e,this._loadData(t),await this._loadAsync(i,s,null,()=>{})}async _loadAsync(e,t,i,r){return await Promise.resolve().then(async()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,await this._loadExtensionsAsync(),!this.parent.skipMaterials&&this._pbrMaterialImpl==null&&(this.parent.useOpenPBR||this.isExtensionUsed("KHR_materials_openpbr")?this._pbrMaterialImpl={materialClass:(await Promise.resolve().then(()=>(jj(),Kj))).OpenPBRMaterial,adapterClass:(await Promise.resolve().then(()=>(qj(),Zj))).OpenPBRMaterialLoadingAdapter}:this._pbrMaterialImpl={materialClass:(await Promise.resolve().then(()=>(iQ(),tQ))).PBRMaterial,adapterClass:(await Promise.resolve().then(()=>(nQ(),rQ))).PBRMaterialLoadingAdapter});let s=`${Ns[Ns.LOADING]} => ${Ns[Ns.READY]}`,a=`${Ns[Ns.LOADING]} => ${Ns[Ns.COMPLETE]}`;this._parent._startPerformanceCounter(s),this._parent._startPerformanceCounter(a),this._parent._setState(Ns.LOADING),this._extensionsOnLoading();let o=new Array,l=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials){if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(this._gltf.scene!=null||this._gltf.scenes&&this._gltf.scenes[0]){let f=ri.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${f.index}`,f))}}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let f=0;f<this._gltf.materials.length;++f){let d=this._gltf.materials[f],u="/materials/"+f,h=Ae.TriangleFillMode;o.push(this._loadMaterialAsync(u,d,null,h,()=>{}))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=l:this._babylonScene._forceBlockMaterialDirtyMechanism(l),this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync()),await Promise.all(o).then(()=>{this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0);for(let f of this._babylonScene.materials){let d=f;d.maxSimultaneousLights!==void 0&&(d.maxSimultaneousLights=Math.max(d.maxSimultaneousLights,this._babylonScene.lights.length))}return this._extensionsOnReady(),this._parent._setState(Ns.READY),this._skipStartAnimationStep||this._startAnimations(),r()}).then(f=>(this._parent._endPerformanceCounter(s),pe.SetImmediate(()=>{this._disposed||Promise.all(this._completePromises).then(()=>{this._parent._endPerformanceCounter(a),this._parent._setState(Ns.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()},d=>{this._parent.onErrorObservable.notifyObservers(d),this._parent.onErrorObservable.clear(),this.dispose()})}),f))}).catch(s=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(s),this._parent.onErrorObservable.clear(),this.dispose()),s})}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){let t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){let i=t[0];(i.byteLength<e.bin.byteLength-3||i.byteLength>e.bin.byteLength)&&te.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else te.Warn("Unexpected BIN chunk")}}_setupData(){if(ri.Assign(this._gltf.accessors),ri.Assign(this._gltf.animations),ri.Assign(this._gltf.buffers),ri.Assign(this._gltf.bufferViews),ri.Assign(this._gltf.cameras),ri.Assign(this._gltf.images),ri.Assign(this._gltf.materials),ri.Assign(this._gltf.meshes),ri.Assign(this._gltf.nodes),ri.Assign(this._gltf.samplers),ri.Assign(this._gltf.scenes),ri.Assign(this._gltf.skins),ri.Assign(this._gltf.textures),this._gltf.nodes){let e={};for(let i of this._gltf.nodes)if(i.children)for(let r of i.children)e[r]=i.index;let t=this._createRootNode();for(let i of this._gltf.nodes){let r=e[i.index];i.parent=r===void 0?t:this._gltf.nodes[r]}}}async _loadExtensionsAsync(){var t;let e=[];if(O9.forEach((i,r)=>{var s;((s=this.parent.extensionOptions[r])==null?void 0:s.enabled)===!1?i.isGLTFExtension&&this.isExtensionUsed(r)&&te.Warn(`Extension ${r} is used but has been explicitly disabled.`):(!i.isGLTFExtension||this.isExtensionUsed(r))&&e.push((async()=>{let a=await i.factory(this);return a.name!==r&&te.Warn(`The name of the glTF loader extension instance does not match the registered name: ${a.name} !== ${r}`),this._parent.onExtensionLoadedObservable.notifyObservers(a),a})())}),this._extensions.push(...await Promise.all(e)),this._extensions.sort((i,r)=>(i.order||Number.MAX_VALUE)-(r.order||Number.MAX_VALUE)),this._parent.onExtensionLoadedObservable.clear(),this._gltf.extensionsRequired){for(let i of this._gltf.extensionsRequired)if(!this._extensions.some(s=>s.name===i&&s.enabled))throw((t=this.parent.extensionOptions[i])==null?void 0:t.enabled)===!1?new Error(`Required extension ${i} is disabled`):new Error(`Required extension ${i} is not available`)}}_createRootNode(){if(this._parent.customRootNode!==void 0)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:this._rootBabylonMesh===null?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;let e=new $("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);let t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case mg.AUTO:{this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],n._LoadTransform(t,this._rootBabylonMesh));break}case mg.FORCE_RIGHT_HANDED:{this._babylonScene.useRightHandedSystem=!0;break}default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){let i=this._extensionsLoadSceneAsync(e,t);if(i)return i;let r=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(let s of t.nodes){let a=ri.Get(`${e}/nodes/${s}`,this._gltf.nodes,s);r.push(this.loadNodeAsync(`/nodes/${a.index}`,a,o=>{o.parent=this._rootBabylonMesh}))}for(let s of this._postSceneLoadActions)s();return r.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(r).then(()=>{})}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(let i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){let e=[],t=this._gltf.nodes;if(t)for(let i of t)this._forEachPrimitive(i,r=>{let s=r.geometry;s&&e.indexOf(s)===-1&&e.push(s)});return e}_getMeshes(){let e=[];this._rootBabylonMesh instanceof Ir&&e.push(this._rootBabylonMesh);let t=this._gltf.nodes;if(t)for(let i of t)this._forEachPrimitive(i,r=>{e.push(r)});return e}_getTransformNodes(){let e=[],t=this._gltf.nodes;if(t)for(let i of t)i._babylonTransformNode&&i._babylonTransformNode.getClassName()==="TransformNode"&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){let e=[],t=this._gltf.skins;if(t)for(let i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){let e=[],t=this._gltf.animations;if(t)for(let i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case hh.NONE:break;case hh.FIRST:{let e=this._getAnimationGroups();e.length!==0&&e[0].start(!0);break}case hh.ALL:{let e=this._getAnimationGroups();for(let t of e)t.start(!0);break}default:{te.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);return}}}loadNodeAsync(e,t,i=()=>{}){let r=this._extensionsLoadNodeAsync(e,t,i);if(r)return r;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);let s=new Array;this.logOpen(`${e} ${t.name||""}`);let a=c=>{if(n.AddPointerMetadata(c,e),n._LoadTransform(t,c),t.camera!=null){let f=ri.Get(`${e}/camera`,this._gltf.cameras,t.camera);s.push(this.loadCameraAsync(`/cameras/${f.index}`,f,d=>{d.parent=c,this._babylonScene.useRightHandedSystem||(c.scaling.x=-1)}))}if(t.children)for(let f of t.children){let d=ri.Get(`${e}/children/${f}`,this._gltf.nodes,f);s.push(this.loadNodeAsync(`/nodes/${d.index}`,d,u=>{u.parent=c}))}i(c)},o=t.mesh!=null,l=this._parent.loadSkins&&t.skin!=null;if(!o||l){let c=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;let f=new ii(c,this._babylonScene);f._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t.mesh==null?t._babylonTransformNode=f:t._babylonTransformNodeForSkin=f,a(f)}if(o)if(l){let c=ri.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${c.index}`,t,c,f=>{let d=t._babylonTransformNodeForSkin;f.metadata=vw(d.metadata,f.metadata||{});let u=ri.Get(`${e}/skin`,this._gltf.skins,t.skin);s.push(this._loadSkinAsync(`/skins/${u.index}`,t,u,h=>{this._forEachPrimitive(t,m=>{m.skeleton=h}),this._postSceneLoadActions.push(()=>{if(u.skeleton!=null){let m=ri.Get(`/skins/${u.index}/skeleton`,this._gltf.nodes,u.skeleton).parent;t.index===m.index?f.parent=d.parent:f.parent=m._babylonTransformNode}else f.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:d,skinnedNode:f})})}))}))}else{let c=ri.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${c.index}`,t,c,a))}return this.logClose(),Promise.all(s).then(()=>(this._forEachPrimitive(t,c=>{let f=c;!f.isAnInstance&&f.geometry&&f.geometry.useBoundingInfoFromGeometry?c._updateBoundingInfo():c.refreshBoundingInfo(!0,!0)}),t._babylonTransformNode))}_loadMeshAsync(e,t,i,r){let s=i.primitives;if(!s||!s.length)throw new Error(`${e}: Primitives are missing`);s[0].index==null&&ri.Assign(s);let a=new Array;this.logOpen(`${e} ${i.name||""}`);let o=t.name||`node${t.index}`;if(s.length===1){let l=i.primitives[0];a.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,o,t,i,l,c=>{t._babylonTransformNode=c,t._primitiveBabylonMeshes=[c]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new ii(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(let l of s)a.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,`${o}_primitive${l.index}`,t,i,l,c=>{c.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(c)}))}return r(t._babylonTransformNode),this.logClose(),Promise.all(a).then(()=>t._babylonTransformNode)}_loadMeshPrimitiveAsync(e,t,i,r,s,a){let o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,r,s,a);if(o)return o;this.logOpen(`${e}`);let l=this._disableInstancedMesh===0&&this._parent.createInstances&&i.skin==null&&!r.primitives[0].targets,c,f;if(l&&s._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,c=s._instanceData.babylonSourceMesh.createInstance(t),c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,f=s._instanceData.promise;else{let d=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;let u=new $(t,this._babylonScene);if(u._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,u.sideOrientation=this._babylonScene.useRightHandedSystem?Ae.CounterClockWiseSideOrientation:Ae.ClockWiseSideOrientation,this._createMorphTargets(e,i,r,s,u),d.push(this._loadVertexDataAsync(e,s,u).then(async h=>await this._loadMorphTargetsAsync(e,s,u,h).then(()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,h.applyToMesh(u),h._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)}))),!this.parent.skipMaterials){let h=n._GetDrawMode(e,s.mode);if(s.material==null){let m=this._defaultBabylonMaterialData[h];m||(m=this._createDefaultMaterial("__GLTFLoader._default",h),this._parent.onMaterialLoadedObservable.notifyObservers(m),this._defaultBabylonMaterialData[h]=m),u.material=m}else{let m=ri.Get(`${e}/material`,this._gltf.materials,s.material);d.push(this._loadMaterialAsync(`/materials/${m.index}`,m,u,h,g=>{u.material=g}))}}f=Promise.all(d),l&&(s._instanceData={babylonSourceMesh:u,promise:f}),c=u}return n.AddPointerMetadata(c,e),this._parent.onMeshLoadedObservable.notifyObservers(c),a(c),this.logClose(),f.then(()=>c)}_loadVertexDataAsync(e,t,i){let r=this._extensionsLoadVertexDataAsync(e,t,i);if(r)return r;let s=t.attributes;if(!s)throw new Error(`${e}: Attributes are missing`);let a=new Array,o=new Cn(i.name,this._babylonScene);if(t.indices==null)i.isUnIndexed=!0;else{let c=ri.Get(`${e}/indices`,this._gltf.accessors,t.indices);a.push(this._loadIndicesAccessorAsync(`/accessors/${c.index}`,c).then(f=>{o.setIndices(f)}))}let l=(c,f,d)=>{if(s[c]==null)return;i._delayInfo=i._delayInfo||[],i._delayInfo.indexOf(f)===-1&&i._delayInfo.push(f);let u=ri.Get(`${e}/attributes/${c}`,this._gltf.accessors,s[c]);a.push(this._loadVertexAccessorAsync(`/accessors/${u.index}`,u,f).then(h=>{if(h.getKind()===D.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton){let m=fSe(u);m&&(o._boundingInfo=m,o.useBoundingInfoFromGeometry=!0)}o.setVerticesBuffer(h,u.count)})),f==D.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),d&&d(u)};return l("POSITION",D.PositionKind),l("NORMAL",D.NormalKind),l("TANGENT",D.TangentKind),l("TEXCOORD_0",D.UVKind),l("TEXCOORD_1",D.UV2Kind),l("TEXCOORD_2",D.UV3Kind),l("TEXCOORD_3",D.UV4Kind),l("TEXCOORD_4",D.UV5Kind),l("TEXCOORD_5",D.UV6Kind),l("JOINTS_0",D.MatricesIndicesKind),l("WEIGHTS_0",D.MatricesWeightsKind),l("JOINTS_1",D.MatricesIndicesExtraKind),l("WEIGHTS_1",D.MatricesWeightsExtraKind),l("COLOR_0",D.ColorKind,c=>{c.type==="VEC4"&&(i.hasVertexAlpha=!0)}),Promise.all(a).then(()=>o)}_createMorphTargets(e,t,i,r,s){if(!r.targets||!this._parent.loadMorphTargets)return;if(t._numMorphTargets==null)t._numMorphTargets=r.targets.length;else if(r.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);let a=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,s.morphTargetManager=new _h(this._babylonScene),s.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.morphTargetManager.areUpdatesFrozen=!0;for(let o=0;o<r.targets.length;o++){let l=t.weights?t.weights[o]:i.weights?i.weights[o]:0,c=a?a[o]:`morphTarget${o}`;s.morphTargetManager.addTarget(new Ud(c,l,s.getScene()))}}_loadMorphTargetsAsync(e,t,i,r){if(!t.targets||!this._parent.loadMorphTargets)return Promise.resolve();let s=new Array,a=i.morphTargetManager;for(let o=0;o<a.numTargets;o++){let l=a.getTarget(o);s.push(this._loadMorphTargetVertexDataAsync(`${e}/targets/${o}`,r,t.targets[o],l))}return Promise.all(s).then(()=>{a.areUpdatesFrozen=!1})}async _loadMorphTargetVertexDataAsync(e,t,i,r){let s=new Array,a=(o,l,c)=>{if(i[o]==null)return;let f=t.getVertexBuffer(l);if(!f)return;let d=ri.Get(`${e}/${o}`,this._gltf.accessors,i[o]);s.push(this._loadFloatAccessorAsync(`/accessors/${d.index}`,d).then(u=>{c(f,u)}))};return a("POSITION",D.PositionKind,(o,l)=>{let c=new Float32Array(l.length);o.forEach(l.length,(f,d)=>{c[d]=l[d]+f}),r.setPositions(c)}),a("NORMAL",D.NormalKind,(o,l)=>{let c=new Float32Array(l.length);o.forEach(c.length,(f,d)=>{c[d]=l[d]+f}),r.setNormals(c)}),a("TANGENT",D.TangentKind,(o,l)=>{let c=new Float32Array(l.length/3*4),f=0;o.forEach(l.length/3*4,(d,u)=>{(u+1)%4!==0&&(c[f]=l[f]+d,f++)}),r.setTangents(c)}),a("TEXCOORD_0",D.UVKind,(o,l)=>{let c=new Float32Array(l.length);o.forEach(l.length,(f,d)=>{c[d]=l[d]+f}),r.setUVs(c)}),a("TEXCOORD_1",D.UV2Kind,(o,l)=>{let c=new Float32Array(l.length);o.forEach(l.length,(f,d)=>{c[d]=l[d]+f}),r.setUV2s(c)}),a("COLOR_0",D.ColorKind,(o,l)=>{let c=null,f=o.getSize();if(f===3){c=new Float32Array(l.length/3*4),o.forEach(l.length,(d,u)=>{let h=Math.floor(u/3),m=u%3;c[4*h+m]=l[3*h+m]+d});for(let d=0;d<l.length/3;++d)c[4*d+3]=1}else if(f===4)c=new Float32Array(l.length),o.forEach(l.length,(d,u)=>{c[u]=l[u]+d});else throw new Error(`${e}: Invalid number of components (${f}) for COLOR_0 attribute`);r.setColors(c)}),await Promise.all(s).then(()=>{})}static _LoadTransform(e,t){if(e.skin!=null)return;let i=b.Zero(),r=je.Identity(),s=b.One();e.matrix?Q.FromArray(e.matrix).decompose(s,r,i):(e.translation&&(i=b.FromArray(e.translation)),e.rotation&&(r=je.FromArray(e.rotation)),e.scale&&(s=b.FromArray(e.scale))),t.position=i,t.rotationQuaternion=r,t.scaling=s}_loadSkinAsync(e,t,i,r){if(!this._parent.loadSkins)return Promise.resolve();let s=this._extensionsLoadSkinAsync(e,t,i);if(s)return s;if(i._data)return r(i._data.babylonSkeleton),i._data.promise;let a=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;let o=new XM(i.name||a,a,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);let l=this._loadSkinInverseBindMatricesDataAsync(e,i).then(c=>{this._updateBoneMatrices(o,c)});return i._data={babylonSkeleton:o,promise:l},r(o),l}_loadBones(e,t,i){if(t.skeleton==null||this._parent.alwaysComputeSkeletonRootNode){let s=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(s)if(t.skeleton===void 0)t.skeleton=s.index;else{let a=(l,c)=>{for(;c.parent;c=c.parent)if(c.parent===l)return!0;return!1},o=ri.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);o!==s&&!a(o,s)&&(te.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=s.index)}else te.Warn(`${e}: Failed to find common root`)}let r={};for(let s of t.joints){let a=ri.Get(`${e}/joints/${s}`,this._gltf.nodes,s);this._loadBone(a,t,i,r)}}_findSkeletonRootNode(e,t){if(t.length===0)return null;let i={};for(let s of t){let a=[],o=ri.Get(`${e}/${s}`,this._gltf.nodes,s);for(;o.index!==-1;)a.unshift(o),o=o.parent;i[s]=a}let r=null;for(let s=0;;++s){let a=i[t[0]];if(s>=a.length)return r;let o=a[s];for(let l=1;l<t.length;++l)if(a=i[t[l]],s>=a.length||o!==a[s])return r;r=o}}_loadBone(e,t,i,r){e._isJoint=!0;let s=r[e.index];if(s)return s;let a=null;e.index!==t.skeleton&&(e.parent&&e.parent.index!==-1?a=this._loadBone(e.parent,t,i,r):t.skeleton!==void 0&&te.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));let o=t.joints.indexOf(e.index);return s=new po(e.name||`joint${e.index}`,i,a,this._getNodeMatrix(e),null,null,o),r[e.index]=s,this._postSceneLoadActions.push(()=>{s.linkTransformNode(e._babylonTransformNode)}),s}_loadSkinInverseBindMatricesDataAsync(e,t){if(t.inverseBindMatrices==null)return Promise.resolve(null);let i=ri.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(let i of e.bones){let r=Q.Identity(),s=i._index;t&&s!==-1&&(Q.FromArrayToRef(t,s*16,r),r.invertToRef(r));let a=i.getParent();a&&r.multiplyToRef(a.getAbsoluteInverseBindMatrix(),r),i.updateMatrix(r,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?Q.FromArray(e.matrix):Q.Compose(e.scale?b.FromArray(e.scale):b.One(),e.rotation?je.FromArray(e.rotation):je.Identity(),e.translation?b.FromArray(e.translation):b.Zero())}loadCameraAsync(e,t,i=()=>{}){let r=this._extensionsLoadCameraAsync(e,t,i);if(r)return r;let s=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;let a=new ff(t.name||`camera${t.index}`,b.Zero(),this._babylonScene,!1);switch(a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonCamera=a,a.setTarget(new b(0,0,-1)),t.type){case"perspective":{let o=t.perspective;if(!o)throw new Error(`${e}: Camera perspective properties are missing`);a.fov=o.yfov,a.minZ=o.znear,a.maxZ=o.zfar||0;break}case"orthographic":{if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);a.mode=Et.ORTHOGRAPHIC_CAMERA,a.orthoLeft=-t.orthographic.xmag,a.orthoRight=t.orthographic.xmag,a.orthoBottom=-t.orthographic.ymag,a.orthoTop=t.orthographic.ymag,a.minZ=t.orthographic.znear,a.maxZ=t.orthographic.zfar;break}default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return n.AddPointerMetadata(a,e),this._parent.onCameraLoadedObservable.notifyObservers(a),i(a),this.logClose(),Promise.all(s).then(()=>a)}_loadAnimationsAsync(){this._parent._startPerformanceCounter("Load animations");let e=this._gltf.animations;if(!e)return Promise.resolve();let t=new Array;for(let i=0;i<e.length;i++){let r=e[i];t.push(this.loadAnimationAsync(`/animations/${r.index}`,r).then(s=>{s.targetedAnimations.length===0&&s.dispose()}))}return Promise.all(t).then(()=>{this._parent._endPerformanceCounter("Load animations")})}loadAnimationAsync(e,t){this._parent._startPerformanceCounter("Load animation");let i=this._extensionsLoadAnimationAsync(e,t);return i||lSe.value.then(({AnimationGroup:r})=>{this._babylonScene._blockEntityCollection=!!this._assetContainer;let s=new r(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;let a=new Array;ri.Assign(t.channels),ri.Assign(t.samplers);for(let o of t.channels)a.push(this._loadAnimationChannelAsync(`${e}/channels/${o.index}`,e,t,o,(l,c)=>{l.animations=l.animations||[],l.animations.push(c),s.addTargetedAnimation(c,l)}));return this._parent._endPerformanceCounter("Load animation"),Promise.all(a).then(()=>(s.normalize(0),s))})}_loadAnimationChannelAsync(e,t,i,r,s){let a=this._extensionsLoadAnimationChannelAsync(e,t,i,r,s);if(a)return a;if(r.target.node==null)return Promise.resolve();let o=ri.Get(`${e}/target/node`,this._gltf.nodes,r.target.node),l=r.target.path,c=l==="weights";return c&&!o._numMorphTargets||!c&&!o._babylonTransformNode||!this._parent.loadNodeAnimations&&!c&&!o._isJoint?Promise.resolve():cSe.value.then(()=>{var u,h,m,g;let f;switch(l){case"translation":{f=(u=ME("/nodes/{}/translation"))==null?void 0:u.interpolation;break}case"rotation":{f=(h=ME("/nodes/{}/rotation"))==null?void 0:h.interpolation;break}case"scale":{f=(m=ME("/nodes/{}/scale"))==null?void 0:m.interpolation;break}case"weights":{f=(g=ME("/nodes/{}/weights"))==null?void 0:g.interpolation;break}default:throw new Error(`${e}/target/path: Invalid value (${r.target.path})`)}if(!f)throw new Error(`${e}/target/path: Could not find interpolation properties for target path (${r.target.path})`);let d={object:o,info:f};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,r,d,s)})}_loadAnimationChannelFromTargetInfoAsync(e,t,i,r,s,a){let o=this.parent.targetFps,l=1/o,c=ri.Get(`${e}/sampler`,i.samplers,r.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${r.sampler}`,c).then(f=>{let d=0,u=s.object,h=s.info;for(let m of h){let g=m.getStride(u),p=f.input,_=f.output,v=new Array(p.length),E=0;switch(f.interpolation){case"STEP":{for(let S=0;S<p.length;S++){let T=m.getValue(u,_,E,1);E+=g,v[S]={frame:p[S]*o,value:T,interpolation:1}}break}case"CUBICSPLINE":{for(let S=0;S<p.length;S++){let T=m.getValue(u,_,E,l);E+=g;let A=m.getValue(u,_,E,1);E+=g;let R=m.getValue(u,_,E,l);E+=g,v[S]={frame:p[S]*o,inTangent:T,value:A,outTangent:R}}break}case"LINEAR":{for(let S=0;S<p.length;S++){let T=m.getValue(u,_,E,1);E+=g,v[S]={frame:p[S]*o,value:T}}break}}if(E>0){let S=`${i.name||`animation${i.index}`}_channel${r.index}_${d}`,T=m.buildAnimations(u,S,o,v);for(let A of T)d++,a(A.babylonAnimatable,A.babylonAnimation)}}})}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;let i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}let r=ri.Get(`${e}/input`,this._gltf.accessors,t.input),s=ri.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${r.index}`,r),this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)]).then(([a,o])=>({input:a,interpolation:i,output:o})),t._data}loadBufferAsync(e,t,i,r){let s=this._extensionsLoadBufferAsync(e,t,i,r);if(s)return s;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then(a=>{try{return new Uint8Array(a.buffer,a.byteOffset+i,r)}catch(o){throw new Error(`${e}: ${o.message}`,{cause:o})}})}loadBufferViewAsync(e,t){let i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;let r=ri.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${r.index}`,r,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;let r=n._GetNumComponents(e,t.type),s=r*D.GetTypeByteLength(t.componentType),a=r*t.count;if(t.bufferView==null)t._data=Promise.resolve(new i(a));else{let o=ri.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then(l=>{if(t.componentType===5126&&!t.normalized&&(!o.byteStride||o.byteStride===s))return n._GetTypedArray(e,t.componentType,l,t.byteOffset,a);{let c=new i(a);return D.ForEach(l,t.byteOffset||0,o.byteStride||s,r,t.componentType,c.length,t.normalized||!1,(f,d)=>{c[d]=f}),c}})}if(t.sparse){let o=t.sparse;t._data=t._data.then(l=>{let c=l,f=ri.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,o.indices.bufferView),d=ri.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,o.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${f.index}`,f),this.loadBufferViewAsync(`/bufferViews/${d.index}`,d)]).then(([u,h])=>{let m=n._GetTypedArray(`${e}/sparse/indices`,o.indices.componentType,u,o.indices.byteOffset,o.count),g=r*o.count,p;if(t.componentType===5126&&!t.normalized)p=n._GetTypedArray(`${e}/sparse/values`,t.componentType,h,o.values.byteOffset,g);else{let v=n._GetTypedArray(`${e}/sparse/values`,t.componentType,h,o.values.byteOffset,g);p=new i(g),D.ForEach(v,0,s,r,t.componentType,p.length,t.normalized||!1,(E,S)=>{p[S]=E})}let _=0;for(let v=0;v<m.length;v++){let E=m[v]*r;for(let S=0;S<r;S++)c[E++]=p[_++]}return c})})}return t._data}_loadFloatAccessorAsync(e,t){return this._loadAccessorAsync(e,t,Float32Array)}_loadIndicesAccessorAsync(e,t){if(t.type!=="SCALAR")throw new Error(`${e}/type: Invalid value ${t.type}`);if(t.componentType!==5121&&t.componentType!==5123&&t.componentType!==5125)throw new Error(`${e}/componentType: Invalid value ${t.componentType}`);if(t._data)return t._data;if(t.sparse){let i=n._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,i)}else{let i=ri.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i).then(r=>n._GetTypedArray(e,t.componentType,r,t.byteOffset,t.count))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;let t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then(i=>new ko(t,i,!1)),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){var s;if((s=t._babylonVertexBuffer)!=null&&s[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});let r=this._babylonScene.getEngine();if(t.sparse||t.bufferView==null)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then(a=>new D(r,a,i,!1));else{let a=ri.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(a).then(o=>{let l=n._GetNumComponents(e,t.type);return new D(r,o,i,!1,void 0,a.byteStride,void 0,t.byteOffset,l,t.componentType,t.normalized,!0,void 0,!0)})}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){let r=new Array,s=this._getOrCreateMaterialAdapter(i);return t&&(t.baseColorFactor?(s.baseColor=he.FromArray(t.baseColorFactor),s.geometryOpacity=t.baseColorFactor[3]):s.baseColor=he.White(),s.baseMetalness=t.metallicFactor==null?1:t.metallicFactor,s.specularRoughness=t.roughnessFactor==null?1:t.roughnessFactor,t.baseColorTexture&&r.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,a=>{a.name=`${i.name} (Base Color)`,s.baseColorTexture=a})),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,a=>{a.name=`${i.name} (Metallic Roughness)`,s.baseMetalnessTexture=a,s.specularRoughnessTexture=a})),s.useRoughnessFromMetallicTextureGreen=!0,s.useMetallicFromMetallicTextureBlue=!0)),Promise.all(r).then(()=>{})}_loadMaterialAsync(e,t,i,r,s=()=>{}){let a=this._extensionsLoadMaterialAsync(e,t,i,r,s);if(a)return a;t._data=t._data||{};let o=t._data[r];if(!o){this.logOpen(`${e} ${t.name||""}`);let l=this.createMaterial(e,t,r);o={babylonMaterial:l,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,l)},t._data[r]=o,n.AddPointerMetadata(l,e),this._parent.onMaterialLoadedObservable.notifyObservers(l),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce(()=>{let l=o.babylonMeshes.indexOf(i);l!==-1&&o.babylonMeshes.splice(l,1)})),s(o.babylonMaterial),o.promise.then(()=>o.babylonMaterial)}_createDefaultMaterial(e,t){if(!this._pbrMaterialImpl)throw new Error("PBR Material class not loaded");this._babylonScene._blockEntityCollection=!!this._assetContainer;let i=new this._pbrMaterialImpl.materialClass(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.transparencyMode=this._pbrMaterialImpl.materialClass.MATERIAL_OPAQUE;let r=this._getOrCreateMaterialAdapter(i);return r.transparencyAsAlphaCoverage=this._parent.transparencyAsCoverage,r.baseMetalness=1,r.specularRoughness=1,i}createMaterial(e,t,i){let r=this._extensionsCreateMaterial(e,t,i);if(r)return r;let s=t.name||`material${t.index}`;return this._createDefaultMaterial(s,i)}loadMaterialPropertiesAsync(e,t,i){let r=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(r)return r;let s=new Array;return s.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&s.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then(()=>{})}loadMaterialBasePropertiesAsync(e,t,i){let r=new Array,s=this._getOrCreateMaterialAdapter(i);s.emissionColor=t.emissiveFactor?he.FromArray(t.emissiveFactor):new he(0,0,0),t.doubleSided&&(s.backFaceCulling=!1,s.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,c=>{var f;c.name=`${i.name} (Normal)`,s.geometryNormalTexture=c,((f=t.normalTexture)==null?void 0:f.scale)!=null&&(c.level=t.normalTexture.scale)})),s.setNormalMapInversions(!this._babylonScene.useRightHandedSystem,this._babylonScene.useRightHandedSystem));let a,o=1,l;return t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,c=>{c.name=`${i.name} (Occlusion)`,a=c})),t.occlusionTexture.strength!=null&&(o=t.occlusionTexture.strength)),t.emissiveTexture&&r.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,c=>{c.name=`${i.name} (Emissive)`,l=c})),Promise.all(r).then(()=>{a&&(s.ambientOcclusionTexture=a,s.ambientOcclusionTextureStrength=o),l&&(s.emissionColorTexture=l)})}loadMaterialAlphaProperties(e,t,i){if(!this._pbrMaterialImpl)throw new Error(`${e}: Material type not supported`);let r=this._getOrCreateMaterialAdapter(i),s=r.baseColorTexture;switch(t.alphaMode||"OPAQUE"){case"OPAQUE":{i.transparencyMode=this._pbrMaterialImpl.materialClass.MATERIAL_OPAQUE,i.alpha=1;break}case"MASK":{i.transparencyMode=this._pbrMaterialImpl.materialClass.MATERIAL_ALPHATEST,r.alphaCutOff=t.alphaCutoff==null?.5:t.alphaCutoff,s&&(s.hasAlpha=!0);break}case"BLEND":{i.transparencyMode=this._pbrMaterialImpl.materialClass.MATERIAL_ALPHABLEND,s&&(s.hasAlpha=!0,r.useAlphaFromBaseColorTexture=!0);break}default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=()=>{}){let r=this._extensionsLoadTextureInfoAsync(e,t,i);if(r)return r;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);let s=ri.Get(`${e}/index`,this._gltf.textures,t.index);s._textureInfo=t;let a=this._loadTextureAsync(`/textures/${t.index}`,s,o=>{o.coordinatesIndex=t.texCoord||0,n.AddPointerMetadata(o,e),this._parent.onTextureLoadedObservable.notifyObservers(o),i(o)});return this.logClose(),a}_loadTextureAsync(e,t,i=()=>{}){let r=this._extensionsLoadTextureAsync(e,t,i);if(r)return r;this.logOpen(`${e} ${t.name||""}`);let s=t.sampler==null?n.DefaultSampler:ri.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),a=ri.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,s,a,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,r=()=>{},s,a){var m,g;let o=this._loadSampler(`/samplers/${t.index}`,t),l=new Array,c=new zM;this._babylonScene._blockEntityCollection=!!this._assetContainer;let f={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||c.resolve()},onError:(p,_)=>{this._disposed||c.reject(new Error(`${e}: ${_&&_.message?_.message:p||"Failed to load texture"}`))},mimeType:(g=i.mimeType)!=null?g:Ek((m=i.uri)!=null?m:""),loaderOptions:s,useSRGBBuffer:!!a&&this._parent.useSRGBBuffers},d=new _e(null,this._babylonScene,f);d._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,l.push(c.promise);let u=i.uri&&!Jf(i.uri)?i.uri:void 0,h=u!=null?u:`${this._fileName}#image${i.index}`;if(l.push(this.loadImageAsync(`/images/${i.index}`,i).then(p=>{let _=`data:${this._uniqueRootUrl}${h}`;d.updateURL(_,p);let v=d.getInternalTexture();v&&(v.label=i.name)})),d.wrapU=o.wrapU,d.wrapV=o.wrapV,r(d),this._parent.useGltfTextureNames){let p=i.name||u||`image${i.index}`;d.name=p}return Promise.all(l).then(()=>d)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:t.minFilter===9728||t.minFilter===9729,samplingMode:n._GetTextureSamplingMode(e,t),wrapU:n._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:n._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{let i=ri.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){let r=this._extensionsLoadUriAsync(e,t,i);if(r)return r;if(!n._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(Jf(i)){let s=new Uint8Array(ed(i));return this.log(`${e}: Decoded ${i.substring(0,64)}... (${s.length} bytes)`),Promise.resolve(s)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then(s=>new Promise((a,o)=>{this._parent._loadFile(this._babylonScene,s,l=>{this._disposed||(this.log(`${e}: Loaded ${i} (${l.byteLength} bytes)`),a(new Uint8Array(l)))},!0,l=>{o(new vp(`${e}: Failed to load '${i}'${l?": "+l.status+" "+l.statusText:""}`,l))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};let i=e._internalMetadata=e._internalMetadata||{},r=i.gltf=i.gltf||{};(r.pointers=r.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=t==null?10497:t,t){case 33071:return _e.CLAMP_ADDRESSMODE;case 33648:return _e.MIRROR_ADDRESSMODE;case 10497:return _e.WRAP_ADDRESSMODE;default:return te.Warn(`${e}: Invalid value (${t})`),_e.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){let i=t.magFilter==null?9729:t.magFilter,r=t.minFilter==null?9987:t.minFilter;if(i===9729)switch(r){case 9728:return _e.LINEAR_NEAREST;case 9729:return _e.LINEAR_LINEAR;case 9984:return _e.LINEAR_NEAREST_MIPNEAREST;case 9985:return _e.LINEAR_LINEAR_MIPNEAREST;case 9986:return _e.LINEAR_NEAREST_MIPLINEAR;case 9987:return _e.LINEAR_LINEAR_MIPLINEAR;default:return te.Warn(`${e}/minFilter: Invalid value (${r})`),_e.LINEAR_LINEAR_MIPLINEAR}else switch(i!==9728&&te.Warn(`${e}/magFilter: Invalid value (${i})`),r){case 9728:return _e.NEAREST_NEAREST;case 9729:return _e.NEAREST_LINEAR;case 9984:return _e.NEAREST_NEAREST_MIPNEAREST;case 9985:return _e.NEAREST_LINEAR_MIPNEAREST;case 9986:return _e.NEAREST_NEAREST_MIPLINEAR;case 9987:return _e.NEAREST_LINEAR_MIPLINEAR;default:return te.Warn(`${e}/minFilter: Invalid value (${r})`),_e.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){try{return mL(t)}catch(i){throw new Error(`${e}: ${i.message}`,{cause:i})}}static _GetTypedArray(e,t,i,r,s){let a=i.buffer;r=i.byteOffset+(r||0);let o=n._GetTypedArrayConstructor(`${e}/componentType`,t),l=D.GetTypeByteLength(t);return r%l!==0?(te.Warn(`${e}: Copying buffer as byte offset (${r}) is not a multiple of component type byte length (${l})`),new o(a.slice(r,r+s*l),0)):new o(a,r,s)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return pe.IsBase64(e)||e.indexOf("..")===-1}static _GetDrawMode(e,t){switch(t==null&&(t=4),t){case 0:return Ae.PointListDrawMode;case 1:return Ae.LineListDrawMode;case 2:return Ae.LineLoopDrawMode;case 3:return Ae.LineStripDrawMode;case 4:return Ae.TriangleFillMode;case 5:return Ae.TriangleStripDrawMode;case 6:return Ae.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");let e=new Array;if(this._gltf.materials){for(let t of this._gltf.materials)if(t._data)for(let i in t._data){let r=t._data[i];for(let s of r.babylonMeshes){s.computeWorldMatrix(!0);let a=r.babylonMaterial;e.push(a.forceCompilationAsync(s)),e.push(a.forceCompilationAsync(s,{useInstances:!0})),this._parent.useClipPlane&&(e.push(a.forceCompilationAsync(s,{clipPlane:!0})),e.push(a.forceCompilationAsync(s,{clipPlane:!0,useInstances:!0})))}}}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile materials")})}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");let e=new Array,t=this._babylonScene.lights;for(let i of t){let r=i.getShadowGenerator();r&&e.push(r.forceCompilationAsync())}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile shadow generators")})}_forEachExtensions(e){for(let t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,i){for(let r of this._extensions)if(r.enabled){let s=`${r.name}.${t}`,a=e;a._activeLoaderExtensionFunctions=a._activeLoaderExtensionFunctions||{};let o=a._activeLoaderExtensionFunctions;if(!o[s]){o[s]=!0;try{let l=i(r);if(l)return l}finally{delete o[s]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}_extensionsOnReady(){this._forEachExtensions(e=>e.onReady&&e.onReady())}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",i=>i.loadSceneAsync&&i.loadSceneAsync(e,t))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",r=>r.loadNodeAsync&&r.loadNodeAsync(e,t,i))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",r=>r.loadCameraAsync&&r.loadCameraAsync(e,t,i))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",r=>r._loadVertexDataAsync&&r._loadVertexDataAsync(e,t,i))}_extensionsLoadMeshPrimitiveAsync(e,t,i,r,s,a){return this._applyExtensions(s,"loadMeshPrimitive",o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,r,s,a))}_extensionsLoadMaterialAsync(e,t,i,r,s){return this._applyExtensions(t,"loadMaterial",a=>a._loadMaterialAsync&&a._loadMaterialAsync(e,t,i,r,s))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",r=>r.createMaterial&&r.createMaterial(e,t,i))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",r=>r.loadMaterialPropertiesAsync&&r.loadMaterialPropertiesAsync(e,t,i))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",r=>r.loadTextureInfoAsync&&r.loadTextureInfoAsync(e,t,i))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",r=>r._loadTextureAsync&&r._loadTextureAsync(e,t,i))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,i,r,s){return this._applyExtensions(i,"loadAnimationChannel",a=>a._loadAnimationChannelAsync&&a._loadAnimationChannelAsync(e,t,i,r,s))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",r=>r._loadSkinAsync&&r._loadSkinAsync(e,t,i))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",r=>r._loadUriAsync&&r._loadUriAsync(e,t,i))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,i,r){return this._applyExtensions(t,"loadBuffer",s=>s.loadBufferAsync&&s.loadBufferAsync(e,t,i,r))}static LoadExtensionAsync(e,t,i,r){if(!t.extensions)return null;let a=t.extensions[i];return a?r(`${e}/extensions/${i}`,a):null}static LoadExtraAsync(e,t,i,r){if(!t.extras)return null;let a=t.extras[i];return a?r(`${e}/extras/${i}`,a):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&this._gltf.extensionsUsed.indexOf(e)!==-1}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}};ay.DefaultSampler={index:-1};Bd._CreateGLTF2Loader=n=>new ay(n)});var VF,UF,aQ=y(()=>{pw();VF="ExtrasAsMetadata",UF=class{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){let i=e.metadata=e.metadata||{},r=i.gltf=i.gltf||{};r.extras=t.extras}}constructor(e){this.name=VF,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,r=>{this._assignExtras(r,t),i(r)})}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,r=>{this._assignExtras(r,t),i(r)})}createMaterial(e,t,i){let r=this._loader.createMaterial(e,t,i);return this._assignExtras(r,t),r}loadAnimationAsync(e,t){return this._loader.loadAnimationAsync(e,t).then(i=>(this._assignExtras(i,t),i))}};bE(VF);KM(VF,!1,n=>new UF(n))});var oy,oQ=y(()=>{oy={name:"obj",extensions:".obj"}});var vh,lQ=y(()=>{$t();Kr();lf();vh=class n{constructor(){this.materials=[]}parseMTL(e,t,i,r){if(t instanceof ArrayBuffer)return;let s=t.split(`
`),a=/\s+/,o,l=null;for(let c=0;c<s.length;c++){let f=s[c].trim();if(f.length===0||f.charAt(0)==="#")continue;let d=f.indexOf(" "),u=d>=0?f.substring(0,d):f;u=u.toLowerCase();let h=d>=0?f.substring(d+1).trim():"";if(u==="newmtl")l&&this.materials.push(l),e._blockEntityCollection=!!r,l=new We(h,e),l._parentContainer=r,e._blockEntityCollection=!1;else if(u==="kd"&&l)o=h.split(a,3).map(parseFloat),l.diffuseColor=he.FromArray(o);else if(u==="ka"&&l)o=h.split(a,3).map(parseFloat),l.ambientColor=he.FromArray(o);else if(u==="ks"&&l)o=h.split(a,3).map(parseFloat),l.specularColor=he.FromArray(o);else if(u==="ke"&&l)o=h.split(a,3).map(parseFloat),l.emissiveColor=he.FromArray(o);else if(u==="ns"&&l)l.specularPower=parseFloat(h);else if(u==="d"&&l)l.alpha=parseFloat(h);else if(u==="map_ka"&&l)l.ambientTexture=n._GetTexture(i,h,e);else if(u==="map_kd"&&l)l.diffuseTexture=n._GetTexture(i,h,e);else if(u==="map_ks"&&l)l.specularTexture=n._GetTexture(i,h,e);else if(u!=="map_ns")if(u==="map_bump"&&l){let m=h.split(a),g=m.indexOf("-bm"),p=null;g>=0&&(p=m[g+1],m.splice(g,2)),l.bumpTexture=n._GetTexture(i,m.join(" "),e),l.bumpTexture&&p!==null&&(l.bumpTexture.level=parseFloat(p))}else u==="map_d"&&l&&(l.opacityTexture=n._GetTexture(i,h,e))}l&&this.materials.push(l)}static _GetTexture(e,t,i){if(!t)return null;let r=e;if(e==="file:"){let s=t.lastIndexOf("\\");s===-1&&(s=t.lastIndexOf("/")),s>-1?r+=t.substring(s+1):r+=t}else r+=t;return new _e(r,i,!1,n.INVERT_TEXTURE_Y)}};vh.INVERT_TEXTURE_Y=!0});var ln,cQ=y(()=>{qi();lf();$t();He();lb();ki();vr();wt();ln=class n{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._extColors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new ht(.5,.5,.5,1),this._hasLineData=!1,this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=i}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});let i=e[t[0]].normals.indexOf(t[1]);return i===-1?-1:e[t[0]].idx[i]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});let i=e[t[0]].normals.indexOf(t[1]);return i!=1&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e){var i,r;(i=e.indiceUvsFromObj)!=null||(e.indiceUvsFromObj=-1),(r=e.indiceNormalFromObj)!=null||(e.indiceNormalFromObj=-1);let t;this._loadingOptions.optimizeWithUV?t=this._isInArrayUV(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj,e.indiceUvsFromObj]):t=this._isInArray(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj]),t===-1?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(e.positionVectorFromOBJ),e.textureVectorFromOBJ!==void 0&&this._wrappedUvsForBabylon.push(e.textureVectorFromOBJ),e.normalsVectorFromOBJ!==void 0&&this._wrappedNormalsForBabylon.push(e.normalsVectorFromOBJ),e.positionColorsFromOBJ!==void 0&&this._wrappedColorsForBabylon.push(e.positionColorsFromOBJ),this._tuplePosNorm[e.indicePositionFromObj].normals.push(e.indiceNormalFromObj),this._tuplePosNorm[e.indicePositionFromObj].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e.indicePositionFromObj].uv.push(e.indiceUvsFromObj)):this._indicesForBabylon.push(t)}_unwrapData(){try{for(let e=0;e<this._wrappedPositionForBabylon.length;e++)this._unwrappedPositionsForBabylon.push(this._wrappedPositionForBabylon[e].x*this._handednessSign,this._wrappedPositionForBabylon[e].y,this._wrappedPositionForBabylon[e].z),this._wrappedNormalsForBabylon.length&&this._unwrappedNormalsForBabylon.push(this._wrappedNormalsForBabylon[e].x*this._handednessSign,this._wrappedNormalsForBabylon[e].y,this._wrappedNormalsForBabylon[e].z),this._wrappedUvsForBabylon.length&&this._unwrappedUVForBabylon.push(this._wrappedUvsForBabylon[e].x,this._wrappedUvsForBabylon[e].y),this._wrappedColorsForBabylon.length&&this._unwrappedColorsForBabylon.push(this._wrappedColorsForBabylon[e].r,this._wrappedColorsForBabylon[e].g,this._wrappedColorsForBabylon[e].b,this._wrappedColorsForBabylon[e].a);this._wrappedPositionForBabylon.length=0,this._wrappedNormalsForBabylon.length=0,this._wrappedUvsForBabylon.length=0,this._wrappedColorsForBabylon.length=0,this._tuplePosNorm.length=0,this._curPositionInIndices=0}catch(e){throw new Error("Unable to unwrap data while parsing OBJ data.",{cause:e})}}_getTriangles(e,t){for(let i=t;i<e.length-1;i++)this._pushTriangle(e,i)}_getColor(e){var t;if(this._loadingOptions.importVertexColors)return(t=this._extColors[e])!=null?t:this._colors[e]}_setDataForCurrentFaceWithPattern1(e,t){this._getTriangles(e,t);for(let i=0;i<this._triangles.length;i++){let r=parseInt(this._triangles[i])-1;this._setData({indicePositionFromObj:r,positionVectorFromOBJ:this._positions[r],positionColorsFromOBJ:this._getColor(r)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern2(e,t){this._getTriangles(e,t);for(let i=0;i<this._triangles.length;i++){let r=this._triangles[i].split("/"),s=parseInt(r[0])-1,a=parseInt(r[1])-1;this._setData({indicePositionFromObj:s,indiceUvsFromObj:a,positionVectorFromOBJ:this._positions[s],textureVectorFromOBJ:this._uvs[a],positionColorsFromOBJ:this._getColor(s)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern3(e,t){this._getTriangles(e,t);for(let i=0;i<this._triangles.length;i++){let r=this._triangles[i].split("/"),s=parseInt(r[0])-1,a=parseInt(r[1])-1,o=parseInt(r[2])-1;this._setData({indicePositionFromObj:s,indiceUvsFromObj:a,indiceNormalFromObj:o,positionVectorFromOBJ:this._positions[s],textureVectorFromOBJ:this._uvs[a],normalsVectorFromOBJ:this._normals[o]})}this._triangles.length=0}_setDataForCurrentFaceWithPattern4(e,t){this._getTriangles(e,t);for(let i=0;i<this._triangles.length;i++){let r=this._triangles[i].split("//"),s=parseInt(r[0])-1,a=parseInt(r[1])-1;this._setData({indicePositionFromObj:s,indiceNormalFromObj:a,positionVectorFromOBJ:this._positions[s],normalsVectorFromOBJ:this._normals[a],positionColorsFromOBJ:this._getColor(s)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern5(e,t){this._getTriangles(e,t);for(let i=0;i<this._triangles.length;i++){let r=this._triangles[i].split("/"),s=this._positions.length+parseInt(r[0]),a=this._uvs.length+parseInt(r[1]),o=this._normals.length+parseInt(r[2]);this._setData({indicePositionFromObj:s,indiceUvsFromObj:a,indiceNormalFromObj:o,positionVectorFromOBJ:this._positions[s],textureVectorFromOBJ:this._uvs[a],normalsVectorFromOBJ:this._normals[o],positionColorsFromOBJ:this._getColor(s)})}this._triangles.length=0}_addPreviousObjMesh(){this._meshesFromObj.length>0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._unwrappedNormalsForBabylon.length&&(this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice()),this._unwrappedUVForBabylon.length&&(this._handledMesh.uvs=this._unwrappedUVForBabylon.slice()),this._unwrappedColorsForBabylon.length&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._handledMesh.hasLines=this._hasLineData,this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0,this._hasLineData=!1)}_optimizeNormals(e){let t=e.getVerticesData(D.PositionKind),i=e.getVerticesData(D.NormalKind),r={};if(!t||!i)return;for(let a=0;a<t.length/3;a++){let o=t[a*3+0],l=t[a*3+1],c=t[a*3+2],f=o+"_"+l+"_"+c,d=r[f];d||(d=[],r[f]=d),d.push(a)}let s=new b;for(let a in r){let o=r[a];if(o.length<2)continue;let l=o[0];for(let c=1;c<o.length;++c){let f=o[c];i[l*3+0]+=i[f*3+0],i[l*3+1]+=i[f*3+1],i[l*3+2]+=i[f*3+2]}s.copyFromFloats(i[l*3+0],i[l*3+1],i[l*3+2]),s.normalize();for(let c=0;c<o.length;++c){let f=o[c];i[f*3+0]=s.x,i[f*3+1]=s.y,i[f*3+2]=s.z}}e.setVerticesData(D.NormalKind,i)}static _IsLineElement(e){return e.startsWith("l")}static _IsObjectElement(e){return e.startsWith("o")}static _IsGroupElement(e){return e.startsWith("g")}static _GetZbrushMRGB(e,t){if(!e.startsWith("mrgb"))return null;if(e=e.replace("mrgb","").trim(),t)return[];let i=/[a-z0-9]/g,r=e.match(i);if(!r||r.length%8!==0)return[];let s=[];for(let a=0;a<r.length/8;a++){let o=r[a*8+2]+r[a*8+3],l=r[a*8+4]+r[a*8+5],c=r[a*8+6]+r[a*8+7];s.push(new ht(parseInt(o,16)/255,parseInt(l,16)/255,parseInt(c,16)/255,1))}return s}parse(e,t,i,r,s){var f,d;t=t.replace(/#MRGB/g,"mrgb"),t=t.replace(/#.*$/gm,"").trim(),this._loadingOptions.useLegacyBehavior?(this._pushTriangle=(u,h)=>this._triangles.push(u[0],u[h],u[h+1]),this._handednessSign=1):i.useRightHandedSystem?(this._pushTriangle=(u,h)=>this._triangles.push(u[0],u[h+1],u[h]),this._handednessSign=1):(this._pushTriangle=(u,h)=>this._triangles.push(u[0],u[h],u[h+1]),this._handednessSign=-1);let a=t.split(`
`),o=[],l=[];o.push(l);for(let u=0;u<a.length;u++){let h=a[u].trim().replace(/\s\s/g," ");if(!(h.length===0||h.charAt(0)==="#"))if((n._IsGroupElement(h)||n._IsObjectElement(h))&&(l=[],o.push(l)),n._IsLineElement(h)){let m=h.split(" ");for(let g=1;g<m.length-1;g++)l.push(`l ${m[g]} ${m[g+1]}`)}else l.push(h)}let c=o.flat();for(let u=0;u<c.length;u++){let h=c[u].trim().replace(/\s\s/g," "),m;if(!(h.length===0||h.charAt(0)==="#"))if(n.VertexPattern.test(h)){if(m=h.match(/[^ ]+/g),this._positions.push(new b(parseFloat(m[1]),parseFloat(m[2]),parseFloat(m[3]))),this._loadingOptions.importVertexColors)if(m.length>=7){let g=parseFloat(m[4]),p=parseFloat(m[5]),_=parseFloat(m[6]);this._colors.push(new ht(g>1?g/255:g,p>1?p/255:p,_>1?_/255:_,m.length===7||m[7]===void 0?1:parseFloat(m[7])))}else this._colors.push(this._grayColor)}else if((m=n.NormalPattern.exec(h))!==null)this._normals.push(new b(parseFloat(m[1]),parseFloat(m[2]),parseFloat(m[3])));else if((m=n.UVPattern.exec(h))!==null)this._uvs.push(new Fe(parseFloat(m[1])*this._loadingOptions.UVScaling.x,parseFloat(m[2])*this._loadingOptions.UVScaling.y));else if((m=n.FacePattern3.exec(h))!==null)this._setDataForCurrentFaceWithPattern3(m[1].trim().split(" "),1);else if((m=n.FacePattern4.exec(h))!==null)this._setDataForCurrentFaceWithPattern4(m[1].trim().split(" "),1);else if((m=n.FacePattern5.exec(h))!==null)this._setDataForCurrentFaceWithPattern5(m[1].trim().split(" "),1);else if((m=n.FacePattern2.exec(h))!==null)this._setDataForCurrentFaceWithPattern2(m[1].trim().split(" "),1);else if((m=n.FacePattern1.exec(h))!==null)this._setDataForCurrentFaceWithPattern1(m[1].trim().split(" "),1);else if((m=n.LinePattern1.exec(h))!==null)this._setDataForCurrentFaceWithPattern1(m[1].trim().split(" "),0),this._hasLineData=!0;else if((m=n.LinePattern2.exec(h))!==null)this._setDataForCurrentFaceWithPattern2(m[1].trim().split(" "),0),this._hasLineData=!0;else if(m=n._GetZbrushMRGB(h,!this._loadingOptions.importVertexColors))for(let g of m)this._extColors.push(g);else if((m=n.LinePattern3.exec(h))!==null)this._setDataForCurrentFaceWithPattern3(m[1].trim().split(" "),0),this._hasLineData=!0;else if(n.GroupDescriptor.test(h)||n.ObjectDescriptor.test(h)){let g={name:h.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:n.ObjectDescriptor.test(h)};this._addPreviousObjMesh(),this._meshesFromObj.push(g),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(n.UseMtlDescriptor.test(h)){if(this._materialNameFromObj=h.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();let g={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:!1};this._increment++,this._meshesFromObj.push(g),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else n.MtlLibGroupDescriptor.test(h)?s(h.substring(7).trim()):n.SmoothDescriptor.test(h)||te.Log("Unhandled expression at line : "+h)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._unwrappedNormalsForBabylon.length&&(this._handledMesh.normals=this._unwrappedNormalsForBabylon),this._unwrappedUVForBabylon.length&&(this._handledMesh.uvs=this._unwrappedUVForBabylon),this._unwrappedColorsForBabylon.length&&(this._handledMesh.colors=this._unwrappedColorsForBabylon),this._handledMesh.hasLines=this._hasLineData),!this._hasMeshes){let u=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(let h of this._positions)this._unwrappedPositionsForBabylon.push(h.x,h.y,h.z);if(this._normals.length)for(let h of this._normals)this._unwrappedNormalsForBabylon.push(h.x,h.y,h.z);if(this._uvs.length)for(let h of this._uvs)this._unwrappedUVForBabylon.push(h.x,h.y);if(this._extColors.length)for(let h of this._extColors)this._unwrappedColorsForBabylon.push(h.r,h.g,h.b,h.a);else if(this._colors.length)for(let h of this._colors)this._unwrappedColorsForBabylon.push(h.r,h.g,h.b,h.a);this._materialNameFromObj||(u=new We(Cn.RandomId(),i),u.pointsCloud=!0,this._materialNameFromObj=u.name,this._normals.length||(u.disableLighting=!0,u.emissiveColor=he.White()))}this._meshesFromObj.push({name:Cn.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:u,isObject:!0,hasLines:this._hasLineData})}for(let u=0;u<this._meshesFromObj.length;u++){if(e&&this._meshesFromObj[u].name){if(e instanceof Array){if(e.indexOf(this._meshesFromObj[u].name)===-1)continue}else if(this._meshesFromObj[u].name!==e)continue}this._handledMesh=this._meshesFromObj[u],i._blockEntityCollection=!!r;let h=new $(this._meshesFromObj[u].name,i);if(h._parentContainer=r,i._blockEntityCollection=!1,this._handledMesh._babylonMesh=h,!this._handledMesh.isObject){for(let g=u-1;g>=0;--g)if(this._meshesFromObj[g].isObject&&this._meshesFromObj[g]._babylonMesh){h.parent=this._meshesFromObj[g]._babylonMesh;break}}if(this._materialToUse.push(this._meshesFromObj[u].materialName),this._handledMesh.hasLines&&((f=h._internalMetadata)!=null||(h._internalMetadata={}),h._internalMetadata._isLine=!0),((d=this._handledMesh.positions)==null?void 0:d.length)===0){this._babylonMeshesArray.push(h);continue}let m=new Ie;if(m.indices=this._handledMesh.indices,m.positions=this._handledMesh.positions,this._loadingOptions.computeNormals||!this._handledMesh.normals){let g=new Array;Ie.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,g),m.normals=g}else m.normals=this._handledMesh.normals;this._handledMesh.uvs&&(m.uvs=this._handledMesh.uvs),this._handledMesh.colors&&(m.colors=this._handledMesh.colors),m.applyToMesh(h),this._loadingOptions.invertY&&(h.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(h),this._babylonMeshesArray.push(h),this._handledMesh.directMaterial&&(h.material=this._handledMesh.directMaterial)}}};ln.ObjectDescriptor=/^o/;ln.GroupDescriptor=/^g/;ln.MtlLibGroupDescriptor=/^mtllib /;ln.UseMtlDescriptor=/^usemtl /;ln.SmoothDescriptor=/^s /;ln.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/;ln.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;ln.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;ln.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/;ln.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;ln.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;ln.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;ln.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;ln.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/;ln.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;ln.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/});var fQ={};Be(fQ,{OBJFileLoader:()=>Ua});var Ua,GF=y(()=>{He();Gi();ug();AE();oQ();lQ();cQ();lf();Ua=class n{static get INVERT_TEXTURE_Y(){return vh.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){vh.INVERT_TEXTURE_Y=e}constructor(e){this.name=oy.name,this.extensions=oy.extensions,this._assetContainer=null,this._loadingOptions={...n._DefaultLoadingOptions,...e!=null?e:{}}}static get _DefaultLoadingOptions(){return{computeNormals:n.COMPUTE_NORMALS,optimizeNormals:n.OPTIMIZE_NORMALS,importVertexColors:n.IMPORT_VERTEX_COLORS,invertY:n.INVERT_Y,invertTextureY:n.INVERT_TEXTURE_Y,UVScaling:n.UV_SCALING,materialLoadingFailsSilently:n.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:n.OPTIMIZE_WITH_UV,skipMaterials:n.SKIP_MATERIALS,useLegacyBehavior:n.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,i,r){let s=t+e;pe.LoadFile(s,i,void 0,void 0,!1,(a,o)=>{r(s,o)})}createPlugin(e){return new n(e[oy.name])}canDirectLoad(){return!1}importMeshAsync(e,t,i,r){return this._parseSolidAsync(e,t,i,r).then(s=>({meshes:s,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then(()=>{})}loadAssetContainerAsync(e,t,i){let r=new ql(e);return this._assetContainer=r,this.importMeshAsync(null,e,t,i).then(s=>(s.meshes.forEach(a=>r.meshes.push(a)),s.meshes.forEach(a=>{let o=a.material;o&&r.materials.indexOf(o)==-1&&(r.materials.push(o),o.getActiveTextures().forEach(c=>{r.textures.indexOf(c)==-1&&r.textures.push(c)}))}),this._assetContainer=null,r)).catch(s=>{throw this._assetContainer=null,s})}_parseSolidAsync(e,t,i,r){let s="",a=new vh,o=[],l=[];i=i.replace(/#.*$/gm,"").trim(),new ln(o,l,this._loadingOptions).parse(e,i,t,this._assetContainer,d=>{s=d});let f=[];return s!==""&&!this._loadingOptions.skipMaterials&&f.push(new Promise((d,u)=>{this._loadMTL(s,r,h=>{try{a.parseMTL(t,h,r,this._assetContainer);for(let m=0;m<a.materials.length;m++){let g=0,p=[],_;for(;(_=o.indexOf(a.materials[m].name,g))>-1;)p.push(_),g=_+1;if(_===-1&&p.length===0)a.materials[m].dispose();else for(let v=0;v<p.length;v++){let E=l[p[v]],S=a.materials[m];E.material=S,E.getTotalIndices()||(S.pointsCloud=!0)}}d()}catch(m){pe.Warn(`Error processing MTL file: '${s}'`),this._loadingOptions.materialLoadingFailsSilently?d():u(m)}},(h,m)=>{pe.Warn(`Error downloading MTL file: '${s}'`),this._loadingOptions.materialLoadingFailsSilently?d():u(m)})})),Promise.all(f).then(()=>{let d=u=>{var h,m;return!!((m=(h=u._internalMetadata)==null?void 0:h._isLine)!=null&&m)};return l.forEach(u=>{var h,m;if(d(u)){let g=(h=u.material)!=null?h:new We(u.name+"_line",t);g.getBindedMeshes().filter(_=>!d(_)).length>0&&(g=(m=g.clone(g.name+"_line"))!=null?m:g),g.wireframe=!0,u.material=g,u._internalMetadata&&(u._internalMetadata._isLine=void 0)}}),l})}};Ua.OPTIMIZE_WITH_UV=!0;Ua.INVERT_Y=!1;Ua.IMPORT_VERTEX_COLORS=!1;Ua.COMPUTE_NORMALS=!1;Ua.OPTIMIZE_NORMALS=!1;Ua.UV_SCALING=new Fe(1,1);Ua.SKIP_MATERIALS=!1;Ua.MATERIAL_LOADING_FAILS_SILENTLY=!0;Ua.USE_LEGACY_BEHAVIOR=!1;Fd(new Ua)});function dSe(n){let e=n.trim();return/^https?:\/\//i.test(e)||/^wss?:\/\//i.test(e)||/^\/\//.test(e)}function kF(n,e){if(dSe(n))throw new Error(`[AI3D] Babylon ${e} is limited to local vault resources. Refused remote URL: ${n}`);return n}function ly(n){throw new Error(`[AI3D] Babylon script loading is disabled in this plugin build. Refused script URL: ${n}`)}function uQ(){if(dQ)return;let n=i=>kF(i,"asset loading"),e=i=>kF(i,"script loading"),t=()=>-1;pe.PreprocessUrl=n,pe.ScriptPreprocessUrl=e,pe.DefaultRetryStrategy=t,pe.LoadScript=(i,r,s)=>{try{e(i),ly(i)}catch(a){s==null||s(a instanceof Error?a.message:String(a),a);return}r==null||r()},pe.LoadScriptAsync=async i=>{e(i),ly(i)},pe.LoadBabylonScript=(i,r,s)=>{try{ly(i)}catch(a){s==null||s(a instanceof Error?a.message:String(a),a);return}r()},pe.LoadBabylonScriptAsync=async i=>{ly(i)},Ji.PreprocessUrl=n,Ji.ScriptPreprocessUrl=e,Ji.DefaultRetryStrategy=t,Ur.CustomRequestModifiers.push((i,r)=>kF(r,"request")),dQ=!0}var dQ,hQ=y(()=>{"use strict";Cc();Gi();Wu();dQ=!1});function cy(n,e){if(e.byteLength<84)throw new Error(`STL buffer too small: ${e.byteLength} bytes (need 84+)`);if(e.byteLength>=6){let g=new TextDecoder().decode(new Uint8Array(e,0,6));if(g==="solid "||g===`solid
`){let p=new TextDecoder().decode(new Uint8Array(e,0,Math.min(e.byteLength,800)));if(p.includes("facet")||p.includes("endsolid"))throw new Error("ASCII STL detected \u2014 only binary STL is supported. Convert to binary STL first.")}}let t=new DataView(e),i=t.getUint32(80,!0);if(i===0)throw new Error("STL file contains 0 triangles");let r=84+i*50;if(e.byteLength<r)throw new Error(`STL buffer truncated: expected ${r} bytes, got ${e.byteLength}`);let s=!1;for(let g=0;g<i;g++){let p=84+g*50+48;if(t.getUint16(p,!0)&32768){s=!0;break}}let a=new Array(i*9).fill(0),o=new Array(i*9).fill(0),l=s?new Array(i*12).fill(0):null,c=new Array(i*3).fill(0),f=0,d=84;for(let g=0;g<i;g++){let p=g*9,_=g*3;d+=12,a[p+0]=t.getFloat32(d,!0),d+=4,a[p+1]=t.getFloat32(d,!0),d+=4,a[p+2]=t.getFloat32(d,!0),d+=4,a[p+3]=t.getFloat32(d,!0),d+=4,a[p+4]=t.getFloat32(d,!0),d+=4,a[p+5]=t.getFloat32(d,!0),d+=4,a[p+6]=t.getFloat32(d,!0),d+=4,a[p+7]=t.getFloat32(d,!0),d+=4,a[p+8]=t.getFloat32(d,!0),d+=4;let v=t.getUint16(d,!0);if(d+=2,l&&v&32768){let G=(v>>0&31)/31,O=(v>>5&31)/31,N=(v>>10&31)/31,B=g*12;l[B+0]=G,l[B+1]=O,l[B+2]=N,l[B+3]=1,l[B+4]=G,l[B+5]=O,l[B+6]=N,l[B+7]=1,l[B+8]=G,l[B+9]=O,l[B+10]=N,l[B+11]=1}let E=a[p+3]-a[p+0],S=a[p+4]-a[p+1],T=a[p+5]-a[p+2],A=a[p+6]-a[p+0],R=a[p+7]-a[p+1],M=a[p+8]-a[p+2],I=S*M-T*R,C=T*A-E*M,L=E*R-S*A,w=Math.sqrt(I*I+C*C+L*L);w>1e-8?(I/=w,C/=w,L/=w):(I=0,C=0,L=1,f++),o[p+0]=I,o[p+1]=C,o[p+2]=L,o[p+3]=I,o[p+4]=C,o[p+5]=L,o[p+6]=I,o[p+7]=C,o[p+8]=L,c[_+0]=p/3+0,c[_+1]=p/3+1,c[_+2]=p/3+2}f>0&&console.warn(`[AI3D STL] ${f} degenerate triangles with zero-area normals`);let u=new Ie;u.positions=a,u.normals=o,u.indices=c,l&&(u.colors=l);let h=new $("stl-model",n);u.applyToMesh(h);let m=new We("stl-mat",n);return m.backFaceCulling=!1,m.specularColor=new he(.3,.3,.3),m.specularPower=32,l?(m.diffuseColor=new he(1,1,1),m.emissiveColor=new he(.05,.05,.05),m.vertexColorEnabled=!0):(m.diffuseColor=new he(.85,.85,.85),m.emissiveColor=new he(.1,.1,.1)),h.material=m,h}function mQ(n,e){return cy(n,e)}function pQ(n){n(uSe)}var uSe,zF=y(()=>{"use strict";ki();AE();vr();lf();$t();uSe={name:"stl",extensions:".stl",importMeshAsync(n,e,t){return Promise.resolve().then(()=>({meshes:[cy(e,t)],particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))},loadAsync(n,e){return Promise.resolve().then(()=>{cy(n,e)})},loadAssetContainerAsync(n,e){return Promise.resolve().then(()=>{let t=cy(n,e),i=new ql(n);return i.meshes.push(t),t.material&&i.materials.push(t.material),i})},canDirectLoad(){return!1},rewriteRootURL(n){return n}}});function hSe(n){let e=n.split(`
`),t=[],i="binary_little_endian",r=null;for(let s of e){let a=s.trim();if(a==="end_header")break;if(a==="ply"||a===""||a.startsWith("comment"))continue;let o=a.split(/\s+/),l=o[0];l==="format"?i=o[1]:l==="element"?(r={name:o[1],count:parseInt(o[2],10),properties:[]},t.push(r)):l==="property"&&r&&(o[1]==="list"?r.properties.push({name:o[4],type:"list",isList:!0,countType:o[2],itemType:o[3]}):r.properties.push({name:o[2],type:o[1],isList:!1}))}return{format:i,elements:t}}function Ag(n){switch(n){case"uchar":case"uint8":return 1;case"char":case"int8":return 1;case"ushort":case"uint16":return 2;case"short":case"int16":return 2;case"uint":case"uint32":return 4;case"int":case"int32":return 4;case"float":case"float32":return 4;case"double":case"float64":return 8;default:return 4}}function fy(n,e,t,i){switch(t){case"uchar":case"uint8":return n.getUint8(e);case"char":case"int8":return n.getInt8(e);case"ushort":case"uint16":return n.getUint16(e,i);case"short":case"int16":return n.getInt16(e,i);case"uint":case"uint32":return n.getUint32(e,i);case"int":case"int32":return n.getInt32(e,i);case"float":case"float32":return n.getFloat32(e,i);case"double":case"float64":return n.getFloat64(e,i);default:return 0}}function mSe(n,e,t,i){let r=i,s=new DataView(n),a=[],o=[],l=[],c=e.elements.find(d=>d.name==="vertex"),f=e.elements.find(d=>d.name==="face");if(c){let d=c.properties.some(h=>h.name==="x"),u=c.properties.some(h=>h.name==="red"||h.name==="r");for(let h=0;h<c.count;h++)for(let m of c.properties){if(m.isList){let p=fy(s,r,m.countType,t);r+=Ag(m.countType),r+=p*Ag(m.itemType);continue}let g=fy(s,r,m.type,t);r+=Ag(m.type),d&&(m.name==="x"||m.name==="y"||m.name==="z")&&a.push(g),u&&(m.name==="red"||m.name==="r"||m.name==="green"||m.name==="g"||m.name==="blue"||m.name==="b")&&o.push(g/255)}}if(f)for(let d=0;d<f.count;d++)for(let u of f.properties)if(u.isList){let h=fy(s,r,u.countType,t);r+=Ag(u.countType);let m=[];for(let g=0;g<h;g++)m.push(fy(s,r,u.itemType,t)),r+=Ag(u.itemType);for(let g=1;g<m.length-1;g++)l.push(m[0],m[g],m[g+1])}else r+=Ag(u.type);return{positions:a,colors:o,indices:l}}function pSe(n,e){var d;let t=n.indexOf("end_header")+10+1,r=n.slice(t).trim().split(/\r?\n/),s=[],a=[],o=[],l=e.elements.find(u=>u.name==="vertex"),c=e.elements.find(u=>u.name==="face"),f=0;if(l){let u=l.properties.some(g=>g.name==="x"),h=l.properties.some(g=>g.name==="red"||g.name==="r"),m=l.properties.filter(g=>!g.isList);for(let g=0;g<l.count&&f<r.length;g++){let p=r[f++].trim().split(/\s+/).map(Number),_=0;for(let v of m){let E=(d=p[_++])!=null?d:0;u&&(v.name==="x"||v.name==="y"||v.name==="z")&&s.push(E),h&&(v.name==="red"||v.name==="r"||v.name==="green"||v.name==="g"||v.name==="blue"||v.name==="b")&&a.push(E/255)}}}if(c)for(let u=0;u<c.count&&f<r.length;u++){let h=r[f++].trim().split(/\s+/).map(Number),m=Math.round(h[0]);for(let g=1;g<m-1;g++)o.push(Math.round(h[1]),Math.round(h[g+1]),Math.round(h[g+2]))}return{positions:s,colors:a,indices:o}}function dy(n,e){let t=new TextDecoder().decode(new Uint8Array(e)),i=hSe(t),r=t.indexOf("end_header")+10+1,s=i.format!=="ascii",a=i.format==="binary_little_endian",o=s?mSe(e,i,a,r):pSe(t,i);if(o.positions.length===0)throw new Error("PLY file contains no vertex data");let l=o.positions,c=new Ie;if(c.positions=l,o.indices.length>0){c.indices=o.indices;let u=new Array(l.length).fill(0),h=o.indices,m=l.length-3;for(let g=0;g<h.length;g+=3){let p=h[g]*3,_=h[g+1]*3,v=h[g+2]*3;if(p<0||_<0||v<0||p>m||_>m||v>m)continue;let E=l[p],S=l[p+1],T=l[p+2],A=l[_]-E,R=l[_+1]-S,M=l[_+2]-T,I=l[v]-E,C=l[v+1]-S,L=l[v+2]-T,w=R*L-M*C,G=M*I-A*L,O=A*C-R*I;u[p]+=w,u[p+1]+=G,u[p+2]+=O,u[_]+=w,u[_+1]+=G,u[_+2]+=O,u[v]+=w,u[v+1]+=G,u[v+2]+=O}for(let g=0;g<u.length;g+=3){let p=Math.sqrt(u[g]**2+u[g+1]**2+u[g+2]**2);p>0&&(u[g]/=p,u[g+1]/=p,u[g+2]/=p)}c.normals=u}else{let u=o.positions.length/3,h=[];for(let m=0;m<u-2;m+=3)h.push(m,m+1,m+2);h.length===0&&u>=3&&h.push(0,1,2),c.indices=h}let f=new $("ply-model",n);c.applyToMesh(f);let d=new We("ply-mat",n);return d.backFaceCulling=!1,o.colors.length>0?(c.colors=o.colors,c.applyToMesh(f),d.diffuseColor=new he(1,1,1),d.vertexColorEnabled=!0):d.diffuseColor=new he(.7,.7,.7),f.material=d,f}function gQ(n,e){return dy(n,e)}function _Q(n){n(gSe)}var gSe,WF=y(()=>{"use strict";ki();AE();vr();lf();$t();gSe={name:"ply",extensions:".ply",importMeshAsync(n,e,t){return Promise.resolve().then(()=>({meshes:[dy(e,t)],particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))},loadAsync(n,e){return Promise.resolve().then(()=>{dy(n,e)})},loadAssetContainerAsync(n,e){return Promise.resolve().then(()=>{let t=dy(n,e),i=new ql(n);return i.meshes.push(t),t.material&&i.materials.push(t.material),i})},canDirectLoad(){return!1},rewriteRootURL(n){return n}}});async function DE(){vQ||(uQ(),pQ(Fd),_Q(Fd),vQ=!0)}var vQ,OE=y(()=>{"use strict";uw();sQ();aQ();GF();ug();hQ();zF();WF();vQ=!1});function NE(n){return Math.floor(n.getTotalIndices()/3)}function kd(n){return n.getTotalVertices()}function Eh(n,e=[]){let t=[n,...e,...n.getChildMeshes(!0)],i=new Set;return t.filter(r=>!r||i.has(r)||r.isDisposed()?!1:(i.add(r),kd(r)>0||r.getTotalIndices()>0))}function EQ(n){let e=Array.from(n),t=new Set(e);return e.filter(i=>{let r=i.parent;return!r||!t.has(r)})}function HF(n){n.computeWorldMatrix(!0);let e=n.getBoundingInfo().boundingBox;return Za(ct(e.minimumWorld),ct(e.maximumWorld))}function Ql(n){let e=null;for(let t of n)!t||t.isDisposed()||(e=Pu(e,HF(t)));return e}function hy(n,e=[]){var t;return(t=Ql(Eh(n,e)))!=null?t:HF(n)}function my(n,e,t,i={}){return YA({rootName:n,boundingSize:Ui(e),meshes:t.map(r=>({triangleCount:NE(r),vertexCount:kd(r),materialKeys:r.material?[r.material.name]:[]})),splatCount:i.splatCount,resourceWarnings:i.resourceWarnings})}function SQ(n,e={}){var t,i;return{name:n.name,triangleCount:e.isSplat?null:NE(n),vertexCount:kd(n),materialName:(i=(t=n.material)==null?void 0:t.name)!=null?i:null}}function XF(n,e=uy){var a,o,l;let t=HF(n),i=n.name||`mesh-${n.uniqueId}`,r=gy(n.metadata,(a=e.get(`node:${i}`))!=null?a:e.get(`mesh:${i}`)),s=Ca(r,{name:i,path:py(n)});return Sc({name:KF(s,i),triangleCount:NE(n),vertexCount:kd(n),materialName:(l=(o=n.material)==null?void 0:o.name)!=null?l:null,boundingSize:Ui(t),center:mr(t),source:s.hasExplicitIdentity?"component":"mesh",meshNames:[i],childCount:1,componentId:s.componentId,occurrenceId:s.occurrenceId,partNumber:s.partNumber,componentPath:s.componentPath})}function TQ(n,e){return n.getChildMeshes(!1).filter(t=>e.has(t))}function _Se(n){let e=n.trim().toLowerCase();return/^(scene|root|model|group|node|object|assembly|component|__root__)[-_\s.]?\d*$/i.test(e)}function vSe(n){return/->\d+(?:[_\s.-]*primitive\d*)?$/i.test(n.trim())}function YF(n,e,t=uy){var h,m;if(e.includes(n))return XF(n,t);let i=new Set(e),r=TQ(n,i),s=ct(n.getAbsolutePosition()),a=(h=Ql(r))!=null?h:Za(s,s),o=new Set,l=0,c=0;for(let g of r)l+=NE(g),c+=kd(g),(m=g.material)!=null&&m.name&&o.add(g.material.name);let f=Gd(n,`component-${n.uniqueId}`),d=gy(n.metadata,t.get(`node:${f}`)),u=Ca(d,{name:f,path:py(n)});return Sc({name:KF(u,f),triangleCount:l,vertexCount:c,materialName:Lu(o),boundingSize:Ui(a),center:mr(a),source:u.hasExplicitIdentity?"component":"group",meshNames:r.map(g=>g.name||`mesh-${g.uniqueId}`),childCount:r.length,componentId:u.componentId,occurrenceId:u.occurrenceId,partNumber:u.partNumber,componentPath:u.componentPath})}function wE(n,e,t,i=uy){var l,c;let r=new Set(t),s=null,a=null,o=e.parent;for(;o&&o!==n;){let f=o,d=TQ(f,r);if(d.length>0&&d.length<t.length){let u=(l=f.name)!=null?l:"",h=Gd(f,`component-${f.uniqueId}`),m=gy(f.metadata,i.get(`node:${h}`));if(Ca(m,{name:h,path:py(f)}).hasExplicitIdentity){if(!vSe(u))return f;a!=null||(a=f)}!s&&d.length>1&&h.trim()&&!_Se(h)&&(s=f)}o=f.parent}return(c=s!=null?s:a)!=null?c:e}function AQ(n,e,t=uy){let i=new Set(n),r=[],s=new Set,a=[];for(let o of e){let l=o.getChildMeshes(!1).filter(u=>i.has(u)),c=Gd(o,`component-${o.uniqueId}`),f=gy(o.metadata,t.get(`node:${c}`)),d=Ca(f,{name:Gd(o,`component-${o.uniqueId}`),path:py(o)});l.length<1||l.length===n.length||!d.hasExplicitIdentity&&(!o.name.trim()||l.length<2)||a.push({node:o,childMeshes:l,identity:d})}return a.sort((o,l)=>o.childMeshes.length-l.childMeshes.length).forEach(({node:o,childMeshes:l,identity:c})=>{var g;let f=l.filter(p=>!s.has(p));if(f.length<1||!c.hasExplicitIdentity&&f.length<2)return;for(let p of f)s.add(p);let d=Ql(f);if(!d)return;let u=new Set,h=0,m=0;for(let p of f)h+=NE(p),m+=kd(p),(g=p.material)!=null&&g.name&&u.add(p.material.name);r.push(Sc({name:KF(c,Gd(o,`component-${o.uniqueId}`)),triangleCount:h,vertexCount:m,materialName:Lu(u),boundingSize:Ui(d),center:mr(d),source:c.hasExplicitIdentity?"component":"group",meshNames:f.map(p=>p.name||`mesh-${p.uniqueId}`),childCount:f.length,componentId:c.componentId,occurrenceId:c.occurrenceId,partNumber:c.partNumber,componentPath:c.componentPath}))}),{parts:r,groupedMeshes:s}}function xQ(n,e){let t=ESe(n,e),i=new Map;if(!t)return i;let r=Array.isArray(t.nodes)?t.nodes:[];for(let a of r){if(!a||typeof a!="object")continue;let o=a,l=typeof o.name=="string"?o.name:"";l&&o.extras&&i.set(`node:${l}`,o.extras)}let s=Array.isArray(t.meshes)?t.meshes:[];for(let a of s){if(!a||typeof a!="object")continue;let o=a,l=typeof o.name=="string"?o.name:"";l&&o.extras&&i.set(`mesh:${l}`,o.extras)}return i}function Gd(n,e){var i;return((i=Ca(n.metadata,{name:n.name}).displayName)==null?void 0:i.trim())||n.name||e}function py(n){let e=[],t=n;for(;t&&typeof t=="object"&&"name"in t;){let i=t,r=Gd(i,"node");r.trim()&&e.push(r),t=i.parent}return e.reverse().join("/")}function ESe(n,e){try{if(e==="gltf")return JSON.parse(new TextDecoder().decode(new Uint8Array(n)));if(e!=="glb")return null;let t=new DataView(n);if(t.byteLength<20||t.getUint32(0,!0)!==1179937895)return null;let i=t.getUint32(12,!0);if(t.getUint32(16,!0)!==1313821514||20+i>t.byteLength)return null;let s=new Uint8Array(n,20,i);return JSON.parse(new TextDecoder().decode(s))}catch(t){return null}}function gy(n,e){return e===void 0?n:n==null?e:{metadata:n,extras:e}}function KF(n,e){var t;return((t=n.displayName)==null?void 0:t.trim())||n.partNumber||n.componentId||e}var uy,FE=y(()=>{"use strict";Lo();IP();iv();xs();KA();uy=new Map});function zd(n){return _n(n)}function RQ(n,e,t,i=[]){Px(new _y(n,i),e,t)}function jF(n,e=[]){Lx(new _y(n,e))}var _y,bQ=y(()=>{"use strict";He();Lo();xs();DP();FE();_y=class{constructor(e,t=[]){this.rootMesh=e,this.loadedMeshes=t}getParts(){return Eh(this.rootMesh,this.loadedMeshes)}getRootCenter(){return mr(hy(this.rootMesh,this.loadedMeshes))}getPartPosition(e){return ct(e.position)}getPartCenter(e){return ct(e.getBoundingInfo().boundingBox.centerWorld)}setPartPosition(e,t){e.position=new b(t.x,t.y,t.z)}getPartState(e){let t=e.metadata;return t!=null&&t._previewExplodeState?{originalPosition:zd(t._previewExplodeState.originalPosition),originalCenter:zd(t._previewExplodeState.originalCenter)}:t!=null&&t._originalPos&&(t!=null&&t._originalCenter)?{originalPosition:zd(t._originalPos),originalCenter:zd(t._originalCenter)}:null}setPartState(e,t){(!e.metadata||typeof e.metadata!="object")&&(e.metadata={});let i=e.metadata;i._previewExplodeState={originalPosition:zd(t.originalPosition),originalCenter:zd(t.originalCenter)},i._originalPos=zd(t.originalPosition),i._originalCenter=zd(t.originalCenter)}}});var vy={};Be(vy,{glowBlurPostProcessPixelShaderWGSL:()=>SSe});var ZF,MQ,SSe,Ey=y(()=>{k();ZF="glowBlurPostProcessPixelShader",MQ=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform screenSize: vec2f;uniform direction: vec2f;uniform blurWidth: f32;fn getLuminance(color: vec3f)->f32
{return dot(color, vec3f(0.2126,0.7152,0.0722));}
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var weights: array<f32 ,7>;weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;var texelSize: vec2f= vec2f(1.0/uniforms.screenSize.x,1.0/uniforms.screenSize.y);var texelStep: vec2f=texelSize*uniforms.direction*uniforms.blurWidth;var start: vec2f=input.vUV-3.0*texelStep;var baseColor: vec4f= vec4f(0.,0.,0.,0.);var texelOffset: vec2f= vec2f(0.,0.);for (var i: i32=0; i<7; i++)
{var texel: vec4f=textureSample(textureSampler,textureSamplerSampler,start+texelOffset);baseColor=vec4f(baseColor.rgb,baseColor.a+texel.a*weights[i]);var luminance: f32=getLuminance(baseColor.rgb);var luminanceTexel: f32=getLuminance(texel.rgb);var choice: f32=step(luminanceTexel,luminance);baseColor=vec4f(choice*baseColor.rgb+(1.0-choice)*texel.rgb,baseColor.a);texelOffset+=texelStep;}
fragmentOutputs.color=baseColor;}`;x.ShadersStoreWGSL[ZF]||(x.ShadersStoreWGSL[ZF]=MQ);SSe={name:ZF,shader:MQ}});var Sy={};Be(Sy,{glowBlurPostProcessPixelShader:()=>TSe});var qF,yQ,TSe,Ty=y(()=>{k();qF="glowBlurPostProcessPixelShader",yQ=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color)
{return dot(color,vec3(0.2126,0.7152,0.0722));}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++)
{vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;}
gl_FragColor=baseColor;}`;x.ShadersStore[qF]||(x.ShadersStore[qF]=yQ);TSe={name:qF,shader:yQ}});var CQ={};Be(CQ,{glowMapGenerationVertexShaderWGSL:()=>ASe});var QF,IQ,ASe,PQ=y(()=>{k();Wc();Hc();yd();Id();Xc();Rd();Cd();Pd();Yc();Kc();jc();Zc();QF="glowMapGenerationVertexShader",IQ=`attribute position: vec3f;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
#include<instancesDeclaration>
uniform viewProjection: mat4x4f;varying vPosition: vec4f;
#ifdef UV1
attribute uv: vec2f;
#endif
#ifdef UV2
attribute uv2: vec2f;
#endif
#ifdef DIFFUSE
varying vUVDiffuse: vec2f;uniform diffuseMatrix: mat4x4f;
#endif
#ifdef OPACITY
varying vUVOpacity: vec2f;uniform opacityMatrix: mat4x4f;
#endif
#ifdef EMISSIVE
varying vUVEmissive: vec2f;uniform emissiveMatrix: mat4x4f;
#endif
#ifdef VERTEXALPHA
attribute color: vec4f;varying vColor: vec4f;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=vertexInputs.position;
#ifdef UV1
var uvUpdated: vec2f=vertexInputs.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=vertexInputs.uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);
#ifdef CUBEMAP
vertexOutputs.vPosition=worldPos;vertexOutputs.position=uniforms.viewProjection*finalWorld* vec4f(vertexInputs.position,1.0);
#else
vertexOutputs.vPosition=uniforms.viewProjection*worldPos;vertexOutputs.position=vertexOutputs.vPosition;
#endif
#ifdef DIFFUSE
#ifdef DIFFUSEUV1
vertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef DIFFUSEUV2
vertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
#ifdef OPACITY
#ifdef OPACITYUV1
vertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef OPACITYUV2
vertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
#ifdef EMISSIVE
#ifdef EMISSIVEUV1
vertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef EMISSIVEUV2
vertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
#ifdef VERTEXALPHA
vertexOutputs.vColor=vertexInputs.color;
#endif
#include<clipPlaneVertex>
}`;x.ShadersStoreWGSL[QF]||(x.ShadersStoreWGSL[QF]=IQ);ASe={name:QF,shader:IQ}});var DQ={};Be(DQ,{glowMapGenerationPixelShaderWGSL:()=>xSe});var $F,LQ,xSe,OQ=y(()=>{k();ao();qc();Qc();$F="glowMapGenerationPixelShader",LQ=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)
#include<helperFunctions>
#endif
#ifdef DIFFUSE
varying vUVDiffuse: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d<f32>;
#endif
#ifdef OPACITY
varying vUVOpacity: vec2f;var opacitySamplerSampler: sampler;var opacitySampler: texture_2d<f32>;uniform opacityIntensity: f32;
#endif
#ifdef EMISSIVE
varying vUVEmissive: vec2f;var emissiveSamplerSampler: sampler;var emissiveSampler: texture_2d<f32>;
#endif
#ifdef VERTEXALPHA
varying vColor: vec4f;
#endif
uniform glowColor: vec4f;uniform glowIntensity: f32;
#include<clipPlaneFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#include<clipPlaneFragment>
var finalColor: vec4f=uniforms.glowColor;
#ifdef DIFFUSE
var albedoTexture: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUVDiffuse);
#ifdef DIFFUSE_ISLINEAR
albedoTexture=toGammaSpace(albedoTexture);
#endif
#ifdef GLOW
finalColor=vec4f(finalColor.rgb,finalColor.a*albedoTexture.a);
#endif
#ifdef HIGHLIGHT
finalColor=vec4f(finalColor.rgb,albedoTexture.a);
#endif
#endif
#ifdef OPACITY
var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vUVOpacity);
#ifdef OPACITYRGB
finalColor=vec4f(finalColor.rgb,finalColor.a*getLuminance(opacityMap.rgb));
#else
finalColor=vec4f(finalColor.rgb,finalColor.a*opacityMap.a);
#endif
finalColor=vec4f(finalColor.rgb,finalColor.a*uniforms.opacityIntensity);
#endif
#ifdef VERTEXALPHA
finalColor=vec4f(finalColor.rgb,finalColor.a*fragmentInputs.vColor.a);
#endif
#ifdef ALPHATEST
if (finalColor.a<ALPHATESTVALUE) {discard;}
#endif
#ifdef EMISSIVE
var emissive: vec4f=textureSample(emissiveSampler,emissiveSamplerSampler,fragmentInputs.vUVEmissive);
#ifdef EMISSIVE_ISLINEAR
emissive=toGammaSpace(emissive);
#endif
fragmentOutputs.color=emissive*finalColor*uniforms.glowIntensity;
#else
fragmentOutputs.color=finalColor*uniforms.glowIntensity;
#endif
#ifdef HIGHLIGHT
fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb,uniforms.glowColor.a);
#endif
}
`;x.ShadersStoreWGSL[$F]||(x.ShadersStoreWGSL[$F]=LQ);xSe={name:$F,shader:LQ}});var wQ={};Be(wQ,{glowMapGenerationVertexShader:()=>RSe});var JF,NQ,RSe,FQ=y(()=>{k();$c();Jc();Ld();Dd();ef();bd();Od();Nd();tf();rf();nf();sf();JF="glowMapGenerationVertexShader",NQ=`attribute vec3 position;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
#include<instancesDeclaration>
uniform mat4 viewProjection;varying vec4 vPosition;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#ifdef DIFFUSE
varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;
#endif
#ifdef OPACITY
varying vec2 vUVOpacity;uniform mat4 opacityMatrix;
#endif
#ifdef EMISSIVE
varying vec2 vUVEmissive;uniform mat4 emissiveMatrix;
#endif
#ifdef VERTEXALPHA
attribute vec4 color;varying vec4 vColor;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#ifdef CUBEMAP
vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);
#else
vPosition=viewProjection*worldPos;gl_Position=vPosition;
#endif
#ifdef DIFFUSE
#ifdef DIFFUSEUV1
vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef DIFFUSEUV2
vUVDiffuse=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#ifdef OPACITY
#ifdef OPACITYUV1
vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef OPACITYUV2
vUVOpacity=vec2(opacityMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#ifdef EMISSIVE
#ifdef EMISSIVEUV1
vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef EMISSIVEUV2
vUVEmissive=vec2(emissiveMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#ifdef VERTEXALPHA
vColor=color;
#endif
#include<clipPlaneVertex>
}`;x.ShadersStore[JF]||(x.ShadersStore[JF]=NQ);RSe={name:JF,shader:NQ}});var UQ={};Be(UQ,{glowMapGenerationPixelShader:()=>bSe});var e1,BQ,bSe,VQ=y(()=>{k();oo();af();of();e1="glowMapGenerationPixelShader",BQ=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)
#include<helperFunctions>
#endif
#ifdef DIFFUSE
varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;
#endif
#ifdef OPACITY
varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;
#endif
#ifdef EMISSIVE
varying vec2 vUVEmissive;uniform sampler2D emissiveSampler;
#endif
#ifdef VERTEXALPHA
varying vec4 vColor;
#endif
uniform vec4 glowColor;uniform float glowIntensity;
#include<clipPlaneFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#include<clipPlaneFragment>
vec4 finalColor=glowColor;
#ifdef DIFFUSE
vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);
#ifdef DIFFUSE_ISLINEAR
albedoTexture=toGammaSpace(albedoTexture);
#endif
#ifdef GLOW
finalColor.a*=albedoTexture.a;
#endif
#ifdef HIGHLIGHT
finalColor.a=albedoTexture.a;
#endif
#endif
#ifdef OPACITY
vec4 opacityMap=texture2D(opacitySampler,vUVOpacity);
#ifdef OPACITYRGB
finalColor.a*=getLuminance(opacityMap.rgb);
#else
finalColor.a*=opacityMap.a;
#endif
finalColor.a*=opacityIntensity;
#endif
#ifdef VERTEXALPHA
finalColor.a*=vColor.a;
#endif
#ifdef ALPHATEST
if (finalColor.a<ALPHATESTVALUE)
discard;
#endif
#ifdef EMISSIVE
vec4 emissive=texture2D(emissiveSampler,vUVEmissive);
#ifdef EMISSIVE_ISLINEAR
emissive=toGammaSpace(emissive);
#endif
gl_FragColor=emissive*finalColor*glowIntensity;
#else
gl_FragColor=finalColor*glowIntensity;
#endif
#ifdef HIGHLIGHT
gl_FragColor.a=glowColor.a;
#endif
}`;x.ShadersStore[e1]||(x.ShadersStore[e1]=BQ);bSe={name:e1,shader:BQ}});var nl,uf,Ay=y(()=>{Si();$t();Yi();qi();Ku();ls();Td();Yu();Hl();os();SL();nl=class n extends sn{constructor(e,t=null,i,r,s){super({...s,name:e,engine:t||Oe.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,uniforms:n.Uniforms}),this.direction=i,this.kernel=r,this.textureWidth=0,this.textureHeight=0}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(()=>(Ey(),vy)))):t.push(Promise.resolve().then(()=>(Ty(),Sy))),super._gatherImports(e,t)}bind(){super.bind(),this._drawWrapper.effect.setFloat2("screenSize",this.textureWidth,this.textureHeight),this._drawWrapper.effect.setVector2("direction",this.direction),this._drawWrapper.effect.setFloat("blurWidth",this.kernel)}};nl.FragmentUrl="glowBlurPostProcess";nl.Uniforms=["screenSize","direction","blurWidth"];uf=class n{get camera(){return this._options.camera}set camera(e){this._options.camera=e}get renderingGroupId(){return this._options.renderingGroupId}set renderingGroupId(e){this._options.renderingGroupId=e}get objectRenderer(){return this._objectRenderer}get shaderLanguage(){return this._shaderLanguage}setMaterialForRendering(e,t){if(this._objectRenderer.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i<e.length;++i){let r=e[i];t?this._materialForRendering[r.uniqueId]=[r,t]:delete this._materialForRendering[r.uniqueId]}else t?this._materialForRendering[e.uniqueId]=[e,t]:delete this._materialForRendering[e.uniqueId]}getEffectIntensity(e){var t;return(t=this._effectIntensity[e.uniqueId])!=null?t:1}setEffectIntensity(e,t){this._effectIntensity[e.uniqueId]=t}constructor(e,t,i=!1,r=!1,s){this._additionalImportShadersAsync=s,this._vertexBuffers={},this._dontCheckIfReady=!1,this._shouldRender=!0,this._emissiveTextureAndColor={texture:null,color:new ht},this._effectIntensity={},this._postProcesses=[],this.neutralColor=new ht,this.isEnabled=!0,this.disableBoundingBoxesFromEffectLayer=!1,this.onDisposeObservable=new re,this.onBeforeRenderLayerObservable=new re,this.onBeforeComposeObservable=new re,this.onBeforeRenderMeshToEffect=new re,this.onAfterRenderMeshToEffect=new re,this.onAfterComposeObservable=new re,this.onBeforeBlurObservable=new re,this.onAfterBlurObservable=new re,this._shaderLanguage=0,this._materialForRendering={},this._shadersLoaded=!1,this.name=e,this._scene=t||Oe.LastCreatedScene,this._dontCheckIfReady=r,this._scene.getEngine().isWebGPU&&!i&&!n.ForceGLSL&&(this._shaderLanguage=1),this._engine=this._scene.getEngine(),this._mergeDrawWrapper=[],this._generateIndexBuffer(),this._generateVertexBuffer()}getEffectName(){return""}isReady(e,t){return!0}needStencil(){return!1}_createMergeEffect(){throw new Error("Effect Layer: no merge effect defined")}_createTextureAndPostProcesses(){}_internalCompose(e,t){}_setEmissiveTextureAndColor(e,t,i){}_numInternalDraws(){return 1}_init(e){this._options={mainTextureRatio:.5,mainTextureFixedSize:0,mainTextureType:0,mainTextureFormat:5,alphaBlendingMode:2,camera:null,renderingGroupId:-1,...e},this._createObjectRenderer()}_generateIndexBuffer(){let e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._engine.createIndexBuffer(e)}_generateVertexBuffer(){let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1);let t=new D(this._engine,e,D.PositionKind,!1,!1,2);this._vertexBuffers[D.PositionKind]=t}_createObjectRenderer(){this._objectRenderer=new eo(`ObjectRenderer for thin effect layer ${this.name}`,this._scene,{doNotChangeAspectRatio:!0}),this._objectRenderer.activeCamera=this._options.camera,this._objectRenderer.renderParticles=!1,this._objectRenderer.renderList=null;let e=!!this._scene.getBoundingBoxRenderer,t=!1;e&&(this._objectRenderer.onBeforeRenderObservable.add(()=>{t=this._scene.getBoundingBoxRenderer().enabled,this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&t}),this._objectRenderer.onAfterRenderObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=t})),this._objectRenderer.customIsReadyFunction=(i,r,s)=>{if((s||r===0)&&i.subMeshes)for(let a=0;a<i.subMeshes.length;++a){let o=i.subMeshes[a],l=o.getMaterial(),c=o.getRenderingMesh();if(!l)continue;let d=c._getInstancesRenderList(o._id,!!o.getReplacementMesh()).hardwareInstancedRendering[o._id]||c.hasThinInstances;if(this._setEmissiveTextureAndColor(c,o,l),!this._isSubMeshReady(o,d,this._emissiveTextureAndColor.texture))return!1}return!0},this._objectRenderer.customRenderFunction=(i,r,s,a)=>{this.onBeforeRenderLayerObservable.notifyObservers(this);let o,l=this._scene.getEngine();if(a.length){for(l.setColorWrite(!1),o=0;o<a.length;o++)this._renderSubMesh(a.data[o]);l.setColorWrite(!0)}for(o=0;o<i.length;o++)this._renderSubMesh(i.data[o]);for(o=0;o<r.length;o++)this._renderSubMesh(r.data[o]);let c=l.getAlphaMode();for(o=0;o<s.length;o++){let f=s.data[o],d=f.getMaterial();if(d&&d.needDepthPrePass){let u=d.getScene().getEngine();u.setColorWrite(!1),this._renderSubMesh(f),u.setColorWrite(!0)}this._renderSubMesh(f,!0)}l.setAlphaMode(c)}}_addCustomEffectDefines(e){}_internalIsSubMeshReady(e,t,i){var S;let r=this._scene.getEngine(),s=e.getMesh(),a=(S=s._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:S[r.currentRenderPassId];if(a)return a.isReadyForSubMesh(s,e,t);let o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh())){o._glowModeEnabled=!0;let T=o.isReadyForSubMesh(e.getMesh(),e,t);return o._glowModeEnabled=!1,T}let l=[],c=[D.PositionKind],f=!1,d=!1,u=!1;if(o){let T=o.needAlphaTestingForMesh(s),A=o.getAlphaTestTexture(),R=A&&A.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);A&&(T||R)&&(l.push("#define DIFFUSE"),s.isVerticesDataPresent(D.UV2Kind)&&A.coordinatesIndex===1?(l.push("#define DIFFUSEUV2"),d=!0):s.isVerticesDataPresent(D.UVKind)&&(l.push("#define DIFFUSEUV1"),f=!0),T&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),A.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));let M=o.opacityTexture;M&&(l.push("#define OPACITY"),s.isVerticesDataPresent(D.UV2Kind)&&M.coordinatesIndex===1?(l.push("#define OPACITYUV2"),d=!0):s.isVerticesDataPresent(D.UVKind)&&(l.push("#define OPACITYUV1"),f=!0))}i&&(l.push("#define EMISSIVE"),s.isVerticesDataPresent(D.UV2Kind)&&i.coordinatesIndex===1?(l.push("#define EMISSIVEUV2"),d=!0):s.isVerticesDataPresent(D.UVKind)&&(l.push("#define EMISSIVEUV1"),f=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),s.useVertexColors&&s.isVerticesDataPresent(D.ColorKind)&&s.hasVertexAlpha&&o.transparencyMode!==Ae.MATERIAL_OPAQUE&&(c.push(D.ColorKind),l.push("#define VERTEXALPHA")),f&&(c.push(D.UVKind),l.push("#define UV1")),d&&(c.push(D.UV2Kind),l.push("#define UV2"));let h=new ds;if(s.useBones&&s.computeBonesUsingShaders){c.push(D.MatricesIndicesKind),c.push(D.MatricesWeightsKind),s.numBoneInfluencers>4&&(c.push(D.MatricesIndicesExtraKind),c.push(D.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers);let T=s.skeleton;T&&T.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(T?T.bones.length+1:0)),s.numBoneInfluencers>0&&h.addCPUSkinningFallback(0,s)}else l.push("#define NUM_BONE_INFLUENCERS 0");let m=s.morphTargetManager?Xl(s.morphTargetManager,l,c,s,!0,!1,!1,f,d,u):0;t&&(l.push("#define INSTANCES"),Qo(c),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES"));let g=s.bakedVertexAnimationManager;g&&g.isEnabled&&(l.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&c.push("bakedVertexAnimationSettingsInstanced")),Wl(o,this._scene,l),this._addCustomEffectDefines(l);let p=e._getDrawWrapper(void 0,!0),_=p.defines,v=l.join(`
`);if(_!==v){let T=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureInfo","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture","glowIntensity"];ns(T),p.setEffect(this._engine.createEffect("glowMapGeneration",c,T,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],v,h,void 0,void 0,{maxSimultaneousMorphTargets:m},this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0}),v)}return p.effect.isReady()&&(this._dontCheckIfReady||!this._dontCheckIfReady&&this.isLayerReady())}_isSubMeshReady(e,t,i){return this._internalIsSubMeshReady(e,t,i)}async _importShadersAsync(){var e;this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(PQ(),CQ)),Promise.resolve().then(()=>(OQ(),DQ))]):await Promise.all([Promise.resolve().then(()=>(FQ(),wQ)),Promise.resolve().then(()=>(VQ(),UQ))]),(e=this._additionalImportShadersAsync)==null||e.call(this)}_internalIsLayerReady(){let e=!0;for(let i=0;i<this._postProcesses.length;i++)e=this._postProcesses[i].isReady()&&e;let t=this._numInternalDraws();for(let i=0;i<t;++i){let r=this._mergeDrawWrapper[i];r||(r=this._mergeDrawWrapper[i]=new Ps(this._engine),r.setEffect(this._createMergeEffect())),e=r.effect.isReady()&&e}return e}isLayerReady(){return this._internalIsLayerReady()}compose(){if(!this._dontCheckIfReady&&!this.isLayerReady())return!1;let e=this._scene.getEngine(),t=this._numInternalDraws();this.onBeforeComposeObservable.notifyObservers(this);let i=e.getAlphaMode();for(let r=0;r<t;++r){let s=this._mergeDrawWrapper[r];e.enableEffect(s),e.setState(!1),e.bindBuffers(this._vertexBuffers,this._indexBuffer,s.effect),e.setAlphaMode(this._options.alphaBlendingMode),this._internalCompose(s.effect,r)}return e.setAlphaMode(i),this.onAfterComposeObservable.notifyObservers(this),!0}_internalHasMesh(e){return this.renderingGroupId===-1||e.renderingGroupId===this.renderingGroupId}hasMesh(e){return this._internalHasMesh(e)}_internalShouldRender(){return this.isEnabled&&this._shouldRender}shouldRender(){return this._internalShouldRender()}_shouldRenderMesh(e){return!0}_internalCanRenderMesh(e,t){return!t.needAlphaBlendingForMesh(e)}_canRenderMesh(e,t){return this._internalCanRenderMesh(e,t)}_renderSubMesh(e,t=!1){var g;if(!this._internalShouldRender())return;let i=e.getMaterial(),r=e.getMesh(),s=e.getReplacementMesh(),a=e.getRenderingMesh(),o=e.getEffectiveMesh(),l=this._scene,c=l.getEngine();if(o._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!i||!this._canRenderMesh(a,i))return;let f=i._getEffectiveOrientation(a);o._getWorldMatrixDeterminant()<0&&(f=f===Ae.ClockWiseSideOrientation?Ae.CounterClockWiseSideOrientation:Ae.ClockWiseSideOrientation);let u=f===Ae.ClockWiseSideOrientation,h=a._getInstancesRenderList(e._id,!!s);if(h.mustReturn||!this._shouldRenderMesh(a))return;let m=h.hardwareInstancedRendering[e._id]||a.hasThinInstances;if(this._setEmissiveTextureAndColor(a,e,i),this.onBeforeRenderMeshToEffect.notifyObservers(r),this._useMeshMaterial(a))e.getMaterial()._glowModeEnabled=!0,a.render(e,t,s||void 0),e.getMaterial()._glowModeEnabled=!1;else if(this._isSubMeshReady(e,m,this._emissiveTextureAndColor.texture)){let p=(g=o._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:g[c.currentRenderPassId],_=e._getDrawWrapper();if(!_&&p&&(_=p._getDrawWrapper()),!_)return;let v=_.effect;c.enableEffect(_),c.setState(i.backFaceCulling,i.zOffset,void 0,u,i.cullBackFaces,i.stencil,i.zOffsetUnits);let E=c.getDepthWrite(),S=c.getColorWrite(),T=c.getDepthFunction()||0;if(i.disableDepthWrite?c.setDepthWrite(!1):i.forceDepthWrite&&c.setDepthWrite(!0),i.disableColorWrite&&c.setColorWrite(!1),i.depthFunction!==0&&c.setDepthFunction(i.depthFunction),m||a._bind(e,v,i.fillMode),p?p.bindForSubMesh(o.getWorldMatrix(),o,e):(v.setMatrix("viewProjection",l.getTransformMatrix()),v.setMatrix("world",o.getWorldMatrix()),v.setFloat4("glowColor",this._emissiveTextureAndColor.color.r,this._emissiveTextureAndColor.color.g,this._emissiveTextureAndColor.color.b,this._emissiveTextureAndColor.color.a)),!p){let A=i.needAlphaTestingForMesh(o),R=i.getAlphaTestTexture(),M=R&&R.hasAlpha&&(i.useAlphaFromDiffuseTexture||i._useAlphaFromAlbedoTexture);if(R&&(A||M)){v.setTexture("diffuseSampler",R);let L=R.getTextureMatrix();L&&v.setMatrix("diffuseMatrix",L)}let I=i.opacityTexture;if(I){v.setTexture("opacitySampler",I),v.setFloat("opacityIntensity",I.level);let L=I.getTextureMatrix();L&&v.setMatrix("opacityMatrix",L)}this._emissiveTextureAndColor.texture&&(v.setTexture("emissiveSampler",this._emissiveTextureAndColor.texture),v.setMatrix("emissiveMatrix",this._emissiveTextureAndColor.texture.getTextureMatrix())),aa(a,v),as(a,v),a.morphTargetManager&&a.morphTargetManager.isUsingTextureForTargets&&a.morphTargetManager._bind(v);let C=e.getMesh().bakedVertexAnimationManager;C&&C.isEnabled&&C.bind(v,m),t&&c.setAlphaMode(i.alphaMode),v.setFloat("glowIntensity",this.getEffectIntensity(a)),ss(v,i,l)}a._processRendering(o,e,v,i.fillMode,h,m,(A,R)=>v.setMatrix("world",R)),(i.disableDepthWrite||i.forceDepthWrite)&&c.setDepthWrite(E),i.disableColorWrite&&c.setColorWrite(S),i.depthFunction!==0&&c.setDepthFunction(T)}else this._objectRenderer.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(r)}_useMeshMaterial(e){return!1}_rebuild(){let e=this._vertexBuffers[D.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}dispose(){let e=this._vertexBuffers[D.PositionKind];e&&(e.dispose(),this._vertexBuffers[D.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);for(let t of this._mergeDrawWrapper)t.dispose();this._mergeDrawWrapper=[],this._objectRenderer.dispose(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderLayerObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear()}};uf.ForceGLSL=!1});var ha,t1=y(()=>{jt();Yt();Gi();Si();Yi();Kr();sd();Mn();Bo();Ay();jR();ha=class n{get _shouldRender(){return this._thinEffectLayer._shouldRender}set _shouldRender(e){this._thinEffectLayer._shouldRender=e}get _emissiveTextureAndColor(){return this._thinEffectLayer._emissiveTextureAndColor}set _emissiveTextureAndColor(e){this._thinEffectLayer._emissiveTextureAndColor=e}get _effectIntensity(){return this._thinEffectLayer._effectIntensity}set _effectIntensity(e){this._thinEffectLayer._effectIntensity=e}static get ForceGLSL(){return uf.ForceGLSL}static set ForceGLSL(e){uf.ForceGLSL=e}get name(){return this._thinEffectLayer.name}set name(e){this._thinEffectLayer.name=e}get neutralColor(){return this._thinEffectLayer.neutralColor}set neutralColor(e){this._thinEffectLayer.neutralColor=e}get isEnabled(){return this._thinEffectLayer.isEnabled}set isEnabled(e){this._thinEffectLayer.isEnabled=e}get camera(){return this._thinEffectLayer.camera}get renderingGroupId(){return this._thinEffectLayer.renderingGroupId}set renderingGroupId(e){this._thinEffectLayer.renderingGroupId=e}get disableBoundingBoxesFromEffectLayer(){return this._thinEffectLayer.disableBoundingBoxesFromEffectLayer}set disableBoundingBoxesFromEffectLayer(e){this._thinEffectLayer.disableBoundingBoxesFromEffectLayer=e}get mainTexture(){return this._mainTexture}get _shaderLanguage(){return this._thinEffectLayer.shaderLanguage}get shaderLanguage(){return this._thinEffectLayer.shaderLanguage}setMaterialForRendering(e,t){this._thinEffectLayer.setMaterialForRendering(e,t)}getEffectIntensity(e){return this._thinEffectLayer.getEffectIntensity(e)}setEffectIntensity(e,t){this._thinEffectLayer.setEffectIntensity(e,t)}constructor(e,t,i=!1,r){this._mainTextureCreatedSize={width:0,height:0},this._maxSize=0,this._mainTextureDesiredSize={width:0,height:0},this._postProcesses=[],this._textures=[],this.uniqueId=Uc.UniqueId,this.onDisposeObservable=new re,this.onBeforeRenderMainTextureObservable=new re,this.onBeforeComposeObservable=new re,this.onBeforeRenderMeshToEffect=new re,this.onAfterRenderMeshToEffect=new re,this.onAfterComposeObservable=new re,this.onSizeChangedObservable=new re,this._internalThinEffectLayer=!r,r||(r=new uf(e,t,i,!1,this._importShadersAsync.bind(this)),r.getEffectName=this.getEffectName.bind(this),r.isReady=this.isReady.bind(this),r._createMergeEffect=this._createMergeEffect.bind(this),r._createTextureAndPostProcesses=this._createTextureAndPostProcesses.bind(this),r._internalCompose=this._internalRender.bind(this),r._setEmissiveTextureAndColor=this._setEmissiveTextureAndColor.bind(this),r._numInternalDraws=this._numInternalDraws.bind(this),r._addCustomEffectDefines=this._addCustomEffectDefines.bind(this),r.hasMesh=this.hasMesh.bind(this),r.shouldRender=this.shouldRender.bind(this),r._shouldRenderMesh=this._shouldRenderMesh.bind(this),r._canRenderMesh=this._canRenderMesh.bind(this),r._useMeshMaterial=this._useMeshMaterial.bind(this)),this._thinEffectLayer=r,this.name=e,this._scene=t||Oe.LastCreatedScene,n._SceneComponentInitialization(this._scene),this._engine=this._scene.getEngine(),this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.addEffectLayer(this),this._thinEffectLayer.onDisposeObservable.add(()=>{this.onDisposeObservable.notifyObservers(this)}),this._thinEffectLayer.onBeforeRenderLayerObservable.add(()=>{this.onBeforeRenderMainTextureObservable.notifyObservers(this)}),this._thinEffectLayer.onBeforeComposeObservable.add(()=>{this.onBeforeComposeObservable.notifyObservers(this)}),this._thinEffectLayer.onBeforeRenderMeshToEffect.add(s=>{this.onBeforeRenderMeshToEffect.notifyObservers(s)}),this._thinEffectLayer.onAfterRenderMeshToEffect.add(s=>{this.onAfterRenderMeshToEffect.notifyObservers(s)}),this._thinEffectLayer.onAfterComposeObservable.add(()=>{this.onAfterComposeObservable.notifyObservers(this)})}get _shadersLoaded(){return this._thinEffectLayer._shadersLoaded}set _shadersLoaded(e){this._thinEffectLayer._shadersLoaded=e}_numInternalDraws(){return this._internalThinEffectLayer?1:this._thinEffectLayer._numInternalDraws()}_init(e){this._effectLayerOptions={mainTextureRatio:.5,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,mainTextureFormat:5,generateStencilBuffer:!1,...e},this._setMainTextureSize(),this._thinEffectLayer._init(e),this._createMainTexture(),this._createTextureAndPostProcesses()}_setMainTextureSize(){this._effectLayerOptions.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._effectLayerOptions.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._effectLayerOptions.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderWidth()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderHeight()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.width=this._engine.needPOTTextures?Un(this._mainTextureDesiredSize.width,this._maxSize):this._mainTextureDesiredSize.width,this._mainTextureDesiredSize.height=this._engine.needPOTTextures?Un(this._mainTextureDesiredSize.height,this._maxSize):this._mainTextureDesiredSize.height),this._mainTextureDesiredSize.width=Math.floor(this._mainTextureDesiredSize.width),this._mainTextureDesiredSize.height=Math.floor(this._mainTextureDesiredSize.height)}_createMainTexture(){this._mainTexture=new jr("EffectLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,{type:this._effectLayerOptions.mainTextureType,format:this._effectLayerOptions.mainTextureFormat,samplingMode:_e.TRILINEAR_SAMPLINGMODE,generateStencilBuffer:this._effectLayerOptions.generateStencilBuffer,existingObjectRenderer:this._thinEffectLayer.objectRenderer}),this._mainTexture.activeCamera=this._effectLayerOptions.camera,this._mainTexture.wrapU=_e.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=_e.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(_e.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._mainTexture.ignoreCameraViewport=!0,this._mainTexture.onClearObservable.add(e=>{e.clear(this.neutralColor,!0,!0,!0)})}_addCustomEffectDefines(e){}_isReady(e,t,i){return this._internalThinEffectLayer?this._thinEffectLayer._internalIsSubMeshReady(e,t,i):this._thinEffectLayer._isSubMeshReady(e,t,i)}async _importShadersAsync(){}_arePostProcessAndMergeReady(){return this._internalThinEffectLayer?this._thinEffectLayer._internalIsLayerReady():this._thinEffectLayer.isLayerReady()}isLayerReady(){return this._arePostProcessAndMergeReady()&&this._mainTexture.isReady()}render(){this._thinEffectLayer.compose()&&(this._setMainTextureSize(),(this._mainTextureCreatedSize.width!==this._mainTextureDesiredSize.width||this._mainTextureCreatedSize.height!==this._mainTextureDesiredSize.height)&&this._mainTextureDesiredSize.width!==0&&this._mainTextureDesiredSize.height!==0&&(this.onSizeChangedObservable.notifyObservers(this),this._disposeTextureAndPostProcesses(),this._createMainTexture(),this._createTextureAndPostProcesses(),this._mainTextureCreatedSize.width=this._mainTextureDesiredSize.width,this._mainTextureCreatedSize.height=this._mainTextureDesiredSize.height))}hasMesh(e){return this._internalThinEffectLayer?this._thinEffectLayer._internalHasMesh(e):this._thinEffectLayer.hasMesh(e)}shouldRender(){return this._internalThinEffectLayer?this._thinEffectLayer._internalShouldRender():this._thinEffectLayer.shouldRender()}_shouldRenderMesh(e){return this._internalThinEffectLayer?!0:this._thinEffectLayer._shouldRenderMesh(e)}_canRenderMesh(e,t){return this._internalThinEffectLayer?this._thinEffectLayer._internalCanRenderMesh(e,t):this._thinEffectLayer._canRenderMesh(e,t)}_shouldRenderEmissiveTextureForMesh(){return!0}_useMeshMaterial(e){return this._internalThinEffectLayer?!1:this._thinEffectLayer._useMeshMaterial(e)}_rebuild(){this._thinEffectLayer._rebuild()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e<this._postProcesses.length;e++)this._postProcesses[e]&&this._postProcesses[e].dispose();this._postProcesses=[];for(let e=0;e<this._textures.length;e++)this._textures[e]&&this._textures[e].dispose();this._textures=[]}dispose(){this._thinEffectLayer.dispose(),this._disposeTextureAndPostProcesses(),this._scene.removeEffectLayer(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return pe.Instantiate(e.customType).Parse(e,t,i)}};ha._SceneComponentInitialization=n=>{throw $e("EffectLayerSceneComponent")};P([F()],ha.prototype,"name",null);P([pp()],ha.prototype,"neutralColor",null);P([F()],ha.prototype,"isEnabled",null);P([fk()],ha.prototype,"camera",null);P([F()],ha.prototype,"renderingGroupId",null);P([F()],ha.prototype,"disableBoundingBoxesFromEffectLayer",null)});var kQ={};Be(kQ,{glowMapMergePixelShaderWGSL:()=>MSe});var i1,GQ,MSe,zQ=y(()=>{k();i1="glowMapMergePixelShader",GQ=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;
#ifdef EMISSIVE
var textureSampler2Sampler: sampler;var textureSampler2: texture_2d<f32>;
#endif
uniform offset: f32;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
var baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);
#ifdef EMISSIVE
baseColor+=textureSample(textureSampler2,textureSampler2Sampler,input.vUV);baseColor*=uniforms.offset;
#else
baseColor=vec4f(baseColor.rgb,abs(uniforms.offset-baseColor.a));
#ifdef STROKE
var alpha: f32=smoothstep(.0,.1,baseColor.a);baseColor=vec4f(baseColor.rgb*alpha,alpha);
#endif
#endif
#if LDR
baseColor=clamp(baseColor,vec4f(0.),vec4f(1.0));
#endif
fragmentOutputs.color=baseColor;
#define CUSTOM_FRAGMENT_MAIN_END
}
`;x.ShadersStoreWGSL[i1]||(x.ShadersStoreWGSL[i1]=GQ);MSe={name:i1,shader:GQ}});var HQ={};Be(HQ,{glowMapMergeVertexShaderWGSL:()=>ySe});var r1,WQ,ySe,XQ=y(()=>{k();r1="glowMapMergeVertexShader",WQ=`attribute position: vec2f;varying vUV: vec2f;
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5);
#define CUSTOM_VERTEX_MAIN_BEGIN
vertexOutputs.vUV=vertexInputs.position*madd+madd;vertexOutputs.position= vec4f(vertexInputs.position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;x.ShadersStoreWGSL[r1]||(x.ShadersStoreWGSL[r1]=WQ);ySe={name:r1,shader:WQ}});var KQ={};Be(KQ,{glowMapMergePixelShader:()=>ISe});var n1,YQ,ISe,jQ=y(()=>{k();n1="glowMapMergePixelShader",YQ=`varying vec2 vUV;uniform sampler2D textureSampler;
#ifdef EMISSIVE
uniform sampler2D textureSampler2;
#endif
uniform float offset;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
vec4 baseColor=texture2D(textureSampler,vUV);
#ifdef EMISSIVE
baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;
#else
baseColor.a=abs(offset-baseColor.a);
#ifdef STROKE
float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;
#endif
#endif
#if LDR
baseColor=clamp(baseColor,0.,1.0);
#endif
gl_FragColor=baseColor;
#define CUSTOM_FRAGMENT_MAIN_END
}`;x.ShadersStore[n1]||(x.ShadersStore[n1]=YQ);ISe={name:n1,shader:YQ}});var qQ={};Be(qQ,{glowMapMergeVertexShader:()=>CSe});var s1,ZQ,CSe,QQ=y(()=>{k();s1="glowMapMergeVertexShader",ZQ=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;x.ShadersStore[s1]||(x.ShadersStore[s1]=ZQ);CSe={name:s1,shader:ZQ}});var $l,$Q=y(()=>{He();qi();ls();wL();Ay();$t();DN();$l=class n extends uf{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}get stencilReference(){return this._instanceGlowingMeshStencilReference<<8-this.numStencilBits}constructor(e,t,i,r=!1){super(e,t,i!==void 0?!!i.forceGLSL:!1),this.innerGlow=!0,this.outerGlow=!0,this._instanceGlowingMeshStencilReference=n.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this._mainObjectRendererRenderPassId=-1,this.numStencilBits=8,this.neutralColor=n.NeutralColor,this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,mainTextureFixedSize:0,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,forceGLSL:!1,mainTextureType:0,mainTextureFormat:5,isStroke:!1,...i},this._init(this._options),this._shouldRender=!1,r&&this._createTextureAndPostProcesses()}getClassName(){return"HighlightLayer"}async _importShadersAsync(){this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(zQ(),kQ)),Promise.resolve().then(()=>(XQ(),HQ)),Promise.resolve().then(()=>(Ey(),vy))]):await Promise.all([Promise.resolve().then(()=>(jQ(),KQ)),Promise.resolve().then(()=>(QQ(),qQ)),Promise.resolve().then(()=>(Ty(),Sy))]),await super._importShadersAsync()}getEffectName(){return n.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[D.PositionKind],["offset"],["textureSampler"],this._options.isStroke?`#define STROKE
`:void 0,void 0,void 0,void 0,void 0,this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0})}_createTextureAndPostProcesses(){this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new Nc("HighlightLayerPPP",this._scene.getEngine()),this._horizontalBlurPostprocess=new nl("HighlightLayerHBP",this._scene.getEngine(),new Fe(1,0),this._options.blurHorizontalSize),this._verticalBlurPostprocess=new nl("HighlightLayerVBP",this._scene.getEngine(),new Fe(0,1),this._options.blurVerticalSize),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new Os("HighlightLayerHBP",this._scene.getEngine(),new Fe(1,0),this._options.blurHorizontalSize/2),this._verticalBlurPostprocess=new Os("HighlightLayerVBP",this._scene.getEngine(),new Fe(0,1),this._options.blurVerticalSize/2),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess])}needStencil(){return!0}isReady(e,t){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let s=null,a=this._meshes[r.uniqueId];return a&&a.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isSubMeshReady(e,t,s)}_canRenderMesh(e,t){return!0}_internalCompose(e,t){this.bindTexturesForCompose(e);let i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference<<8-this.numStencilBits),i.setStencilFunctionMask(255-((1<<8-this.numStencilBits)-1)),this.outerGlow&&t===0&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(Ae.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(Ae.TriangleFillMode,0,6)),i.restoreStencilState()}_setEmissiveTextureAndColor(e,t,i){let r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}shouldRender(){return!!(this._meshes&&super.shouldRender())}_shouldRenderMesh(e){return this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?!1:super.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}addExcludedMesh(e){if(!this._excludedMeshes)return;if(!this._excludedMeshes[e.uniqueId]){let i={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};i.beforeBind=e.onBeforeBindObservable.add(r=>{this._mainObjectRendererRenderPassId!==-1&&this._mainObjectRendererRenderPassId!==this._engine.currentRenderPassId||(i.stencilState=r.getEngine().getStencilBuffer(),r.getEngine().setStencilBuffer(!1))}),i.afterRender=e.onAfterRenderObservable.add(r=>{this._mainObjectRendererRenderPassId!==-1&&this._mainObjectRendererRenderPassId!==this._engine.currentRenderPassId||r.getEngine().setStencilBuffer(i.stencilState)}),this._excludedMeshes[e.uniqueId]=i}}removeExcludedMesh(e){if(!this._excludedMeshes)return;let t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!this._meshes||!super.hasMesh(e)?!1:!!this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;let r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(s=>{this._mainObjectRendererRenderPassId!==-1&&this._mainObjectRendererRenderPassId!==this._engine.currentRenderPassId||this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[s.uniqueId]?this._defaultStencilReference(s):s.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference<<8-this.numStencilBits))}),observerDefault:e.onAfterRenderObservable.add(s=>{this._mainObjectRendererRenderPassId!==-1&&this._mainObjectRendererRenderPassId!==this._engine.currentRenderPassId||this.isEnabled&&this._defaultStencilReference(s)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;let t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(let i in this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(let e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){let t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(n.NormalMeshStencilReference<<8-this.numStencilBits)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(let e in this._meshes){let t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(let e in this._excludedMeshes){let t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}};$l.EffectName="HighlightLayer";$l.NeutralColor=new ht(0,0,0,0);$l.GlowingMeshStencilReference=2;$l.NormalMeshStencilReference=1});var xy,Va,JQ=y(()=>{jt();Yt();Si();na();He();Kr();sd();Oc();BL();ON();t1();wt();ir();$t();$Q();Or();Bo();Ay();ai.prototype.getHighlightLayerByName=function(n){var e;for(let t=0;t<((e=this.effectLayers)==null?void 0:e.length);t++)if(this.effectLayers[t].name===n&&this.effectLayers[t].getEffectName()===Va.EffectName)return this.effectLayers[t];return null};xy=class extends Ni{constructor(e,t,i,r,s=null,a=_e.BILINEAR_SAMPLINGMODE,o,l){let c={uniforms:nl.Uniforms,size:typeof r=="number"?r:void 0,camera:s,samplingMode:a,engine:o,reusable:l,...r};super(e,nl.FragmentUrl,{effectWrapper:typeof r=="number"||!r.effectWrapper?new nl(e,o,t,i,c):void 0,...c}),this.direction=t,this.kernel=i,this.onApplyObservable.add(()=>{this._effectWrapper.textureWidth=this.width,this._effectWrapper.textureHeight=this.height})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(()=>(Ey(),vy)))):t.push(Promise.resolve().then(()=>(Ty(),Sy))),super._gatherImports(e,t)}},Va=class n extends ha{static get NeutralColor(){return $l.NeutralColor}static set NeutralColor(e){$l.NeutralColor=e}get innerGlow(){return this._thinEffectLayer.innerGlow}set innerGlow(e){this._thinEffectLayer.innerGlow=e}get outerGlow(){return this._thinEffectLayer.outerGlow}set outerGlow(e){this._thinEffectLayer.outerGlow=e}set blurHorizontalSize(e){this._thinEffectLayer.blurHorizontalSize=e}set blurVerticalSize(e){this._thinEffectLayer.blurVerticalSize=e}get blurHorizontalSize(){return this._thinEffectLayer.blurHorizontalSize}get blurVerticalSize(){return this._thinEffectLayer.blurVerticalSize}get numStencilBits(){return this._thinEffectLayer.numStencilBits}set numStencilBits(e){this._thinEffectLayer.numStencilBits=e}get stencilReference(){return this._thinEffectLayer.stencilReference}constructor(e,t,i){super(e,t,i!==void 0?!!i.forceGLSL:!1,new $l(e,t,i)),this.onBeforeBlurObservable=new re,this.onAfterBlurObservable=new re,this._engine.isStencilEnable||te.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,mainTextureFixedSize:0,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,mainTextureFormat:5,forceGLSL:!1,isStroke:!1,generateStencilBuffer:!1,...i},this._init(this._options),this._shouldRender=!1}getEffectName(){return n.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._thinEffectLayer._createMergeEffect()}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?Un(e,this._maxSize):e,t=this._engine.needPOTTextures?Un(t,this._maxSize):t;let i;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new jr("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=_e.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=_e.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(_e.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._thinEffectLayer.bindTexturesForCompose=r=>{r.setTexture("textureSampler",this._blurTexture)},this._thinEffectLayer._createTextureAndPostProcesses(),this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new ju("HighlightLayerPPP",{size:this._options.blurTextureSizeRatio,samplingMode:_e.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),effectWrapper:this._thinEffectLayer._postProcesses[0]}),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(r=>{r.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new xy("HighlightLayerHBP",new Fe(1,0),this._options.blurHorizontalSize,{samplingMode:_e.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),effectWrapper:this._thinEffectLayer._postProcesses[1]}),this._horizontalBlurPostprocess.onApplyObservable.add(r=>{r.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new xy("HighlightLayerVBP",new Fe(0,1),this._options.blurVerticalSize,{samplingMode:_e.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),effectWrapper:this._thinEffectLayer._postProcesses[2]}),this._verticalBlurPostprocess.onApplyObservable.add(r=>{r.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new mo("HighlightLayerHBP",new Fe(1,0),this._options.blurHorizontalSize/2,{size:{width:e,height:t},samplingMode:_e.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),textureType:i,effectWrapper:this._thinEffectLayer._postProcesses[0]}),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add(r=>{r.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new mo("HighlightLayerVBP",new Fe(0,1),this._options.blurVerticalSize/2,{size:{width:e,height:t},samplingMode:_e.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),textureType:i}),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);let r=this._blurTexture.renderTarget;r&&(this._scene.postProcessManager.directRender(this._postProcesses,r,!0),this._engine.unBindFramebuffer(r,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(r=>{r.autoClear=!1}),this._mainTextureCreatedSize.width=this._mainTextureDesiredSize.width,this._mainTextureCreatedSize.height=this._mainTextureDesiredSize.height}needStencil(){return this._thinEffectLayer.needStencil()}isReady(e,t){return this._thinEffectLayer.isReady(e,t)}_internalRender(e,t){this._thinEffectLayer._internalCompose(e,t)}shouldRender(){return this._thinEffectLayer.shouldRender()}_shouldRenderMesh(e){return this._thinEffectLayer._shouldRenderMesh(e)}_canRenderMesh(e,t){return this._thinEffectLayer._canRenderMesh(e,t)}_addCustomEffectDefines(e){this._thinEffectLayer._addCustomEffectDefines(e)}_setEmissiveTextureAndColor(e,t,i){this._thinEffectLayer._setEmissiveTextureAndColor(e,t,i)}addExcludedMesh(e){this._thinEffectLayer.addExcludedMesh(e)}removeExcludedMesh(e){this._thinEffectLayer.removeExcludedMesh(e)}hasMesh(e){return this._thinEffectLayer.hasMesh(e)}addMesh(e,t,i=!1){this._thinEffectLayer.addMesh(e,t,i)}removeMesh(e){this._thinEffectLayer.removeMesh(e)}removeAllMeshes(){this._thinEffectLayer.removeAllMeshes()}_disposeMesh(e){this._thinEffectLayer._disposeMesh(e)}getClassName(){return"HighlightLayer"}serialize(){let e=at.Serialize(this);e.customType="BABYLON.HighlightLayer",e.meshes=[];let t=this._thinEffectLayer._meshes;if(t)for(let r in t){let s=t[r];s&&e.meshes.push({glowEmissiveOnly:s.glowEmissiveOnly,color:s.color.asArray(),meshId:s.mesh.id})}e.excludedMeshes=[];let i=this._thinEffectLayer._excludedMeshes;if(i)for(let r in i){let s=i[r];s&&e.excludedMeshes.push(s.mesh.id)}return e}static Parse(e,t,i){let r=at.Parse(()=>new n(e.name,t,e.options),e,t,i),s;for(s=0;s<e.excludedMeshes.length;s++){let a=t.getMeshById(e.excludedMeshes[s]);a&&r.addExcludedMesh(a)}for(s=0;s<e.meshes.length;s++){let a=e.meshes[s],o=t.getMeshById(a.meshId);o&&r.addMesh(o,he.FromArray(a.color),a.glowEmissiveOnly)}return r}};Va.EffectName="HighlightLayer";P([F()],Va.prototype,"innerGlow",null);P([F()],Va.prototype,"outerGlow",null);P([F()],Va.prototype,"blurHorizontalSize",null);P([F()],Va.prototype,"blurVerticalSize",null);P([F()],Va.prototype,"numStencilBits",null);P([F("options")],Va.prototype,"_options",void 0);zt("BABYLON.HighlightLayer",Va)});var a1,e$=y(()=>{zl();Sp();t1();Yi();JN();UM(tt.NAME_EFFECTLAYER,(n,e,t,i)=>{if(n.effectLayers){t.effectLayers||(t.effectLayers=[]);for(let r=0;r<n.effectLayers.length;r++){let s=ha.Parse(n.effectLayers[r],e,i);t.effectLayers.push(s)}}});a1=class{constructor(e){this.name=tt.NAME_EFFECTLAYER,this._renderEffects=!1,this._needStencil=!1,this._previousStencilState=!1,this.scene=e||Oe.LastCreatedScene,this.scene&&(this._engine=this.scene.getEngine())}register(){this.scene._isReadyForMeshStage.registerStep(tt.STEP_ISREADYFORMESH_EFFECTLAYER,this,this._isReadyForMesh),this.scene._cameraDrawRenderTargetStage.registerStep(tt.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER,this,this._renderMainTexture),this.scene._beforeCameraDrawStage.registerStep(tt.STEP_BEFORECAMERADRAW_EFFECTLAYER,this,this._setStencil),this.scene._afterRenderingGroupDrawStage.registerStep(tt.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW,this,this._drawRenderingGroup),this.scene._afterCameraDrawStage.registerStep(tt.STEP_AFTERCAMERADRAW_EFFECTLAYER,this,this._setStencilBack),this.scene._afterCameraDrawStage.registerStep(tt.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW,this,this._drawCamera)}rebuild(){let e=this.scene.effectLayers;for(let t of e)t._rebuild()}serialize(e){e.effectLayers=[];let t=this.scene.effectLayers;for(let i of t)i.serialize&&e.effectLayers.push(i.serialize())}addFromContainer(e){if(e.effectLayers)for(let t of e.effectLayers)this.scene.addEffectLayer(t)}removeFromContainer(e,t){if(e.effectLayers)for(let i of e.effectLayers)this.scene.removeEffectLayer(i),t&&i.dispose()}dispose(){let e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){let i=this._engine.currentRenderPassId,r=this.scene.effectLayers;for(let s of r){if(!s.hasMesh(e))continue;let a=s._mainTexture;this._engine.currentRenderPassId=a.renderPassId;for(let o of e.subMeshes)if(!s.isReady(o,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1,i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(let r of i)if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===Et.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==Et.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();let s=r._mainTexture;s._shouldRender()&&(this.scene.incrementRenderId(),s.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);let t=this.scene.effectLayers;for(let i=0;i<t.length;i++){let r=t[i];r.renderingGroupId===e&&r.shouldRender()&&r.render()}this._engine.setDepthBuffer(!0)}}_drawCamera(){this._renderEffects&&this._draw(-1)}_drawRenderingGroup(e){!this.scene._isInIntermediateRendering()&&this._renderEffects&&this._draw(e)}};ha._SceneComponentInitialization=n=>{let e=n._getComponent(tt.NAME_EFFECTLAYER);e||(e=new a1(n),n._addComponent(e))}});function t$(n,e,t=()=>!0,i=r=>[r]){let r=new Va("ai3d-pick-highlight",n),s=new he(.15,.45,1),a=[];function o(){r.removeAllMeshes();for(let d of a)d.isDisposed()||(d.renderOutline=!1,d.outlineWidth=0);a=[]}function l(d){a=d.filter(u=>!u.isDisposed());for(let u of a)r.addMesh(u,s),u.renderOutline=!0,u.outlineColor=s,u.outlineWidth=.045}let c=n.onPointerObservable.add(d=>{var _;if(d.type!==ot.POINTERDOWN)return;let u=d.event,h=u.clientX,m=u.clientY,g={altKey:u.altKey,ctrlKey:u.ctrlKey,metaKey:u.metaKey,shiftKey:u.shiftKey},p=d.pickInfo;if(p!=null&&p.hit&&p.pickedMesh){if(t()){let v=i(p.pickedMesh).filter(S=>!S.isDisposed());a.length===v.length&&a.every((S,T)=>S===v[T])||(o(),l(v))}else o();e({mesh:p.pickedMesh,pickedPoint:(_=p.pickedPoint)!=null?_:null,screenX:h,screenY:m,modifiers:g})}else o(),e({mesh:null,pickedPoint:null,screenX:h,screenY:m,modifiers:g})}),f=(()=>{o(),r.dispose(),n.onPointerObservable.remove(c)});return f.clearHighlight=o,f}var i$=y(()=>{"use strict";Xo();$t();JQ();e$()});function FSe(n,e,t){let i=he.FromHexString(e),r=new We(n,t);return r.emissiveColor=i,r.diffuseColor=he.Black(),r.specularColor=he.Black(),r.backFaceCulling=!1,r}function BSe(n){let e=new We("gizmo-origin-mat",n);return e.emissiveColor=new he(.72,.78,.86),e.diffuseColor=he.Black(),e.specularColor=he.Black(),e}var PSe,Ry,LSe,l1,DSe,OSe,o1,NSe,wSe,by,r$=y(()=>{"use strict";na();Eb();Sb();He();$t();up();QO();lf();PSe=.32,Ry=1.05,LSe=.075,l1=.28,DSe=.22,OSe=.16,o1=(Ry+l1)*.42,NSe=new b(o1,o1,o1),wSe=[{name:"x",color:"#e74c3c",rot:new b(0,0,-Math.PI/2),dir:new b(1,0,0)},{name:"y",color:"#2ecc71",rot:new b(0,0,0),dir:new b(0,1,0)},{name:"z",color:"#3498db",rot:new b(Math.PI/2,0,0),dir:new b(0,0,1)}];by=class{constructor(e,t){this.engine=e,this.scene=new ai(e),this.scene.clearColor=new ht(0,0,0,0),this.scene.autoClear=!1,this.camera=new Mi("gizmo-cam",0,0,4.1,NSe,this.scene),this.camera.minZ=.01,this.camera.fov=.56,this.camera.detachControl(),new Fa("gizmo-light",new b(0,1,.5),this.scene);let i=Pn.CreateSphere("gizmo-origin",{diameter:OSe,segments:16},this.scene);i.material=BSe(this.scene);for(let{name:s,color:a,rot:o,dir:l}of wSe){let c=FSe(`gizmo-${s}-mat`,a,this.scene),f=Pn.CreateCylinder(`gizmo-${s}-shaft`,{height:Ry,diameter:LSe,tessellation:8},this.scene);f.material=c,f.position=l.scale(Ry/2),f.rotation=o;let d=Pn.CreateCylinder(`gizmo-${s}-head`,{height:l1,diameterTop:0,diameterBottom:DSe,tessellation:8},this.scene);d.material=c;let u=Ry+l1/2;d.position=l.scale(u),d.rotation=o}let r=PSe;this.viewport=new Go(.02,.03,r,r),this.camera.viewport=this.viewport,this.syncWith(t)}syncWith(e){this.camera.alpha=e.alpha,this.camera.beta=e.beta}render(){let e=this.engine.getRenderWidth(),t=this.engine.getRenderHeight(),i=this.viewport.x*e,r=this.viewport.y*t,s=this.viewport.width*e,a=this.viewport.height*t;this.engine.enableScissor(i,r,s,a),this.engine.clear(null,!1,!0,!0),this.scene.render(),this.engine.disableScissor()}dispose(){this.scene.dispose()}}});var f1={};Be(f1,{boundingBoxRendererVertexShaderWGSL:()=>USe});var c1,n$,USe,d1=y(()=>{k();c1="boundingBoxRendererVertexShader",n$=`attribute position: vec3f;uniform world: mat4x4f;uniform viewProjection: mat4x4f;
#ifdef INSTANCES
attribute world0 : vec4<f32>;attribute world1 : vec4<f32>;attribute world2 : vec4<f32>;attribute world3 : vec4<f32>;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef INSTANCES
var finalWorld=mat4x4<f32>(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);var worldPos: vec4f=finalWorld* vec4f(vertexInputs.position,1.0);
#else
var worldPos: vec4f=uniforms.world* vec4f(vertexInputs.position,1.0);
#endif
vertexOutputs.position=uniforms.viewProjection*worldPos;
#define CUSTOM_VERTEX_MAIN_END
}
`;x.ShadersStoreWGSL[c1]||(x.ShadersStoreWGSL[c1]=n$);USe={name:c1,shader:n$}});var h1={};Be(h1,{boundingBoxRendererPixelShaderWGSL:()=>VSe});var u1,s$,VSe,m1=y(()=>{k();u1="boundingBoxRendererPixelShader",s$=`uniform color: vec4f;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
fragmentOutputs.color=uniforms.color;
#define CUSTOM_FRAGMENT_MAIN_END
}`;x.ShadersStoreWGSL[u1]||(x.ShadersStoreWGSL[u1]=s$);VSe={name:u1,shader:s$}});var a$,GSe,o$=y(()=>{k();a$="boundingBoxRendererVertexDeclaration",GSe=`uniform mat4 world;uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
`;x.IncludesShadersStore[a$]||(x.IncludesShadersStore[a$]=GSe)});var l$,kSe,p1=y(()=>{k();l$="boundingBoxRendererUboDeclaration",kSe=`#ifdef WEBGL2
uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
#else
layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;};
#endif
`;x.IncludesShadersStore[l$]||(x.IncludesShadersStore[l$]=kSe)});var _1={};Be(_1,{boundingBoxRendererVertexShader:()=>zSe});var g1,c$,zSe,v1=y(()=>{k();o$();p1();g1="boundingBoxRendererVertexShader",c$=`attribute vec3 position;
#include<__decl__boundingBoxRendererVertex>
#ifdef INSTANCES
attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef INSTANCES
mat4 finalWorld=mat4(world0,world1,world2,world3);vec4 worldPos=finalWorld*vec4(position,1.0);
#else
vec4 worldPos=world*vec4(position,1.0);
#endif
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}
#else
gl_Position=viewProjection*worldPos;
#endif
#define CUSTOM_VERTEX_MAIN_END
}
`;x.ShadersStore[g1]||(x.ShadersStore[g1]=c$);zSe={name:g1,shader:c$}});var f$,WSe,d$=y(()=>{k();f$="boundingBoxRendererFragmentDeclaration",WSe=`uniform vec4 color;
`;x.IncludesShadersStore[f$]||(x.IncludesShadersStore[f$]=WSe)});var S1={};Be(S1,{boundingBoxRendererPixelShader:()=>HSe});var E1,u$,HSe,T1=y(()=>{k();d$();p1();E1="boundingBoxRendererPixelShader",u$=`#include<__decl__boundingBoxRendererFragment>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
gl_FragColor=color;
#define CUSTOM_FRAGMENT_MAIN_END
}`;x.ShadersStore[E1]||(x.ShadersStore[E1]=u$);HSe={name:E1,shader:u$}});var p$,h$,My,XSe,YSe,m$,A1,g$=y(()=>{na();qi();Pp();He();Wo();Sp();KD();ls();CO();$t();Si();Yu();rd();SO();Ll();wt();Object.defineProperty(ai.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(n){this._forceShowBoundingBoxes=n,n&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0});ai.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new A1(this)),this._boundingBoxRenderer};Object.defineProperty(Ir.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(n){this._showBoundingBox=n,n&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});p$=Q.Identity(),h$=new Q,My=new b,XSe=new b,YSe=p$.asArray(),m$=new ld(My,My),A1=class{get shaderLanguage(){return this._shaderLanguage}constructor(e){this.name=tt.NAME_BOUNDINGBOXRENDERER,this.frontColor=new he(1,1,1),this.backColor=new he(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new re,this.onAfterBoxRenderingObservable=new re,this.onResourcesReadyObservable=new re,this.enabled=!0,this._shaderLanguage=0,this.renderList=new Qi(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this._matrixBuffer=null,this._matrices=null,this._useInstances=!1,this._drawWrapperFront=null,this._drawWrapperBack=null,this.scene=e,this.scene.getEngine().isWebGPU&&(this._shaderLanguage=1),e._addComponent(this),this._uniformBufferFront=new xr(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!0),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new xr(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!0),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(tt.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(tt.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(tt.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(tt.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}async whenReadyAsync(e=16,t=3e4){return this._prepareResources(),await new Promise(i=>{Pl(()=>this._colorShader.isReady(),()=>{i()},(r,s)=>{s?(te.Error("BoundingBoxRenderer: Timeout while waiting for the renderer to be ready."),r&&te.Error(r)):(te.Error("BoundingBoxRenderer: An unexpected error occurred while waiting for the renderer to be ready."),r&&(te.Error(r),r.stack&&te.Error(r.stack)))},e,t)})}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){let i=t.getBoundingInfo();i!=null&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){let t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new tl("colorShader",this.scene,"boundingBoxRenderer",{attributes:[D.PositionKind,"world0","world1","world2","world3"],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(d1(),f1)),Promise.resolve().then(()=>(m1(),h1))]):await Promise.all([Promise.resolve().then(()=>(v1(),_1)),Promise.resolve().then(()=>(T1(),S1))])}},!1),this._colorShader.setDefine("INSTANCES",this._useInstances),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new tl("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[D.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(d1(),f1)),Promise.resolve().then(()=>(m1(),h1))]):await Promise.all([Promise.resolve().then(()=>(v1(),_1)),Promise.resolve().then(()=>(T1(),S1))])}},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};let e=this.scene.getEngine(),t=Ab({size:1});this._vertexBuffers[D.PositionKind]=new D(e,t.positions,D.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){let e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){let e=this._vertexBuffers[D.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this._matrixBuffer&&this._matrixBuffer._rebuild()}reset(){this.renderList.reset()}render(e){var r,s;if(this.renderList.length===0||!this.enabled)return;if(this._useInstances){this._renderInstanced(e);return}if(this._prepareResources(),!this._colorShader.isReady())return;let t=this.scene.getEngine();t.setDepthWrite(!1);let i=this.scene.getTransformMatrix();for(let a=0;a<this.renderList.length;a++){let o=this.renderList.data[a];if(o._tag!==e)continue;this._createWrappersForBoundingBox(o),this.onBeforeBoxRenderingObservable.notifyObservers(o);let l=o.minimum,f=o.maximum.subtract(l),d=l.add(f.scale(.5)),u=Q.Scaling(f.x,f.y,f.z).multiply(Q.Translation(d.x,d.y,d.z)).multiply(o.getWorldMatrix()),h=t.useReverseDepthBuffer;if(this.showBackLines){let g=(r=o._drawWrapperBack)!=null?r:this._colorShader._getDrawWrapper();this._colorShader._preBind(g),t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),h?t.setDepthFunctionToLessOrEqual():t.setDepthFunctionToGreaterOrEqual(),this._uniformBufferBack.bindToEffect(g.effect,"BoundingBoxRenderer"),this._uniformBufferBack.updateColor4("color",this.backColor,1),this._uniformBufferBack.updateMatrix("world",u),this._uniformBufferBack.updateMatrix("viewProjection",i),this._uniformBufferBack.update(),t.drawElementsType(Ae.LineListDrawMode,0,24)}let m=(s=o._drawWrapperFront)!=null?s:this._colorShader._getDrawWrapper();this._colorShader._preBind(m),t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),h?t.setDepthFunctionToGreater():t.setDepthFunctionToLess(),this._uniformBufferFront.bindToEffect(m.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateColor4("color",this.frontColor,1),this._uniformBufferFront.updateMatrix("world",u),this._uniformBufferFront.updateMatrix("viewProjection",i),this._uniformBufferFront.update(),t.drawElementsType(Ae.LineListDrawMode,0,24),this.onAfterBoxRenderingObservable.notifyObservers(o)}this._colorShader.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0)}_createWrappersForBoundingBox(e){if(!e._drawWrapperFront){let t=this.scene.getEngine();e._drawWrapperFront=new Ps(t),e._drawWrapperBack=new Ps(t),e._drawWrapperFront.setEffect(this._colorShader.getEffect()),e._drawWrapperBack.setEffect(this._colorShader.getEffect())}}renderOcclusionBoundingBox(e){let t=this.scene.getEngine();this._renderPassIdForOcclusionQuery===void 0&&(this._renderPassIdForOcclusionQuery=t.createRenderPassId("Render pass for occlusion query"));let i=t.currentRenderPassId;t.currentRenderPassId=this._renderPassIdForOcclusionQuery,this._prepareResources();let r=e.subMeshes[0];if(!this._colorShaderForOcclusionQuery.isReady(e,void 0,r)||!e.hasBoundingInfo){t.currentRenderPassId=i;return}this._fillIndexBuffer||(this._fillIndexBuffer=t.createIndexBuffer(this._fillIndexData));let s=t.useReverseDepthBuffer;t.setDepthWrite(!1),t.setColorWrite(!1);let a=e.getBoundingInfo().boundingBox,o=a.minimum,c=a.maximum.subtract(o),f=o.add(c.scale(.5)),d=Q.Scaling(c.x,c.y,c.z).multiply(Q.Translation(f.x,f.y,f.z)).multiply(a.getWorldMatrix()),u=r._drawWrapper;this._colorShaderForOcclusionQuery._preBind(u),t.bindBuffers(this._vertexBuffers,this._fillIndexBuffer,u.effect),s?t.setDepthFunctionToGreater():t.setDepthFunctionToLess(),this.scene.resetCachedMaterial(),this._uniformBufferFront.bindToEffect(u.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateMatrix("world",d),this._uniformBufferFront.updateMatrix("viewProjection",this.scene.getTransformMatrix()),this._uniformBufferFront.update(),t.drawElementsType(Ae.TriangleFillMode,0,36),this._colorShaderForOcclusionQuery.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0),t.setColorWrite(!0),t.currentRenderPassId=i}set useInstances(e){this._useInstances=e,this._colorShader&&this._colorShader.setDefine("INSTANCES",e),e||this._cleanupInstances()}get useInstances(){return this._useInstances}_renderInstanced(e){var g,p;if(this.renderList.length===0||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;let t=this._colorShader,i=this._matrices,r=this.renderList.length*16;(!i||i.length<r||i.length>r*2)&&(i=new Float32Array(r),this._matrices=i),this.onBeforeBoxRenderingObservable.notifyObservers(m$);let s=0,a=this.scene.floatingOriginOffset;for(let _=0;_<this.renderList.length;_++){let v=this.renderList.data[_];if(v._tag!==e)continue;let E=v.minimum,T=v.maximum.subtractToRef(E,XSe),A=E.addToRef(T.scaleToRef(.5,My),My),R=YSe;R[0]=T._x,R[3]=A._x,R[5]=T._y,R[7]=A._y,R[10]=T._z,R[11]=A._z;let M=s*16,I=h$.asArray();p$.multiplyToArray(v.getWorldMatrix(),I,0),I[12]-=a.x,I[13]-=a.y,I[14]-=a.z,h$.copyToArray(i,M),s++}let o=this.scene.getEngine(),l=(g=o.getDepthFunction())!=null?g:515,c=o.getDepthWrite();o.setDepthWrite(!1);let f=this._matrixBuffer;f!=null&&f.isUpdatable()&&f.getData()===i?f.update(i):this._createInstanceBuffer(i),this._createWrappersForBoundingBox(this);let d=o.useReverseDepthBuffer,u=this.scene.getTransformMatrix();if(this.showBackLines){let _=(p=this._drawWrapperBack)!=null?p:t._getDrawWrapper();t._preBind(_),o.bindBuffers(this._vertexBuffers,this._indexBuffer,t.getEffect()),d?o.setDepthFunctionToLessOrEqual():o.setDepthFunctionToGreaterOrEqual();let v=this._uniformBufferBack;v.bindToEffect(_.effect,"BoundingBoxRenderer"),v.updateColor4("color",this.backColor,1),v.updateMatrix("viewProjection",u),v.update(),o.drawElementsType(Ae.LineListDrawMode,0,24,s)}let h=t._getDrawWrapper();t._preBind(h),o.bindBuffers(this._vertexBuffers,this._indexBuffer,t.getEffect()),d?o.setDepthFunctionToGreater():o.setDepthFunctionToLess();let m=this._uniformBufferFront;m.bindToEffect(h.effect,"BoundingBoxRenderer"),m.updateColor4("color",this.frontColor,1),m.updateMatrix("viewProjection",u),m.update(),o.drawElementsType(Ae.LineListDrawMode,0,24,s),this.onAfterBoxRenderingObservable.notifyObservers(m$),t.unbind(),o.setDepthFunction(l),o.setDepthWrite(c)}_createInstanceBuffer(e){let t=this._vertexBuffers;this._cleanupInstanceBuffer();let i=new ko(this.scene.getEngine(),e,!0,16,!1,!0);t.world0=i.createVertexBuffer("world0",0,4),t.world1=i.createVertexBuffer("world1",4,4),t.world2=i.createVertexBuffer("world2",8,4),t.world3=i.createVertexBuffer("world3",12,4),this._matrixBuffer=i}_cleanupInstanceBuffer(){let e=this._vertexBuffers;e.world0&&(e.world0.dispose(),delete e.world0),e.world1&&(e.world1.dispose(),delete e.world1),e.world2&&(e.world2.dispose(),delete e.world2),e.world3&&(e.world3.dispose(),delete e.world3),this._matrices=null,this._matrixBuffer&&(this._matrixBuffer.dispose(),this._matrixBuffer=null)}_cleanupInstances(){this._cleanupInstanceBuffer(),this._drawWrapperFront&&(this._drawWrapperFront.dispose(),this._drawWrapperFront=null),this._drawWrapperBack&&(this._drawWrapperBack.dispose(),this._drawWrapperBack=null)}dispose(){if(this._renderPassIdForOcclusionQuery!==void 0&&(this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery),this._renderPassIdForOcclusionQuery=void 0),!this._colorShader)return;this.onBeforeBoxRenderingObservable.clear(),this.onAfterBoxRenderingObservable.clear(),this.onResourcesReadyObservable.clear(),this.renderList.dispose(),this._colorShader.dispose(),this._colorShaderForOcclusionQuery.dispose(),this._uniformBufferFront.dispose(),this._uniformBufferBack.dispose();let e=this._vertexBuffers[D.PositionKind];e&&(e.dispose(),this._vertexBuffers[D.PositionKind]=null),this.scene.getEngine()._releaseBuffer(this._indexBuffer),this._fillIndexBuffer&&(this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer),this._fillIndexBuffer=null),this._cleanupInstances()}}});function KSe(n){return!!n&&typeof n=="object"&&"node"in n&&"meshes"in n}function jSe(n){return n.uniqueId}function ZSe(n){return typeof n.isDisposed=="function"?n.isDisposed():!1}function x1(n){let e=Ql(n.meshes);return e?new b((e.min.x+e.max.x)/2,(e.min.y+e.max.y)/2,(e.min.z+e.max.z)/2):n.node.getAbsolutePosition().clone()}function qSe(n,e,t){let i=new Map;for(let r of e){let s=wE(n,r,e,t),a=i.get(s);a||(a={id:jSe(s),node:s,meshes:[]},i.set(s,a)),a.meshes.push(r)}return Array.from(i.values())}function _$(n,e,t,i,r){return Rx(new R1(n,e,t,i,r))}var Wd,R1,v$=y(()=>{"use strict";He();bN();$t();Xo();g$();xs();FE();yP();Wd=class Wd{constructor(e,t,i,r,s){this.meshToPart=new Map;this.occlusionDirection=b.Zero();this.occlusionRay=new on(b.Zero(),b.Zero(),1);this.lastOccluded=!1;this.selected=null;this.partPointerActive=!1;this.activePointerId=null;this.scene=e,this.camera=t,this.meshes=r,this.parts=qSe(i,r,s);for(let a of this.parts)for(let o of a.meshes)this.meshToPart.set(o.uniqueId,a);this.setBoundingBoxColor(Wd.BBOX_VISIBLE)}getParts(){return this.parts}getPartId(e){return e.id}isDisposed(e){return ZSe(e.node)||e.meshes.every(t=>t.isDisposed())}captureTransform(e){var t,i;return{parent:e.node.parent,position:e.node.position.clone(),rotation:e.node.rotation.clone(),rotationQuaternion:(i=(t=e.node.rotationQuaternion)==null?void 0:t.clone())!=null?i:null,scaling:e.node.scaling.clone()}}restoreTransform(e,t){var i,r;e.node.setParent(t.parent),e.node.position.copyFrom(t.position),e.node.rotation.copyFrom(t.rotation),e.node.rotationQuaternion=(r=(i=t.rotationQuaternion)==null?void 0:i.clone())!=null?r:null,e.node.scaling.copyFrom(t.scaling),e.node.computeWorldMatrix(!0);for(let s of e.meshes)s.computeWorldMatrix(!0)}subscribe(e){let t=this.scene.getEngine().getRenderingCanvas();t==null||t.classList.add("ai3d-disassembly-active");let i=this.scene.onPointerObservable.add(s=>{var o,l,c,f;let a=s.event;if(a.isPrimary!==!1){if(s.type===ot.POINTERDOWN){if(a.button!==0)return;let d=(l=(o=s.pickInfo)==null?void 0:o.pickedMesh)!=null?l:null;if(this.partPointerActive=!!this.resolvePart(d),this.partPointerActive){a.preventDefault(),a.stopPropagation(),this.activePointerId=a.pointerId;try{(c=t==null?void 0:t.setPointerCapture)==null||c.call(t,a.pointerId)}catch(u){}this.camera.detachControl()}e.onPointerDown(d,a)}else if(s.type===ot.POINTERMOVE){if(this.activePointerId!==null&&a.pointerId!==this.activePointerId)return;this.partPointerActive&&(a.preventDefault(),a.stopPropagation()),e.onPointerMove(a)}else if(s.type===ot.POINTERUP){if(this.activePointerId!==null&&a.pointerId!==this.activePointerId)return;if(this.partPointerActive&&(a.preventDefault(),a.stopPropagation()),e.onPointerUp(a),this.activePointerId!==null&&((f=t==null?void 0:t.hasPointerCapture)!=null&&f.call(t,this.activePointerId)))try{t.releasePointerCapture(this.activePointerId)}catch(d){}this.partPointerActive=!1,this.activePointerId=null,this.camera.attachControl(this.scene.getEngine().getRenderingCanvas(),!0)}}}),r=this.scene.onAfterRenderCameraObservable.add(s=>{s===this.camera&&e.onRender()});return()=>{var s;if(this.scene.onPointerObservable.remove(i),this.scene.onAfterRenderCameraObservable.remove(r),t==null||t.classList.remove("ai3d-disassembly-active","ai3d-disassembly-dragging"),this.activePointerId!==null&&((s=t==null?void 0:t.hasPointerCapture)!=null&&s.call(t,this.activePointerId)))try{t.releasePointerCapture(this.activePointerId)}catch(a){}this.partPointerActive=!1,this.activePointerId=null,this.camera.attachControl(t,!0)}}resolvePart(e){var t;return KSe(e)?this.parts.includes(e)?e:null:!e||typeof e!="object"?null:(t=this.meshToPart.get(e.uniqueId))!=null?t:null}setSelected(e){if(this.selected)for(let t of this.selected.meshes)t.isDisposed()||(t.showBoundingBox=!1);if(this.selected=e,this.lastOccluded=!1,this.setBoundingBoxColor(Wd.BBOX_VISIBLE),this.selected&&!this.isDisposed(this.selected))for(let t of this.selected.meshes)t.isDisposed()||(t.showBoundingBox=!0)}beginDrag(e,t){var o,l,c;let i=this.getPointOnDragPlane(e,t);if(!i)return null;t.preventDefault(),t.stopPropagation(),(o=this.scene.getEngine().getRenderingCanvas())==null||o.classList.add("ai3d-disassembly-dragging"),e.node.setParent(null),e.node.computeWorldMatrix(!0);for(let f of e.meshes)f.computeWorldMatrix(!0);t.shiftKey&&!e.node.rotationQuaternion&&(e.node.rotationQuaternion=je.FromEulerVector(e.node.rotation),e.node.rotation.set(0,0,0));let r=x1(e),s=Um(ct(i),ct(this.camera.getForwardRay().direction));if(!s)return null;let a={part:e,mode:t.shiftKey?"rotate":"move",plane:s,startPoint:i,startPosition:e.node.position.clone(),startRotationQuaternion:(c=(l=e.node.rotationQuaternion)==null?void 0:l.clone())!=null?c:null,pivot:r,pointerX:t.clientX,pointerY:t.clientY};return this.camera.detachControl(),a}updateDrag(e,t){if(t.preventDefault(),t.stopPropagation(),e.mode==="rotate"){this.updateRotation(e,t);return}let i=this.getRayPlanePoint(t,e.plane);if(!i)return;let r=i.subtract(e.startPoint);e.part.node.position=e.startPosition.add(r),e.part.node.computeWorldMatrix(!0);for(let s of e.part.meshes)s.computeWorldMatrix(!0)}endDrag(e){var t;(t=this.scene.getEngine().getRenderingCanvas())==null||t.classList.remove("ai3d-disassembly-dragging"),this.camera.attachControl(this.scene.getEngine().getRenderingCanvas(),!0)}updateSelectionOcclusion(e){let t=x1(e),i=this.camera.position,r=kf(ct(i),ct(t));if(!r)return;let s=this.occlusionDirection;s.set(r.direction.x,r.direction.y,r.direction.z),this.occlusionRay.origin=i,this.occlusionRay.direction=s,this.occlusionRay.length=r.distance;let a=this.scene.pickWithRay(this.occlusionRay),o=!!(a!=null&&a.hit)&&Gf(a.distance,r.distance,r.epsilon);o!==this.lastOccluded&&(this.lastOccluded=o,this.setBoundingBoxColor(o?Wd.BBOX_OCCLUDED:Wd.BBOX_VISIBLE))}setBoundingBoxColor(e){var i,r;let t=(r=(i=this.scene).getBoundingBoxRenderer)==null?void 0:r.call(i);t&&(t.frontColor=e,t.backColor=e)}updateRotation(e,t){if(!e.startRotationQuaternion)return;let i=t.clientX-e.pointerX,r=t.clientY-e.pointerY,s=WA({startPosition:ct(e.startPosition),pivot:ct(e.pivot),startRotationQuaternion:zA(e.startRotationQuaternion),yawAxis:ct(this.camera.getDirection(b.Up()).normalize()),pitchAxis:ct(this.camera.getDirection(b.Right()).normalize()),deltaX:i,deltaY:r,sensitivity:.01});if(s){e.part.node.position=new b(s.position.x,s.position.y,s.position.z),e.part.node.rotationQuaternion=new je(s.rotationQuaternion.x,s.rotationQuaternion.y,s.rotationQuaternion.z,s.rotationQuaternion.w),e.part.node.rotation.set(0,0,0),e.part.node.computeWorldMatrix(!0);for(let a of e.part.meshes)a.computeWorldMatrix(!0)}}getPointOnDragPlane(e,t){var s;let i=x1(e),r=Um(ct(i),ct(this.camera.getForwardRay().direction));return r&&(s=this.getRayPlanePoint(t,r))!=null?s:i}getRayPlanePoint(e,t){let i=this.scene.getEngine().getRenderingCanvas();if(!i)return null;let r=i.getBoundingClientRect(),s=e.clientX-r.left,a=e.clientY-r.top,o=this.scene.createPickingRay(s,a,Q.Identity(),this.camera),l=kA({origin:ct(o.origin),direction:ct(o.direction)},t);return l?new b(l.x,l.y,l.z):null}};Wd.BBOX_VISIBLE=new he(.25,.7,1),Wd.BBOX_OCCLUDED=new he(.1,.25,.4);R1=Wd});var C$={};Be(C$,{BabylonModelPreview:()=>Iy,createBabylonModelPreview:()=>_Te});function b$(n,e,t){let i=t.x-e.x,r=t.y-e.y,s=i*i+r*r;if(s<=Number.EPSILON)return Math.hypot(n.x-e.x,n.y-e.y);let a=Math.max(0,Math.min(1,((n.x-e.x)*i+(n.y-e.y)*r)/s));return Math.hypot(n.x-(e.x+i*a),n.y-(e.y+r*a))}function fTe(n){let e=n.getClassName();return e==="DirectionalLight"||e==="PointLight"||e==="SpotLight"}function b1(n){return n.getClassName()==="GaussianSplattingMesh"}function dTe(n){return!!n&&typeof n=="object"&&"getBoundingInfo"in n}function M$(n){return n instanceof ii}function hf(n){return typeof n.isDisposed=="function"?n.isDisposed():!1}function xg(n,e){let t=n;for(;t;){if(t===e)return!0;t=t.parent}return!1}function M1(n,e=[]){for(let t of n)t.isDisposed()||t.dispose(!0,!0);for(let t of e)t.isDisposed()||t.dispose(!1,!0)}function go(n){return new b(n.x,n.y,n.z)}function y$(n){return Number.isFinite(n)?Math.max(0,Math.min(n,1)):0}function I$(n){let e=new We("measure-marker-mat",n);return e.diffuseColor=UE.clone(),e.emissiveColor=UE.clone(),e.specularColor=new he(0,0,0),e.disableLighting=!0,e.alpha=.48,e}function BE(n,e){let t=n.material;t&&(t.diffuseColor=e.clone(),t.emissiveColor=e.clone())}function uTe(n){let e=n.replace(/\s+#.*$/,"").trim();if(e.startsWith('"')){let t=e.indexOf('"',1);if(t>1)return e.slice(1,t)}return e}function hTe(n){let e=n.trim().split(/\s+/),t=e.findIndex(i=>!i.startsWith("-")&&!/^[-+]?\d*\.?\d+$/.test(i));return e.slice(Math.max(0,t)).join(" ").replace(/^"|"$/g,"")}function mTe(n){var t,i;let e=(i=(t=n.split(".").pop())==null?void 0:t.toLowerCase())!=null?i:"png";return e==="jpg"||e==="jpeg"?"image/jpeg":e==="png"?"image/png":e==="bmp"?"image/bmp":e==="tga"?"image/x-tga":e==="webp"?"image/webp":`image/${e}`}function pTe(n,e,t){let i=Qs(e),r=i.replace(/\.[^.]+$/,""),s=gn(t),a=[Nn(n,e),Nn(n,i)];if(s)for(let o of E$)a.push(Nn(n,`${s}.${o}`));for(let o of E$){let l=`${r}.${o}`;l!==i&&a.push(Nn(n,l))}return a}function gTe(n){return Number.isFinite(n)?n.toPrecision(10):String(n)}function _Te(n){return new Iy(n)}var yy,E$,QSe,$Se,JSe,S$,UE,eTe,tTe,T$,iTe,rTe,nTe,sTe,aTe,A$,x$,R$,oTe,lTe,cTe,Ga,Iy,P$=y(()=>{"use strict";zD();na();Eb();Sb();d4();u4();uO();He();Gu();$t();ki();cd();QO();vr();qi();lf();QY();bN();OM();l9();tO();ug();OE();OE();zF();WF();bQ();i$();FA();Ma();As();r$();v$();FE();Lo();HA();hP();iv();xs();qA();ev();sv();bP();yy=null,E$=["jpg","jpeg","png","bmp","tga","webp","tif","tiff"],QSe=/^\s*(map_Kd|map_Ka|map_Ks|map_Ns|map_d|map_bump|bump|disp|decal)\s+(.+)/i,$Se=.242,JSe=320,S$=new he(.97,.98,.99),UE=new he(.97,.98,.99),eTe=new he(.96,.62,.04),tTe=new he(1,1,1),T$=new he(.9,.91,.92),iTe=new he(.22,.74,.97),rTe=new he(.58,.77,.99),nTe=new he(.88,.95,1),sTe=new he(.96,.62,.04),aTe=new he(.99,.83,.3),A$=new he(.94,.27,.27),x$=new he(.13,.77,.37),R$=new he(.23,.51,.96),oTe=new he(.97,.98,.99),lTe=new he(.98,.8,.08),cTe=.32;Ga=class Ga{constructor(e){this.rootMesh=null;this.loadedMeshes=[];this.loadedTransformNodes=[];this.cachedRenderableMeshes=null;this.cachedRenderableRoot=null;this.loadedExt="";this.rendering=!1;this.contextLost=!1;this.viewportVisible=!0;this.viewportObserver=null;this.cleanupPicking=null;this.configLights=[];this.shadowGenerator=null;this.groundMesh=null;this.gridMesh=null;this.axisMeshes=[];this.autoRotateBehavior=null;this.sliceAutoRotatePaused=!1;this.wireframeEnabled=!1;this.sliceActive=!1;this.sliceNormal=new b(Dr.x,Dr.y,Dr.z);this.slicePlaneX=new b(1,0,0);this.slicePlaneY=new b(0,0,-1);this.sliceCenter=null;this.sliceReferenceNormal=new b(Dr.x,Dr.y,Dr.z);this.sliceOffset=Il;this.sliceInteractionMode=Xf;this.sliceThickness=Hm;this.slicePlane=null;this.sliceOverlayPlanes=[];this.sliceOverlayLines=[];this.sliceOverlayLabels=[];this.sliceRotationLabel=null;this.sliceRotationLabelText="";this.sliceDragState=null;this.pendingSliceMove=null;this.sliceMoveFrame=0;this.sliceObservers=new Set;this.sliceOriginalMaterialClipping=new Map;this.gizmo=null;this.gizmoEnabled=!1;this.disassembly=null;this.focusSelectionEnabled=!1;this.focusedNode=null;this.originalMeshVisibility=new Map;this.bboxMesh=null;this.bboxEnabled=!1;this.currentQuality="high";this.renderScale=1;this.resourceWarnings=[];this.gltfComponentMetadata=new Map;this.animPlaying=!1;this.initialCamera={alpha:Math.PI/4,beta:Math.PI/3,radius:5,target:b.Zero()};this.focusWorldPointFrame=0;this._lastPickResult={mesh:null,pickedPoint:null,screenX:0,screenY:0};this._onPickCallbacks=[];this.measurementActive=!1;this.measurementScale={x:1,y:1,z:1};this.measurementBaseRootScaling=new b(1,1,1);this.measurementBaseBounds=null;this.measurementUnit="mm";this.measurementSegments=[];this.measurementMarkers=[];this.measurementMarkerPoints=[];this.measurementTargetNode=null;this.measurementTargetMeshes=[];this.measurementSnapInputCache=null;this.measurementSnapInputCacheTargetId=null;this.measurementSnapInputCacheSignature=null;this.measurementSnapKind=null;this.measurementObservers=new Set;this.pendingPoint=null;this.pendingMarker=null;this.hoveredMarkerIndex=-1;this.lastPointerClient={x:0,y:0,altKey:!1};this.previewLine=null;this.cameraZoomObservers=new Set;this.handlePointerDown=e=>{e.button!==0||e.isPrimary===!1||this.sliceActive&&this.beginSliceDrag(e)};this.handlePointerUp=e=>{e.button!==0||e.isPrimary===!1||this.endSliceDrag(e)};this.handlePointerMove=e=>{if(this.lastPointerClient={x:e.clientX,y:e.clientY,altKey:e.altKey},this.updateSliceDrag(e)||!this.measurementActive||(this.pendingPoint&&this.updatePreviewLine(),this.measurementMarkers.length===0))return;let t=this.engine.getRenderingCanvas();if(!t)return;let i=t.getBoundingClientRect(),r=e.clientX-i.left,s=e.clientY-i.top,a=this.scene.pick(r,s,l=>this.measurementMarkers.includes(l)),o=a.hit?this.measurementMarkers.indexOf(a.pickedMesh):-1;if(o!==this.hoveredMarkerIndex){if(this.hoveredMarkerIndex>=0&&this.hoveredMarkerIndex<this.measurementMarkers.length){let l=this.measurementMarkers[this.hoveredMarkerIndex];l!==this.pendingMarker&&(l.scaling.setAll(1),BE(l,UE))}if(o>=0&&o<this.measurementMarkers.length){let l=this.measurementMarkers[o];l.scaling.setAll(1.6),BE(l,tTe)}this.hoveredMarkerIndex=o}};this.handlePointerCancel=e=>{this.endSliceDrag(e,!0)};this.handlePointerCaptureLost=e=>{this.endSliceDrag(e,!0)};this.preventCanvasWheelScroll=e=>{e.preventDefault(),e.stopPropagation()};this.handleMeasurementModifierKey=e=>{e.key==="Alt"&&this.updateMeasurementModifierAltKey(e.type==="keydown")};this.handleMeasurementModifierBlur=()=>{this.updateMeasurementModifierAltKey(!1),this.endSliceDrag(null,!0)};this.handleViewportIntersection=e=>{let t=e.some(i=>i.isIntersecting);t!==this.viewportVisible&&(this.viewportVisible=t,t?this.startRenderLoop():this.rendering&&(this.engine.stopRenderLoop(),this.rendering=!1))};this.handleContextLost=e=>{e.preventDefault(),this.contextLost=!0,this.rendering&&(this.engine.stopRenderLoop(),this.rendering=!1)};this.handleContextRestored=()=>{this.contextLost=!1,this.engine.resize(),this.startRenderLoop()};this.engine=new ze(e,!0,{preserveDrawingBuffer:!0}),this.scene=new ai(this.engine),this.scene.clearColor=new ht(.12,.12,.14,1),this.scene.setRenderingAutoClearDepthStencil(2,!0,!0,!0),this.camera=new Mi("cam",Math.PI/4,Math.PI/3,5,b.Zero(),this.scene),this.camera.attachControl(e,!0),this.camera.lowerRadiusLimit=.1,this.camera.wheelPrecision=45,this.camera.onViewMatrixChangedObservable.add(()=>{this.measurementSegments.length>0&&this.updateMeasurementOverlayPositions(),this.notifyCameraZoomChanged()}),e.addEventListener("wheel",this.preventCanvasWheelScroll,{passive:!1}),e.addEventListener("pointerdown",this.handlePointerDown,!0),e.addEventListener("pointerup",this.handlePointerUp,!0),e.addEventListener("pointermove",this.handlePointerMove,!0),e.addEventListener("pointercancel",this.handlePointerCancel,!0),e.addEventListener("lostpointercapture",this.handlePointerCaptureLost,!0),e.addEventListener("webglcontextlost",this.handleContextLost),e.addEventListener("webglcontextrestored",this.handleContextRestored),window.addEventListener("keydown",this.handleMeasurementModifierKey),window.addEventListener("keyup",this.handleMeasurementModifierKey),window.addEventListener("blur",this.handleMeasurementModifierBlur),this.scene.ambientColor=new he(.3,.3,.3);let t=new Fa("default-light",new b(0,1,.5),this.scene);t.intensity=1.2,this.resizeObs=new ResizeObserver(()=>this.engine.resize()),this.resizeObs.observe(e),typeof IntersectionObserver!="undefined"&&(this.viewportObserver=new IntersectionObserver(this.handleViewportIntersection,{root:null,threshold:[0,.01]}),this.viewportObserver.observe(e)),window.requestAnimationFrame(()=>this.engine.resize())}canRender(){let e=this.engine.getRenderingCanvas();return!!(e!=null&&e.isConnected)&&e.clientWidth>0&&e.clientHeight>0}getCameraZoomRange(){if(!this.rootMesh)return null;let e=this.camera.radius,t=this.camera.lowerRadiusLimit,i=this.camera.upperRadiusLimit,r=typeof t=="number"&&Number.isFinite(t)&&t>0?t:Math.max(e*.08,1e-5),s=typeof i=="number"&&Number.isFinite(i)&&i>r?i:Math.max(e*8,r*10);return{current:Math.max(r,Math.min(e,s)),min:r,max:s}}notifyCameraZoomChanged(){if(this.cameraZoomObservers.size===0)return;let e=this.getCameraZoomState();for(let t of this.cameraZoomObservers)t(e)}ensureDisassemblyController(){return this.rootMesh?(this.disassembly||(this.disassembly=_$(this.scene,this.camera,this.rootMesh,this.getRenderableMeshes(this.rootMesh),this.gltfComponentMetadata)),this.disassembly):null}isDisassemblyActive(){var e,t;return(t=(e=this.disassembly)==null?void 0:e.isEnabled())!=null?t:!1}async loadModel(e,t,i,r,s){var g,p,_,v;xi(s),await DE(),xi(s),this.rootMesh&&((g=this.engine.getRenderingCanvas())==null||g.classList.remove("ai3d-slice-active","ai3d-slice-dragging","ai3d-slice-rotate"),this.restoreSliceMaterialClipping(),this.disposeSliceOverlay(!1),M1(this.loadedMeshes,this.loadedTransformNodes),this.rootMesh=null,this.notifyCameraZoomChanged()),this.invalidateMeshCache(),this.loadedMeshes=[],this.loadedTransformNodes=[],this.disposeMeasurementOverlays(!0),this.resetMeasurementCalibrationState(),(p=this.disassembly)==null||p.dispose(),this.disassembly=null,this.clearFocusedMesh(),this.originalMeshVisibility.clear();let a=t.toLowerCase().replace(".","");this.loadedExt=a,this.resourceWarnings=[],xi(s),this.gltfComponentMetadata=xQ(e,a);let o=this.scene,c=(_={glb:".glb",gltf:".gltf",stl:".stl",obj:".obj",splat:".splat",ply:".ply"}[a])!=null?_:`.${a}`;xi(s);let f=`data:application/octet-stream;base64,${Iu(e)}`;xi(s);let d=E=>{try{xi(s)}catch(S){throw M1(E.meshes,E.transformNodes),S}this.loadedMeshes=E.meshes,this.loadedTransformNodes=E.transformNodes,E.meshes.length>0&&(this.rootMesh=E.meshes[0])},u=()=>{try{xi(s)}catch(E){throw M1(this.loadedMeshes,this.loadedTransformNodes),this.loadedMeshes=[],this.loadedTransformNodes=[],this.rootMesh=null,this.invalidateMeshCache(),this.notifyCameraZoomChanged(),E}};if(a==="obj"&&i&&r){yy&&await yy,xi(s);let E;yy=new Promise(S=>{E=S});try{let{OBJFileLoader:S}=await Promise.resolve().then(()=>(GF(),fQ)),T=S.prototype;typeof T._loadMTL!="function"&&console.warn("[AI3D] OBJFileLoader._loadMTL not found \u2014 MTL vault resolution disabled");let A=T._loadMTL,M=new TextDecoder().decode(new Uint8Array(e)).match(/mtllib\s+(.+)/),I=null;if(M&&i&&r){let L=uTe(M[1]),w=J_(r),G=Nn(w,L);try{let O=await i(G);xi(s);let B=new TextDecoder().decode(new Uint8Array(O)).split(`
`);for(let K=0;K<B.length;K++){let J=B[K].match(QSe);if(!J)continue;let Y=hTe(J[2]),j=pTe(w,Y,r),ue=!1;for(let Ee of j)try{xi(s);let Ue=await i(Ee);xi(s);let se=`data:${mTe(Ee)};base64,${Iu(Ue)}`;B[K]=`${J[1]} ${se}`,ue=!0;break}catch(Ue){if(Vf(Ue))throw Ue}ue||(this.resourceWarnings.push(`OBJ material texture not found: ${Y}`),B[K]="")}let V=B.filter(K=>K!=="");if(!V.some(K=>/^\s*Kd\s+/i.test(K))){let K=V.findIndex(J=>/^\s*newmtl\s+/i.test(J));V.splice(K>=0?K+1:0,0,"Kd 0.80 0.80 0.80")}I=V.join(`
`)}catch(O){if(Vf(O))throw O;this.resourceWarnings.push(`OBJ material library not found: ${G}`)}}T._loadMTL=function(L,w,G){let O=I!=null?I:"";G(O)};let C=await TE(f,o,{meshNames:"",pluginExtension:c});d(C),T._loadMTL=A}catch(S){throw Vf(S)||console.error("[AI3D] OBJ load error:",S),S}finally{E(),yy=null}}else if(a==="stl"){let E=mQ(o,e);try{xi(s)}catch(S){throw E==null||E.dispose(!1,!0),S}this.rootMesh=E,this.rootMesh&&(this.loadedMeshes=[this.rootMesh])}else if(a==="ply"){let E=gQ(o,e);try{xi(s)}catch(S){throw E==null||E.dispose(!1,!0),S}this.rootMesh=E,this.rootMesh&&(this.loadedMeshes=[this.rootMesh])}else{let E=await TE(f,o,{meshNames:"",pluginExtension:c});d(E)}if(u(),!this.rootMesh)throw new Error("No mesh found in model file");let h=this.getRenderableBounds(this.rootMesh);this.captureMeasurementBaseState(this.rootMesh,h);for(let E of this.getRenderableMeshes(this.rootMesh))E.material&&(E.material.backFaceCulling=!1);this.syncSliceClipping(),this.notifySliceChanged();let m=tv(h);return this.camera.target=go(m.target),this.camera.radius=m.radius,this.camera.lowerRadiusLimit=m.lowerRadiusLimit,this.camera.upperRadiusLimit=m.upperRadiusLimit,this.camera.minZ=m.near,this.camera.maxZ=m.far,this.initialCamera={alpha:this.camera.alpha,beta:this.camera.beta,radius:this.camera.radius,target:this.camera.target.clone()},this.notifyCameraZoomChanged(),this.startRenderLoop(),this.engine.resize(),(v=this.cleanupPicking)==null||v.call(this),this.cleanupPicking=t$(this.scene,E=>{var A,R,M;if(this.sliceActive||this.isDisassemblyActive())return;let S=E.mesh&&this.rootMesh?wE(this.rootMesh,E.mesh,this.getRenderableMeshes(this.rootMesh),this.gltfComponentMetadata):null,T={mesh:S,pickedPoint:E.pickedPoint,screenX:E.screenX,screenY:E.screenY,modifiers:E.modifiers};if(this.lastPointerClient={x:E.screenX,y:E.screenY,altKey:((A=E.modifiers)==null?void 0:A.altKey)===!0},this._lastPickResult=T,this.measurementActive){if(((R=E.modifiers)==null?void 0:R.altKey)===!0){if(!E.pickedPoint)return;this.setMeasurementSnapKind("free"),this.addMeasurementPoint(go(E.pickedPoint));return}if(!this.measurementTargetNode){S&&this.setMeasurementTargetNode(S);return}let I=this.getMeasurementTargetPickPoint(E.mesh,E.pickedPoint);if(!I){this.setMeasurementSnapKind(null);return}this.addMeasurementPoint(this.resolveMeasurementPickPoint(I,!1));return}this.focusSelectionEnabled&&(S?this.setFocusedNode(S):(M=this.cleanupPicking)==null||M.clearHighlight()),this._onPickCallbacks.forEach(I=>I(T))},()=>!this.focusSelectionEnabled&&!this.measurementActive&&!this.sliceActive,E=>this.resolvePickHighlightMeshes(E)),this.ensureDisassemblyController(),this.createModelSummary(this.rootMesh)}applyConfig(e){e.camera&&this.applyCameraConfig(e.camera),e.lights&&this.applyLightConfig(e.lights),e.scene&&this.applySceneConfig(e.scene),e.stl&&this.loadedExt==="stl"&&(e.stl.color&&this.setSTLColor(e.stl.color),e.stl.wireframe!==void 0&&this.setWireframe(e.stl.wireframe))}applyCameraConfig(e){var i;let t=this.engine.getRenderingCanvas();if(t){if(e.mode==="orthographic"){let r=this.camera.radius,s=t.clientWidth/t.clientHeight,a=(i=e.zoom)!=null?i:1,o=r/a;this.camera.mode=1,this.camera.orthoLeft=-o*s,this.camera.orthoRight=o*s,this.camera.orthoTop=o,this.camera.orthoBottom=-o}else this.camera.mode=0,e.fov&&(this.camera.fov=e.fov*Math.PI/180);if(e.position){let[r,s,a]=e.position;this.camera.setPosition(new b(r,s,a))}if(e.lookAt){let[r,s,a]=e.lookAt;this.camera.setTarget(new b(r,s,a))}e.near!==void 0&&(this.camera.minZ=e.near),e.far!==void 0&&(this.camera.maxZ=e.far),this.notifyCameraZoomChanged()}}applyLightConfig(e){var i;for(let r of this.configLights)r.dispose();this.configLights=[],(i=this.shadowGenerator)==null||i.dispose(),this.shadowGenerator=null;let t=this.scene.getLightByName("default-light");t&&t.dispose();for(let r of e){let s=this.createLight(r);s&&this.configLights.push(s)}}createLight(e){var r,s;let t=e.color?he.FromHexString(e.color):he.White(),i=(r=e.intensity)!=null?r:1;switch(e.type){case"hemisphere":{let a=e.groundColor?he.FromHexString(e.groundColor):new he(.2,.2,.2),o=new Fa("hemi",new b(0,1,0),this.scene);return o.diffuse=t,o.groundColor=a,o.intensity=i,o}case"directional":{let a=e.position?new b(...e.position).normalize():new b(-1,-2,-1).normalize(),o=new ca("dir",a,this.scene);return o.diffuse=t,o.intensity=i,e.castShadow&&this.rootMesh&&this.setupShadow(o),o}case"point":{let a=e.position?new b(...e.position):new b(0,5,0),o=new Sd("point",a,this.scene);return o.diffuse=t,o.intensity=i,e.decay!==void 0&&(o.decay=e.decay),o}case"spot":{let a=e.position?new b(...e.position):new b(0,5,0),l=(e.target?new b(...e.target):b.Zero()).subtract(a).normalize(),c=e.angle?e.angle*Math.PI/180:Math.PI/4,f=(s=e.penumbra)!=null?s:.5,d=new Zr("spot",a,l,c,f,this.scene);return d.diffuse=t,d.intensity=i,e.decay!==void 0&&(d.decay=e.decay),e.castShadow&&this.rootMesh&&this.setupShadow(d),d}case"attachToCam":{let a=new Sd("cam-light",b.Zero(),this.scene);return a.diffuse=t,a.intensity=i,a.parent=this.camera,a}default:return null}}setupShadow(e){if(!this.rootMesh)return;if(!fTe(e)){console.warn("[AI3D] Light type does not support shadows:",e.name);return}let t=new zi(1024,e);t.useBlurExponentialShadowMap=!0,t.blurKernel=32;for(let i of this.getRenderableMeshes(this.rootMesh))t.addShadowCaster(i),i.receiveShadows=!0;this.shadowGenerator=t}applySceneConfig(e){var t,i;if(e.background!==void 0){let r=ht.FromColor3(he.FromHexString(e.background),e.transparent?0:1);this.scene.clearColor=r}e.autoRotate===!0?this.autoRotateBehavior?this.autoRotateBehavior.idleRotationSpeed=(i=e.autoRotateSpeed)!=null?i:.5:(this.autoRotateBehavior=new qp,this.autoRotateBehavior.idleRotationSpeed=(t=e.autoRotateSpeed)!=null?t:.5,this.autoRotateBehavior.idleRotationWaitTime=1e3,this.autoRotateBehavior.idleRotationSpinupTime=500,this.sliceDragState?this.sliceAutoRotatePaused=!0:this.camera.addBehavior(this.autoRotateBehavior)):e.autoRotate===!1&&this.autoRotateBehavior&&(this.sliceAutoRotatePaused||this.camera.removeBehavior(this.autoRotateBehavior),this.autoRotateBehavior=null,this.sliceAutoRotatePaused=!1),e.groundShadow&&this.rootMesh&&this.createGround(),e.grid&&this.createGrid(),e.axis&&this.createAxis()}createGround(){if(!this.rootMesh||this.groundMesh)return;let e=this.getRenderableBounds(this.rootMesh),t=Ui(e),i=Math.max(t.x,t.z)*3,r=e.min.y;this.groundMesh=Pn.CreateGround("ground",{width:i,height:i},this.scene),this.groundMesh.position.y=r;let s=new We("ground-mat",this.scene);s.diffuseColor=new he(.15,.15,.15),s.specularColor=he.Black(),s.alpha=.5,this.groundMesh.material=s,this.groundMesh.receiveShadows=!0}createGrid(){if(!this.rootMesh||this.gridMesh)return;let e=this.getRenderableBounds(this.rootMesh),t=Ui(e),i=Math.max(t.x,t.z)*2,r=e.min.y-.01;this.gridMesh=Pn.CreateGround("grid",{width:i,height:i,subdivisions:20},this.scene),this.gridMesh.position.y=r;let s=new We("grid-mat",this.scene);s.wireframe=!0,s.diffuseColor=new he(.3,.3,.3),s.emissiveColor=new he(.1,.1,.1),this.gridMesh.material=s}createAxis(){if(!this.rootMesh||this.axisMeshes.length>0)return;let e=this.getRenderableBounds(this.rootMesh),t=aV(e)*1.5,i=go(e.min),r=Rs(e)*.01,s=[["x",he.Red(),new b(t,0,0)],["y",he.Green(),new b(0,t,0)],["z",he.Blue(),new b(0,0,t)]];for(let[a,o,l]of s){let c=Pn.CreateTube(`axis-${a}`,{path:[i,i.add(l)],radius:r,tessellation:8},this.scene),f=new We(`axis-${a}-mat`,this.scene);f.emissiveColor=o,f.diffuseColor=he.Black(),c.material=f,this.axisMeshes.push(c)}}setSTLColor(e){if(!this.rootMesh)return;let t=he.FromHexString(e);for(let i of this.getRenderableMeshes(this.rootMesh))if(i.material&&i.material.name==="stl-mat"){let r=i.material;r.diffuseColor=t,r.emissiveColor=t.scale(.1)}}setWireframe(e){this.rootMesh&&(b1(this.rootMesh)||(this.wireframeEnabled=e,this.scene.forceWireframe=e))}toggleWireframe(){return this.setWireframe(!this.wireframeEnabled),this.wireframeEnabled}hasAnimations(){return this.scene.animationGroups.length>0}toggleAnimation(){let e=this.scene.animationGroups;if(e.length===0)return!1;this.animPlaying=!this.animPlaying;for(let t of e)this.animPlaying?t.play(!0):t.pause();return this.animPlaying}toggleMeasurement(){var t;if(this.measurementActive)return this.deactivateMeasurementMode(),!1;this.isDisassemblyActive()&&this.disableDisassemblyAndReset(),this.deactivateSliceMode();let e=this.getCurrentMeasurementTargetNode();return(t=this.cleanupPicking)==null||t.clearHighlight(),this.clearFocusedMesh(),this.focusSelectionEnabled&&(this.focusSelectionEnabled=!1),this.measurementActive=!0,this.setMeasurementTargetNode(e,!1),Wf(this.engine.getRenderingCanvas(),this.measurementActive),this.notifyMeasurementsChanged(),this.measurementActive}isMeasurementActive(){return this.measurementActive}clearMeasurements(){this.disposeMeasurementOverlays(!1)}cancelMeasurement(){let e=!!this.pendingPoint;this.cancelPendingMeasurement(),e&&this.notifyMeasurementsChanged()}deactivateMeasurementMode(){return this.measurementActive?(this.measurementActive=!1,Wf(this.engine.getRenderingCanvas(),!1),this.setMeasurementTargetNode(null,!1),this.cancelPendingMeasurement(),this.notifyMeasurementsChanged(),!0):!1}disposeMeasurementOverlays(e){e&&(this.measurementActive=!1,Wf(this.engine.getRenderingCanvas(),!1),this.setMeasurementTargetNode(null,!1)),this.cancelPendingMeasurement(!1);for(let t of this.measurementSegments)t.line.dispose(!1,!0),t.label.dispose(!1,!0);this.measurementSegments=[];for(let t of this.measurementMarkers)t.dispose(!1,!0);this.measurementMarkers=[],this.measurementMarkerPoints=[],this.setMeasurementSnapKind(null,!1),this.notifyMeasurementsChanged()}setMeasurementScale(e){this.measurementScale=Ms(e),this.invalidateMeasurementSnapInputCache(),this.applyMeasurementModelScale(),this.sliceActive&&(this.setSliceCenterFromOffset(this.sliceOffset),this.syncSliceClipping()),this.updateMeasurementOverlayPositions(),this.updateMeasurementLabels(),this.notifyMeasurementsChanged()}getMeasurementScale(){return{...this.measurementScale}}setMeasurementUnit(e){this.measurementUnit=rv(e),this.updateMeasurementLabels(),this.notifyMeasurementsChanged()}getMeasurementUnit(){return this.measurementUnit}getMeasurementBounds(){var t;if(!this.rootMesh)return null;let e=(t=this.measurementBaseBounds)!=null?t:this.getRenderableBounds(this.rootMesh);return e?{x:e.max.x-e.min.x,y:e.max.y-e.min.y,z:e.max.z-e.min.z}:null}getMeasurementRecords(){return this.createMeasurementRecords()}getMeasurementState(){return fx({active:this.measurementActive,pending:!!this.pendingPoint,records:this.createMeasurementRecords(),unit:this.measurementUnit,scale:this.getMeasurementScale(),bounds:this.getMeasurementBounds(),targetLocked:!!this.measurementTargetNode,targetName:this.getMeasurementTargetName(),targetScope:this.measurementTargetNode===this.rootMesh?"model":"part",snapKind:this.measurementSnapKind})}exportMeasurements(){return hx(this.createMeasurementRecords())}observeMeasurements(e){return this.measurementObservers.add(e),e(),()=>{this.measurementObservers.delete(e)}}updateMeasurementLabels(){var t;if(this.measurementSegments.length===0)return;let e=this.getMeasurementMarkerSize()*3.2;for(let i of this.measurementSegments){this.updateMeasurementLineGeometry(i);let r=Wm(this.createMeasurementReading(i.start,i.end));i.label.dispose(!1,!0);let s=this.createBabylonMeasurementDraftingLayout(i.start,i.end),a=(t=s==null?void 0:s.labelPosition)!=null?t:b.Center(this.toMeasurementDisplayPoint(i.start),this.toMeasurementDisplayPoint(i.end));i.label=this.createMeasurementLabelMesh(r,a,e)}}captureMeasurementBaseState(e,t){this.measurementBaseRootScaling=e.scaling.clone(),this.measurementBaseBounds=t?Za(t.min,t.max):null,this.measurementScale={x:1,y:1,z:1}}resetMeasurementCalibrationState(){this.measurementScale={x:1,y:1,z:1},this.measurementBaseRootScaling=new b(1,1,1),this.measurementBaseBounds=null,this.measurementMarkerPoints=[],this.invalidateMeasurementSnapInputCache()}applyMeasurementModelScale(){if(!this.rootMesh)return;let e=Ms(this.measurementScale);this.rootMesh.scaling=new b(this.measurementBaseRootScaling.x*e.x,this.measurementBaseRootScaling.y*e.y,this.measurementBaseRootScaling.z*e.z),this.rootMesh.computeWorldMatrix(!0);for(let t of this.loadedMeshes)t.computeWorldMatrix(!0);this.invalidateMeshCache(),this.rebuildScaledSceneHelpers(),this.refitCameraToModel(),this.startRenderLoop()}rebuildScaledSceneHelpers(){var s,a,o;let e=!!this.bboxMesh,t=!!this.groundMesh,i=!!this.gridMesh,r=this.axisMeshes.length>0;(s=this.bboxMesh)==null||s.dispose(),this.bboxMesh=null,(a=this.groundMesh)==null||a.dispose(),this.groundMesh=null,(o=this.gridMesh)==null||o.dispose(),this.gridMesh=null;for(let l of this.axisMeshes)l.dispose();if(this.axisMeshes=[],e&&this.rootMesh){let l=this.getRenderableBounds(this.rootMesh),c=go(mr(l)),f=go(Ui(l));this.bboxMesh=Pn.CreateBox("bbox",{width:f.x,height:f.y,depth:f.z},this.scene),this.bboxMesh.position=c;let d=new We("bbox-mat",this.scene);d.wireframe=!0,d.emissiveColor=new he(1,1,0),d.disableLighting=!0,d.alpha=.6,this.bboxMesh.material=d}t&&this.createGround(),i&&this.createGrid(),r&&this.createAxis()}refitCameraToModel(){if(!this.rootMesh)return;let e=tv(this.getRenderableBounds(this.rootMesh));this.camera.target=go(e.target),this.camera.radius=e.radius,this.camera.lowerRadiusLimit=e.lowerRadiusLimit,this.camera.upperRadiusLimit=e.upperRadiusLimit,this.camera.minZ=e.near,this.camera.maxZ=e.far,this.initialCamera={alpha:this.camera.alpha,beta:this.camera.beta,radius:this.camera.radius,target:this.camera.target.clone()},this.notifyCameraZoomChanged()}getMeasurementPivot(){var e,t;return(t=(e=this.rootMesh)==null?void 0:e.getAbsolutePosition().clone())!=null?t:b.Zero()}toMeasurementDisplayPoint(e){let t=rx(e,this.getMeasurementPivot(),this.measurementScale);return new b(t.x,t.y,t.z)}toMeasurementBasePoint(e){let t=nx(e,this.getMeasurementPivot(),this.measurementScale);return new b(t.x,t.y,t.z)}updateMeasurementOverlayPositions(){for(let e=0;e<this.measurementMarkers.length;e++){let t=this.measurementMarkerPoints[e];t&&(this.measurementMarkers[e].position=this.toMeasurementDisplayPoint(t))}for(let e of this.measurementSegments)this.updateMeasurementLineGeometry(e);this.pendingPoint&&this.previewLine&&this.updatePreviewLine()}updateMeasurementLineGeometry(e){var r;let t=this.createBabylonMeasurementDraftingLayout(e.start,e.end),i=(r=t==null?void 0:t.lineSegments)!=null?r:[[this.toMeasurementDisplayPoint(e.start),this.toMeasurementDisplayPoint(e.end)]];e.line=Pn.CreateLineSystem("measure-line",{lines:i,instance:e.line},this.scene),e.line.isPickable=!1,e.line.renderingGroupId=2,e.line.color=S$.clone(),e.line.alpha=1,t&&(e.label.position=t.labelPosition)}notifyMeasurementsChanged(){for(let e of Array.from(this.measurementObservers))e()}setAnimationSpeed(e){for(let t of this.scene.animationGroups)t.speedRatio=e}captureSnapshot(){let e=this.engine.getRenderingCanvas();return e?(this.scene.render(),e.toDataURL("image/png")):null}toggleOrientationGizmo(){return this.gizmoEnabled=!this.gizmoEnabled,this.gizmoEnabled&&!this.gizmo&&(this.gizmo=new by(this.engine,this.camera)),this.gizmoEnabled}isOrientationGizmoEnabled(){return this.gizmoEnabled}setRenderScale(e){let t=Math.max(.25,Math.min(e,2));this.renderScale=t;let i={low:2,medium:1.33,high:1}[this.currentQuality],r=Rr()?1.5:1;return this.engine.setHardwareScalingLevel(i*r/t),this.getRenderScale()}getRenderScale(){return Number(this.renderScale.toFixed(2))}getCameraZoomState(){let e=this.getCameraZoomRange();if(!e)return null;let t=(e.max-e.current)/(e.max-e.min),i=y$(t);return{value:i,percentage:Math.round(i*100)}}setCameraZoom(e){let t=this.getCameraZoomRange();if(!t)return null;let i=y$(e);return this.camera.radius=t.max-i*(t.max-t.min),this.startRenderLoop(),this.notifyCameraZoomChanged(),this.getCameraZoomState()}observeCameraZoom(e){return this.cameraZoomObservers.add(e),e(this.getCameraZoomState()),()=>{this.cameraZoomObservers.delete(e)}}getPerformanceSnapshot(){return{backend:"babylon",renderScale:Number((1/this.engine.getHardwareScalingLevel()).toFixed(2)),quality:this.currentQuality,meshCount:this.rootMesh?this.getRenderableMeshes(this.rootMesh).length:0}}toggleBoundingBox(){var e;if(this.bboxEnabled=!this.bboxEnabled,this.bboxEnabled){if(!this.rootMesh)return this.bboxEnabled;this.bboxMesh&&this.bboxMesh.dispose();let t=this.getRenderableBounds(this.rootMesh),i=go(mr(t)),r=go(Ui(t));this.bboxMesh=Pn.CreateBox("bbox",{width:r.x,height:r.y,depth:r.z},this.scene),this.bboxMesh.position=i;let s=new We("bbox-mat",this.scene);s.wireframe=!0,s.emissiveColor=new he(1,1,0),s.disableLighting=!0,s.alpha=.6,this.bboxMesh.material=s}else(e=this.bboxMesh)==null||e.dispose(),this.bboxMesh=null;return this.bboxEnabled}toggleSlice(){var e;return this.sliceActive?(this.deactivateSliceMode(),!1):(this.disableDisassemblyAndReset(),this.deactivateMeasurementMode(),this.focusSelectionEnabled&&(this.focusSelectionEnabled=!1,this.clearFocusedMesh(),(e=this.cleanupPicking)==null||e.clearHighlight()),this.alignSlicePlaneToWorld(),this.sliceInteractionMode=Xf,this.sliceActive=!0,this.syncSliceClipping(),this.notifySliceChanged(),this.sliceActive)}isSliceActive(){return this.sliceActive}setSlicePlane(e,t=this.sliceOffset){let i=wo(e);return this.sliceNormal.set(i.x,i.y,i.z),this.rebuildSlicePlaneAxes(),this.sliceOffset=Ia(t),this.setSliceCenterFromOffset(this.sliceOffset),this.syncSliceClipping(),this.notifySliceChanged(),this.getSliceState()}setSliceOffset(e){return this.sliceOffset=Ia(e),this.setSliceCenterFromOffset(this.sliceOffset),this.syncSliceClipping(),this.notifySliceChanged(),this.getSliceState()}setSliceRotation(e){var a,o;let t=this.rootMesh?this.getRenderableBounds(this.rootMesh):null,i=this.getSliceRange(),r=(o=(a=this.sliceCenter)==null?void 0:a.clone())!=null?o:i?new b(i.point.x,i.point.y,i.point.z):null,s=gx(e);return this.slicePlaneX.set(s.x.x,s.x.y,s.x.z),this.slicePlaneY.set(s.y.x,s.y.y,s.y.z),this.sliceNormal.set(s.z.x,s.z.y,s.z.z),r?(this.sliceCenter=r,this.sliceOffset=Xm(t,s.z,ct(r))):this.setSliceCenterFromOffset(this.sliceOffset),this.syncSliceClipping(),this.notifySliceChanged(),this.getSliceState()}setSliceInteractionMode(e){let t=ov(e);return t===this.sliceInteractionMode?this.getSliceState():(this.endSliceDrag(null,!0),this.sliceInteractionMode=t,this.syncSliceClipping(),this.notifySliceChanged(),this.getSliceState())}resetSlicePlane(){return this.alignSlicePlaneToWorld(),this.sliceOffset=Il,this.setSliceCenterFromOffset(this.sliceOffset),this.syncSliceClipping(),this.notifySliceChanged(),this.getSliceState()}setSliceAxis(e){let t=av(e);return this.setSlicePlane({x:t==="x"?1:0,y:t==="y"?1:0,z:t==="z"?1:0})}setSlicePosition(e){return this.setSliceOffset(e)}setSliceThickness(e){return this.sliceThickness=lv(e),this.notifySliceChanged(),this.getSliceState()}getSliceState(){let e=px(this.sliceActive,ct(this.sliceNormal),this.sliceOffset,this.rootMesh?this.getRenderableBounds(this.rootMesh):null,!!this.sliceDragState,this.sliceThickness,this.sliceInteractionMode,ct(this.sliceReferenceNormal)),t=this.getSliceRange(),i=_x({x:ct(this.slicePlaneX),y:ct(this.slicePlaneY),z:ct(this.sliceNormal)});return t?{...e,rotationDegrees:i,offset:t.offset,position:t.offset,point:{...t.point}}:{...e,rotationDegrees:i}}observeSlice(e){return this.sliceObservers.add(e),e(),()=>{this.sliceObservers.delete(e)}}toggleFocusSelection(){let e=!this.focusSelectionEnabled;return e&&this.isDisassemblyActive()&&this.disableDisassemblyAndReset(),e&&(this.deactivateMeasurementMode(),this.deactivateSliceMode()),this.focusSelectionEnabled=e,this.focusSelectionEnabled?this._lastPickResult.mesh&&this.setFocusedNode(this._lastPickResult.mesh):this.clearFocusedMesh(),this.focusSelectionEnabled}isFocusSelectionEnabled(){return this.focusSelectionEnabled}toggleDisassembly(){let e=this.ensureDisassemblyController();if(!e)return!1;let t=!e.isEnabled();t&&(this.focusSelectionEnabled=!1,this.clearFocusedMesh(),this.deactivateMeasurementMode(),this.deactivateSliceMode());let i=e.setEnabled(t);return i||e.reset(),i}resetDisassembly(){var e;(e=this.disassembly)==null||e.reset()}disableDisassemblyAndReset(){var e;this.isDisassemblyActive()&&((e=this.disassembly)==null||e.setEnabled(!1),this.resetDisassembly())}isDisassemblyEnabled(){return this.isDisassemblyActive()}setExplode(e,t){this.rootMesh&&RQ(this.rootMesh,e,t,this.loadedMeshes)}resetExplode(){this.rootMesh&&jF(this.rootMesh,this.loadedMeshes)}resetView(){this.rootMesh&&jF(this.rootMesh,this.loadedMeshes),this.resetDisassembly(),this.clearFocusedMesh(),this.camera.mode=0,this.camera.alpha=this.initialCamera.alpha,this.camera.beta=this.initialCamera.beta,this.camera.radius=this.initialCamera.radius,this.camera.target=this.initialCamera.target.clone(),this.startRenderLoop(),this.notifyCameraZoomChanged()}exportModelInfo(e){if(!this.rootMesh)return"";let t=this.getRenderableMeshes(this.rootMesh),i=b1(this.rootMesh),r=this.createModelSummary(this.rootMesh),s=e&&Qs(e)||r.rootName;return jA({title:s,format:this.loadedExt.toUpperCase(),summary:r,meshBreakdown:t.map(a=>SQ(a,{isSplat:i})),materialNames:t.map(a=>{var o;return(o=a.material)==null?void 0:o.name})})}getModelEvidence(){if(!this.rootMesh)return null;let e=this.getRenderableMeshes(this.rootMesh),t=AQ(e,this.loadedTransformNodes,this.gltfComponentMetadata);return JA({summary:this.createModelSummary(this.rootMesh),renderableMeshes:e,groupedPartCandidates:t,createMeshPart:i=>XF(i,this.gltfComponentMetadata),getMeshMaterialNames:i=>{var r;return[(r=i.material)==null?void 0:r.name]},resourceWarnings:this.resourceWarnings})}getSelectedPartInfo(){var t;if(!this.rootMesh)return null;let e=(t=this.focusedNode)!=null?t:M$(this._lastPickResult.mesh)?this._lastPickResult.mesh:null;return!e||hf(e)?null:YF(e,this.getRenderableMeshes(this.rootMesh),this.gltfComponentMetadata)}exportSelectedPartInfo(){let e=this.getSelectedPartInfo();return e?ZA(e):""}getPickWorldPoint(e){return e.pickedPoint&&typeof e.pickedPoint=="object"?ct(e.pickedPoint):this.rootMesh&&M$(e.mesh)?YF(e.mesh,this.getRenderableMeshes(this.rootMesh),this.gltfComponentMetadata).center:null}focusWorldPoint(e){let t=new b(e.x,e.y,e.z),i=this.camera.target.clone(),r=performance.now();this.focusWorldPointFrame&&(window.cancelAnimationFrame(this.focusWorldPointFrame),this.focusWorldPointFrame=0);let s=a=>{let o=Math.min(1,Math.max(0,(a-r)/JSe)),l=o<.5?4*o*o*o:1-Math.pow(-2*o+2,3)/2;if(this.camera.target=b.Lerp(i,t,l),o<1&&!this.scene.isDisposed){this.focusWorldPointFrame=window.requestAnimationFrame(s);return}this.focusWorldPointFrame=0};this.focusWorldPointFrame=window.requestAnimationFrame(s)}getAnnotationCameraStateKey(){return $A([{value:this.camera.alpha,digits:3},{value:this.camera.beta,digits:3},{value:this.camera.radius,digits:3},{value:this.camera.target.x,digits:2},{value:this.camera.target.y,digits:2},{value:this.camera.target.z,digits:2}])}projectAnnotationWorldPoint(e,t){let i=this.engine.getRenderingCanvas();if(!i||this.scene.isDisposed)return!1;let r=this.engine.getRenderWidth(),s=this.engine.getRenderHeight();if(r===0||s===0||i.clientWidth===0||i.clientHeight===0)return!1;let a=Ga.annotationWorldPoint;return a.set(e.x,e.y,e.z),b.ProjectToRef(a,Ga.annotationIdentity,this.scene.getTransformMatrix(),this.camera.viewport.toGlobal(r,s),Ga.annotationProjection),mV(Ga.annotationProjection,r,s,i,t)}isAnnotationWorldPointOccluded(e){if(this.scene.isDisposed)return!1;let t=kf(ct(this.camera.position),e);if(!t)return!1;let i=Ga.annotationDirection,r=Ga.annotationRay;i.set(t.direction.x,t.direction.y,t.direction.z),r.origin=this.camera.position,r.direction=i,r.length=t.distance;let s=this.scene.pickWithRay(r);return!!(s!=null&&s.hit)&&Gf(s.distance,t.distance,t.epsilon)}getAnnotationProvider(){let e=this.engine.getRenderingCanvas();if(!e)throw new Error("Preview canvas is unavailable");return QA({canvas:e,observeRender:t=>{let i=this.scene.onAfterRenderCameraObservable.add(r=>{r===this.camera&&t()});return{remove:()=>this.scene.onAfterRenderCameraObservable.remove(i)}},getCameraStateKey:()=>this.getAnnotationCameraStateKey(),projectWorldPoint:(t,i)=>this.projectAnnotationWorldPoint(t,i),isWorldPointOccluded:t=>this.isAnnotationWorldPointOccluded(t)})}getCanvas(){return this.engine.getRenderingCanvas()}getLastPickResult(){return this._lastPickResult}onPick(e){return this._onPickCallbacks.push(e),()=>{this._onPickCallbacks=this._onPickCallbacks.filter(t=>t!==e)}}setRenderQuality(e,t=this.renderScale){this.currentQuality=e,this.renderScale=Math.max(.25,Math.min(t,2));let i={low:2,medium:1.33,high:1},r=Rr()?1.5:1,s=i[e]*r/this.renderScale;if(this.engine.setHardwareScalingLevel(s),this.shadowGenerator){let a={low:0,medium:16,high:32};this.shadowGenerator.blurKernel=a[e],e==="low"?(this.shadowGenerator.useBlurExponentialShadowMap=!1,this.shadowGenerator.useExponentialShadowMap=!0):(this.shadowGenerator.useBlurExponentialShadowMap=!0,this.shadowGenerator.useExponentialShadowMap=!1)}}destroy(){var t,i,r,s,a,o,l,c;this.engine.stopRenderLoop(),this.focusWorldPointFrame&&(window.cancelAnimationFrame(this.focusWorldPointFrame),this.focusWorldPointFrame=0),this._onPickCallbacks=[],this.cameraZoomObservers.clear(),this.sliceObservers.clear(),(t=this.cleanupPicking)==null||t.call(this),this.cleanupPicking=null,(i=this.gizmo)==null||i.dispose(),this.gizmo=null,(r=this.disassembly)==null||r.dispose(),this.disassembly=null,this.restoreSliceMaterialClipping(),this.disposeSliceOverlay(!1),this.disposeMeasurementOverlays(!0),this.measurementObservers.clear(),this.clearFocusedMesh(),this.originalMeshVisibility.clear(),(s=this.bboxMesh)==null||s.dispose(),this.bboxMesh=null,this.camera.detachControl();let e=this.engine.getRenderingCanvas();e==null||e.classList.remove("ai3d-slice-active","ai3d-slice-dragging","ai3d-slice-rotate"),e==null||e.removeEventListener("wheel",this.preventCanvasWheelScroll),e==null||e.removeEventListener("pointerdown",this.handlePointerDown,!0),e==null||e.removeEventListener("pointerup",this.handlePointerUp,!0),e==null||e.removeEventListener("pointermove",this.handlePointerMove,!0),e==null||e.removeEventListener("pointercancel",this.handlePointerCancel,!0),e==null||e.removeEventListener("lostpointercapture",this.handlePointerCaptureLost,!0),e==null||e.removeEventListener("webglcontextlost",this.handleContextLost),e==null||e.removeEventListener("webglcontextrestored",this.handleContextRestored),window.removeEventListener("keydown",this.handleMeasurementModifierKey),window.removeEventListener("keyup",this.handleMeasurementModifierKey),window.removeEventListener("blur",this.handleMeasurementModifierBlur),(a=this.viewportObserver)==null||a.disconnect(),this.viewportObserver=null,this.resizeObs.disconnect(),this.sliceMoveFrame&&(window.cancelAnimationFrame(this.sliceMoveFrame),this.sliceMoveFrame=0),this.pendingSliceMove=null,this.invalidateMeshCache(),this.rootMesh=null,this.loadedMeshes=[],this.loadedTransformNodes=[],this.autoRotateBehavior&&(this.camera.removeBehavior(this.autoRotateBehavior),this.autoRotateBehavior=null);for(let f of this.configLights)f.dispose();this.configLights=[],(o=this.shadowGenerator)==null||o.dispose(),this.shadowGenerator=null,(l=this.groundMesh)==null||l.dispose(),this.groundMesh=null,(c=this.gridMesh)==null||c.dispose(),this.gridMesh=null;for(let f of this.axisMeshes)f.dispose();this.axisMeshes=[],this.scene.dispose(),this.engine.dispose()}startRenderLoop(){this.rendering||!this.viewportVisible||this.contextLost||(this.rendering=!0,this.engine.runRenderLoop(()=>{if(!this.canRender()||!this.viewportVisible||this.contextLost){this.engine.stopRenderLoop(),this.rendering=!1;return}this.scene.render(),this.gizmo&&this.gizmoEnabled&&(this.gizmo.syncWith(this.camera),this.gizmo.render())}))}getRenderableMeshes(e){if(this.cachedRenderableMeshes&&this.cachedRenderableRoot===e)return this.cachedRenderableMeshes;let t=Eh(e,this.loadedMeshes);return this.cachedRenderableMeshes=t,this.cachedRenderableRoot=e,t}getRenderableBounds(e){return hy(e,this.loadedMeshes)}getSliceRange(){let e=Du(this.rootMesh?this.getRenderableBounds(this.rootMesh):null,{normal:ct(this.sliceNormal),offset:this.sliceOffset});if(!e||!this.sliceCenter)return e;let t=b.Dot(this.sliceCenter,this.sliceNormal),i=Ia((t-e.min)/e.span);return this.sliceOffset=i,{...e,offset:i,distance:t,point:ct(this.sliceCenter)}}setSliceCenterFromOffset(e){if(!this.rootMesh)return;let t=Du(this.getRenderableBounds(this.rootMesh),{normal:ct(this.sliceNormal),offset:e});t&&(this.sliceCenter=new b(t.point.x,t.point.y,t.point.z))}alignSlicePlaneToWorld(){this.sliceNormal.set(Dr.x,Dr.y,Dr.z),this.rebuildSlicePlaneAxes(new b(1,0,0)),this.sliceReferenceNormal.copyFrom(this.sliceNormal),this.sliceCenter=null,this.setSliceCenterFromOffset(this.sliceOffset)}rebuildSlicePlaneAxes(e=this.slicePlaneX){let t=this.sliceNormal.clone().normalize(),i=e.clone().subtract(t.scale(b.Dot(e,t)));i.lengthSquared()<=1e-6&&(i.copyFrom(Math.abs(t.y)<.92?new b(0,1,0):new b(1,0,0)),i.subtractInPlace(t.scale(b.Dot(i,t)))),i.normalize(),this.slicePlaneX.copyFrom(i),b.CrossToRef(t,i,this.slicePlaneY),this.slicePlaneY.normalize()}deactivateSliceMode(){return!this.sliceActive&&!this.sliceDragState?!1:(this.endSliceDrag(null,!0),this.sliceActive=!1,this.syncSliceClipping(),this.notifySliceChanged(),!0)}beginSliceDrag(e){if(!this.rootMesh||!this.sliceActive)return!1;let t=this.getSlicePointerTarget(e);if(!t)return!1;let i=this.engine.getRenderingCanvas();if(!i)return!1;let r=i.getBoundingClientRect(),s=t.mode;this.sliceInteractionMode=s;let a={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,mode:s,moved:!1};if(s==="rotate"){let o=this.getSliceRange();if(!o)return!1;let l=this.getSlicePointerPolar(e,t.axis);if(!l)return!1;this.sliceDragState={...a,mode:s,axis:t.axis,startNormal:ct(this.sliceNormal),anchorPoint:{...o.point},rotationAxis:ct(t.axis==="x"?this.slicePlaneX:t.axis==="y"?this.slicePlaneY:this.sliceNormal),startPlaneX:ct(this.slicePlaneX),startPlaneY:ct(this.slicePlaneY),screenTangent:t.screenTangent,radiansPerPixel:t.radiansPerPixel,rotationRadians:0,startPointerAngle:l.angle,currentPointerAngle:l.angle,snapMode:Ym(l.radiusRatio),useScreenRotation:Ex(l.rayPlaneAlignment),labelPoint:t.labelPoint}}else this.sliceDragState={...a,mode:s,startOffset:this.sliceOffset,screenAxis:this.getSliceScreenAxis(),pixelsToOffset:1/Math.max(Math.min(r.width,r.height)*.72,1)};this.syncSliceClipping(),i.classList.add("ai3d-slice-dragging"),this.stabilizeCameraForSliceDrag(),this.camera.detachControl();try{i.setPointerCapture(e.pointerId)}catch(o){}return e.preventDefault(),e.stopImmediatePropagation(),this.notifySliceChanged(),this.startRenderLoop(),!0}getSlicePointerPolar(e,t,i,r){let s=this.engine.getRenderingCanvas(),a=this.getSliceRange();if(!s||!this.rootMesh||!a)return null;let o=s.getBoundingClientRect();if(o.width<=0||o.height<=0)return null;let l=this.scene.createPickingRay(e.clientX-o.left,e.clientY-o.top,Q.Identity(),this.camera),c=r!=null?r:a.point,f=new b(c.x,c.y,c.z),d=i?{x:new b(i.x.x,i.x.y,i.x.z),y:new b(i.y.x,i.y.y,i.y.z),z:new b(i.z.x,i.z.y,i.z.z)}:{x:this.slicePlaneX,y:this.slicePlaneY,z:this.sliceNormal},u=(t==="x"?d.x:t==="y"?d.y:d.z).clone().normalize(),h=(t==="x"?d.y:t==="y"?d.z:d.x).clone().normalize(),m=(t==="x"?d.z:t==="y"?d.x:d.y).clone().normalize(),g=b.Dot(u,l.direction);if(Math.abs(g)<=1e-6)return null;let p=b.Dot(f.subtract(l.origin),u)/g,v=l.origin.add(l.direction.scale(p)).subtract(f),E=this.getRenderableBounds(this.rootMesh),S=Math.max(Rs(E)*.62,a.span*.16,Number.EPSILON);return{angle:Math.atan2(b.Dot(v,m),b.Dot(v,h)),radiusRatio:v.length()/S,rayPlaneAlignment:Math.abs(g)}}getSlicePointerTarget(e){if(e.altKey||!this.rootMesh)return null;let t=this.engine.getRenderingCanvas(),i=this.getSliceRange();if(!t||!i)return null;let r=this.getRenderableBounds(this.rootMesh),s=t.getBoundingClientRect(),a=this.engine.getRenderWidth(),o=this.engine.getRenderHeight();if(s.width<=0||s.height<=0||a<=0||o<=0)return null;let l=this.camera.viewport.toGlobal(a,o),c=p=>{let _=b.Project(new b(p.x,p.y,p.z),Q.Identity(),this.scene.getTransformMatrix(),l);return{x:s.left+_.x/a*s.width,y:s.top+_.y/o*s.height}},f={x:e.clientX,y:e.clientY},d=e.pointerType==="touch"?28:14,u=c(i.point);if(Math.hypot(f.x-u.x,f.y-u.y)<=d*1.35)return{mode:"move"};let h=Km(r,i,64,{x:ct(this.slicePlaneX),y:ct(this.slicePlaneY),z:ct(this.sliceNormal)});if(h.moveGuide.some(([p,_])=>{let v=c(p),E=c(_);return b$(f,v,E)<=d}))return{mode:"move"};let m=null,g=Number.POSITIVE_INFINITY;for(let p of["x","y","z"]){let _=h.rotationRings[p].map(([E,S])=>[c(E),c(S)]),v=_.reduce((E,[S,T])=>E+Math.hypot(T.x-S.x,T.y-S.y),0);for(let[E,S]of _){let T=b$(f,E,S);if(T>d||T>=g)continue;let A=Math.hypot(S.x-E.x,S.y-E.y);A<=Number.EPSILON||(g=T,m={mode:"rotate",axis:p,screenTangent:{x:(S.x-E.x)/A,y:(S.y-E.y)/A},radiansPerPixel:Math.PI*2/Math.max(v,80),labelPoint:{...i.point}})}}return m}updateSliceDrag(e){let t=this.sliceDragState;return!t||t.pointerId!==e.pointerId?!1:(e.preventDefault(),e.stopImmediatePropagation(),this.pendingSliceMove={pointerId:e.pointerId,clientX:e.clientX,clientY:e.clientY},this.sliceMoveFrame||(this.sliceMoveFrame=window.requestAnimationFrame(()=>{this.sliceMoveFrame=0,this.flushSliceDragUpdate()})),!0)}flushSliceDragUpdate(){this.sliceMoveFrame&&(window.cancelAnimationFrame(this.sliceMoveFrame),this.sliceMoveFrame=0);let e=this.pendingSliceMove;this.pendingSliceMove=null;let t=this.sliceDragState;if(!e||!t||t.pointerId!==e.pointerId)return;let i=e.clientX-t.startX,r=e.clientY-t.startY;if(t.moved=t.moved||Math.hypot(i,r)>2,t.mode==="rotate"){let o=this.getSlicePointerPolar(e,t.axis,{x:t.startPlaneX,y:t.startPlaneY,z:t.startNormal},t.anchorPoint);if(!o)return;let l=(i*t.screenTangent.x+r*t.screenTangent.y)*t.radiansPerPixel,c=cv(t.useScreenRotation?l:o.angle-t.startPointerAngle);t.useScreenRotation||(t.snapMode=Ym(o.radiusRatio,t.snapMode)),t.rotationRadians=vx(c,t.snapMode),t.currentPointerAngle=t.startPointerAngle+t.rotationRadians;let f=Yf(t.startNormal,t.rotationAxis,t.rotationRadians),d=Yf(t.startPlaneX,t.rotationAxis,t.rotationRadians),u=Yf(t.startPlaneY,t.rotationAxis,t.rotationRadians),h=b.DistanceSquared(this.sliceNormal,new b(f.x,f.y,f.z)),m=b.DistanceSquared(this.slicePlaneX,new b(d.x,d.y,d.z))+b.DistanceSquared(this.slicePlaneY,new b(u.x,u.y,u.z));if(h<=1e-6&&m<=1e-6)return;if(h>1e-6){let g=this.rootMesh?this.getRenderableBounds(this.rootMesh):null;this.sliceNormal.set(f.x,f.y,f.z),this.sliceCenter=new b(t.anchorPoint.x,t.anchorPoint.y,t.anchorPoint.z),this.sliceOffset=Xm(g,f,t.anchorPoint)}this.slicePlaneX.set(d.x,d.y,d.z),this.slicePlaneY.set(u.x,u.y,u.z),this.syncSliceClipping(),this.notifySliceChanged();return}let s=i*t.screenAxis.x+r*t.screenAxis.y,a=Ia(t.startOffset+s*t.pixelsToOffset);Math.abs(a-this.sliceOffset)<=5e-4||(this.sliceOffset=a,this.setSliceCenterFromOffset(a),this.syncSliceClipping(),this.notifySliceChanged())}endSliceDrag(e,t=!1){let i=this.sliceDragState;if(!i||e&&i.pointerId!==e.pointerId)return!1;this.flushSliceDragUpdate();let r=this.engine.getRenderingCanvas();if(this.sliceDragState=null,r==null||r.classList.remove("ai3d-slice-dragging"),this.syncSliceClipping(),this.camera.attachControl(r,!0),this.resumeCameraAfterSliceDrag(),e&&r){try{r.releasePointerCapture(e.pointerId)}catch(s){}e.preventDefault(),e.stopImmediatePropagation()}return(!t||i.moved)&&this.notifySliceChanged(),this.startRenderLoop(),!0}stabilizeCameraForSliceDrag(){this.focusWorldPointFrame&&(window.cancelAnimationFrame(this.focusWorldPointFrame),this.focusWorldPointFrame=0),this.camera.inertialAlphaOffset=0,this.camera.inertialBetaOffset=0,this.camera.inertialRadiusOffset=0,this.camera.inertialPanningX=0,this.camera.inertialPanningY=0,this.autoRotateBehavior&&!this.sliceAutoRotatePaused&&(this.camera.removeBehavior(this.autoRotateBehavior),this.sliceAutoRotatePaused=!0)}resumeCameraAfterSliceDrag(){!this.autoRotateBehavior||!this.sliceAutoRotatePaused||(this.camera.addBehavior(this.autoRotateBehavior),this.sliceAutoRotatePaused=!1)}getSliceScreenAxis(){let e=this.getSliceRange();if(!this.rootMesh||!e)return{x:0,y:-1};let t=this.getRenderableBounds(this.rootMesh),i=this.engine.getRenderingCanvas();if(!i)return{x:0,y:-1};let r=Math.max(Rs(t),e.span*.25,Number.EPSILON),s=new b(e.point.x,e.point.y,e.point.z),a=s.add(new b(e.normal.x,e.normal.y,e.normal.z).normalize().scale(r*.35)),o=this.engine.getRenderWidth(),l=this.engine.getRenderHeight();if(o===0||l===0||i.clientWidth===0||i.clientHeight===0)return{x:0,y:-1};let c=this.camera.viewport.toGlobal(o,l),f=b.Project(s,Q.Identity(),this.scene.getTransformMatrix(),c),d=b.Project(a,Q.Identity(),this.scene.getTransformMatrix(),c),u={x:d.x-f.x,y:d.y-f.y},h=Math.hypot(u.x,u.y);return!Number.isFinite(h)||h<=1e-6?{x:0,y:-1}:{x:u.x/h,y:u.y/h}}updateBabylonSlicePlane(e){let t=Tx(e,"babylon");if(!(t!=null&&t.length))return null;let i=t[0];return this.slicePlane?(this.slicePlane.normal.set(i.normal.x,i.normal.y,i.normal.z),this.slicePlane.d=i.constant):this.slicePlane=new Da(i.normal.x,i.normal.y,i.normal.z,i.constant),this.slicePlane}syncSliceClipping(){let e=this.engine.getRenderingCanvas();if(e==null||e.classList.toggle("ai3d-slice-active",this.sliceActive),e==null||e.classList.toggle("ai3d-slice-rotate",this.sliceActive&&this.sliceInteractionMode==="rotate"),!this.rootMesh||!this.sliceActive){this.restoreSliceMaterialClipping(),this.disposeSliceOverlay(!1),this.slicePlane=null,e==null||e.classList.remove("ai3d-slice-dragging"),e==null||e.classList.remove("ai3d-slice-rotate"),this.startRenderLoop();return}let t=this.getSliceRange(),i=this.updateBabylonSlicePlane(t);if(!i){this.restoreSliceMaterialClipping(),this.disposeSliceOverlay(!1),this.startRenderLoop();return}this.syncSliceOverlay(t);let r=new Set;for(let s of this.getRenderableMeshes(this.rootMesh)){let a=s.material;if(!a)continue;r.add(a.uniqueId);let o=!this.sliceOriginalMaterialClipping.has(a.uniqueId);o&&this.sliceOriginalMaterialClipping.set(a.uniqueId,{material:a,clipPlane:a.clipPlane,clipPlane2:a.clipPlane2}),(o||a.clipPlane!==i)&&(a.clipPlane=i,a.markDirty(!0))}for(let[s,a]of Array.from(this.sliceOriginalMaterialClipping.entries()))r.has(s)||(a.material.clipPlane=a.clipPlane,a.material.clipPlane2=a.clipPlane2,a.material.markDirty(!0),this.sliceOriginalMaterialClipping.delete(s));this.startRenderLoop()}restoreSliceMaterialClipping(){for(let e of this.sliceOriginalMaterialClipping.values())e.material.clipPlane=e.clipPlane,e.material.clipPlane2=e.clipPlane2,e.material.markDirty(!0);this.sliceOriginalMaterialClipping.clear()}syncSliceOverlay(e){var w,G,O,N,B,V;this.disposeSliceOverlay(!1,!0);let t=this.rootMesh?this.getRenderableBounds(this.rootMesh):null;if(!t||!e)return;let i={x:ct(this.slicePlaneX),y:ct(this.slicePlaneY),z:ct(this.sliceNormal)},r=Sx(t,e,.12,i),s=this.createSliceOverlayPlane(r),a=this.sliceInteractionMode==="rotate"?aTe:rTe,o=this.createSliceOverlayLines(r.segments,a),l=this.createSliceOverlayLines(this.createSliceNormalGuide(t,e),nTe),c=((w=this.sliceDragState)==null?void 0:w.mode)==="rotate"?{[this.sliceDragState.axis]:this.sliceDragState.currentPointerAngle}:void 0,f=((G=this.sliceDragState)==null?void 0:G.mode)==="rotate"?{x:this.sliceDragState.startPlaneX,y:this.sliceDragState.startPlaneY,z:this.sliceDragState.startNormal}:i,d=Km(t,e,64,f,c),u=((O=this.sliceDragState)==null?void 0:O.mode)==="rotate"?this.sliceDragState.axis:null,h=((N=this.sliceDragState)==null?void 0:N.mode)==="move",m=(q,K)=>({color:u===q?oTe:K,alpha:u?u===q?.98:0:h?.1:.34,tickAlpha:u?u===q?.82:0:h?.04:.14}),g=m("x",A$),p=m("y",x$),_=m("z",R$),v=this.createSliceOverlayLines(d.rotationRings.x,g.color,g.alpha),E=this.createSliceOverlayLines(d.rotationRings.y,p.color,p.alpha),S=this.createSliceOverlayLines(d.rotationRings.z,_.color,_.alpha),T=this.createSliceOverlayLines(d.rotationTicks.x,g.color,g.tickAlpha),A=this.createSliceOverlayLines(d.rotationTicks.y,p.color,p.tickAlpha),R=this.createSliceOverlayLines(d.rotationTicks.z,_.color,_.tickAlpha),M=this.createSliceOverlayLines(d.moveGuide,lTe,u?.22:.96),I=u==="x"?A$:u==="y"?x$:R$,C=u?this.createSliceOverlayLines(d.rotationArcs[u],I,1):null,L=u?this.createSliceOverlayLines(d.rotationArrowheads[u],I,1):null;if(this.sliceOverlayPlanes.push(s),this.sliceOverlayLines.push(o,l,v,E,S,T,A,R,M),u&&C&&L){this.sliceOverlayLines.push(C,L);let q=this.sliceDragState;if((q==null?void 0:q.mode)==="rotate"){let K=(q.currentPointerAngle*180/Math.PI%360+360)%360,J=d.rotationArcs[u],Y=(V=(B=J[J.length-1])==null?void 0:B[1])!=null?V:q.labelPoint;this.updateSliceRotationLabel(`${u.toUpperCase()}: ${K.toFixed(1)}\xB0`,new b(Y.x,Y.y,Y.z),this.getMeasurementMarkerSize()*2.5)}}else this.disposeSliceRotationLabel()}createSliceOverlayPlane(e){let t=new $("ai3d-slice-plane",this.scene),i=e.corners,r=[i[0].x,i[0].y,i[0].z,i[1].x,i[1].y,i[1].z,i[2].x,i[2].y,i[2].z,i[3].x,i[3].y,i[3].z],s=[0,1,2,0,2,3],a=[];Ie.ComputeNormals(r,s,a);let o=new Ie;o.positions=r,o.indices=s,o.normals=a,o.applyToMesh(t);let l=new We("slice-plane-mat",this.scene),c=this.sliceInteractionMode==="rotate"?sTe:iTe;return l.diffuseColor=c.clone(),l.emissiveColor=c.scale(.75),l.specularColor=new he(0,0,0),l.alpha=cTe,l.backFaceCulling=!1,l.disableLighting=!0,l.zOffset=-2,t.material=l,t.isPickable=!1,t.renderingGroupId=2,t}createSliceOverlayLines(e,t,i=.88){let r=Pn.CreateLineSystem("ai3d-slice-frame",{lines:e.map(([s,a])=>[new b(s.x,s.y,s.z),new b(a.x,a.y,a.z)]),updatable:!1},this.scene);return r.color=t.clone(),r.alpha=i,r.isPickable=!1,r.renderingGroupId=2,r}createSliceNormalGuide(e,t){var o;let i=Math.max(Rs(e),t.span*.25,Number.EPSILON),r=(o=wn(t.normal))!=null?o:Dr,s=t.point,a={x:s.x+r.x*i*.26,y:s.y+r.y*i*.26,z:s.z+r.z*i*.26};return[[s,a]]}disposeSliceOverlay(e=!0,t=!1){for(let i of this.sliceOverlayPlanes)i.dispose(!1,!0);for(let i of this.sliceOverlayLines)i.dispose(!1,!0);for(let i of this.sliceOverlayLabels)i.dispose(!1,!0);this.sliceOverlayPlanes=[],this.sliceOverlayLines=[],this.sliceOverlayLabels=[],t||this.disposeSliceRotationLabel(),e&&this.startRenderLoop()}updateSliceRotationLabel(e,t,i){if(!this.sliceRotationLabel){this.sliceRotationLabel=this.createMeasurementLabelMesh({primary:e,secondary:""},t,i),this.sliceRotationLabelText=e;return}if(this.sliceRotationLabel.position.copyFrom(t),e===this.sliceRotationLabelText)return;let r=this.sliceRotationLabel.material,s=r instanceof We&&r.diffuseTexture instanceof EE?r.diffuseTexture:null;if(!s){this.disposeSliceRotationLabel(),this.updateSliceRotationLabel(e,t,i);return}let a=s.getContext();nv(a,{primary:e,secondary:""},Oo.width,Oo.height),s.update(),this.sliceRotationLabelText=e}disposeSliceRotationLabel(){var e;(e=this.sliceRotationLabel)==null||e.dispose(!1,!0),this.sliceRotationLabel=null,this.sliceRotationLabelText=""}notifySliceChanged(){for(let e of this.sliceObservers)e()}invalidateMeshCache(){this.cachedRenderableMeshes=null,this.cachedRenderableRoot=null}resolvePickHighlightMeshes(e){if(!this.rootMesh)return[e];let t=this.getRenderableMeshes(this.rootMesh),i=wE(this.rootMesh,e,t,this.gltfComponentMetadata),r=t.filter(s=>xg(s,i));return r.length>0?r:[e]}setFocusedNode(e){if(!this.rootMesh)return;let t=e?this.findSelectableNode(e):null;if(!t||hf(t)){this.clearFocusedMesh();return}if(this.focusedNode===t)return;let i=this.getRenderableMeshes(this.rootMesh),r=i.filter(a=>xg(a,t));if(r.length===0){this.clearFocusedMesh();return}let s=new Set(r);for(let a of i){this.originalMeshVisibility.has(a.uniqueId)||this.originalMeshVisibility.set(a.uniqueId,a.visibility);let o=s.has(a);a.visibility=o?1:$Se,a.renderOutline=o,a.outlineColor=new he(.18,.76,1),a.outlineWidth=o?.045:0}this.focusedNode=t}clearFocusedMesh(){if(!this.rootMesh){this.focusedNode=null;return}for(let e of this.getRenderableMeshes(this.rootMesh)){let t=this.originalMeshVisibility.get(e.uniqueId);t!==void 0&&(e.visibility=t),e.renderOutline=!1,e.outlineWidth=0}this.originalMeshVisibility.clear(),this.focusedNode=null,this.applyMeasurementTargetVisual(this.measurementTargetMeshes)}findSelectableNode(e){if(!this.rootMesh)return null;let t=this.getRenderableMeshes(this.rootMesh);if(t.includes(e)||t.some(r=>xg(r,e)))return e;if(!dTe(e))return null;let i=e.parent;for(;i&&"uniqueId"in i;){let r=i;if(t.includes(r)||t.some(s=>xg(s,r)))return r;i=i.parent}return null}getCurrentMeasurementTargetNode(){return this.focusSelectionEnabled&&this.focusedNode&&!hf(this.focusedNode)?this.findSelectableNode(this.focusedNode):this.rootMesh&&!this.rootMesh.isDisposed()?this.rootMesh:null}setMeasurementTargetNode(e,t=!0){this.clearMeasurementTargetVisual(!1),this.invalidateMeasurementSnapInputCache();let i=e&&!hf(e)?this.findSelectableNode(e):null;if(!i||hf(i)){this.measurementTargetNode=null,this.measurementTargetMeshes=[],this.setMeasurementSnapKind(null,!1),t&&this.notifyMeasurementsChanged();return}let r=this.getMeasurementTargetMeshes(i);if(r.length===0){this.measurementTargetNode=null,this.measurementTargetMeshes=[],this.setMeasurementSnapKind(null,!1),t&&this.notifyMeasurementsChanged();return}this.measurementTargetNode=i,this.measurementTargetMeshes=r,this.setMeasurementSnapKind(null,!1),this.applyMeasurementTargetVisual(r),this.scene.render(),t&&this.notifyMeasurementsChanged()}clearMeasurementTargetVisual(e=!0){for(let t of this.measurementTargetMeshes)t.isDisposed()||(t.renderOutline=!1,t.outlineWidth=0);this.measurementTargetMeshes=[],e&&!this.scene.isDisposed&&this.scene.render()}applyMeasurementTargetVisual(e){if(!(!this.measurementActive||e.length===0))for(let t of e)t.isDisposed()||(t.renderOutline=!0,t.outlineColor=new he(.38,.65,.98),t.outlineWidth=.045)}setMeasurementSnapKind(e,t=!0){this.measurementSnapKind!==e&&(this.measurementSnapKind=e,t&&this.notifyMeasurementsChanged())}updateMeasurementModifierAltKey(e){this.lastPointerClient.altKey!==e&&(this.lastPointerClient={...this.lastPointerClient,altKey:e},this.measurementActive&&this.pendingPoint&&this.updatePreviewLine())}invalidateMeasurementSnapInputCache(){this.measurementSnapInputCache=null,this.measurementSnapInputCacheTargetId=null,this.measurementSnapInputCacheSignature=null}getMeasurementTargetName(){let e=this.measurementTargetNode;return!e||hf(e)?null:Gd(e,e.name||`node-${e.uniqueId}`)}getMeasurementTargetBounds(){if(!this.rootMesh||!this.measurementTargetNode||hf(this.measurementTargetNode))return null;let e=this.findSelectableNode(this.measurementTargetNode);if(!e)return null;this.measurementTargetNode=e;let t=this.getRenderableMeshes(this.rootMesh).filter(i=>xg(i,e));return Ql(t)}resolveMeasurementPickPoint(e,t){if(t)return this.setMeasurementSnapKind("free"),e;let i=this.createMeasurementGeometrySnapInput();if(!i)return this.setMeasurementSnapKind("free"),e;let r=sx(this.toMeasurementPoint(e),i);return r?(this.setMeasurementSnapKind(r.kind),go(r.point)):(this.setMeasurementSnapKind("free"),e)}createMeasurementGeometrySnapInput(){var f;let e=this.measurementTargetNode;if(!this.rootMesh||!e||hf(e))return null;let t=this.getMeasurementTargetMeshes(e);if(t.length===0)return null;let i=this.createMeasurementSnapInputSignature(t);if(this.measurementSnapInputCache&&this.measurementSnapInputCacheTargetId===e.uniqueId&&this.measurementSnapInputCacheSignature===i)return this.measurementSnapInputCache;let r=[],s=[],a=`babylon:${e.uniqueId}`;for(let d of t){if(d.isDisposed())continue;let u=d.getVerticesData(D.PositionKind);if(!u||u.length<3)continue;let h=d.computeWorldMatrix(!0),m=[],g=Math.floor(u.length/3);for(let _=0;_<g;_++){let v=new b(u[_*3],u[_*3+1],u[_*3+2]),E=b.TransformCoordinates(v,h),S=this.toMeasurementPoint(E);m.push(S),r.push({point:S,targetId:a})}let p=lx(g,(f=d.getIndices())!=null?f:null);s.push(...ox(m,p,a))}if(r.length===0&&s.length===0)return null;let o=this.getMeasurementTargetBounds(),l=o?Ui(o):{x:1,y:1,z:1},c={vertices:r,edges:s,targetId:a,vertexRadius:ax(l,s)};return this.measurementSnapInputCache=c,this.measurementSnapInputCacheTargetId=e.uniqueId,this.measurementSnapInputCacheSignature=i,c}createMeasurementSnapInputSignature(e){return e.map(t=>{var r;let i="geometry"in t&&t.geometry?(r=t.geometry.uniqueId)!=null?r:"geometry":"none";return[t.uniqueId,i,t.getTotalVertices(),t.getTotalIndices(),t.computeWorldMatrix(!0).asArray().map(gTe).join(",")].join(":")}).join("|")}getMeasurementTargetMeshes(e=this.measurementTargetNode){return!this.rootMesh||!e||hf(e)?[]:this.getRenderableMeshes(this.rootMesh).filter(t=>!t.isDisposed()&&xg(t,e))}getMeasurementTargetPickPoint(e,t){return!e||e.isDisposed()||!t?null:this.measurementTargetMeshes.includes(e)?t.clone():null}pickFrontmostMeasurementTargetPoint(e,t){let i=this.engine.getRenderingCanvas();if(!i||this.measurementTargetMeshes.length===0)return null;let r=i.getBoundingClientRect(),s=e-r.left,a=t-r.top,o=this.scene.pick(s,a,l=>l!==this.previewLine&&!this.measurementMarkers.includes(l));return o!=null&&o.hit?this.getMeasurementTargetPickPoint(o.pickedMesh,o.pickedPoint):null}createBabylonMeasurementDraftingLayout(e,t){var l,c,f;let i=this.toMeasurementDisplayPoint(e),r=this.toMeasurementDisplayPoint(t),s=this.getMeasurementMarkerSize(),a=(f=(c=(l=this.camera.upVector)==null?void 0:l.clone)==null?void 0:c.call(l))!=null?f:new b(0,1,0);a.normalize();let o=cx(this.toMeasurementPoint(i),this.toMeasurementPoint(r),{viewPosition:this.toMeasurementPoint(this.camera.position),viewUp:this.toMeasurementPoint(a),offset:s*4.2,extensionGap:s*.55,extensionOvershoot:s*.8,arrowLength:s*2.35,arrowWidth:s*.78,labelGap:s*1.05});return o?{lineSegments:o.lineSegments.map(([d,u])=>[go(d),go(u)]),labelPosition:go(o.labelPoint)}:null}getMeasurementMarkerSize(){if(!this.rootMesh)return .02;let e=this.getRenderableBounds(this.rootMesh);return e?Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z,.001)*.018:.02}cancelPendingMeasurement(e=!0){var r,s;let t=this.pendingMarker,i=(s=(r=this.pendingPoint)==null?void 0:r.clone())!=null?s:null;if(this.pendingPoint=null,this.pendingMarker=null,this.hoveredMarkerIndex=-1,i&&this.setMeasurementSnapKind(null,!1),this.removePreviewLine(),t&&i&&!this.isMeasurementPointUsed(i)){let a=this.measurementMarkers.indexOf(t);a>=0&&(this.measurementMarkers.splice(a,1),this.measurementMarkerPoints.splice(a,1)),t.dispose(!1,!0)}else t&&(t.scaling.setAll(1),BE(t,UE));e&&this.scene.render()}isMeasurementPointUsed(e){return this.measurementSegments.some(t=>b.Distance(t.start,e)<1e-4||b.Distance(t.end,e)<1e-4)}findNearestMarkerIndex(e){let t=this.getMeasurementMarkerSize()*2.5,i=this.toMeasurementDisplayPoint(e);for(let r=0;r<this.measurementMarkers.length;r++){let s=this.measurementMarkerPoints[r]?this.toMeasurementDisplayPoint(this.measurementMarkerPoints[r]):this.measurementMarkers[r].position;if(b.Distance(s,i)<t)return r}return-1}addMeasurementPoint(e){let t=this.toMeasurementBasePoint(e),i=this.findNearestMarkerIndex(t),r=i>=0?this.measurementMarkerPoints[i].clone():t;if(this.pendingPoint){if(b.Distance(r,this.pendingPoint)<1e-4)return;if(i<0){let s=this.getMeasurementMarkerSize(),a=Pn.CreateSphere("measure-marker",{diameter:s*.76,segments:12},this.scene);a.position=this.toMeasurementDisplayPoint(r),a.isPickable=!1,a.material=I$(this.scene),a.renderingGroupId=2,this.measurementMarkers.push(a),this.measurementMarkerPoints.push(r.clone())}this.createMeasurementSegment(this.pendingPoint,r),this.pendingMarker&&(this.pendingMarker.scaling.setAll(1),BE(this.pendingMarker,UE)),this.pendingPoint=null,this.pendingMarker=null,this.removePreviewLine()}else{if(i<0){let s=this.getMeasurementMarkerSize(),a=Pn.CreateSphere("measure-marker",{diameter:s*.76,segments:12},this.scene);a.position=this.toMeasurementDisplayPoint(r),a.isPickable=!1,a.material=I$(this.scene),a.renderingGroupId=2,this.measurementMarkers.push(a),this.measurementMarkerPoints.push(r.clone()),this.pendingMarker=a}else this.pendingMarker=this.measurementMarkers[i];this.pendingMarker.scaling.setAll(1.6),BE(this.pendingMarker,eTe),this.pendingPoint=r,this.ensurePreviewLine()}this.notifyMeasurementsChanged()}createMeasurementSegment(e,t){var f,d;let i=this.toMeasurementDisplayPoint(e),r=this.toMeasurementDisplayPoint(t),s=this.createBabylonMeasurementDraftingLayout(e,t),a=Pn.CreateLineSystem("measure-line",{lines:(f=s==null?void 0:s.lineSegments)!=null?f:[[i,r]]},this.scene);a.color=S$.clone(),a.alpha=1,a.isPickable=!1,a.renderingGroupId=2;let o=Wm(this.createMeasurementReading(e,t)),l=(d=s==null?void 0:s.labelPosition)!=null?d:b.Center(i,r),c=this.createMeasurementLabelMesh(o,l,this.getMeasurementMarkerSize()*3.2);this.measurementSegments.push({start:e.clone(),end:t.clone(),line:a,label:c})}createMeasurementLabelMesh(e,t,i){let r=Pn.CreatePlane("measure-label",{width:i*3.7,height:i*1.08},this.scene);r.position=t,r.billboardMode=$.BILLBOARDMODE_ALL,r.isPickable=!1,r.renderingGroupId=2;let s=new EE("measure-label-tex",{...Oo},this.scene);s.hasAlpha=!0;let a=s.getContext();nv(a,e,Oo.width,Oo.height),s.update();let o=new We("measure-label-mat",this.scene);return o.diffuseTexture=s,o.emissiveColor=new he(1,1,1),o.disableLighting=!0,o.disableDepthWrite=!0,o.opacityTexture=s,o.useAlphaFromDiffuseTexture=!0,r.material=o,r}ensurePreviewLine(){this.previewLine||(this.previewLine=Pn.CreateLineSystem("measure-preview",{lines:Array.from({length:7},()=>[b.Zero(),b.Zero()]),updatable:!0},this.scene),this.previewLine.color=T$.clone(),this.previewLine.alpha=.82,this.previewLine.isPickable=!1,this.previewLine.renderingGroupId=2)}updatePreviewLine(){var l;if(!this.pendingPoint||!this.previewLine||!this.rootMesh)return;let e=this.toMeasurementDisplayPoint(this.pendingPoint),t=this.engine.getRenderingCanvas();if(!t)return;let i=t.getBoundingClientRect(),r=this.lastPointerClient.x-i.left,s=this.lastPointerClient.y-i.top,a=null;if(this.lastPointerClient.altKey){this.setMeasurementSnapKind("free");let c=this.scene.pick(r,s,f=>f!==this.previewLine&&!this.measurementMarkers.includes(f));a=c.hit&&c.pickedPoint?this.resolveMeasurementPickPoint(c.pickedPoint,!0):e.add(this.scene.createPickingRay(r,s,Q.Identity(),this.camera).direction.scale(5))}else{let c=this.pickFrontmostMeasurementTargetPoint(this.lastPointerClient.x,this.lastPointerClient.y);c?a=this.resolveMeasurementPickPoint(c,!1):this.setMeasurementSnapKind(null)}let o=a?this.createBabylonMeasurementDraftingLayout(this.pendingPoint,this.toMeasurementBasePoint(a)):null;this.previewLine=Pn.CreateLineSystem("measure-preview",{lines:(l=o==null?void 0:o.lineSegments)!=null?l:[[e,e]],instance:this.previewLine},this.scene),this.previewLine.color=T$.clone(),this.previewLine.alpha=.82,this.previewLine.isPickable=!1,this.previewLine.renderingGroupId=2}removePreviewLine(){this.previewLine&&(this.previewLine.dispose(),this.previewLine=null)}createMeasurementReading(e,t){return ux(this.toMeasurementPoint(e),this.toMeasurementPoint(t),this.measurementScale,this.measurementUnit)}createMeasurementRecords(){return this.measurementSegments.map((e,t)=>({index:t+1,start:this.toMeasurementPoint(e.start),end:this.toMeasurementPoint(e.end),reading:this.createMeasurementReading(e.start,e.end)}))}toMeasurementPoint(e){return{x:e.x,y:e.y,z:e.z}}createModelSummary(e){let t=this.getRenderableMeshes(e),i=b1(e),r=t.reduce((s,a)=>s+kd(a),0);return my(e.name,this.getRenderableBounds(e),t,{splatCount:i?r:void 0,resourceWarnings:this.resourceWarnings})}};Ga.annotationIdentity=Q.Identity(),Ga.annotationWorldPoint=b.Zero(),Ga.annotationProjection=b.Zero(),Ga.annotationDirection=b.Zero(),Ga.annotationRay=new on(b.Zero(),b.Zero(),1);Iy=Ga});async function L$(n,e){if(Bh(e).backend==="three"){let{createThreeModelPreview:r}=await Promise.resolve().then(()=>($V(),QV));return r(n)}let{createBabylonModelPreview:i}=await Promise.resolve().then(()=>(P$(),C$));return i(n)}var D$=y(()=>{"use strict";_S()});var N$={};Be(N$,{createBabylonGridRenderer:()=>ETe});function vTe(n){return n.replace(/\|/g,"\\|").replace(/\r?\n/g," ")}function y1(n){return new b(n.x,n.y,n.z)}function O$(n){return Number.isFinite(n)?Math.max(0,Math.min(n,1)):0}function ETe(n){return new I1(n)}var Rg,I1,w$=y(()=>{"use strict";zD();na();Eb();Sb();He();$t();up();ug();cd();lf();OE();OE();FE();FA();Ma();Lo();HA();Rg=32;I1=class{constructor(e){this.cells=[];this.initialCameras=[];this.wireframeEnabled=!1;this.rendering=!1;this.dirty=!0;this.contextLost=!1;this.warmupFrame=null;this.renderScale=1;this.cameraZoomObservers=new Set;this.preventCanvasWheelScroll=e=>{e.preventDefault(),e.stopPropagation()};this.handleContextLost=e=>{e.preventDefault(),this.contextLost=!0,this.rendering&&(this.engine.stopRenderLoop(),this.rendering=!1)};this.handleContextRestored=()=>{this.contextLost=!1,this.engine.resize(),this.startRenderLoop(),this.markDirty(),this.scheduleWarmupFrames()};e.className="ai3d-canvas-full",e.addEventListener("wheel",this.preventCanvasWheelScroll,{passive:!1}),this.engine=new ze(e,!0,{preserveDrawingBuffer:!0}),e.addEventListener("webglcontextlost",this.handleContextLost),e.addEventListener("webglcontextrestored",this.handleContextRestored),this.scene=new ai(this.engine),this.scene.clearColor=new ht(.12,.12,.14,1),this.scene.autoClear=!1,new Fa("default-light",new b(0,1,.5),this.scene),this.resizeObs=new ResizeObserver(()=>{this.engine.resize(),this.markDirty()}),this.resizeObs.observe(e),window.requestAnimationFrame(()=>this.engine.resize())}canRender(){let e=this.engine.getRenderingCanvas();return!!(e!=null&&e.isConnected)&&e.clientWidth>0&&e.clientHeight>0}markDirty(){this.dirty=!0}getCameraZoomRange(e){let t=e.radius,i=e.lowerRadiusLimit,r=e.upperRadiusLimit,s=typeof i=="number"&&Number.isFinite(i)&&i>0?i:Math.max(t*.08,1e-5),a=typeof r=="number"&&Number.isFinite(r)&&r>s?r:Math.max(t*8,s*10);return{current:Math.max(s,Math.min(t,a)),min:s,max:a}}notifyCameraZoomChanged(){if(this.cameraZoomObservers.size===0)return;let e=this.getCameraZoomState();for(let t of this.cameraZoomObservers)t(e)}scheduleWarmupFrames(e=8){this.warmupFrame!==null&&window.cancelAnimationFrame(this.warmupFrame),this.warmupFrame=window.requestAnimationFrame(()=>{this.warmupFrame=null,!(!this.canRender()||this.contextLost)&&(this.markDirty(),e>1&&this.scheduleWarmupFrames(e-1))})}getCellBounds(e){let t=Ql(e);if(!t)throw new Error("Grid cell has no renderable meshes");return t}async loadModels(e,t,i){var d,u,h;await DE();let r=e.length>Rg?(console.warn(`[AI3D Grid] Capping ${e.length} models to ${Rg} (layerMask limit)`),e.slice(0,Rg)):e,s=(d=t.columns)!=null?d:Math.min(r.length,3),a=(u=t.gapX)!=null?u:.02,o=(h=t.gapY)!=null?h:.02,l=Math.ceil(r.length/s),c=(1-a*(s+1))/s,f=(1-o*(l+1))/l;for(let m=0;m<r.length;m++){let g=r[m],p=m%s,_=Math.floor(m/s),v=a+p*(c+a),E=o+(l-1-_)*(f+o);try{await this.loadOne(g,i,v,E,c,f,m)}catch(S){console.error(`[AI3D Grid] Failed to load ${g.path}:`,S)}}this.startRenderLoop(),this.markDirty(),this.engine.resize(),this.scheduleWarmupFrames(),this.notifyCameraZoomChanged()}async loadWithPreset(e,t){await DE();let i=e.placements.length>Rg?(console.warn(`[AI3D Preset] Capping ${e.placements.length} placements to ${Rg} (layerMask limit)`),e.placements.slice(0,Rg)):e.placements,r=[];for(let f=0;f<i.length;f++){let d=i[f];try{let u=await this.loadPlacementMesh(d,t,f);r.push(u)}catch(u){console.error(`[AI3D Preset] Failed to load ${d.path}:`,u),r.push([])}}let s=r.flat(),a=b.Zero(),o=1,l=Ql(s);l&&(a=y1(mr(l)),o=Rs(l));let c=e.cells.length===1;for(let f of e.cells){let d=r[f.modelIndex];if(!d||d.length===0)continue;let u,h;if(c){u=[],h=0;for(let g=0;g<r.length;g++)r[g].length>0&&(u.push(...r[g]),h|=1<<g)}else u=d?[...d]:[],h=1<<f.modelIndex;for(let g of u)g.layerMask=h;let m=this.createCameraFromDef(f,d,this.cells.length,c?a:void 0,c?o:void 0);m.layerMask=h,this.cells.push({meshes:u,camera:m})}this.startRenderLoop(),this.markDirty(),this.engine.resize(),this.scheduleWarmupFrames(),this.notifyCameraZoomChanged()}async importMesh(e,t,i){var h,m,g;let r=(m=(h=e.split(".").pop())==null?void 0:h.replace(".","").toLowerCase())!=null?m:"glb",s=`data:application/octet-stream;base64,${Iu(t)}`,o=(g={glb:".glb",gltf:".gltf",stl:".stl",obj:".obj",splat:".splat",ply:".ply"}[r])!=null?g:`.${r}`,l=await TE(s,this.scene,{meshNames:"",pluginExtension:o});if(l.meshes.length===0)throw new Error(`No mesh in ${e}`);let c=l.meshes[0],f=Eh(c,l.meshes),d=EQ(l.meshes),u=1<<i;for(let p of f)p.layerMask=u;return"layerMask"in c&&(c.layerMask=u),{root:c,renderableMeshes:f,topLevelMeshes:d}}async loadPlacementMesh(e,t,i){let r=await t(e.path),{renderableMeshes:s,topLevelMeshes:a}=await this.importMesh(e.path,r,i),o=new ii(`placement-root-${i}`,this.scene);for(let l of a)l.parent=o;return e.position&&(o.position=new b(...e.position)),e.rotation&&(o.rotation=new b(...e.rotation)),e.scale!==void 0&&(o.scaling=new b(e.scale,e.scale,e.scale)),s}createCameraFromDef(e,t,i,r,s){var u,h;let a=this.getCellBounds(t),o=e.camera,l=o.target?{x:o.target[0],y:o.target[1],z:o.target[2]}:r?{x:r.x,y:r.y,z:r.z}:mr(a),c=dP(l,s!=null?s:Rs(a),{radiusMultiplier:(u=o.radiusMultiplier)!=null?u:2.5}),f=new Mi(`cell-cam-${i}`,o.alpha,o.beta,c.radius,y1(c.target),this.scene);f.fov=((h=o.fov)!=null?h:45)*Math.PI/180,f.minZ=c.near,f.maxZ=c.far,f.lowerRadiusLimit=c.lowerRadiusLimit,f.upperRadiusLimit=c.upperRadiusLimit,f.wheelPrecision=45,f.viewport=new Go(e.viewport.x,e.viewport.y,e.viewport.w,e.viewport.h),f.layerMask=1<<i;let d=this.engine.getRenderingCanvas();return d&&(f.attachControl(d,!0),f.onViewMatrixChangedObservable.add(()=>{this.markDirty(),this.notifyCameraZoomChanged()})),this.initialCameras.push({alpha:f.alpha,beta:f.beta,radius:f.radius,target:f.target.clone()}),f}async loadOne(e,t,i,r,s,a,o){var u,h;let l=await t(e.path),c=(h=(u=e.path.split(".").pop())==null?void 0:u.replace(".","").toLowerCase())!=null?h:"glb",{renderableMeshes:f}=await this.importMesh(e.path,l,o);if(c==="stl"&&e.color){let m=he.FromHexString(e.color);for(let g of f)g.material instanceof We&&g.material.name==="stl-mat"&&(g.material.diffuseColor=m)}if(c==="stl"&&e.wireframe!==void 0)for(let m of f)m.material instanceof We&&(m.material.wireframe=e.wireframe);let d=this.createCellCamera(f,o,i,r,s,a);this.cells.push({meshes:f,camera:d})}createCellCamera(e,t,i,r,s,a){let o=tv(this.getCellBounds(e)),l=new Mi(`cell-cam-${t}`,Math.PI/4,Math.PI/3,o.radius,y1(o.target),this.scene);l.fov=45*Math.PI/180,l.minZ=o.near,l.maxZ=o.far,l.lowerRadiusLimit=o.lowerRadiusLimit,l.upperRadiusLimit=o.upperRadiusLimit,l.wheelPrecision=45,l.viewport=new Go(i,r,s,a),l.layerMask=1<<t;let c=this.engine.getRenderingCanvas();return c&&(l.attachControl(c,!0),l.onViewMatrixChangedObservable.add(()=>{this.markDirty(),this.notifyCameraZoomChanged()})),this.initialCameras.push({alpha:l.alpha,beta:l.beta,radius:l.radius,target:l.target.clone()}),l}renderFrame(){if(!this.canRender()||!this.dirty||this.contextLost)return;this.dirty=!1;let e=this.engine,t=this.scene;e.clear(t.clearColor,!0,!0);for(let i of this.cells){e.setViewport(i.camera.viewport);let r=i.camera.viewport,s=e.getRenderWidth(),a=e.getRenderHeight();e.enableScissor(r.x*s,r.y*a,r.width*s,r.height*a),t.activeCamera=i.camera,t.render(),e.disableScissor()}}startRenderLoop(){this.rendering||(this.rendering=!0,this.engine.runRenderLoop(()=>this.renderFrame()))}captureSnapshot(){let e=this.engine.getRenderingCanvas();return e?(this.renderFrame(),e.toDataURL("image/png")):null}getEngine(){return this.engine}getScene(){return this.scene}getCellCount(){return this.cells.length}getCanvas(){return this.engine.getRenderingCanvas()}getPrimaryCamera(){var e,t;return(t=(e=this.cells[0])==null?void 0:e.camera)!=null?t:null}setRenderScale(e){let t=Math.max(.25,Math.min(e,2));this.renderScale=t;let i=Rr()?1.5:1;return this.engine.setHardwareScalingLevel(i/t),this.getRenderScale()}getRenderScale(){return Number(this.renderScale.toFixed(2))}getCameraZoomState(){var s;let e=(s=this.cells[0])==null?void 0:s.camera;if(!e)return null;let t=this.getCameraZoomRange(e),i=(t.max-t.current)/(t.max-t.min),r=O$(i);return{value:r,percentage:Math.round(r*100)}}setCameraZoom(e){if(this.cells.length===0)return null;let t=O$(e);for(let i of this.cells){let r=this.getCameraZoomRange(i.camera);i.camera.radius=r.max-t*(r.max-r.min)}return this.markDirty(),this.startRenderLoop(),this.notifyCameraZoomChanged(),this.getCameraZoomState()}observeCameraZoom(e){return this.cameraZoomObservers.add(e),e(this.getCameraZoomState()),()=>{this.cameraZoomObservers.delete(e)}}resetView(){for(let e=0;e<this.cells.length;e++){let t=this.cells[e].camera,i=this.initialCameras[e];i&&(t.alpha=i.alpha,t.beta=i.beta,t.radius=i.radius,t.target=i.target.clone())}this.markDirty(),this.notifyCameraZoomChanged()}toggleWireframe(){this.wireframeEnabled=!this.wireframeEnabled;for(let e of this.cells)for(let t of e.meshes)t.material instanceof We&&(t.material.wireframe=this.wireframeEnabled);return this.wireframeEnabled}exportModelInfo(){if(this.cells.length===0)return"";let e=[];e.push("## Grid Models \u2014 Model Info"),e.push(""),e.push("| # | Model | Meshes | Triangles | Vertices | Materials |"),e.push("|---|-------|--------|-----------|----------|-----------|");for(let t=0;t<this.cells.length;t++){let i=this.cells[t],r=i.meshes[0];if(!r)continue;let s=r.name||`Model ${t+1}`,a=my(s,this.getCellBounds(i.meshes),i.meshes);e.push(`| ${t+1} | ${vTe(s)} | ${a.meshCount} | ${a.triangleCount.toLocaleString()} | ${a.vertexCount.toLocaleString()} | ${a.materialCount} |`)}return e.push(""),e.join(`
`)}destroy(){this.cameraZoomObservers.clear(),this.warmupFrame!==null&&(window.cancelAnimationFrame(this.warmupFrame),this.warmupFrame=null),this.engine.stopRenderLoop();for(let t of this.cells)t.camera.detachControl();let e=this.engine.getRenderingCanvas();e==null||e.removeEventListener("wheel",this.preventCanvasWheelScroll),this.resizeObs.disconnect(),this.scene.dispose(),this.engine.dispose(),this.cells=[]}}});async function F$(n){let{createBabylonGridRenderer:e}=await Promise.resolve().then(()=>(w$(),N$));return e(n)}var B$=y(()=>{"use strict"});var G$={};Be(G$,{createLoggedGridRenderer:()=>C1,createLoggedModelPreview:()=>bg,logGridPreviewSelection:()=>V$,logModelPreviewSelection:()=>U$});function U$(n,e,t){n.info("select preview backend",{...e,backend:t.backend,reason:t.reason,ext:t.ext,annotationMode:t.annotationMode,requireWorkbenchFeatures:t.requireWorkbenchFeatures,rendererRollout:t.rendererRollout})}async function bg(n,e,t,i){let r=Bh(i);return U$(n,e,r),{preview:await L$(t,i),route:r}}function V$(n,e,t){n.info("select preview backend",{...e,backend:t.backend,reason:t.reason})}async function C1(n,e,t){let i=uB();return V$(n,e,i),{renderer:await F$(t),route:i}}var Cy=y(()=>{"use strict";D$();B$();_S()});function P1(n){z$=n}function Py(n){return k$[n]>=k$[z$]}function Ly(){return new Date().toISOString()}function Dy(n){return n&&Object.keys(n).length>0?n:void 0}function er(n){let e=`[AI3D][${n}]`;return{debug(t,i){Py("debug")&&console.debug(e,Ly(),t,Dy(i))},info(t,i){Py("info")&&console.debug(e,Ly(),t,Dy(i))},warn(t,i){Py("warn")&&console.warn(e,Ly(),t,Dy(i))},error(t,i){Py("error")&&console.error(e,Ly(),t,Dy(i))}}}var k$,z$,zn=y(()=>{"use strict";k$={debug:10,info:20,warn:30,error:40},z$="warn"});var H$={};Be(H$,{supportsAnimationPreview:()=>Ny,supportsAnnotationPreview:()=>Oy,supportsBoundingBoxPreview:()=>Fy,supportsCameraZoomPreview:()=>By,supportsDisassemblyPreview:()=>Sh,supportsFocusSelectionPreview:()=>Th,supportsMeasurementPreview:()=>cn,supportsOrientationGizmoPreview:()=>VE,supportsRenderScalePreview:()=>GE,supportsSlicePreview:()=>Hd,supportsWireframePreview:()=>wy,supportsWorkbenchPreview:()=>W$});function Di(n,e){return!!n&&typeof n=="object"&&typeof n[e]=="function"}function Oy(n){return Di(n,"getAnnotationProvider")}function Ny(n){return Di(n,"hasAnimations")&&Di(n,"toggleAnimation")}function cn(n){return Di(n,"toggleMeasurement")&&Di(n,"isMeasurementActive")&&Di(n,"cancelMeasurement")&&Di(n,"clearMeasurements")&&Di(n,"setMeasurementScale")&&Di(n,"getMeasurementScale")&&Di(n,"setMeasurementUnit")&&Di(n,"getMeasurementUnit")&&Di(n,"getMeasurementBounds")&&Di(n,"getMeasurementRecords")&&Di(n,"getMeasurementState")&&Di(n,"updateMeasurementLabels")&&Di(n,"exportMeasurements")}function Hd(n){return Di(n,"toggleSlice")&&Di(n,"isSliceActive")&&Di(n,"setSlicePlane")&&Di(n,"setSliceOffset")&&Di(n,"setSliceRotation")&&Di(n,"resetSlicePlane")&&Di(n,"getSliceState")}function Sh(n){return Di(n,"toggleDisassembly")&&Di(n,"resetDisassembly")&&Di(n,"isDisassemblyEnabled")}function Th(n){return Di(n,"toggleFocusSelection")&&Di(n,"isFocusSelectionEnabled")}function wy(n){return Di(n,"toggleWireframe")}function VE(n){return Di(n,"toggleOrientationGizmo")}function Fy(n){return Di(n,"toggleBoundingBox")}function GE(n){return Di(n,"setRenderScale")}function By(n){return Di(n,"getCameraZoomState")&&Di(n,"setCameraZoom")}function W$(n){return Di(n,"setExplode")&&Di(n,"resetExplode")&&Di(n,"focusWorldPoint")}var Ah=y(()=>{"use strict"});function Uy(n,e){return Cu(n,e)}function X$(n){return Number.isFinite(n)?Math.max(0,Math.min(n,1)):0}function Vy(n,e){let t=Uy("div","ai3d-zoom-control is-hidden"),i=Uy("div","ai3d-zoom-track"),r=Uy("div","ai3d-zoom-fill"),s=Uy("input","ai3d-zoom-range");s.type="range",s.min="0",s.max="100",s.step="1",s.value="0",s.setAttribute("aria-label",H("helper.cameraZoomLabel")),s.setAttribute("aria-orientation","vertical"),i.appendChild(r),t.append(i,s),n.appendChild(t);let a=null,o=null,l=null,c=E=>{E.stopPropagation()};t.addEventListener("mousedown",c),t.addEventListener("click",c);function f(){let E=e();return By(E)?E:null}function d(E){if(!E){t.classList.add("is-hidden"),s.disabled=!0;return}let S=X$(E.value),T=Math.round(S*100);s.disabled=!1,s.value=String(T),t.style.setProperty("--ai3d-zoom-percent",`${T}%`);let A=Wi("helper.cameraZoomValue",{value:`${E.percentage}%`});s.setAttribute("aria-valuenow",String(T)),s.setAttribute("aria-valuetext",A),t.setAttribute("title",A),t.classList.remove("is-hidden")}function u(E){E!==a&&(o==null||o(),o=null,a=E,E!=null&&E.observeCameraZoom&&(o=E.observeCameraZoom(d)))}function h(){var S;let E=f();u(E),d((S=E==null?void 0:E.getCameraZoomState())!=null?S:null)}function m(){g(s.valueAsNumber/100)}function g(E){let S=a!=null?a:f();if(!S){h();return}u(S),d(S.setCameraZoom(X$(E)))}function p(E){let S=i.getBoundingClientRect();return S.height<=0?s.valueAsNumber/100:1-(E-S.top)/S.height}function _(E){E.preventDefault(),E.stopPropagation(),s.focus({preventScroll:!0}),g(p(E.clientY))}function v(E){var S;l===E.pointerId&&(E.preventDefault(),E.stopPropagation(),(S=t.hasPointerCapture)!=null&&S.call(t,E.pointerId)&&t.releasePointerCapture(E.pointerId),l=null,t.classList.remove("is-dragging"))}return s.addEventListener("input",m),t.addEventListener("pointerdown",E=>{var S;if(E.button!==0||s.disabled){E.stopPropagation();return}l=E.pointerId,(S=t.setPointerCapture)==null||S.call(t,E.pointerId),t.classList.add("is-dragging"),_(E)}),t.addEventListener("pointermove",E=>{l===E.pointerId&&_(E)}),t.addEventListener("pointerup",v),t.addEventListener("pointercancel",v),t.addEventListener("wheel",E=>{E.preventDefault(),E.stopPropagation();let S=E.deltaY<0?6:-6;s.value=String(Math.max(0,Math.min(100,s.valueAsNumber+S))),m()},{passive:!1}),h(),{sync:h,destroy(){o==null||o(),o=null,a=null,t.remove()}}}var L1=y(()=>{"use strict";xn();Ah();Fm()});function Y$(n){for(let e of STe)if(n[e])return e;return"idle"}function K$(n){return n!=="idle"}var STe,j$=y(()=>{"use strict";STe=["annotation","slice","measurement","disassembly","focus"]});function Br(n){let e=createSvg("svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","16"),e.setAttribute("height","16");let t=new DOMParser().parseFromString(`<svg xmlns="http://www.w3.org/2000/svg">${n}</svg>`,"image/svg+xml");for(let i of Array.from(t.documentElement.childNodes))e.appendChild(activeDocument.importNode(i,!0));return e}function Z$(n){var a,o;let[e,t]=n.split(","),i=(o=(a=e.match(/:(.*?);/))==null?void 0:a[1])!=null?o:"image/png",r=atob(t),s=new Uint8Array(r.length);for(let l=0;l<r.length;l++)s[l]=r.charCodeAt(l);return new Blob([s],{type:i})}function Gy(n){return typeof n!="number"||!Number.isFinite(n)?1:Math.max(.25,Math.min(n,2))}function D1(n){let e=Gy(n),t=ATe;return Mg.forEach((i,r)=>{let s=Math.abs(i-e),a=Math.abs(Mg[t]-e);s<a&&(t=r)}),t}function q$(n){return`${Math.round(Gy(n)*100)}%`}function O1(n,e){var t,i;return Gy((i=(t=n==null?void 0:n.getRenderScale)==null?void 0:t.call(n))!=null?i:e)}function Qr(n,e){return n.dataset.ai3dAction=e,n.dataset.testid=`ai3d-action-${e}`,n}function Q$(n,e){n.classList.toggle("is-mobile-interactive",e),n.classList.toggle("is-mobile-scroll-mode",!e)}function kE(n,e,t,i,r,s,a,o,l,c){var Hn,Oi;let f=Rr(),d=c!=null?c:{labelKey:"helper.toggleAnnotationLabel",activeTooltipKey:"helper.annotateOn",inactiveTooltipKey:"helper.annotateOff"},u=n.createDiv({cls:"ai3d-helper-toolbar ai3d-helper-toolbar-adaptive"}),h=u.createDiv({cls:"ai3d-helper-group ai3d-helper-group-view"}),m=u.createDiv({cls:"ai3d-helper-group ai3d-helper-group-inspect"}),g=u.createDiv({cls:"ai3d-helper-group ai3d-helper-group-output"}),p=u.createSpan({cls:"ai3d-interaction-status is-hidden"}),_=X=>{X.stopPropagation()};u.addEventListener("pointerdown",_),u.addEventListener("mousedown",_),u.addEventListener("click",_);let v=X=>{if(X.key!=="Escape"||X.defaultPrevented)return;let xe=X.target;if(xe instanceof Node&&!u.contains(xe)&&!e.contains(xe))return;let At=U();!At||!dx(At)||(Qe(),X.preventDefault(),X.stopPropagation())};u.addEventListener("keydown",v),e.addEventListener("keydown",v),f&&(u.classList.add("is-mobile"),Q$(e,!1));let E=Vy(e,i),S=null,T=null,A=null,R=null,M=!1,I="idle",C=X=>(X.classList.add("is-secondary"),X),L=(X,xe)=>{X.classList.toggle("ai3d-btn-active",xe),X.setAttribute("aria-pressed",String(xe))},w=()=>{for(let X of[h,m,g]){let xe=Array.from(X.querySelectorAll(".ai3d-inline-btn")).filter(st=>!st.classList.contains("is-hidden")),At=xe.length>0,kt=xe.some(st=>!st.classList.contains("is-secondary"));X.classList.toggle("is-hidden",!At),X.classList.toggle("has-primary-visible",kt)}},G=!1,O=!1,N=f?h.createEl("button",{cls:"ai3d-inline-btn ai3d-mobile-mode-btn",attr:{"aria-label":H("helper.enableInteractionLabel"),"aria-pressed":"false"}}):null;N==null||N.appendChild(Br('<path d="M12 2v8"/><path d="M8 6l4-4 4 4"/><path d="M6 14a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v5a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3z"/>'));let B=(Hn=N==null?void 0:N.createSpan({cls:"ai3d-mobile-mode-btn-label"}))!=null?Hn:null,V=()=>{f&&N&&(Q$(e,G),L(N,G),B==null||B.setText(G?H("helper.scrollAction"):H("helper.interactAction")),N.setAttribute("aria-label",G?H("helper.disableInteractionLabel"):H("helper.enableInteractionLabel"))),L(Wt,O),u.classList.toggle("show-secondary",O),w()},q=X=>{G=X,V()};N==null||N.addEventListener("click",()=>{let X=!G;l==null||l(X),q(X),vi(N,X?H("helper.interactionOn"):H("helper.interactionOff"))});let K=(X,xe)=>{X.classList.toggle("is-hidden",!xe)},J=null,Y=X=>{switch(X){case"annotation":return H("helper.interactionModeAnnotation");case"focus":return H("helper.interactionModeFocus");case"disassembly":return H("helper.interactionModeDisassembly");case"measurement":return H("helper.interactionModeMeasurement");case"slice":return H("helper.interactionModeSlice");case"idle":return""}},j=(X,xe,At,kt)=>{let st=Y$({annotation:M,focus:!!(X!=null&&X.isFocusSelectionEnabled()),disassembly:!!(xe!=null&&xe.isDisassemblyEnabled()),measurement:!!(At!=null&&At.isMeasurementActive()),slice:!!(kt!=null&&kt.isSliceActive())});u.dataset.ai3dInteractionMode=st,e.dataset.ai3dInteractionMode=st,e.classList.toggle("ai3d-interaction-active",K$(st)),I!==st&&(e.classList.remove(`ai3d-interaction-${I}`),st!=="idle"&&e.classList.add(`ai3d-interaction-${st}`),I=st),p.textContent=Y(st),p.classList.toggle("is-hidden",st==="idle");let Qt=[["annotation",qe],["focus",we],["disassembly",dt],["measurement",Ti],["slice",Ve]];for(let[$r,Zi]of Qt)Zi.classList.toggle("ai3d-linked-inactive",st!=="idle"&&st!==$r)},ue=()=>{var Qt;let X=i(),xe=X&&Th(X)?X:null,At=X&&Sh(X)?X:null,kt=X&&cn(X)?X:null,st=X&&Hd(X)?X:null;L(we,!!(xe!=null&&xe.isFocusSelectionEnabled())),L(dt,!!(At!=null&&At.isDisassemblyEnabled())),L(Ti,!!(kt!=null&&kt.isMeasurementActive())),L(Ve,!!(st!=null&&st.isSliceActive())),L(qe,M),X&&VE(X)&&L(de,!!((Qt=X.isOrientationGizmoEnabled)!=null&&Qt.call(X))),j(xe,At,kt,st)},Ee=()=>{!M||!o||(M=o(),L(qe,M))},Ue=()=>{let X=i();X&&(Hd(X)&&X.isSliceActive()&&X.toggleSlice(),cn(X)&&X.isMeasurementActive()&&X.toggleMeasurement(),Sh(X)&&X.isDisassemblyEnabled()&&X.toggleDisassembly(),Th(X)&&X.isFocusSelectionEnabled()&&X.toggleFocusSelection())},se=()=>{let X=i(),xe=X&&Th(X)?X:null,At=X&&Sh(X)?X:null,kt=X&&Ny(X)?X:null,st=X&&GE(X)?X:null;X!==J&&(J=X,L(Le,!1),L(be,!1),L(ae,!1),ae.replaceChildren(Br('<polygon points="5 3 19 12 5 21 5 3"/>')),K(ve,!!(X!=null&&X.resetView)),K(ne,!!(X!=null&&X.exportModelInfo)),K(me,!!(X!=null&&X.exportSelectedPartInfo)),K(Le,!!X&&wy(X)),K(de,!!X&&VE(X)),K(be,!!X&&Fy(X)),K(we,!!xe),K(dt,!!At),K(Bt,!!st),K(Ve,!!X&&Hd(X)),K(ae,!!(kt!=null&&kt.hasAnimations()))),wi(st),K(Ti,!!X&&cn(X)),ue(),Qe(),$i(),w(),E.sync()},ve=h.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":H("helper.resetViewLabel")}});Qr(ve,"reset-view"),ve.appendChild(Br('<polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/>')),ve.addEventListener("click",()=>{let X=i();X!=null&&X.resetView&&(X.resetView(),se(),vi(ve,H("helper.resetViewDone")))});let ne=C(m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":H("helper.copyModelInfoLabel")}}));Qr(ne,"copy-model-info"),ne.appendChild(Br('<circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/>')),ne.addEventListener("click",()=>{let X=i();if(X!=null&&X.exportModelInfo)try{let xe=X.exportModelInfo(r());if(!xe)return;navigator.clipboard.writeText(xe).then(()=>{vi(ne,H("helper.copied"))}).catch(()=>{vi(ne,H("helper.failed"))})}catch(xe){console.error("[AI3D] Export model info failed:",xe),vi(ne,H("helper.failed"))}});let me=C(m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":H("helper.copySelectedPartInfoLabel")}}));Qr(me,"copy-selected-part-info"),me.appendChild(Br('<path d="M12 2v4"/><path d="M12 18v4"/><path d="M2 12h4"/><path d="M18 12h4"/><circle cx="12" cy="12" r="4"/><path d="M17 19h5"/><path d="M17 16h5"/><path d="M17 22h5"/>')),me.addEventListener("click",()=>{let X=i();if(X!=null&&X.exportSelectedPartInfo)try{let xe=X.exportSelectedPartInfo();if(!xe){vi(me,H("helper.noSelectedPart"));return}navigator.clipboard.writeText(xe).then(()=>{vi(me,H("helper.copied"))}).catch(()=>{vi(me,H("helper.failed"))})}catch(xe){console.error("[AI3D] Export selected part info failed:",xe),vi(me,H("helper.failed"))}});let Le=h.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":H("helper.toggleWireframeLabel"),"aria-pressed":"false"}});Qr(Le,"toggle-wireframe"),Le.appendChild(Br('<rect x="3" y="3" width="18" height="18" rx="2"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="12" y1="3" x2="12" y2="21"/>')),Le.addEventListener("click",()=>{let X=i();if(!(X!=null&&X.toggleWireframe))return;let xe=X.toggleWireframe();L(Le,xe),vi(Le,xe?H("helper.wireframeOn"):H("helper.wireframeOff"))});let de=h.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":H("helper.toggleAxesLabel"),"aria-pressed":"false"}});Qr(de,"toggle-axes"),de.appendChild(Br('<path d="M12 2v20"/><path d="M2 12h20"/><path d="M12 2l4 4"/><path d="M12 2l-4 4"/><path d="M22 12l-4-4"/><path d="M22 12l-4 4"/>')),de.addEventListener("click",()=>{let X=i();if(!(X!=null&&X.toggleOrientationGizmo))return;let xe=X.toggleOrientationGizmo();L(de,xe),vi(de,xe?H("helper.axesOn"):H("helper.axesOff"))});let be=h.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":H("helper.toggleBoundingBoxLabel"),"aria-pressed":"false"}});Qr(be,"toggle-bounding-box"),be.appendChild(Br('<path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/>')),be.addEventListener("click",()=>{let X=i();if(!(X!=null&&X.toggleBoundingBox))return;let xe=X.toggleBoundingBox();L(be,xe),vi(be,xe?H("helper.boundingBoxOn"):H("helper.boundingBoxOff"))});let we=m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":H("helper.toggleFocusSelectionLabel"),"aria-pressed":"false"}});Qr(we,"toggle-focus"),we.appendChild(Br('<circle cx="12" cy="12" r="3"/><path d="M12 2v3"/><path d="M12 19v3"/><path d="M2 12h3"/><path d="M19 12h3"/><path d="M4.93 4.93l2.12 2.12"/><path d="M16.95 16.95l2.12 2.12"/><path d="M19.07 4.93l-2.12 2.12"/><path d="M7.05 16.95l-2.12 2.12"/>')),we.addEventListener("click",()=>{let X=i();if(!X||!Th(X))return;X.isFocusSelectionEnabled()||Ee();let xe=X.toggleFocusSelection();se(),vi(we,xe?H("helper.focusSelectionOn"):H("helper.focusSelectionOff"))});let dt=m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":H("helper.toggleDisassemblyLabel"),"aria-pressed":"false"}});Qr(dt,"toggle-disassembly"),dt.appendChild(Br('<rect x="4" y="4" width="6" height="6" rx="1"/><rect x="14" y="4" width="6" height="6" rx="1"/><rect x="4" y="14" width="6" height="6" rx="1"/><path d="M14 17h6"/><path d="M17 14v6"/>')),dt.addEventListener("click",()=>{let X=i();if(!X||!Sh(X))return;X.isDisassemblyEnabled()||Ee();let xe=X.toggleDisassembly();se(),vi(dt,xe?H("helper.disassemblyOn"):H("helper.disassemblyOff"))});let Ve=m.createEl("button",{cls:"ai3d-inline-btn ai3d-slice-btn is-hidden",attr:{"aria-label":H("helper.toggleSliceLabel"),"aria-pressed":"false"}});Qr(Ve,"toggle-slice"),Ve.appendChild(Br('<path d="M4 7l8-4 8 4-8 4-8-4z"/><path d="M4 12l8 4 8-4"/><path d="M4 17l8 4 8-4"/><path d="M4 12l3-1.5"/><path d="M17 10.5l3 1.5"/>')),Ve.createSpan({cls:"ai3d-slice-btn-text",text:H("helper.sliceButtonText")}),Ve.addEventListener("click",()=>{let X=i();if(!X||!Hd(X))return;X.isSliceActive()||Ee();let xe=X.toggleSlice();se(),vi(Ve,xe?H("helper.sliceOn"):H("helper.sliceOff"))});let Ze=Gy((Oi=a==null?void 0:a().renderScale)!=null?Oi:1),Kt=D1(Ze),Bt=C(h.createEl("button",{cls:"ai3d-inline-btn ai3d-res-btn",attr:{"aria-label":H("helper.changeResolutionLabel")}}));Qr(Bt,"change-resolution");function wi(X=null){var kt,st;let xe=O1(X,(st=(kt=a==null?void 0:a().renderScale)!=null?kt:Mg[Kt])!=null?st:1);Kt=D1(xe);let At=q$(xe);Bt.textContent=At,Bt.setAttribute("title",Wi("helper.resolutionValue",{value:At}))}wi(),Bt.addEventListener("click",()=>{let X=i();if(!X||!GE(X))return;Kt=(D1(O1(X,Mg[Kt]))+1)%Mg.length;let At=X.setRenderScale(Mg[Kt]),kt=O1(X,At);wi(X),vi(Bt,Wi("helper.resolutionValue",{value:q$(kt)}))});let ae=C(h.createEl("button",{cls:"ai3d-inline-btn is-hidden",attr:{"aria-label":H("helper.toggleAnimationLabel"),"aria-pressed":"false"}}));Qr(ae,"toggle-animation"),ae.appendChild(Br('<polygon points="5 3 19 12 5 21 5 3"/>')),ae.addEventListener("click",()=>{let X=i();if(!(X!=null&&X.toggleAnimation))return;let xe=X.toggleAnimation();ae.replaceChildren(Br(xe?'<rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/>':'<polygon points="5 3 19 12 5 21 5 3"/>')),L(ae,xe),vi(ae,xe?H("helper.playing"):H("helper.paused"))});let Ti=m.createEl("button",{cls:"ai3d-inline-btn is-hidden",attr:{"aria-label":H("helper.toggleMeasurementLabel"),"aria-pressed":"false",title:H("helper.toggleMeasurementLabel")}});Qr(Ti,"toggle-measurement"),Ti.appendChild(Br('<line x1="2" y1="21" x2="22" y2="21"/><line x1="2" y1="3" x2="22" y2="3"/><line x1="2" y1="12" x2="22" y2="12"/><line x1="6" y1="3" x2="6" y2="12"/><line x1="12" y1="3" x2="12" y2="12"/><line x1="18" y1="3" x2="18" y2="12"/>')),Ti.addEventListener("click",()=>{let X=i();if(!X||!cn(X))return;X.isMeasurementActive()||Ee();let xe=X.toggleMeasurement();se(),vi(Ti,xe?H("helper.measurementOn"):H("helper.measurementOff")),xe||L(ft,!1)});function hi(X){let xe=i();!xe||!cn(xe)||(xe.clearMeasurements(),L(Ti,xe.isMeasurementActive()),Qe(),vi(X,H("helper.measurementsCleared")))}function rr(X){let xe=i();if(!xe||!cn(xe))return;let At=xe.exportMeasurements();if(!At){vi(X,H("helper.noMeasurements"));return}navigator.clipboard.writeText(At).then(()=>{vi(X,H("helper.measurementsCopied"))}).catch(()=>{vi(X,H("helper.failed"))})}let Ke=m.createEl("button",{cls:"ai3d-measurement-strip is-hidden",attr:{"aria-expanded":"false","aria-label":H("helper.calibrateLabel")}});Qr(Ke,"toggle-measurement-details"),Ke.setAttribute("aria-live","polite");let ar=Ke.createSpan({cls:"ai3d-measurement-strip-value"}),Z=Ke.createSpan({cls:"ai3d-measurement-strip-meta"});function U(){let X=i();return X&&cn(X)?X:null}function ge(X){X!==S&&(T==null||T(),T=null,S=X,X!=null&&X.observeMeasurements&&(T=X.observeMeasurements(()=>{ue(),Qe()})))}function De(X){var At;if(X.phase==="select-target")return H("helper.measurementSelectTarget");if(X.phase==="picking-end"&&X.snapKind)return ke(X.snapKind);if(X.phase==="picking-end")return H("helper.measurementPickEnd");let xe=(At=X.records[X.records.length-1])!=null?At:null;return xe?zf(xe.reading.distance,xe.reading.unit):X.snapKind?ke(X.snapKind):X.phase==="ready"?H("helper.measurementPickStart"):X.phase==="reviewing"?H("helper.measurementReviewing"):H("helper.measurementStripEmpty")}function ke(X){switch(X){case"vertex":return H("helper.measurementSnapVertex");case"edge":return H("helper.measurementSnapEdge");case"free":return H("helper.measurementSnapFree")}}function it(X){return X.records.length>0?Wi("helper.measurementStripSaved",{count:String(X.records.length)}):X.phase==="select-target"?H("helper.measurementTargetMissing"):X.targetScope==="model"?H("helper.measurementTargetModel"):X.targetName?Wi("helper.measurementTargetLabel",{target:X.targetName}):X.unit}function Qe(){let X=U();if(ge(X),!X){Ke.classList.add("is-hidden"),Ut.classList.add("is-hidden"),Ke.classList.remove("is-expanded"),Ke.setAttribute("aria-expanded","false"),Ce.disabled=!0,ft.disabled=!0;return}let xe=X.getMeasurementState(),At=xe.active,kt=xe.records,st=kt.length>0;Ke.classList.toggle("is-hidden",xe.phase==="inactive"),!At&&!st&&(Ut.classList.add("is-hidden"),Ke.classList.remove("is-expanded"),Ke.setAttribute("aria-expanded","false")),Ke.classList.toggle("is-active",At),Ke.classList.toggle("is-pending",xe.phase==="picking-end"),Ke.classList.toggle("is-targeting",xe.phase==="select-target"),Ke.classList.toggle("is-reviewing",xe.phase==="reviewing"),Ke.classList.toggle("has-records",st),Ke.dataset.ai3dMeasurementPhase=xe.phase,ar.textContent=De(xe),Z.textContent=it(xe),Ke.setAttribute("aria-label",[H("helper.measurementStripTitle"),ar.textContent,Z.textContent,H("helper.calibrateLabel")].filter(Boolean).join(" ")),rt.textContent=st?Wi("helper.measurementStripSaved",{count:String(kt.length)}):H("helper.measurementNoRecords");let Qt=st;Ce.disabled=!Qt,ft.disabled=!Qt,L(Ti,At)}let Me=g.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":H("helper.copySnapshotLabel")}});Qr(Me,"copy-snapshot"),Me.appendChild(Br('<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>')),Me.addEventListener("click",()=>{let X=i();if(X)try{let xe=X.captureSnapshot();if(!xe)return;let At=Z$(xe);navigator.clipboard.write([new ClipboardItem({"image/png":At})]).then(()=>{vi(Me,H("helper.copied"))}).catch(()=>{vi(Me,H("helper.failed"))})}catch(xe){console.error("[AI3D] Copy snapshot failed:",xe),vi(Me,H("helper.failed"))}});let Pe=C(g.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":H("helper.saveSnapshotLabel")}}));Qr(Pe,"save-snapshot"),Pe.appendChild(Br('<path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/>')),Pe.addEventListener("click",()=>{var xe,At;let X=i();if(X)try{let kt=X.captureSnapshot();if(!kt)return;let st=r(),Qt=gn(st)||"model",$r=a==null?void 0:a(),Zi=(xe=$r==null?void 0:$r.snapshotFolder)!=null?xe:"Media/3D Previews",cl=(At=$r==null?void 0:$r.snapshotNaming)!=null?At:"model-name",nc=Date.now(),cS=cl==="timestamp"?`snapshot_${nc}.png`:`${Qt}_snapshot_${nc}.png`,Vte=Z$(kt),Yg=new FileReader;Yg.onload=()=>{let Gte=Yg.result;t.vault.adapter.exists(Zi).then(D0=>D0?Promise.resolve():t.vault.createFolder(Zi).catch(kte=>{TTe.warn("Failed to create vault folder",{path:Zi,error:String(kte)})})).then(()=>t.vault.createBinary(`${Zi}/${cS}`,Gte)).then(()=>{vi(Pe,H("helper.saved"))}).catch(D0=>{console.error("[AI3D] Save snapshot failed:",D0),vi(Pe,H("helper.failed"))})},Yg.onerror=()=>{console.error("[AI3D] FileReader error"),vi(Pe,H("helper.failed"))},Yg.onabort=()=>{console.error("[AI3D] FileReader aborted"),vi(Pe,H("helper.failed"))},Yg.readAsArrayBuffer(Vte)}catch(kt){console.error("[AI3D] Save snapshot failed:",kt),vi(Pe,H("helper.failed"))}});let ut=C(g.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":H("helper.downloadSnapshotLabel")}}));Qr(ut,"download-snapshot"),ut.appendChild(Br('<path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/>')),ut.addEventListener("click",()=>{let X=i();if(X)try{let xe=X.captureSnapshot();if(!xe)return;let At=r(),st=`${gn(At)||"model"}_snapshot_${Date.now()}.png`,Qt=createEl("a");Qt.href=xe,Qt.download=st,activeDocument.body.appendChild(Qt),Qt.click(),Qt.remove(),vi(ut,H("helper.downloaded"))}catch(xe){console.error("[AI3D] Download snapshot failed:",xe),vi(ut,H("helper.failed"))}});let bt=C(g.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":H("helper.removePreviewLabel")}}));Qr(bt,"remove-preview"),bt.appendChild(Br('<polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2"/>')),bt.addEventListener("click",s);let qe=m.createEl("button",{cls:"ai3d-inline-btn is-hidden ai3d-annot-btn",attr:{"aria-label":H(d.labelKey),"aria-pressed":"false"}});Qr(qe,"toggle-annotation"),qe.appendChild(Br('<path d="M20.59 13.41l-7.17 7.17a2 2 0 01-2.83 0L2 12V2h10l8.59 8.59a2 2 0 010 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/>'));let Je=qe.createSpan({cls:"ai3d-pin-badge is-hidden"});qe.addEventListener("click",()=>{if(!o)return;M||Ue();let X=o();M=X,se(),vi(qe,X?H(d.activeTooltipKey):H(d.inactiveTooltipKey))});let Wt=u.createEl("button",{cls:"ai3d-inline-btn ai3d-mobile-more-toggle",attr:{"aria-label":H("helper.showMoreActionsLabel"),"aria-pressed":"false"}});Wt.appendChild(Br('<circle cx="5" cy="12" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="19" cy="12" r="1.5"/>')),Wt.addEventListener("click",()=>{O=!O,Wt.setAttribute("aria-label",O?H("helper.hideMoreActionsLabel"):H("helper.showMoreActionsLabel")),V(),vi(Wt,O?H("helper.moreActionsShown"):H("helper.moreActionsHidden"))}),n.insertBefore(u,e.nextSibling);let Ut=u.createDiv({cls:"ai3d-measurement-details is-hidden"});Ut.setAttribute("role","group"),Ut.setAttribute("aria-label",H("helper.calibrateTitle")),Ut.addEventListener("pointerdown",_),Ut.addEventListener("mousedown",_),Ut.addEventListener("click",_),Ut.createDiv({cls:"ai3d-measurement-details-title",text:H("helper.calibrateTitle")});let yi=Ut.createDiv({cls:"ai3d-measurement-section ai3d-measurement-records-section"});yi.createDiv({cls:"ai3d-measurement-section-title",text:H("helper.measurementRecordsTitle")});let oe=yi.createDiv({cls:"ai3d-measurement-detail-row ai3d-measurement-detail-actions"}),rt=oe.createSpan({cls:"ai3d-measurement-record-summary"}),Ce=oe.createEl("button",{cls:"ai3d-inline-btn ai3d-measurement-detail-action",attr:{"aria-label":H("helper.copyMeasurementsLabel")}});Qr(Ce,"copy-measurements"),Ce.appendChild(Br('<path d="M4 19h16"/><path d="M7 16V8"/><path d="M12 16V5"/><path d="M17 16v-6"/><path d="M4 4h16"/>')),Ce.addEventListener("click",()=>{rr(Ce)});let ft=oe.createEl("button",{cls:"ai3d-inline-btn ai3d-measurement-detail-action",attr:{"aria-label":H("helper.clearMeasurementsLabel")}});Qr(ft,"clear-measurements"),ft.appendChild(Br('<polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/>')),ft.addEventListener("click",()=>{hi(ft)});let nt=Ut.createDiv({cls:"ai3d-measurement-section ai3d-measurement-calibration-section"});nt.createDiv({cls:"ai3d-measurement-section-title",text:H("helper.measurementCalibrationTitle")});let Ge=nt.createDiv({cls:"ai3d-measurement-detail-row ai3d-measurement-unit-row"});Ge.createSpan({cls:"ai3d-measurement-detail-label",text:H("helper.measurementUnitLabel")});let Mt=Ge.createEl("select",{cls:"ai3d-measurement-detail-select"});for(let X of["um","mm","cm","m"]){let xe=Mt.createEl("option");xe.value=X,xe.textContent=X}Mt.value="mm";let qt=nt.createDiv({cls:"ai3d-measurement-detail-row ai3d-measurement-reference-row"});qt.createSpan({cls:"ai3d-measurement-detail-label",text:H("helper.calibrateReference")});let Er=qt.createSpan({cls:"ai3d-measurement-detail-readonly ai3d-measurement-reference-value"}),_i=qt.createEl("input",{cls:"ai3d-measurement-detail-input ai3d-measurement-reference-input",attr:{type:"number",step:"any",min:"0",placeholder:H("helper.calibrateReferencePlaceholder")}}),Gr=qt.createEl("button",{cls:"ai3d-inline-btn ai3d-measurement-reference-apply",text:H("helper.calibrateReferenceApply"),attr:{type:"button"}});Qr(Gr,"calibrate-reference");let cr=Ut.createDiv({cls:"ai3d-measurement-section ai3d-measurement-size-section"});cr.createDiv({cls:"ai3d-measurement-section-title",text:H("helper.measurementModelSizeTitle")});let Bs=cr.createDiv({cls:"ai3d-measurement-detail-row"});Bs.createSpan({cls:"ai3d-measurement-detail-label",text:H("helper.calibrateCurrent")});let aS=Bs.createSpan({cls:"ai3d-measurement-detail-readonly"}),kg=Bs.createSpan({cls:"ai3d-measurement-detail-readonly"}),zg=Bs.createSpan({cls:"ai3d-measurement-detail-readonly"}),za=cr.createDiv({cls:"ai3d-measurement-detail-row ai3d-measurement-size-row"});za.createSpan({cls:"ai3d-measurement-detail-label",text:H("helper.calibrateReal")});let ll=za.createEl("input",{cls:"ai3d-measurement-detail-input",attr:{type:"number",step:"any",placeholder:"X"}}),ic=za.createEl("input",{cls:"ai3d-measurement-detail-input",attr:{type:"number",step:"any",placeholder:"Y"}}),rc=za.createEl("input",{cls:"ai3d-measurement-detail-input",attr:{type:"number",step:"any",placeholder:"Z"}}),Hg=cr.createDiv({cls:"ai3d-measurement-detail-row ai3d-measurement-size-options"}).createEl("label",{cls:"ai3d-measurement-detail-lock"}),Zd=Hg.createEl("input",{attr:{type:"checkbox",checked:"true"}});Hg.appendChild(activeDocument.createTextNode(" "+H("helper.calibrateLock")));let Xg=cr.createDiv({cls:"ai3d-measurement-detail-row ai3d-measurement-detail-scale-actions"}),Oh=Xg.createEl("button",{cls:"ai3d-inline-btn",text:H("helper.calibrateApply")}),oS=Xg.createEl("button",{cls:"ai3d-inline-btn",text:H("helper.calibrateReset")}),Us=null;function lS(){var At;let X=i();if(!X||!cn(X))return null;let xe=X.getMeasurementState().records;return(At=xe[xe.length-1])!=null?At:null}function I0(){let X=i();if(!X||!cn(X))return;let xe=X.getMeasurementState(),At=xe.bounds,kt=xe.scale;if(Mt.value=xe.unit,Us=At,At){let Qt=xe.unit;aS.textContent=`X: ${No(At.x*kt.x)} ${Qt}`,kg.textContent=`Y: ${No(At.y*kt.y)} ${Qt}`,zg.textContent=`Z: ${No(At.z*kt.z)} ${Qt}`}else aS.textContent="X: -",kg.textContent="Y: -",zg.textContent="Z: -";let st=lS();Er.textContent=st?zf(st.reading.distance,st.reading.unit,!1):H("helper.calibrateReferenceEmpty"),_i.disabled=!st,Gr.disabled=!st,_i.placeholder=st?No(st.reading.distance):H("helper.calibrateReferencePlaceholder")}function C0(){var Qt,$r;let X=i();if(!X||!cn(X)||!Us)return;let xe=parseFloat(ll.value),At=parseFloat(ic.value),kt=parseFloat(rc.value),st=EV(Us,{x:Number.isFinite(xe)?xe:void 0,y:Number.isFinite(At)?At:void 0,z:Number.isFinite(kt)?kt:void 0},X.getMeasurementScale(),Zd.checked);if(!st){vi(Oh,H("helper.calibrateNeedsValue"));return}(Qt=X.setMeasurementUnit)==null||Qt.call(X,Mt.value),($r=X.setMeasurementScale)==null||$r.call(X,st),ce(),Qe(),vi(Oh,H("helper.calibrated"))}function P0(){var st,Qt;let X=i();if(!X||!cn(X))return;let xe=parseFloat(_i.value);(st=X.setMeasurementUnit)==null||st.call(X,Mt.value);let At=lS();if(!At||!Number.isFinite(xe)||xe<=0){vi(Gr,H("helper.calibrateNeedsValue"));return}let kt=vV(X.getMeasurementScale(),At.reading.distance,xe);if(!kt){vi(Gr,H("helper.calibrateNeedsValue"));return}(Qt=X.setMeasurementScale)==null||Qt.call(X,kt),_i.value="",ce(),Qe(),vi(Gr,H("helper.calibrated"))}function L0(){var xe,At;let X=i();!X||!cn(X)||((xe=X.setMeasurementUnit)==null||xe.call(X,Mt.value),(At=X.setMeasurementScale)==null||At.call(X,{x:1,y:1,z:1}),_i.value="",ce(),Qe(),vi(oS,H("helper.calibrateResetDone")))}function W(X){if(!Zd.checked||!Us)return;let At=parseFloat((X==="x"?ll:X==="y"?ic:rc).value);if(!isFinite(At)||At===0)return;let kt=Us[X];if(kt<=1e-4)return;let st=At/kt;X!=="x"&&(ll.value=No(Us.x*st)),X!=="y"&&(ic.value=No(Us.y*st)),X!=="z"&&(rc.value=No(Us.z*st))}ll.addEventListener("input",()=>W("x")),ic.addEventListener("input",()=>W("y")),rc.addEventListener("input",()=>W("z")),Mt.addEventListener("change",()=>{let X=i();!X||!cn(X)||(X.setMeasurementUnit(Mt.value),ce(),Qe())}),Gr.addEventListener("click",P0),Oh.addEventListener("click",C0),oS.addEventListener("click",L0);function ce(){if(I0(),Us){let X=i(),xe=X&&cn(X)?X.getMeasurementScale():{x:1,y:1,z:1};ll.value=No(Us.x*xe.x),ic.value=No(Us.y*xe.y),rc.value=No(Us.z*xe.z)}else ll.value="",ic.value="",rc.value=""}function Re(X,xe){X&&ce(),Ut.classList.toggle("is-hidden",!X),Ke.classList.toggle("is-expanded",X),Ke.setAttribute("aria-expanded",String(X)),Qe(),vi(xe,X?H("helper.calibrateOpen"):H("helper.calibrateClose"))}Ke.addEventListener("click",()=>{Ke.classList.contains("is-hidden")||Re(Ut.classList.contains("is-hidden"),Ke)});let Se=u.createDiv({cls:"ai3d-slice-details is-hidden"});Se.setAttribute("role","group"),Se.setAttribute("aria-label",H("helper.sliceTitle")),Se.addEventListener("pointerdown",_),Se.addEventListener("mousedown",_),Se.addEventListener("click",_);let Te=Se.createDiv({cls:"ai3d-slice-header"});Te.createSpan({cls:"ai3d-slice-title",text:H("helper.sliceTitle")});let St=Te.createSpan({cls:"ai3d-slice-summary"}),It=Te.createEl("button",{cls:"ai3d-slice-reset-btn",attr:{type:"button","aria-label":H("helper.sliceReset")}});It.appendChild(Br('<polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/>'));let pt=Se.createDiv({cls:"ai3d-slice-row ai3d-slice-status-row"});pt.createSpan({cls:"ai3d-slice-label",text:H("helper.sliceOffsetLabel")});let Lt=pt.createDiv({cls:"ai3d-slice-number-control"}),Dt=Lt.createEl("input",{cls:"ai3d-slice-number-input ai3d-slice-offset-value",attr:{type:"number",min:"0",max:"100",step:"0.1",inputmode:"decimal"}});Lt.createSpan({cls:"ai3d-slice-number-unit",text:"%"});let oi=Se.createDiv({cls:"ai3d-slice-row ai3d-slice-rotation-row"});oi.createSpan({cls:"ai3d-slice-label",text:H("helper.sliceRotationLabel")});let si={};for(let X of["x","y","z"]){let xe=oi.createDiv({cls:`ai3d-slice-axis-control ai3d-slice-axis-${X}`});xe.createSpan({cls:"ai3d-slice-axis-label",text:X.toUpperCase()}),si[X]=xe.createEl("input",{cls:"ai3d-slice-number-input ai3d-slice-rotation-input",attr:{type:"number",min:"-180",max:"180",step:"0.1",inputmode:"decimal","aria-label":`${H("helper.sliceRotationLabel")} ${X.toUpperCase()}`}}),xe.createSpan({cls:"ai3d-slice-number-unit",text:"\xB0"})}function Ft(X){let xe=Math.round((Number.isFinite(X)?X:0)*10)/10;return Number.isInteger(xe)?String(xe):xe.toFixed(1)}function ji(){let X=i();return X&&Hd(X)?X:null}function Nr(){let X=ji();X&&(X.resetSlicePlane(),$i())}function Pr(X){X!==A&&(R==null||R(),R=null,A=X,X!=null&&X.observeSlice&&(R=X.observeSlice(()=>{ue(),$i()})))}function $i(){var kt;let X=ji();if(Pr(X),!X){Se.classList.add("is-hidden");return}let xe=X.getSliceState();L(Ve,xe.active),Se.classList.toggle("is-hidden",!xe.active),activeDocument.activeElement!==Dt&&(Dt.value=Ft(Math.max(0,Math.min(xe.offset,1))*100));let At=(kt=xe.rotationDegrees)!=null?kt:{x:0,y:0,z:0};for(let st of["x","y","z"])activeDocument.activeElement!==si[st]&&(si[st].value=Ft(At[st]));St.textContent=xe.dragging?H(xe.interactionMode==="rotate"?"helper.sliceRotating":"helper.sliceMoving"):H("helper.sliceGizmoReady")}It.addEventListener("click",Nr);let dn=()=>{let X=ji();if(!X)return;let xe=Number.parseFloat(Dt.value);if(!Number.isFinite(xe)){$i();return}X.setSliceOffset(Math.max(0,Math.min(xe,100))/100)},yt=()=>{var kt;let X=ji();if(!X)return;let xe=(kt=X.getSliceState().rotationDegrees)!=null?kt:{x:0,y:0,z:0},At=st=>{let Qt=Number.parseFloat(si[st].value);return Number.isFinite(Qt)?Qt:xe[st]};X.setSliceRotation({x:At("x"),y:At("y"),z:At("z")})};Dt.addEventListener("change",dn),Dt.addEventListener("keydown",X=>{X.key==="Enter"&&dn()});for(let X of["x","y","z"])si[X].addEventListener("change",yt),si[X].addEventListener("keydown",xe=>{xe.key==="Enter"&&yt()});return V(),se(),{showAnimButton(){ae.classList.remove("is-hidden"),w()},showAnnotateButton(){qe.classList.remove("is-hidden"),w()},updateAnnotationBadge(X){X>0?(Je.textContent=String(X),Je.classList.remove("is-hidden")):Je.classList.add("is-hidden")},setMobileInteractionMode(X){f&&q(X)},syncCapabilities:se}}function vi(n,e){var i;(i=N1.get(n))==null||i.remove();let t=n.createSpan({cls:"ai3d-tooltip"});t.textContent=e,N1.set(n,t),window.setTimeout(()=>{t.remove(),N1.delete(n)},1500)}var TTe,Mg,ATe,N1,w1=y(()=>{"use strict";xn();zn();Ah();Ma();As();sv();L1();j$();TTe=er("helper-buttons");Mg=[.5,.75,1,1.25,1.5,2],ATe=2;N1=new WeakMap});function $$(n){let e=ma(n.sourceExt),t=[];return e!==n.sourceExt&&t.push(`Normalized extension '${n.sourceExt}' -> '${e}'.`),xTe.debug("prepare direct load",{path:n.path,sourceExt:n.sourceExt,normalizedExt:e,warningCount:t.length}),{effectivePath:n.path,effectiveExt:e,warnings:t}}var xTe,J$=y(()=>{"use strict";Wa();zn();xTe=er("direct-load-service")});var eJ={};Be(eJ,{MissingConverterError:()=>Xd,MobileConversionUnavailableError:()=>xh,describeModelLoadFailure:()=>WE,formatModelLoadFailure:()=>ky,isMissingConverterError:()=>zE});function zy(n){return`.${n.trim().toLowerCase()}`}function zE(n){return n instanceof Xd}function ky(n){var e;if(n instanceof Xd){let t=(e=RTe[n.converterId])!=null?e:n.converterId;return Wi("modelLoad.warningMessage",{ext:zy(n.sourceExt),converterName:t})}return n instanceof xh?Wi("modelLoad.mobileWarningMessage",{ext:zy(n.sourceExt)}):Wi("modelLoad.errorMessage",{reason:n instanceof Error?n.message:String(n)})}function WE(n){return n instanceof Xd?{level:"warning",title:H("modelLoad.warningTitle"),message:ky(n),hint:H("modelLoad.warningHint")}:n instanceof xh?{level:"warning",title:H("modelLoad.warningTitle"),message:ky(n),hint:H("modelLoad.mobileWarningHint")}:{level:"error",title:H("modelLoad.errorTitle"),message:ky(n),hint:H("modelLoad.errorHint")}}var RTe,Xd,xh,yg=y(()=>{"use strict";xn();RTe={freecad:"FreeCAD",obj2gltf:"obj2gltf",fbx2gltf:"FBX2glTF",assimp:"mesh",sldprt:"SolidWorks"};Xd=class extends Error{constructor(t,i){super(`Converter '${t}' is not registered for ${zy(i)}. Enable the matching converter in plugin settings before loading this format.`);this.converterId=t;this.sourceExt=i;this.name="MissingConverterError"}},xh=class extends Error{constructor(t){super(`Format ${zy(t)} requires local conversion tools that are unavailable on iOS, iPadOS, and Android.`);this.sourceExt=t;this.name="MobileConversionUnavailableError"}}});var nJ={};Be(nJ,{convertForPreview:()=>LTe});function iJ(n,e){let t=n.lastIndexOf("."),i=t>0?n.slice(0,t):n,r=Math.max(i.lastIndexOf("/"),i.lastIndexOf("\\")),s=i.slice(0,r+1),a=i.slice(r+1);return`${s}${a}.ai3d-converted.${e}`}function bTe(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")}function rJ(n){let e=$n(n);return Qn(n,e).replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,80)||"model"}function tJ(n){return Qn(n,$n(n)).toLowerCase()}function MTe(n,e,t){if(!t)return iJ(n,e);let i=rJ(n),r=bTe(`${n}::${e}`);return tr(t,`${i}-${r}.ai3d-converted.${e}`)}function yTe(n,e,t){return n.converterId!==e?!1:t?n.converterId===t.converterId&&n.converterCacheKey===t.cacheKey:!0}async function ITe(n){if(!n)return!1;try{return await Ss(n,Ts),!0}catch(e){return!1}}async function Hy(n,e,t){if(!e)return!1;try{let[i,r]=await Promise.all([t!=null?t:Mu(n),Mu(e)]);return r.size>0&&r.mtimeMs>=i.mtimeMs}catch(i){return!1}}async function CTe(n){return typeof n=="function"?await n():n}async function PTe(n,e,t,i){var l,c;let r=(c=(l=n.convertedAssetCache)==null?void 0:l.entries())!=null?c:[];if(r.length===0)return;let s=tJ(n.sourcePath),a=rJ(n.sourcePath),o=r.filter(f=>f.sourcePath!==n.sourcePath&&f.sourceExt===n.sourceExt&&f.targetExt===e&&f.outputExt===e&&f.converterId===t&&tJ(f.sourcePath)===s&&Qn(f.outputPath).startsWith(`${a}-`)&&Qn(f.outputPath).endsWith(`.ai3d-converted.${e}`)).sort((f,d)=>d.createdAt-f.createdAt);for(let f of o)if(await Hy(n.sourcePath,f.outputPath,i))return f}async function LTe(n){var u,h,m,g,p,_,v,E,S,T;if(n.capability.strategy!=="convert")throw new Error(`Expected convert strategy, got '${n.capability.strategy}'.`);let e=n.capability.converterId,t=(u=n.capability.outputFormat)!=null?u:"glb";if(!e)throw new Error(`Format .${n.sourceExt} does not define a converter id.`);mf.info("prepare conversion route",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,converterId:e});let i=null,r=()=>(i!=null||(i=Mu(n.sourcePath)),i),s=(h=n.convertedAssetCache)==null?void 0:h.get(n.sourcePath,n.sourceExt,t);if(s)if(!await ITe(s.outputPath))mf.warn("conversion cache stale",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:s.outputPath}),(m=n.convertedAssetCache)==null||m.delete(n.sourcePath,n.sourceExt,t);else if(!yTe(s,e))mf.warn("conversion cache identity mismatch",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,cachedConverterId:s.converterId,cachedConverterCacheKey:s.converterCacheKey,currentConverterId:e}),(g=n.convertedAssetCache)==null||g.delete(n.sourcePath,n.sourceExt,t);else if(!await Hy(n.sourcePath,s.outputPath,r()))mf.warn("conversion cache output older than source",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:s.outputPath}),(p=n.convertedAssetCache)==null||p.delete(n.sourcePath,n.sourceExt,t);else return mf.info("conversion cache hit",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:s.outputPath}),{effectivePath:s.outputPath,effectiveExt:s.outputExt,warnings:[...s.warnings,"Using cached conversion output."]};let a=MTe(n.sourcePath,t,n.outputRoot);if(await Hy(n.sourcePath,a,r()))return mf.info("conversion output already exists",{sourcePath:n.sourcePath,outputPath:a}),(_=n.convertedAssetCache)==null||_.set({cacheVersion:2,converterId:e,converterCacheKey:e,sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:a,outputExt:t,warnings:["Using existing conversion output."],createdAt:Date.now()}),{effectivePath:a,effectiveExt:t,warnings:["Using existing conversion output."]};let o=iJ(n.sourcePath,t);if(o!==a&&await Hy(n.sourcePath,o,r()))return mf.info("legacy conversion output already exists",{sourcePath:n.sourcePath,outputPath:o}),(v=n.convertedAssetCache)==null||v.set({cacheVersion:2,converterId:e,converterCacheKey:e,sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:o,outputExt:t,warnings:["Using existing conversion output."],createdAt:Date.now()}),{effectivePath:o,effectiveExt:t,warnings:["Using existing conversion output."]};let l=await PTe(n,t,e,r());if(l)return mf.info("relocated conversion cache hit",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,previousSourcePath:l.sourcePath,outputPath:l.outputPath}),(E=n.convertedAssetCache)==null||E.set({cacheVersion:2,converterId:l.converterId,converterCacheKey:l.converterCacheKey,sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:l.outputPath,outputExt:t,warnings:[...l.warnings,"Using relocated conversion output."],createdAt:Date.now()}),{effectivePath:l.outputPath,effectiveExt:t,warnings:[...l.warnings,"Using relocated conversion output."]};let c=await CTe(n.conversionManager);if(!c)throw new Error(`Format .${n.sourceExt} requires conversion support, but no conversion manager is available.`);if(!c.canConvert(n.sourceExt))throw new Xd(e,n.sourceExt);let f=await c.getConverterCacheIdentity(n.sourceExt);n.outputRoot&&await Zn(n.outputRoot,{recursive:!0});let d=await c.convert({sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:a});return(T=n.convertedAssetCache)==null||T.set({cacheVersion:2,converterId:e,converterCacheKey:(S=f==null?void 0:f.cacheKey)!=null?S:e,sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:d.outputPath,outputExt:d.outputExt,warnings:d.warnings,createdAt:Date.now()}),mf.info("conversion route done",{sourcePath:n.sourcePath,outputPath:d.outputPath,warningCount:d.warnings.length}),{effectivePath:d.outputPath,effectiveExt:d.outputExt,warnings:d.warnings}}var mf,sJ=y(()=>{"use strict";N0();zn();hr();yg();mf=er("conversion-service")});var aJ={};Be(aJ,{prepareModelInput:()=>Ig});function DTe(n,e){var t;return!!((t=n.preferConversionExts)!=null&&t.includes(e))}async function Ig(n){var a,o;let e=ma((a=n.path.split(".").pop())!=null?a:""),t=Kg(e);if(Yd.info("prepare model input",{path:n.path,sourceExt:e}),!t||!t.enabled)throw Yd.warn("unsupported format",{sourceExt:e,path:n.path}),jg(e)?new Error("SPLAT preview is disabled in packaged builds. Local-only .splat support is planned; .spz and .sog remain unavailable until their decoders can be bundled locally."):new Error(`Unsupported format: .${e}`);let i=DTe(n,e);if(t.strategy==="convert"||i&&!!t.converterId){if(Rr())throw Yd.warn("conversion unavailable on mobile",{sourceExt:e,path:n.path}),new xh(e);if(!n.absolutePath)throw Yd.error("filesystem path missing for conversion",{sourceExt:e,path:n.path}),new Error(`Format .${e} requires a local filesystem path for conversion, but none was resolved for '${n.path}'.`);let l=t.strategy==="convert"?t:{...t,strategy:"convert",outputFormat:(o=t.outputFormat)!=null?o:"glb"};if(!l.converterId)throw Yd.error("preferred conversion route missing converter id",{sourceExt:e,path:n.path}),new Error(`Format .${e} is configured to prefer conversion, but no converter id is defined.`);i&&t.strategy==="direct"&&Yd.info("preferred conversion route",{sourceExt:e,path:n.path,converterId:l.converterId});let{convertForPreview:c}=await Promise.resolve().then(()=>(sJ(),nJ)),f=await c({sourcePath:n.absolutePath,sourceExt:e,capability:l,conversionManager:n.conversionManager,convertedAssetCache:n.convertedAssetCache,outputRoot:n.conversionOutputRoot});return Yd.info("conversion completed",{sourceExt:e,outputExt:f.effectiveExt,outputPath:f.effectivePath,warningCount:f.warnings.length}),{sourcePath:n.path,sourceExt:e,strategy:"convert",effectivePath:f.effectivePath,effectiveExt:f.effectiveExt,warnings:f.warnings}}let s=$$({path:n.path,sourceExt:e});return Yd.debug("direct route",{sourceExt:e,path:n.path,warningCount:s.warnings.length}),{sourcePath:n.path,sourceExt:e,strategy:t.strategy,effectivePath:s.effectivePath,effectiveExt:s.effectiveExt,warnings:s.warnings}}var Yd,Xy=y(()=>{"use strict";Wa();J$();yg();zn();Ma();Yd=er("model-pipeline")});function HE(n){return{path:n.effectivePath,ext:n.effectiveExt,strategy:n.strategy,sourcePath:n.sourcePath,sourceExt:n.sourceExt,warnings:n.warnings}}var F1=y(()=>{"use strict"});function Rh(n,e){var r;let i=e.auxiliaryFileFolder.trim()||HU(n,OTe);return(r=Ec(n,i))!=null?r:void 0}var OTe,Yy=y(()=>{"use strict";As();OTe="ai-model-workbench/converted-assets"});function bh(n){let e=n.createDiv({cls:"ai3d-loading-overlay"}),t=e.createDiv({cls:"ai3d-loading-skeleton"});t.createDiv({cls:"ai3d-loading-skeleton-canvas"});let i=t.createDiv({cls:"ai3d-loading-skeleton-meta"});i.createDiv({cls:"ai3d-loading-skeleton-line"}),i.createDiv({cls:"ai3d-loading-skeleton-line is-short"}),e.createDiv({cls:"ai3d-loading-spinner"});let r=e.createDiv({cls:"ai3d-loading-text"}),s="loading.default",a="",o=()=>{r.textContent=s?H(s):a};o();let c=e.createDiv({cls:"ai3d-loading-bar-track"}).createDiv({cls:"ai3d-loading-bar-fill is-indeterminate"}),f=!1,d=nB(()=>{!f&&s&&o()});return{el:e,setPhase(u){s=null,a=u,f||o()},setPhaseKey(u){s=u,f||o()},setProgress(u){f||(u<0?(c.className="ai3d-loading-bar-fill is-indeterminate",c.style.removeProperty("--bar-width")):(c.className="ai3d-loading-bar-fill",c.style.setProperty("--bar-width",`${Math.min(100,Math.max(0,u))}%`)))},hide(){f||(f=!0,d(),e.classList.add("is-hiding"),window.setTimeout(()=>e.remove(),300))}}}var Ky=y(()=>{"use strict";xn()});var B1={};Be(B1,{renderModelLoadFailure:()=>XE,renderModelPerformanceFeedback:()=>YE});function XE(n,e){let t=n.createDiv({cls:"ai3d-inline-empty ai3d-load-feedback-shell"});Rr()&&t.classList.add("is-mobile");let i=t.createDiv({cls:`ai3d-load-feedback is-${e.level}`});return i.createDiv({cls:"ai3d-load-feedback-title",text:e.title}),i.createDiv({cls:"ai3d-load-feedback-message",text:e.message}),i.createDiv({cls:"ai3d-load-feedback-hint",text:e.hint}),t}function YE(n,e){var o,l,c,f,d,u,h;if((!e.performanceTier||e.performanceTier==="light")&&!((o=e.resourceWarnings)!=null&&o.length))return null;let t=(l=e.performanceTier)!=null?l:"light",i=((c=e.splatCount)!=null?c:e.triangleCount).toLocaleString(),r=e.splatCount!==void 0?"splats":"triangles",s=n.createDiv({cls:`ai3d-performance-feedback is-${t}`});s.createDiv({cls:"ai3d-performance-feedback-tier",text:(f=e.resourceWarnings)!=null&&f.length?"assets":(d=e.performanceTier)!=null?d:"light"}),s.createDiv({cls:"ai3d-performance-feedback-meta",text:(u=e.resourceWarnings)!=null&&u.length?e.resourceWarnings[0]:`${i} ${r} \xB7 ${e.materialCount.toLocaleString()} materials`});let a=[...(h=e.resourceWarnings)!=null?h:[],...e.performanceHint?[e.performanceHint]:[]];return a.length>0&&(s.title=a.join(`
`)),window.setTimeout(()=>s.classList.add("is-subtle"),4200),s}var KE=y(()=>{"use strict";Ma()});function pf(n){var t;let e=(t=(n!=null?n:"").split(".").pop())==null?void 0:t.trim().toLowerCase();return NTe.has(e)?e:"glb"}function Mh(n,e,t){return typeof n=="string"&&wTe.has(n)?n:e===t?"direct":"convert"}var NTe,wTe,jy=y(()=>{"use strict";NTe=new Set(["glb","gltf","stl","obj","splat","ply","fbx","step","stp","iges","igs","brep","sldprt","3mf","dae"]),wTe=new Set(["direct","convert"])});function Cg(n,e,t){uJ(n,{label:Wi(cJ[e],{model:Qs(t)||H("workbench.modelTitle")}),shortcutKeys:FTe})}function fJ(n){uJ(n,{label:H(cJ.grid),shortcutKeys:BTe})}function Pg(n,e){n.addEventListener("keydown",t=>{var s,a,o,l,c;let i=e();if(!i)return;let r=t.key.toLowerCase();r==="r"?((s=i.resetView)==null||s.call(i),t.preventDefault()):r==="w"?((a=i.toggleWireframe)==null||a.call(i),t.preventDefault()):r==="g"?((o=i.toggleOrientationGizmo)==null||o.call(i),t.preventDefault()):r==="b"?((l=i.toggleBoundingBox)==null||l.call(i),t.preventDefault()):r===" "?((c=i.toggleAnimation)==null||c.call(i),t.preventDefault()):r==="m"?(cn(i)&&i.toggleMeasurement(),t.preventDefault()):r==="escape"&&cn(i)&&dx(i)&&t.preventDefault()})}function dJ(n,e){n.addEventListener("keydown",t=>{var s,a;let i=e();if(!i)return;let r=t.key.toLowerCase();r==="r"?((s=i.resetView)==null||s.call(i),t.preventDefault()):r==="w"&&((a=i.toggleWireframe)==null||a.call(i),t.preventDefault())})}function uJ(n,e){zTe(n),n.setAttribute("role","application"),VTe(n,e.label),n.setAttribute("aria-keyshortcuts",e.shortcutKeys.join(" ")),kTe(n),n.dataset.testid="ai3d-preview-canvas"}function VTe(n,e){let t=n.dataset.ai3dLabelId,i=t?n.ownerDocument.getElementById(t):null,r=i instanceof HTMLElement?i:GTe(n);if(!r){n.removeAttribute("aria-label"),n.removeAttribute("aria-labelledby"),delete n.dataset.ai3dLabelId;return}r.setText(e),n.dataset.ai3dLabelId=r.id,n.setAttribute("aria-labelledby",r.id),n.removeAttribute("aria-label")}function GTe(n){let e=n.parentElement;if(!e)return null;let t=e.createSpan({cls:"ai3d-visually-hidden"});return t.id=`ai3d-preview-canvas-label-${++UTe}`,t}function kTe(n){n.removeAttribute("title"),n.removeAttribute("data-tooltip"),n.removeAttribute("aria-description")}function zTe(n){if(lJ(n),oJ.has(n)||typeof MutationObserver=="undefined")return;oJ.add(n),new MutationObserver(()=>lJ(n)).observe(n,{attributes:!0,attributeFilter:["tabindex"]})}function lJ(n){n.tabIndex!==0&&(n.tabIndex=0),n.getAttribute("tabindex")!=="0"&&n.setAttribute("tabindex","0")}var FTe,BTe,oJ,UTe,cJ,Zy=y(()=>{"use strict";xn();sv();Ah();As();FTe=["R","W","G","B","M","Space"],BTe=["R","W"],oJ=new WeakSet,UTe=0,cJ={inline:"previewCanvas.inlineLabel",grid:"previewCanvas.gridLabel","live-preview":"previewCanvas.liveLabel","direct-view":"previewCanvas.directLabel"}});function hJ(n){let{contentEl:e,filePath:t,mobile:i,getPreview:r}=n,s=e.createDiv({cls:"ai3d-workspace"}),a=s.createDiv({cls:"ai3d-workspace-track-top"}),o=a.createDiv({cls:"ai3d-workspace-main"}),l=a.createDiv({cls:"ai3d-resize-handle ai3d-resize-handle-h"}),c=a.createDiv({cls:"ai3d-workspace-sidebar"}),f=createDiv(),d=f.createDiv({cls:"ai3d-preview-host"}),u=f.createEl("canvas");u.className="ai3d-canvas-full",Cg(u,"direct-view",t),Pg(u,r),d.appendChild(u);let h=f.createDiv();h.className="ai3d-annot-mode-overlay is-hidden",d.appendChild(h),o.appendChild(d);let m=c.createDiv({cls:"ai3d-sidebar-content"}),g=m.createDiv({cls:"ai3d-direct-workbench-panel is-hidden"}),p=m.createDiv({cls:"ai3d-sidebar-body"}),_=s.createDiv({cls:"ai3d-resize-handle ai3d-resize-handle-v"});return i&&o.createDiv({cls:"ai3d-mobile-mode-hint ai3d-mobile-mode-hint--inline",text:H("directView.mobileHint")}),{workspace:s,topTrack:a,mainArea:o,hHandle:l,host:d,canvas:u,modeOverlay:h,sidebarContent:p,vHandle:_,workbenchPanel:g}}var mJ=y(()=>{"use strict";xn();Zy()});function qy(n){return Math.round(n!=null?n:0).toLocaleString()}function WTe(n){return[n.boundingSize.x,n.boundingSize.y,n.boundingSize.z].map(e=>e.toFixed(2)).join(" x ")}function HTe(n){return n==="three"?"Three.js":"Babylon.js"}function pJ(n){var f,d;let{panel:e,summary:t,route:i,registeredPartCount:r}=n;e.empty(),e.removeClass("is-hidden"),e.dataset.ai3dBackend=i.backend,e.dataset.ai3dRouteReason=i.reason;let s=e.createDiv({cls:"ai3d-direct-workbench-overview"}),a=s.createDiv({cls:"ai3d-direct-workbench-status"}),o=a.createDiv({cls:"ai3d-direct-workbench-line"});o.createSpan({cls:"ai3d-direct-workbench-label",text:H("directWorkbench.backendLabel")}),o.createSpan({cls:"ai3d-direct-workbench-value",text:HTe(i.backend)});let l=a.createDiv({cls:"ai3d-direct-workbench-line ai3d-direct-workbench-route"});l.createSpan({cls:"ai3d-direct-workbench-label",text:H("directWorkbench.routeLabel")}),l.createSpan({cls:"ai3d-direct-workbench-value",text:i.reason});let c=s.createDiv({cls:"ai3d-direct-workbench-metrics"});Lg(c,H("workbench.meshesLabel"),qy(t.meshCount)),Lg(c,H("directWorkbench.partCandidatesLabel"),qy(r)),Lg(c,t.splatCount!==void 0?H("workbench.splatsLabel"):H("workbench.trianglesLabel"),qy((f=t.splatCount)!=null?f:t.triangleCount)),Lg(c,H("workbench.materialsLabel"),qy(t.materialCount)),Lg(c,H("workbench.boundingSizeLabel"),WTe(t)),Lg(c,H("directWorkbench.performanceLabel"),(d=t.performanceTier)!=null?d:"light")}function Lg(n,e,t){let i=n.createDiv({cls:"ai3d-direct-workbench-metric"});i.createSpan({cls:"ai3d-direct-workbench-label",text:e}),i.createSpan({cls:"ai3d-direct-workbench-value",text:t})}var gJ=y(()=>{"use strict";xn()});function XTe(n,e){return n.experimentalThreeWorkbench&&n.useThreeRenderer&&e.strategy==="direct"&&Qy.has(e.ext)&&Qy.has(e.sourceExt)}function YTe(n){return _J.has(n.ext)?n.strategy==="direct"?_J.has(n.sourceExt):n.strategy==="convert"&&Qy.has(n.ext):!1}function KTe(n,e){return n.useThreeForConvertedDirectView&&e.strategy==="convert"&&Qy.has(e.ext)}function vJ(n,e){let t=XTe(n,e),i=YTe(e),r=KTe(n,e);return{ext:e.ext,annotationMode:"edit",allowEditModeOnThree:!0,allowWorkbenchFeaturesOnThree:t,requireWorkbenchFeatures:t||!i,rendererRollout:r?"three-direct-glb":n.previewRendererRollout,useThreeRenderer:r?!0:n.useThreeRenderer}}var _J,Qy,EJ=y(()=>{"use strict";_J=new Set(["glb","gltf","stl","ply","obj"]),Qy=new Set(["glb","gltf"])});function Dg(n){return{renderQuality:n.renderQuality,renderScale:n.renderScale}}function tAe(n,e){return!Number.isFinite(e!=null?e:Number.NaN)||(e!=null?e:0)<=0?Dg(n):(e!=null?e:0)>=ZTe?{renderQuality:n.renderQuality==="high"?"medium":n.renderQuality,renderScale:Math.min(n.renderScale,U1)}:(e!=null?e:0)>=jTe?{renderQuality:n.renderQuality==="low"?"low":"medium",renderScale:Math.min(n.renderScale,AJ)}:Dg(n)}function G1(n){var e;return(e=n.splatCount)!=null?e:n.triangleCount}function iAe(n){return n.splatCount!==void 0?n.splatCount>=TJ:G1(n)>=QTe}function rAe(n){return n.splatCount!==void 0?n.splatCount>=JTe:G1(n)>=$Te}function nAe(n){return n.splatCount!==void 0?n.splatCount>=TJ:G1(n)>=qTe}function xJ(n,e){return e.performanceTier==="extreme"?rAe(e)?{renderQuality:n.renderQuality==="low"?"low":"medium",renderScale:Math.min(n.renderScale,U1)}:Dg(n):e.performanceTier==="heavy"?iAe(e)?{renderQuality:n.renderQuality==="low"?"low":"medium",renderScale:Math.min(n.renderScale,U1)}:Dg(n):e.performanceTier==="medium"&&nAe(e)?{renderQuality:n.renderQuality,renderScale:Math.min(n.renderScale,AJ)}:Dg(n)}function Og(n){return n.startsWith("/")||n.startsWith("\\")||/^[A-Za-z]:[\\/]/.test(n)}function $y(n){var e;return(e=n.split(/[?#]/,1)[0])!=null?e:n}function RJ(n){try{return decodeURIComponent(n)}catch(e){return n}}function V1(n){let e=RJ(n).replace(/\\/g,"/"),t=[];for(let i of e.split("/"))if(!(!i||i===".")){if(i===".."){t.pop();continue}t.push(i)}return t.join("/")}function bJ(n,e){return V1(n?`${n}/${$y(e)}`:$y(e))}function MJ(n){let e=n.replace(/\\/g,"/").replace(/\/+$/,""),t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function sAe(n){return!n||n.startsWith("data:")?!0:eAe.test(n)&&!Og(n)}function aAe(n,e){return Og(n)?V1($y(e)):bJ(MJ(n),e)}async function oAe(n,e){let t=await lAe(n,e);return t===null?null:e.toLowerCase().split(/[?#]/,1)[0].endsWith(".gltf")?dAe(n,e,t):t}async function lAe(n,e){if(Og(e))try{let{stat:i}=await Promise.resolve().then(()=>(hr(),OA));return(await i(e)).size}catch(i){return null}let t=n.vault.getAbstractFileByPath(e);return yJ(t)?t.stat.size:null}async function cAe(n,e){if(Og(e))try{let{readFile:r}=await Promise.resolve().then(()=>(hr(),OA));return new TextDecoder().decode(await r(e))}catch(r){return null}let t=n.vault.getAbstractFileByPath(e),i=n.vault;if(!(t instanceof SJ.TFile)||typeof i.read!="function")return null;try{return await i.read(t)}catch(r){return null}}async function fAe(n,e,t){if(Og(e))try{let{pathJoin:a,pathNormalize:o,stat:l}=await Promise.resolve().then(()=>(hr(),OA)),c=$y(RJ(t)),f=o(e.replace(/[\\/][^\\/]*$/,"")),d=Og(c)?o(c):o(a(f,c));return(await l(d)).size}catch(a){return null}let i=MJ(e),r=bJ(i,t),s=n.vault.getAbstractFileByPath(r);return yJ(s)?s.stat.size:null}async function dAe(n,e,t){var l,c;let i=await cAe(n,e);if(!i)return t;let r;try{r=JSON.parse(i)}catch(f){return t}let s=t,a=new Set,o=async(f,d)=>{var p;let u=f==null?void 0:f.uri;if(!u||sAe(u))return;let h=aAe(e,u);if(!h||a.has(h))return;a.add(h);let m=await fAe(n,e,u);if(m!==null&&Number.isFinite(m)&&m>0){s+=m;return}let g=(p=f==null?void 0:f.byteLength)!=null?p:d;Number.isFinite(g)&&(g!=null?g:0)>0&&(s+=g!=null?g:0)};for(let f of(l=r.buffers)!=null?l:[])await o(f,f.byteLength);for(let f of(c=r.images)!=null?c:[])await o(f);return s}function yJ(n){let e=n;return!!e&&typeof e=="object"&&!!e.stat&&typeof e.stat.size=="number"}async function Ng(n,e,t){return tAe(t,await oAe(n,e))}var SJ,jTe,ZTe,qTe,QTe,$Te,TJ,JTe,AJ,U1,eAe,Jy=y(()=>{"use strict";SJ=require("obsidian"),jTe=64*1024*1024,ZTe=192*1024*1024,qTe=18e4,QTe=45e4,$Te=12e5,TJ=65e4,JTe=15e5,AJ=1.25,U1=1,eAe=/^[a-z][a-z0-9+.-]*:/i});function hAe(n,e,t){let i=new Promise((r,s)=>{let a=window.setTimeout(()=>{s(new k1(`Conversion did not complete within ${e}ms`))},e);n.then(()=>window.clearTimeout(a)).catch(()=>window.clearTimeout(a))});return Promise.race([n,i])}var jE,uAe,k1,e0,IJ=y(()=>{"use strict";Wa();zn();jE=er("conversion-manager"),uAe=3e5,k1=class extends Error{constructor(e="Conversion timed out"){super(e),this.name="ConversionTimeoutError"}};e0=class{constructor(){this.converters=new Map;this.pending=new Map}getConverter(e){return this.converters.get(ma(e))}registerConverter(e){jE.info("register converter",{converterId:e.id,sourceExts:[...e.sourceExts]});for(let t of e.sourceExts)this.converters.set(ma(t),e)}canConvert(e){let t=ma(e),i=this.converters.has(t);return jE.debug("can convert",{ext:t,ok:i}),i}async getConverterCacheIdentity(e){let t=this.getConverter(e);if(t)return{converterId:t.id,cacheKey:await t.getCacheKey()}}async convert(e){var o;let t=ma(e.sourceExt),i=this.getConverter(t);if(!i)throw jE.error("converter missing",{ext:t,targetExt:e.targetExt}),new Error(`No converter registered for .${t}`);let r=`${e.sourcePath}::${t}::${e.targetExt}`,s=this.pending.get(r);if(s)return jE.info("joining in-flight conversion",{key:r}),s;jE.info("dispatch conversion",{converterId:i.id,ext:t,targetExt:e.targetExt});let a=hAe(i.convert({...e,sourceExt:t}),(o=e.timeoutMs)!=null?o:uAe,{converterId:i.id,ext:t,targetExt:e.targetExt});this.pending.set(r,a);try{return await a}finally{this.pending.delete(r)}}}});var Q1={};Be(Q1,{describeConverterCommandSource:()=>K1,inspectAllConverterCommands:()=>DAe,inspectConverterCommand:()=>q1,listConverterCommandSpecs:()=>LAe,resolveConverterCommand:()=>OAe,resolveConverterInvocation:()=>Wn});function H1(...n){let e=(Xe==null?void 0:Xe.platform)==="darwin"?["/opt/homebrew/bin","/usr/local/bin","/opt/local/bin","/usr/bin"]:["/usr/local/bin","/opt/homebrew/bin","/opt/local/bin","/usr/bin"];return Array.from(new Set(e.flatMap(t=>n.map(i=>`${t}/${i}`))))}function gAe(){var r,s,a;if((Xe==null?void 0:Xe.platform)==="darwin")return["/Applications/FreeCAD.app/Contents/MacOS/FreeCADCmd","/Applications/FreeCAD.app/Contents/Resources/bin/FreeCADCmd","/Applications/FreeCAD.app/Contents/Resources/bin/freecadcmd",...H1("FreeCADCmd","freecadcmd")];if((Xe==null?void 0:Xe.platform)!=="win32")return["/usr/local/bin/freecadcmd","/opt/homebrew/bin/freecadcmd","/opt/local/bin/freecadcmd","/snap/freecad/current/usr/bin/freecadcmd","/usr/bin/freecadcmd"];let n=[],e=(r=Xe==null?void 0:Xe.env)==null?void 0:r.LOCALAPPDATA,t=(s=Xe==null?void 0:Xe.env)==null?void 0:s.ProgramFiles,i=(a=Xe==null?void 0:Xe.env)==null?void 0:a["ProgramFiles(x86)"];if(e&&n.push(tr(e,"Programs","FreeCAD","bin","FreeCADCmd.exe")),t&&n.push(tr(t,"FreeCAD","bin","FreeCADCmd.exe")),e)for(let o of["1.2","1.1","1.0","0.22","0.21","0.20"])n.push(`${e}/Programs/FreeCAD ${o}/bin/FreeCADCmd.exe`);if(t)for(let o of["1.2","1.1","1.0","0.22","0.21","0.20"])n.push(`${t}/FreeCAD ${o}/bin/FreeCADCmd.exe`);return i&&n.push(`${i}/FreeCAD/bin/FreeCADCmd.exe`),n}function _Ae(n){var a,o,l,c;if((Xe==null?void 0:Xe.platform)!=="win32")return[];let e=(a=Xe==null?void 0:Xe.env)==null?void 0:a.APPDATA,t=(o=Xe==null?void 0:Xe.env)==null?void 0:o.LOCALAPPDATA,i=(l=Xe==null?void 0:Xe.env)==null?void 0:l.npm_config_prefix,r=(c=Xe==null?void 0:Xe.env)==null?void 0:c.USERPROFILE,s=[i,e?tr(e,"npm"):void 0,t?tr(t,"npm"):void 0,r?tr(r,"AppData","Roaming","npm"):void 0].filter(f=>!!f);return Array.from(new Set(s.map(f=>tr(f,n))))}function vAe(...n){var s,a,o;if((Xe==null?void 0:Xe.platform)!=="win32")return[];let e=(s=Xe==null?void 0:Xe.env)==null?void 0:s.ProgramFiles,t=(a=Xe==null?void 0:Xe.env)==null?void 0:a["ProgramFiles(x86)"],i=(o=Xe==null?void 0:Xe.env)==null?void 0:o.LOCALAPPDATA,r=[e,t,i?tr(i,"Programs"):void 0].filter(l=>!!l);return Array.from(new Set(r.flatMap(l=>n.map(c=>tr(l,c)))))}async function Z1(n){try{return await Ss(n,(Xe==null?void 0:Xe.platform)==="win32"?Ts:nP),!0}catch(e){return!1}}function z1(n){let e=n==null?void 0:n.trim();if(e)return e}function PJ(n){return EAe.test(n)?{ok:!1,reason:"Command contains unsafe shell metacharacters."}:{ok:!0}}function SAe(n,e){for(let t of[n,...e]){let i=PJ(t);if(!i.ok)return i}return{ok:!0}}async function TAe(n){try{return(await Mu(n)).isFile()}catch(e){return!1}}function AAe(n){let e=[],t="",i=null;for(let r=0;r<n.length;r++){let s=n[r];if(i==="'"){s==="'"?i=null:t+=s;continue}if(i==='"'){if(s==="\\"){let a=n[r+1];if(a==="\\"||a==='"'){t+=a,r++;continue}}s==='"'?i=null:t+=s;continue}if(s==="'"||s==='"'){i=s;continue}if(s==="\\"){let a=n[r+1];if(a&&/\s|"|'|\\/.test(a)){t+=a,r++;continue}t+=s;continue}if(/\s/.test(s)){t&&(e.push(t),t="");continue}t+=s}return i?[n]:(t&&e.push(t),e)}function xAe(n){let e=AAe(n).filter(Boolean);return e.length===0?{executable:n,args:[]}:{executable:e[0],args:e.slice(1)}}function RAe(n){return Ra(n)||/[\\/]/.test(n)||n.startsWith(".")}function bAe(n){var t,i;if($n(n))return[""];let e=(i=(t=Xe==null?void 0:Xe.env)==null?void 0:t.PATHEXT)==null?void 0:i.split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return e!=null&&e.length?e:mAe}async function MAe(n){var r;let e=(r=Xe==null?void 0:Xe.env)==null?void 0:r.PATH;if(!e)return;let t=e.split(sP).map(s=>s.trim()).filter(Boolean),i=(Xe==null?void 0:Xe.platform)==="win32"?bAe(n):[""];for(let s of t)for(let a of i){let o=tr(s,a?`${n}${a}`:n);if(await Z1(o))return o}}function X1(n,e,t=15e3){let i=PJ(n);return i.ok?new Promise((r,s)=>{ba(n,e,{timeout:t,windowsHide:!0,maxBuffer:4*1024*1024},(a,o,l)=>{if(a){s(new Error((l||o||a.message).toString().trim()||a.message));return}r({stdout:o!=null?o:"",stderr:l!=null?l:""})})}):Promise.reject(new Error(`Refusing to execute converter command: ${i.reason}`))}function Y1(n){let t=(n instanceof Error?n.message:String(n)).replace(/\s+/g," ").trim();return t.length>180?`${t.slice(0,177)}...`:t}async function W1(n,e,t,i){let r="";for(let s of t)try{return await X1(n,[...e,...s]),{ok:!0,detail:""}}catch(a){let o=Y1(a);if(i.test(o))return{ok:!0,detail:""};r=o}return{ok:!1,detail:r||"Command probe failed."}}async function yAe(n){var i;if(!n.available)return[];let e=(i=n.resolvedPath)!=null?i:n.executable,t=[...n.args];if(n.id==="freecad"){let r=[];for(let s of pAe)try{await X1(e,[...t,"-c",s.probe]),r.push({kind:"cad-python",label:s.label,ok:!0,detail:""})}catch(a){r.push({kind:"cad-python",label:s.label,ok:!1,detail:Y1(a)})}return r}if(n.id==="assimp")try{return await X1(e,[...t,"-c","import trimesh, numpy, networkx, collada; print('ok')"]),[{kind:"mesh-python",ok:!0,detail:""}]}catch(r){return[{kind:"mesh-python",ok:!1,detail:Y1(r)}]}if(n.id==="freecadcmd"){let r=await W1(e,t,[["--version"],["--help"]],/freecad|usage|help|version/i);return[{kind:"freecadcmd-cli",ok:r.ok,detail:r.detail}]}if(n.id==="obj2gltf"){let r=await W1(e,t,[["--version"],["--help"]],/obj2gltf|usage|help|version/i);return[{kind:"obj2gltf-cli",ok:r.ok,detail:r.detail}]}if(n.id==="fbx2gltf"){let r=await W1(e,t,[["--version"],["--help"]],/fbx2gltf|usage|help|version/i);return[{kind:"fbx2gltf-cli",ok:r.ok,detail:r.detail}]}return[]}function IAe(n){let e=j1.find(t=>t.id===n);if(!e)throw new Error(`Unknown converter command id: ${n}`);return e}function CAe(n){var s,a,o,l;let e=(a=(s=Xe==null?void 0:Xe.env)==null?void 0:s.ProgramFiles)==null?void 0:a.toLowerCase(),t=(l=(o=Xe==null?void 0:Xe.env)==null?void 0:o["ProgramFiles(x86)"])==null?void 0:l.toLowerCase(),i=[],r=[];for(let c of n.knownCandidates){let f=c.toLowerCase(),d=(Xe==null?void 0:Xe.platform)==="win32"&&((e?f.startsWith(e):!1)||(t?f.startsWith(t):!1)),u=(Xe==null?void 0:Xe.platform)!=="win32"&&(c.startsWith("/usr/bin/")||c.startsWith("/snap/freecad/current/usr/bin/"));d||u?r.push(c):i.push(c)}return{userCandidates:i,systemCandidates:r}}async function CJ(n,e,t){for(let i of e)if(await Z1(i))return{id:n.id,label:n.label,envVar:n.envVar,settingsKey:n.settingsKey,command:i,executable:i,args:[],resolvedPath:i,available:!0,source:"candidate",detail:t,checkedCandidates:[i]}}function PAe(n,e){let t=[];return n.length&&t.push(`Checked common user locations: ${n.join("; ")}`),e.length&&t.push(`Checked system fallback locations: ${e.join("; ")}`),t.join(". ")}async function t0(n,e,t,i){let r=xAe(e),s=SAe(r.executable,r.args);if(!s.ok)return{id:n.id,label:n.label,envVar:n.envVar,settingsKey:n.settingsKey,configuredCommand:i,command:e,executable:r.executable,args:r.args,resolvedPath:void 0,available:!1,source:t,detail:s.reason,checkedCandidates:[r.executable]};if(RAe(r.executable)){let[o,l]=await Promise.all([Z1(r.executable),TAe(r.executable)]),c=o&&l;return{id:n.id,label:n.label,envVar:n.envVar,settingsKey:n.settingsKey,configuredCommand:i,command:e,executable:r.executable,args:r.args,resolvedPath:c?r.executable:void 0,available:c,source:t,detail:c?`Using ${K1(t)} path.`:"Configured path was not found or is not executable.",checkedCandidates:[r.executable]}}let a=await MAe(r.executable);return{id:n.id,label:n.label,envVar:n.envVar,settingsKey:n.settingsKey,configuredCommand:i,command:e,executable:r.executable,args:r.args,resolvedPath:a,available:!!a,source:t,detail:a?`Resolved from ${K1(t)} via PATH lookup.`:"Command name was not found on PATH.",checkedCandidates:[r.executable]}}function LAe(){return j1}function K1(n){switch(n){case"settings":return"plugin settings";case"env":return"environment variable";case"candidate":return"known install location";case"path":return"PATH fallback"}}async function q1(n,e){var u,h,m;let t=IAe(n),{userCandidates:i,systemCandidates:r}=CAe(t),s=z1(e);if(s)return t0(t,s,"settings",s);let a=z1((u=Xe==null?void 0:Xe.env)==null?void 0:u[t.envVar]);if(a)return t0(t,a,"env");for(let g of(h=t.envVarAliases)!=null?h:[]){let p=z1((m=Xe==null?void 0:Xe.env)==null?void 0:m[g]);if(p)return t0(t,p,"env")}let o=await CJ(t,i,"Detected at a common user-managed install location.");if(o)return o;let l=[];for(let g of t.fallbackCommands){let p=await t0(t,g,"path");if(l.push(p),p.available)return p}let c=await CJ(t,r,"Detected at a system fallback install location.");if(c)return c;let f=l.flatMap(g=>g.checkedCandidates),d=PAe(i,r);return{...l[0],detail:d?`Command name was not found on PATH. ${d}`:"Command name was not found on PATH.",checkedCandidates:[...i,...f,...r]}}async function DAe(n){let e=await Promise.all(j1.map(t=>q1(t.id,n[t.settingsKey])));return Promise.all(e.map(async t=>({...t,dependencyChecks:await yAe(t)})))}async function OAe(n,e){return(await Wn(n,e)).command}async function Wn(n,e){var i;let t=await q1(n,e);if(!t.available&&t.detail==="Command contains unsafe shell metacharacters.")throw new Error(`Refusing to resolve converter command '${n}': ${t.detail}`);return{command:(i=t.resolvedPath)!=null?i:t.executable,args:[...t.args]}}var Xe,mAe,pAe,j1,EAe,Kd=y(()=>{"use strict";hr();hr();hr();Xe=Dm(),mAe=[".exe",".cmd",".bat",".com"],pAe=[{label:"CadQuery import",probe:"import cadquery; print('ok')"},{label:"trimesh import",probe:"import trimesh; print('ok')"},{label:"OCP STEP readers",probe:["from OCP.STEPCAFControl import STEPCAFControl_Reader","from OCP.STEPControl import STEPControl_Reader","from OCP.BRepMesh import BRepMesh_IncrementalMesh","print('ok')"].join("; ")},{label:"OCCT GLB writer",probe:"from OCP.RWGltf import RWGltf_CafWriter, RWGltf_WriterTrsfFormat; print('ok')"}];j1=[{id:"freecad",label:"Python (CadQuery/OCCT)",settingsKey:"freecadCommand",envVar:"AI3D_FREECAD_CMD",fallbackCommands:(Xe==null?void 0:Xe.platform)==="win32"?["py","python"]:["python3","python"],knownCandidates:(Xe==null?void 0:Xe.platform)==="win32"?[]:["/usr/local/bin/python3","/opt/homebrew/bin/python3","/opt/local/bin/python3","/usr/bin/python3"]},{id:"obj2gltf",label:"obj2gltf",settingsKey:"obj2gltfCommand",envVar:"AI3D_OBJ2GLTF_CMD",fallbackCommands:(Xe==null?void 0:Xe.platform)==="win32"?["obj2gltf.cmd"]:["obj2gltf"],knownCandidates:(Xe==null?void 0:Xe.platform)==="win32"?_Ae("obj2gltf.cmd"):H1("obj2gltf")},{id:"fbx2gltf",label:"FBX2glTF",settingsKey:"fbx2gltfCommand",envVar:"AI3D_FBX2GLTF_CMD",fallbackCommands:(Xe==null?void 0:Xe.platform)==="win32"?["FBX2glTF.exe"]:["FBX2glTF","fbx2gltf"],knownCandidates:(Xe==null?void 0:Xe.platform)==="win32"?vAe(tr("FBX2glTF","FBX2glTF-windows-x64.exe"),tr("FBX2glTF","FBX2glTF.exe")):H1("FBX2glTF","fbx2gltf")},{id:"assimp",label:"Python (trimesh)",settingsKey:"assimpCommand",envVar:"AI3D_ASSIMP_CMD",fallbackCommands:(Xe==null?void 0:Xe.platform)==="win32"?["py","python"]:["python3","python"],knownCandidates:(Xe==null?void 0:Xe.platform)==="win32"?[]:["/usr/local/bin/python3","/opt/homebrew/bin/python3","/opt/local/bin/python3","/usr/bin/python3"]},{id:"freecadcmd",label:"FreeCAD (SLDPRT)",settingsKey:"freecadcmdCommand",envVar:"AI3D_FREECADCMD",envVarAliases:["AI3D_FREECMDCMD"],fallbackCommands:(Xe==null?void 0:Xe.platform)==="win32"?["FreeCADCmd.exe"]:["freecadcmd","FreeCADCmd"],knownCandidates:gAe()}];EAe=/[;|&<>$`\r\n\t]/});var DJ,LJ=y(()=>{DJ=`import cadquery as cq
import trimesh
import trimesh.visual
import numpy as np
import sys
import os
import re
import json
import struct
import shutil
import tempfile
src = r"__AI3D_SOURCE_PATH__"
out = r"__AI3D_OUTPUT_PATH__"
source_ext = "__AI3D_SOURCE_EXT__"
src_occt = src
try:
src.encode('ascii')
except UnicodeEncodeError:
safe_src = os.path.join(tempfile.gettempdir(), f'ai3d-occt-source-{os.getpid()}.{source_ext}')
shutil.copyfile(src, safe_src)
src_occt = safe_src
from OCP.TopoDS import TopoDS
from OCP.TopAbs import TopAbs_FACE
from OCP.TopExp import TopExp_Explorer
from OCP.BRep import BRep_Tool
from OCP.BRepMesh import BRepMesh_IncrementalMesh
from OCP.TopLoc import TopLoc_Location
from OCP.IFSelect import IFSelect_RetDone
from OCP.BRepTools import BRepTools
DEFAULT_COLOR = [180, 180, 180, 255]
def triangulate_face(face, linear=0.5, angular=1.0):
BRepMesh_IncrementalMesh(face, linear, False, angular, True)
loc = TopLoc_Location()
tri = BRep_Tool.Triangulation_s(face, loc)
if tri is None:
return None, None
n = tri.NbNodes()
verts = []
for i in range(1, n + 1):
p = tri.Node(i)
if not loc.IsIdentity():
p = p.Transformed(loc.Transformation())
verts.append([p.X(), p.Y(), p.Z()])
ntri = tri.NbTriangles()
faces = []
for i in range(1, ntri + 1):
t = tri.Triangle(i)
n1, n2, n3 = t.Get()
faces.append([n1 - 1, n2 - 1, n3 - 1])
return verts, faces
# BREP: load geometry from native OpenCascade format
from OCP.TopoDS import TopoDS_Shape
from OCP.BRep import BRep_Builder
shape = TopoDS_Shape()
builder = BRep_Builder()
success = BRepTools.Read_s(shape, src_occt, builder)
if not success:
print(f"Failed to read BREP file: {src}", file=sys.stderr)
sys.exit(1)
all_verts = []
all_faces = []
all_colors = []
matched_count = 0
total_faces = 0
exp = TopExp_Explorer(shape, TopAbs_FACE)
while exp.More():
face = TopoDS.Face_s(exp.Current())
total_faces += 1
verts, faces = triangulate_face(face)
if verts and faces:
offset = len(all_verts)
all_verts.extend(verts)
for tri in faces:
all_faces.append([tri[0] + offset, tri[1] + offset, tri[2] + offset])
rgba = DEFAULT_COLOR
n = len(verts)
all_colors.extend([rgba] * n)
exp.Next()
print(f"Triangulated: {total_faces} faces, {len(all_verts)} verts, {matched_count} colored ({matched_count*100//max(total_faces,1)}%)")
if not all_verts or not all_faces:
# Fallback: use CadQuery import (works for STEP/IGES, not BREP)
cq_shape = cq.importers.importStep(src_occt) # CadQuery BREP import
cq.exporters.export(cq_shape, out, exportType='STL')
mesh = trimesh.load(out)
data = mesh.export(file_type='glb')
if isinstance(data, str):
with open(data, 'rb') as f:
data = f.read()
with open(out, 'wb') as f:
f.write(data)
print(f"Fallback CadQuery STL->GLB: {out} ({len(data)} bytes)")
sys.exit(0)
verts_arr = np.array(all_verts, dtype=float)
faces_arr = np.array(all_faces, dtype=int)
colors_arr = np.array(all_colors, dtype=np.uint8)
mesh = trimesh.Trimesh(
vertices=verts_arr,
faces=faces_arr,
visual=trimesh.visual.ColorVisuals(vertex_colors=colors_arr),
process=True,
)
mesh.fix_normals()
scene = trimesh.Scene([mesh])
result = scene.export(file_type='glb')
if isinstance(result, bytes):
data = result
elif isinstance(result, str):
with open(result, 'rb') as f:
data = f.read()
else:
data = bytes(result)
with open(out, 'wb') as f:
f.write(data)
print(f'Converted {src} -> {out} ({len(data)} bytes, {matched_count}/{total_faces} colored faces)')
`});var NJ,OJ=y(()=>{NJ=`import cadquery as cq
import trimesh
import trimesh.visual
import numpy as np
import sys
import os
import re
import json
import struct
import shutil
import tempfile
src = r"__AI3D_SOURCE_PATH__"
out = r"__AI3D_OUTPUT_PATH__"
source_ext = "__AI3D_SOURCE_EXT__"
src_occt = src
try:
src.encode('ascii')
except UnicodeEncodeError:
safe_src = os.path.join(tempfile.gettempdir(), f'ai3d-occt-source-{os.getpid()}.{source_ext}')
shutil.copyfile(src, safe_src)
src_occt = safe_src
from OCP.IGESControl import IGESControl_Reader
from OCP.TopoDS import TopoDS
from OCP.TopAbs import TopAbs_FACE
from OCP.TopExp import TopExp_Explorer
from OCP.BRep import BRep_Tool
from OCP.BRepMesh import BRepMesh_IncrementalMesh
from OCP.TopLoc import TopLoc_Location
from OCP.IFSelect import IFSelect_RetDone
from OCP.BRepTools import BRepTools
DEFAULT_COLOR = [180, 180, 180, 255]
def triangulate_face(face, linear=0.5, angular=1.0):
BRepMesh_IncrementalMesh(face, linear, False, angular, True)
loc = TopLoc_Location()
tri = BRep_Tool.Triangulation_s(face, loc)
if tri is None:
return None, None
n = tri.NbNodes()
verts = []
for i in range(1, n + 1):
p = tri.Node(i)
if not loc.IsIdentity():
p = p.Transformed(loc.Transformation())
verts.append([p.X(), p.Y(), p.Z()])
ntri = tri.NbTriangles()
faces = []
for i in range(1, ntri + 1):
t = tri.Triangle(i)
n1, n2, n3 = t.Get()
faces.append([n1 - 1, n2 - 1, n3 - 1])
return verts, faces
# IGES: load geometry (no XDE color support for IGES)
ir = IGESControl_Reader()
status = ir.ReadFile(src_occt)
if status != IFSelect_RetDone:
print(f"Failed to read IGES file: {src}", file=sys.stderr)
sys.exit(1)
ir.TransferRoots()
shape = ir.OneShape()
all_verts = []
all_faces = []
all_colors = []
matched_count = 0
total_faces = 0
exp = TopExp_Explorer(shape, TopAbs_FACE)
while exp.More():
face = TopoDS.Face_s(exp.Current())
total_faces += 1
verts, faces = triangulate_face(face)
if verts and faces:
offset = len(all_verts)
all_verts.extend(verts)
for tri in faces:
all_faces.append([tri[0] + offset, tri[1] + offset, tri[2] + offset])
rgba = DEFAULT_COLOR
n = len(verts)
all_colors.extend([rgba] * n)
exp.Next()
print(f"Triangulated: {total_faces} faces, {len(all_verts)} verts, {matched_count} colored ({matched_count*100//max(total_faces,1)}%)")
if not all_verts or not all_faces:
# Fallback: use CadQuery import (works for STEP/IGES, not BREP)
cq_shape = cq.importers.importStep(src_occt) # CadQuery reads IGES via importStep
cq.exporters.export(cq_shape, out, exportType='STL')
mesh = trimesh.load(out)
data = mesh.export(file_type='glb')
if isinstance(data, str):
with open(data, 'rb') as f:
data = f.read()
with open(out, 'wb') as f:
f.write(data)
print(f"Fallback CadQuery STL->GLB: {out} ({len(data)} bytes)")
sys.exit(0)
verts_arr = np.array(all_verts, dtype=float)
faces_arr = np.array(all_faces, dtype=int)
colors_arr = np.array(all_colors, dtype=np.uint8)
mesh = trimesh.Trimesh(
vertices=verts_arr,
faces=faces_arr,
visual=trimesh.visual.ColorVisuals(vertex_colors=colors_arr),
process=True,
)
mesh.fix_normals()
scene = trimesh.Scene([mesh])
result = scene.export(file_type='glb')
if isinstance(result, bytes):
data = result
elif isinstance(result, str):
with open(result, 'rb') as f:
data = f.read()
else:
data = bytes(result)
with open(out, 'wb') as f:
f.write(data)
print(f'Converted {src} -> {out} ({len(data)} bytes, {matched_count}/{total_faces} colored faces)')
`});var FJ,wJ=y(()=>{FJ=`import cadquery as cq
import trimesh
import trimesh.visual
import numpy as np
import sys
import os
import re
import json
import struct
import shutil
import tempfile
src = r"__AI3D_SOURCE_PATH__"
out = r"__AI3D_OUTPUT_PATH__"
source_ext = "__AI3D_SOURCE_EXT__"
src_occt = src
try:
src.encode('ascii')
except UnicodeEncodeError:
safe_src = os.path.join(tempfile.gettempdir(), f'ai3d-occt-source-{os.getpid()}.{source_ext}')
shutil.copyfile(src, safe_src)
src_occt = safe_src
from OCP.STEPCAFControl import STEPCAFControl_Reader
from OCP.STEPControl import STEPControl_Reader
from OCP.XCAFDoc import XCAFDoc_DocumentTool, XCAFDoc_ColorType, XCAFDoc_ShapeTool
from OCP.TDocStd import TDocStd_Document
from OCP.TCollection import TCollection_ExtendedString
from OCP.Quantity import Quantity_Color
from OCP.TDF import TDF_ChildIterator, TDF_LabelSequence
from OCP.TDataStd import TDataStd_Name
from OCP.TopoDS import TopoDS
from OCP.TopAbs import TopAbs_FACE
from OCP.TopExp import TopExp_Explorer
from OCP.BRep import BRep_Tool
from OCP.BRepMesh import BRepMesh_IncrementalMesh
from OCP.TopLoc import TopLoc_Location
from OCP.IFSelect import IFSelect_RetDone
DEFAULT_COLOR = [180, 180, 180, 255]
def triangulate_face(face, linear=0.5, angular=1.0):
BRepMesh_IncrementalMesh(face, linear, False, angular, True)
loc = TopLoc_Location()
tri = BRep_Tool.Triangulation_s(face, loc)
if tri is None:
return None, None
n = tri.NbNodes()
verts = []
for i in range(1, n + 1):
p = tri.Node(i)
if not loc.IsIdentity():
p = p.Transformed(loc.Transformation())
verts.append([p.X(), p.Y(), p.Z()])
ntri = tri.NbTriangles()
faces = []
for i in range(1, ntri + 1):
t = tri.Triangle(i)
n1, n2, n3 = t.Get()
faces.append([n1 - 1, n2 - 1, n3 - 1])
return verts, faces
def build_xde_color_lookup(step_path):
"""Load XDE with STEPCAFControl, extract per-face colors via surface signature."""
from OCP.BRepAdaptor import BRepAdaptor_Surface
lookup = {}
try:
reader = STEPCAFControl_Reader()
reader.SetColorMode(True)
reader.SetNameMode(True)
status = reader.ReadFile(step_path)
if status != IFSelect_RetDone:
return lookup
doc = TDocStd_Document(TCollection_ExtendedString('XmlOcaf'))
reader.Transfer(doc)
shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
color_tool = XCAFDoc_DocumentTool.ColorTool_s(doc.Main())
def walk(label):
if XCAFDoc_ShapeTool.IsShape_s(label):
s = XCAFDoc_ShapeTool.GetShape_s(label)
if s is not None and s.ShapeType() == TopAbs_FACE:
c = Quantity_Color()
if color_tool.GetColor(s, XCAFDoc_ColorType.XCAFDoc_ColorSurf, c):
face = TopoDS.Face_s(s)
try:
adaptor = BRepAdaptor_Surface(face)
u_r = (adaptor.FirstUParameter(), adaptor.LastUParameter())
v_r = (adaptor.FirstVParameter(), adaptor.LastVParameter())
key = (adaptor.GetType(), tuple(round(x, 4) for x in u_r), tuple(round(x, 4) for x in v_r))
color = (c.Red(), c.Green(), c.Blue())
if key not in lookup:
lookup[key] = color
except Exception:
pass
children = TDF_ChildIterator(label)
while children.More():
walk(children.Value())
children.Next()
walk(doc.Main())
except Exception as e:
print(f"XDE color extraction failed: {e}", file=sys.stderr)
return lookup
def get_face_color(face, color_lookup):
"""Match a geometry face to an XDE face via surface signature, return color."""
from OCP.BRepAdaptor import BRepAdaptor_Surface
try:
adaptor = BRepAdaptor_Surface(face)
u_r = (adaptor.FirstUParameter(), adaptor.LastUParameter())
v_r = (adaptor.FirstVParameter(), adaptor.LastVParameter())
key = (adaptor.GetType(), tuple(round(x, 4) for x in u_r), tuple(round(x, 4) for x in v_r))
return color_lookup.get(key)
except Exception:
return None
def label_name(label):
name_attr = TDataStd_Name()
try:
if label.FindAttribute(TDataStd_Name.GetID_s(), name_attr):
return name_attr.Get().ToExtString()
except Exception:
pass
return ''
def clean_component_name(value, fallback):
text = re.sub(r'\\s+', ' ', str(value or '')).strip()
if not text or text.startswith('=>'):
text = fallback
return text[:96]
def count_shape_faces(shape):
count = 0
exp = TopExp_Explorer(shape, TopAbs_FACE)
while exp.More():
count += 1
exp.Next()
return count
def unique_component_name(name, used):
base = clean_component_name(name, f'component-{len(used) + 1:03d}')
candidate = base
suffix = 2
while candidate in used:
candidate = f'{base}-{suffix}'
suffix += 1
used.add(candidate)
return candidate
def collect_xde_components(step_path):
components = []
try:
reader = STEPCAFControl_Reader()
reader.SetColorMode(True)
reader.SetNameMode(True)
status = reader.ReadFile(step_path)
if status != IFSelect_RetDone:
return components
doc = TDocStd_Document(TCollection_ExtendedString('XmlOcaf'))
if not reader.Transfer(doc):
return components
shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
free = TDF_LabelSequence()
shape_tool.GetFreeShapes(free)
used_names = set()
def walk(label, path_parts):
if not XCAFDoc_ShapeTool.IsShape_s(label):
child = TDF_ChildIterator(label)
while child.More():
walk(child.Value(), path_parts)
child.Next()
return
raw_name = label_name(label)
next_path = path_parts + ([raw_name] if raw_name and not raw_name.startswith('=>') else [])
shape = XCAFDoc_ShapeTool.GetShape_s(label)
face_count = 0 if shape is None or shape.IsNull() else count_shape_faces(shape)
try:
is_assembly = XCAFDoc_ShapeTool.IsAssembly_s(label)
except Exception:
is_assembly = False
try:
is_component = XCAFDoc_ShapeTool.IsComponent_s(label)
except Exception:
is_component = False
if face_count > 0 and not is_assembly:
name = unique_component_name(raw_name, used_names)
component_path = '/'.join([part for part in next_path if part]) or name
components.append({
'name': name,
'path': component_path,
'shape': shape,
'face_count': face_count,
'is_component': is_component,
})
return
child = TDF_ChildIterator(label)
while child.More():
walk(child.Value(), next_path)
child.Next()
for index in range(1, free.Length() + 1):
walk(free.Value(index), [])
except Exception as e:
print(f'XDE component extraction failed: {e}', file=sys.stderr)
return components
def mesh_from_shape(shape, color_lookup, name, component_path):
try:
BRepMesh_IncrementalMesh(shape, 0.5, False, 1.0, True)
except Exception:
pass
verts_acc = []
faces_acc = []
colors_acc = []
matched = 0
total = 0
exp = TopExp_Explorer(shape, TopAbs_FACE)
while exp.More():
face = TopoDS.Face_s(exp.Current())
total += 1
verts, faces = triangulate_face(face)
if verts and faces:
offset = len(verts_acc)
verts_acc.extend(verts)
for tri in faces:
faces_acc.append([tri[0] + offset, tri[1] + offset, tri[2] + offset])
color = get_face_color(face, color_lookup)
if color:
matched += 1
r, g, b = color
rgba = [int(r * 255), int(g * 255), int(b * 255), 255]
else:
rgba = DEFAULT_COLOR
colors_acc.extend([rgba] * len(verts))
exp.Next()
if not verts_acc or not faces_acc:
return None, total, matched
mesh = trimesh.Trimesh(
vertices=np.array(verts_acc, dtype=float),
faces=np.array(faces_acc, dtype=int),
visual=trimesh.visual.ColorVisuals(vertex_colors=np.array(colors_acc, dtype=np.uint8)),
process=True,
)
mesh.fix_normals()
mesh.metadata.update({
'name': name,
'ai3d': {
'partId': name,
'componentId': name,
'occurrenceId': component_path,
'componentPath': component_path,
'displayName': name,
},
})
return mesh, total, matched
def read_step_xde(step_path):
"""Read STEP into an XDE document with colors and names preserved."""
reader = STEPCAFControl_Reader()
reader.SetColorMode(True)
reader.SetNameMode(True)
status = reader.ReadFile(step_path)
if status != IFSelect_RetDone:
return None
doc = TDocStd_Document(TCollection_ExtendedString('XmlOcaf'))
if not reader.Transfer(doc):
return None
return doc
def triangulate_document(doc, linear=1.0, angular=2.0):
"""Triangulate all free shapes in the XDE document."""
shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
free = TDF_LabelSequence()
shape_tool.GetFreeShapes(free)
for i in range(1, free.Length() + 1):
shape = XCAFDoc_ShapeTool.GetShape_s(free.Value(i))
if shape is not None and not shape.IsNull():
BRepMesh_IncrementalMesh(shape, linear, False, angular, True)
def write_gltf_from_xde(doc, out_path, binary=True):
"""Use OCCT RWGltf_CafWriter to preserve colors and hierarchy."""
try:
from OCP.RWGltf import RWGltf_CafWriter, RWGltf_WriterTrsfFormat
from OCP.Message import Message_ProgressRange
from OCP.TColStd import TColStd_IndexedDataMapOfStringString
from OCP.TCollection import TCollection_AsciiString
writer = RWGltf_CafWriter(TCollection_AsciiString(out_path), binary)
writer.SetTransformationFormat(RWGltf_WriterTrsfFormat.RWGltf_WriterTrsfFormat_Compact)
info = TColStd_IndexedDataMapOfStringString()
return bool(writer.Perform(doc, info, Message_ProgressRange()))
except Exception as e:
print(f'OCCT glTF writer unavailable: {e}', file=sys.stderr)
return False
def clean_node_name(value, fallback='node'):
text = re.sub(r'\\s+', ' ', str(value or '')).strip()
if not text or text.startswith('=>'):
text = fallback
return re.sub(r'[^\\w\\-_.]', '_', text)[:96]
def postprocess_occt_glb(raw_glb, out_path):
"""Force opaque/double-sided materials and add ai3d metadata without altering colors."""
if len(raw_glb) < 20:
raise ValueError('GLB file is too small')
magic, version, _total = struct.unpack('<III', raw_glb[:12])
if magic != 0x46546C67 or version != 2:
raise ValueError('Expected GLB v2 output from OCCT writer')
json_len, json_type = struct.unpack('<II', raw_glb[12:20])
if json_type != 0x4E4F534A:
raise ValueError('GLB JSON chunk missing')
json_start = 20
json_end = json_start + json_len
gltf = json.loads(raw_glb[json_start:json_end].decode('utf-8'))
chunks = []
offset = json_end
while offset + 8 <= len(raw_glb):
chunk_len, chunk_type = struct.unpack('<II', raw_glb[offset:offset + 8])
start = offset + 8
end = start + chunk_len
if end > len(raw_glb):
raise ValueError('GLB chunk length exceeds file size')
chunks.append((chunk_type, raw_glb[start:end]))
offset = end
nodes = gltf.setdefault('nodes', [])
meshes = gltf.setdefault('meshes', [])
materials = gltf.setdefault('materials', [])
if materials:
for material in materials:
material['alphaMode'] = 'OPAQUE'
material['doubleSided'] = True
else:
materials.append({
'pbrMetallicRoughness': {
'baseColorFactor': [0.7, 0.7, 0.7, 1.0],
'metallicFactor': 0.0,
'roughnessFactor': 0.8,
},
'alphaMode': 'OPAQUE',
'doubleSided': True,
})
for mesh in meshes:
for primitive in mesh.get('primitives', []):
primitive['material'] = 0
for i, node in enumerate(nodes):
name = clean_node_name(node.get('name'), f'node_{i}')
if 'name' not in node:
node['name'] = name
extras = node.setdefault('extras', {})
ai3d = extras.setdefault('ai3d', {})
ai3d.update({
'partId': name,
'componentId': name,
'occurrenceId': name,
'componentPath': name,
'displayName': name,
})
for i, mesh in enumerate(meshes):
name = clean_node_name(mesh.get('name'), f'mesh_{i}')
if 'name' not in mesh:
mesh['name'] = name
extras = mesh.setdefault('extras', {})
ai3d = extras.setdefault('ai3d', {})
ai3d.update({
'partId': name,
'componentId': name,
'occurrenceId': name,
'componentPath': name,
'displayName': name,
})
new_json = json.dumps(gltf, separators=(',', ':')).encode('utf-8')
new_json_padded = new_json + b' ' * ((4 - (len(new_json) % 4)) % 4)
new_total = 12 + 8 + len(new_json_padded) + sum(8 + len(payload) for _chunk_type, payload in chunks)
with open(out_path, 'wb') as f:
f.write(struct.pack('<III', 0x46546C67, 2, new_total))
f.write(struct.pack('<II', len(new_json_padded), 0x4E4F534A))
f.write(new_json_padded)
for chunk_type, payload in chunks:
f.write(struct.pack('<II', len(payload), chunk_type))
f.write(payload)
def convert_step_to_glb(step_path, out_path):
try:
doc = read_step_xde(step_path)
if doc is None:
return False
triangulate_document(doc)
glb_tmp = os.path.join(tempfile.gettempdir(), f'ai3d-occt-{os.getpid()}.glb')
if not write_gltf_from_xde(doc, glb_tmp, binary=True):
return False
try:
with open(glb_tmp, 'rb') as f:
raw = f.read()
postprocess_occt_glb(raw, out_path)
print(f'Converted {step_path} -> {out_path} ({os.path.getsize(out_path)} bytes, OCCT glTF writer)')
return True
finally:
try:
os.remove(glb_tmp)
except Exception:
pass
except Exception as e:
print(f'OCCT glTF writer failed: {e}', file=sys.stderr)
return False
# STEP: use OCCT glTF writer first, then fall back to XDE component meshes
if convert_step_to_glb(src_occt, out):
sys.exit(0)
# STEP: build XDE color lookup + load geometry
color_lookup = build_xde_color_lookup(src_occt)
print(f"XDE color lookup: {len(color_lookup)} surface signatures")
xde_components = collect_xde_components(src_occt)
component_meshes = []
component_faces = 0
component_matched = 0
for component in xde_components:
mesh_result, total, matched = mesh_from_shape(component['shape'], color_lookup, component['name'], component['path'])
component_faces += total
component_matched += matched
if mesh_result is not None:
component_meshes.append((component, mesh_result))
if len(component_meshes) > 1:
scene = trimesh.Scene()
for component, mesh_result in component_meshes:
scene.add_geometry(mesh_result, node_name=component['name'], geom_name=component['name'])
result = scene.export(file_type='glb')
if isinstance(result, bytes):
data = result
elif isinstance(result, str):
with open(result, 'rb') as f:
data = f.read()
else:
data = bytes(result)
with open(out, 'wb') as f:
f.write(data)
print(f'Converted {src} -> {out} ({len(data)} bytes, {len(component_meshes)} XDE components, {component_matched}/{component_faces} colored faces)')
sys.exit(0)
print(f"XDE component export unavailable: {len(component_meshes)} usable components from {len(xde_components)} labels; falling back to whole-shape mesh")
sr = STEPControl_Reader()
status = sr.ReadFile(src_occt)
if status != IFSelect_RetDone:
print(f"Failed to read STEP file: {src}", file=sys.stderr)
sys.exit(1)
sr.TransferRoots()
shape = sr.OneShape()
all_verts = []
all_faces = []
all_colors = []
matched_count = 0
total_faces = 0
exp = TopExp_Explorer(shape, TopAbs_FACE)
while exp.More():
face = TopoDS.Face_s(exp.Current())
total_faces += 1
verts, faces = triangulate_face(face)
if verts and faces:
offset = len(all_verts)
all_verts.extend(verts)
for tri in faces:
all_faces.append([tri[0] + offset, tri[1] + offset, tri[2] + offset])
color = get_face_color(face, color_lookup)
if color:
matched_count += 1
r, g, b = color
rgba = [int(r * 255), int(g * 255), int(b * 255), 255]
else:
rgba = DEFAULT_COLOR
n = len(verts)
all_colors.extend([rgba] * n)
exp.Next()
print(f"Triangulated: {total_faces} faces, {len(all_verts)} verts, {matched_count} colored ({matched_count*100//max(total_faces,1)}%)")
if not all_verts or not all_faces:
# Fallback: use CadQuery import (works for STEP/IGES, not BREP)
cq_shape = cq.importers.importStep(src_occt)
cq.exporters.export(cq_shape, out, exportType='STL')
mesh = trimesh.load(out)
data = mesh.export(file_type='glb')
if isinstance(data, str):
with open(data, 'rb') as f:
data = f.read()
with open(out, 'wb') as f:
f.write(data)
print(f"Fallback CadQuery STL->GLB: {out} ({len(data)} bytes)")
sys.exit(0)
verts_arr = np.array(all_verts, dtype=float)
faces_arr = np.array(all_faces, dtype=int)
colors_arr = np.array(all_colors, dtype=np.uint8)
mesh = trimesh.Trimesh(
vertices=verts_arr,
faces=faces_arr,
visual=trimesh.visual.ColorVisuals(vertex_colors=colors_arr),
process=True,
)
mesh.fix_normals()
scene = trimesh.Scene([mesh])
result = scene.export(file_type='glb')
if isinstance(result, bytes):
data = result
elif isinstance(result, str):
with open(result, 'rb') as f:
data = f.read()
else:
data = bytes(result)
with open(out, 'wb') as f:
f.write(data)
print(f'Converted {src} -> {out} ({len(data)} bytes, {matched_count}/{total_faces} colored faces)')
`});function gf(n){if(n.includes('"'))throw new Error(`File path contains double-quote character, not supported for Python conversion: ${n}`);return n.replace(/\\/g,"/")}var i0=y(()=>{"use strict"});function BJ(n){return n.toLowerCase().replace(/^\./,"")}function GAe(n){let e=BJ(n);return e==="step"||e==="stp"?FJ:e==="iges"||e==="igs"?NJ:DJ}function $1(n,e,t){return n.split(e).join(t)}function UJ(n,e,t){let i=BJ(t),r=$1(GAe(i),BAe,gf(n)),s=$1(r,UAe,gf(e));return $1(s,VAe,i)}var BAe,UAe,VAe,VJ=y(()=>{"use strict";LJ();OJ();wJ();i0();BAe="__AI3D_SOURCE_PATH__",UAe="__AI3D_OUTPUT_PATH__",VAe="__AI3D_SOURCE_EXT__"});async function WAe(n){try{return await Ss(n,Ts),!0}catch(e){return!1}}function HAe(n,e,t){return new Promise((i,r)=>{ba(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i();return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`CAD conversion failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}var kAe,zAe,r0,GJ=y(()=>{"use strict";hr();hr();hr();hr();zn();Kd();VJ();kAe=er("freecad-converter"),zAe=300*1e3;r0=class{constructor(e){this.configuredCommand=e;this.id="freecad";this.sourceExts=["step","stp","iges","igs","brep"];this.targetExt="glb"}async getCacheKey(){let e=await Wn(this.id,this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){var c;if(!Ra(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking CAD conversion.`);let t=await Wn(this.id,this.configuredCommand),i=qn(e.sourcePath),r=Qn(e.sourcePath,$n(e.sourcePath)),s=(c=e.outputPath)!=null?c:tr(i,`${r}.ai3d-converted.glb`),a=tr(yu(),"ai3d-freecad"),o=tr(a,`${r}-${Date.now()}.py`);await Zn(qn(s),{recursive:!0}),await Zn(a,{recursive:!0}),await Ru(o,UJ(e.sourcePath,s,e.sourceExt),"utf8"),kAe.info("run CAD conversion (CadQuery/OCCT)",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{await HAe(t.command,[...t.args,o],zAe)}catch(f){throw new Error(`CAD conversion failed for '${e.sourcePath}'. Ensure Python can import CadQuery/OCP and trimesh. A dedicated conda/mamba environment from conda-forge is recommended; pip install cadquery trimesh can work when compatible wheels are available. Set Python command path in plugin settings or AI3D_FREECAD_CMD if Python is not discoverable. ${f instanceof Error?f.message:String(f)}`)}finally{bu(o,{force:!0})}if(!await WAe(s))throw new Error(`CAD conversion finished but output was not found: '${s}'. Check that CadQuery supports this CAD format.`);if((await xa(s)).byteLength===0)throw new Error(`CAD conversion output is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local Python/CadQuery(OCCT) bridge."]}}}});async function KAe(n){try{return await Ss(n,Ts),!0}catch(e){return!1}}function jAe(n,e,t){return new Promise((i,r)=>{ba(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i();return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`obj2gltf command failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}var XAe,YAe,n0,kJ=y(()=>{"use strict";hr();hr();hr();zn();Kd();XAe=er("obj2gltf-converter"),YAe=180*1e3;n0=class{constructor(e){this.configuredCommand=e;this.id="obj2gltf";this.sourceExts=["obj"];this.targetExt="glb"}async getCacheKey(){let e=await Wn(this.id,this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){var o;if(!Ra(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking obj2gltf.`);let t=await Wn(this.id,this.configuredCommand),i=qn(e.sourcePath),r=Qn(e.sourcePath,$n(e.sourcePath)),s=(o=e.outputPath)!=null?o:tr(i,`${r}.ai3d-converted.glb`);await Zn(qn(s),{recursive:!0}),XAe.info("run obj2gltf conversion",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{await jAe(t.command,[...t.args,"-i",e.sourcePath,"-o",s,"-b"],YAe)}catch(l){throw new Error(`obj2gltf conversion failed for '${e.sourcePath}'. Set obj2gltf command path in plugin settings or AI3D_OBJ2GLTF_CMD if obj2gltf is not discoverable. ${l instanceof Error?l.message:String(l)}`)}if(!await KAe(s))throw new Error(`obj2gltf conversion finished but output was not found: '${s}'.`);if((await xa(s)).byteLength===0)throw new Error(`obj2gltf output file is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local obj2gltf CLI bridge."]}}}});async function QAe(n){try{return await Ss(n,Ts),!0}catch(e){return!1}}function $Ae(n,e,t){return new Promise((i,r)=>{ba(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i();return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`FBX2glTF command failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}var ZAe,qAe,s0,zJ=y(()=>{"use strict";hr();hr();hr();zn();Kd();ZAe=er("fbx2gltf-converter"),qAe=180*1e3;s0=class{constructor(e){this.configuredCommand=e;this.id="fbx2gltf";this.sourceExts=["fbx"];this.targetExt="glb"}async getCacheKey(){let e=await Wn(this.id,this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){var o;if(!Ra(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking FBX2glTF.`);let t=await Wn(this.id,this.configuredCommand),i=qn(e.sourcePath),r=Qn(e.sourcePath,$n(e.sourcePath)),s=(o=e.outputPath)!=null?o:tr(i,`${r}.ai3d-converted.glb`);await Zn(qn(s),{recursive:!0}),ZAe.info("run FBX2glTF conversion",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{await $Ae(t.command,[...t.args,"-i",e.sourcePath,"-o",s,"-b"],qAe)}catch(l){throw new Error(`FBX2glTF conversion failed for '${e.sourcePath}'. Set FBX2glTF command path in plugin settings or AI3D_FBX2GLTF_CMD if FBX2glTF is not discoverable. ${l instanceof Error?l.message:String(l)}`)}if(!await QAe(s))throw new Error(`FBX2glTF conversion finished but output was not found: '${s}'.`);if((await xa(s)).byteLength===0)throw new Error(`FBX2glTF output file is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local FBX2glTF CLI bridge."]}}}});async function txe(n){try{return await Ss(n,Ts),!0}catch(e){return!1}}function ixe(n,e,t){return new Promise((i,r)=>{ba(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i();return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`mesh conversion failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}function rxe(n,e){let t=gf(n),i=gf(e);return["import trimesh","import sys","",`src = r"${t}"`,`out = r"${i}"`,"","try:"," loaded = trimesh.load(src, force=None)","except Exception as e:",' print(f"Failed to load {src}: {e}", file=sys.stderr)'," sys.exit(1)","","if isinstance(loaded, trimesh.Scene):"," scene = loaded","elif isinstance(loaded, trimesh.Trimesh):"," scene = trimesh.Scene([loaded])","else:",' print(f"Unsupported type: {type(loaded)}", file=sys.stderr)'," sys.exit(1)","","try:"," data = scene.export(file_type='glb')","except Exception as e:",' print(f"Failed to export GLB: {e}", file=sys.stderr)'," sys.exit(1)","","with open(out, 'wb') as f:"," f.write(data)","","print(f'Converted {src} -> {out} ({len(data)} bytes)')"].join(`
`)}var JAe,exe,a0,WJ=y(()=>{"use strict";hr();hr();hr();hr();zn();Kd();i0();JAe=er("assimp-converter"),exe=300*1e3;a0=class{constructor(e){this.configuredCommand=e;this.id="assimp";this.sourceExts=["3mf","dae"];this.targetExt="glb"}async getCacheKey(){let e=await Wn(this.id,this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){var c;if(!Ra(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking mesh conversion.`);let t=await Wn(this.id,this.configuredCommand),i=qn(e.sourcePath),r=Qn(e.sourcePath,$n(e.sourcePath)),s=(c=e.outputPath)!=null?c:tr(i,`${r}.ai3d-converted.glb`),a=tr(yu(),"ai3d-mesh-convert"),o=tr(a,`${r}-${Date.now()}.py`);await Zn(qn(s),{recursive:!0}),await Zn(a,{recursive:!0}),await Ru(o,rxe(e.sourcePath,s),"utf8"),JAe.info("run mesh conversion (trimesh)",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{await ixe(t.command,[...t.args,o],exe)}catch(f){throw new Error(`Mesh conversion failed for '${e.sourcePath}'. Ensure Python with trimesh is installed: pip install trimesh numpy networkx pycollada. Set Python command path in plugin settings or AI3D_ASSIMP_CMD if Python is not discoverable. ${f instanceof Error?f.message:String(f)}`)}finally{bu(o,{force:!0})}if(!await txe(s))throw new Error(`Mesh conversion finished but output was not found: '${s}'. Check that trimesh supports this format.`);if((await xa(s)).byteLength===0)throw new Error(`Mesh conversion output is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local Python/trimesh bridge."]}}}});async function sxe(n){try{return await Ss(n,Ts),!0}catch(e){return!1}}function axe(n,e,t){return new Promise((i,r)=>{ba(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i({stdout:a!=null?a:"",stderr:o!=null?o:""});return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`SLDPRT conversion failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}function oxe(n,e){let t=gf(n),i=gf(e),r=i.replace(/\.glb$/i,".intermediate.step");return["import sys","import os","",`src = r"${t}"`,`out = r"${i}"`,`step_out = r"${r}"`,"","# Step 1: Import SLDPRT via FreeCAD","try:"," import FreeCAD"," import ImportGui"," import Mesh","except ImportError as e:",' print(f"FreeCAD modules not available: {e}", file=sys.stderr)',' print("Ensure this script runs under FreeCADCmd (not system Python).", file=sys.stderr)'," sys.exit(1)","","print(f'Opening SLDPRT: {src}')","try:"," doc = FreeCAD.newDocument('Convert')"," ImportGui.open(src, doc.Name)","except Exception as e:",' print(f"Failed to open SLDPRT file: {e}", file=sys.stderr)'," sys.exit(1)","","if not doc.Objects:",' print("SLDPRT file imported but contains no objects", file=sys.stderr)'," sys.exit(1)","",'print(f"Imported {len(doc.Objects)} object(s) from SLDPRT")',"","# Step 2: Export to STEP (intermediate)","try:"," import Import"," objs = [o for o in doc.Objects if hasattr(o, 'Shape')]"," if not objs:",' print("No shape objects found after import", file=sys.stderr)'," sys.exit(1)"," Import.export(objs, step_out)",' print(f"Exported intermediate STEP: {step_out}")',"except Exception as e:",' print(f"Failed to export STEP: {e}", file=sys.stderr)'," sys.exit(1)","","FreeCAD.closeDocument(doc.Name)","","# Step 3: Convert STEP to GLB using OCP (same pipeline as FreecadConverter)","import trimesh","import trimesh.visual","import numpy as np","","from OCP.STEPControl import STEPControl_Reader","from OCP.TopoDS import TopoDS","from OCP.TopAbs import TopAbs_FACE","from OCP.TopExp import TopExp_Explorer","from OCP.BRep import BRep_Tool","from OCP.BRepMesh import BRepMesh_IncrementalMesh","from OCP.TopLoc import TopLoc_Location","from OCP.IFSelect import IFSelect_RetDone","","DEFAULT_COLOR = [180, 180, 180, 255]","","def triangulate_face(face, linear=0.1, angular=0.5):"," BRepMesh_IncrementalMesh(face, linear, False, angular, True)"," loc = TopLoc_Location()"," tri = BRep_Tool.Triangulation_s(face, loc)"," if tri is None:"," return None, None"," n = tri.NbNodes()"," verts = []"," for i in range(1, n + 1):"," p = tri.Node(i)"," if not loc.IsIdentity():"," p = p.Transformed(loc.Transformation())"," verts.append([p.X(), p.Y(), p.Z()])"," ntri = tri.NbTriangles()"," faces = []"," for i in range(1, ntri + 1):"," t = tri.Triangle(i)"," n1, n2, n3 = t.Get()"," faces.append([n1 - 1, n2 - 1, n3 - 1])"," return verts, faces","","sr = STEPControl_Reader()","status = sr.ReadFile(step_out)","if status != IFSelect_RetDone:",' print(f"Failed to read intermediate STEP: {step_out}", file=sys.stderr)'," sys.exit(1)","sr.TransferRoots()","shape = sr.OneShape()","","all_verts = []","all_faces = []","all_colors = []","total_faces = 0","","exp = TopExp_Explorer(shape, TopAbs_FACE)","while exp.More():"," face = TopoDS.Face_s(exp.Current())"," total_faces += 1"," verts, faces = triangulate_face(face)"," if verts and faces:"," offset = len(all_verts)"," all_verts.extend(verts)"," for tri in faces:"," all_faces.append([tri[0] + offset, tri[1] + offset, tri[2] + offset])"," all_colors.extend([DEFAULT_COLOR] * len(verts))"," exp.Next()","","if not all_verts or not all_faces:",' print(f"No geometry extracted from STEP ({total_faces} faces scanned)", file=sys.stderr)'," sys.exit(1)","",'print(f"Triangulated: {total_faces} faces, {len(all_verts)} verts")',"","verts_arr = np.array(all_verts, dtype=float)","faces_arr = np.array(all_faces, dtype=int)","colors_arr = np.array(all_colors, dtype=np.uint8)","","mesh = trimesh.Trimesh("," vertices=verts_arr,"," faces=faces_arr,"," visual=trimesh.visual.ColorVisuals(vertex_colors=colors_arr),"," process=True,",")","mesh.fix_normals()","scene = trimesh.Scene([mesh])","","result = scene.export(file_type='glb')","if isinstance(result, bytes):"," data = result","elif isinstance(result, str):"," with open(result, 'rb') as f:"," data = f.read()","else:"," data = bytes(result)","","with open(out, 'wb') as f:"," f.write(data)","","# Cleanup intermediate STEP","try:"," os.remove(step_out)","except OSError:"," pass","","print(f'Converted {src} -> {out} ({len(data)} bytes, {total_faces} faces)')"].join(`
`)}var J1,nxe,o0,HJ=y(()=>{"use strict";hr();hr();hr();hr();zn();Kd();i0();J1=er("sldprt-converter"),nxe=600*1e3;o0=class{constructor(e){this.configuredCommand=e;this.id="sldprt";this.sourceExts=["sldprt"];this.targetExt="glb"}async getCacheKey(){let e=await Wn("freecadcmd",this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){var c;if(!Ra(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking SLDPRT conversion.`);let t=await Wn("freecadcmd",this.configuredCommand),i=qn(e.sourcePath),r=Qn(e.sourcePath,$n(e.sourcePath)),s=(c=e.outputPath)!=null?c:tr(i,`${r}.ai3d-converted.glb`),a=tr(yu(),"ai3d-sldprt"),o=tr(a,`${r}-${Date.now()}.py`);await Zn(qn(s),{recursive:!0}),await Zn(a,{recursive:!0}),await Ru(o,oxe(e.sourcePath,s),"utf8"),J1.info("run SLDPRT conversion (FreeCAD + OCP)",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{let{stdout:f,stderr:d}=await axe(t.command,[...t.args,o],nxe);f&&J1.info("FreeCAD stdout",{stdout:f.trim().slice(0,500)}),d&&J1.warn("FreeCAD stderr",{stderr:d.trim().slice(0,500)})}catch(f){throw new Error(`SLDPRT conversion failed for '${e.sourcePath}'. Ensure FreeCAD is installed (https://www.freecad.org/downloads.php). Set FreeCADCmd path in plugin settings or AI3D_FREECADCMD env var. ${f instanceof Error?f.message:String(f)}`)}finally{bu(o,{force:!0})}if(!await sxe(s))throw new Error(`SLDPRT conversion finished but output was not found: '${s}'. Check that FreeCAD can import this SolidWorks file version.`);if((await xa(s)).byteLength===0)throw new Error(`SLDPRT conversion output is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local FreeCAD + OpenCASCADE bridge."]}}}});var l0={};Be(l0,{createConversionManager:()=>lxe});function lxe(n){var r;let e=new e0,t=new Set((r=n==null?void 0:n.enabledConverterIds)!=null?r:[]);e3.debug("create conversion manager",{enabledConverterIds:[...t]});let i=[new r0(n==null?void 0:n.freecadCommand),new n0(n==null?void 0:n.obj2gltfCommand),new s0(n==null?void 0:n.fbx2gltfCommand),new a0(n==null?void 0:n.assimpCommand),new o0(n==null?void 0:n.freecadcmdCommand)];for(let s of i)t.has(s.id)?(e.registerConverter(s),e3.info("enabled converter",{converterId:s.id})):e3.debug("converter disabled",{converterId:s.id});return e}var e3,c0=y(()=>{"use strict";IJ();GJ();kJ();zJ();WJ();HJ();zn();e3=er("conversion-factory")});var f0={};Be(f0,{AnnotationManager:()=>i3});function hxe(){return`pin-${Date.now()}-${cxe++}`}function jJ(n){return _n(n)}function mxe(n,e,t){return n.left<e.right+t&&n.right>e.left-t&&n.top<e.bottom+t&&n.bottom>e.top-t}var ZE,wg,cxe,t3,fxe,dxe,XJ,YJ,uxe,KJ,Fg,i3,d0=y(()=>{"use strict";ZE=require("obsidian");xn();As();xs();wg=["#4a9eff","#ff6b6b","#51cf66","#ffd43b","#845ef7","#ff922b","#22b8cf","#f06595","#94d82d","#ffa8a8"],cxe=1,t3=4,fxe=2,dxe=6,XJ=6,YJ=72,uxe=80,KJ=200;Fg=class Fg{constructor(e,t,i,r,s,a,o,l={}){this.provider=e;this.hostEl=t;this.mode=i;this.onChange=s;this.noteReader=a;this.headingSearch=o;this.pinEls=new Map;this.observer=null;this.resizeObs=null;this.annotations=[];this.editorEl=null;this.disposeCallbacks=[];this.frameCount=0;this.lastCamState="";this.idleFrames=0;this.cameraIdle=!1;this.movingOcclusionCursor=0;this.hoverPopover=null;this.hoverTimeout=null;this.hoverCloseTimeout=null;this.hoverRequestId=0;this._highlightHandler=null;this._pulseTimeout=null;this._headingDropdown=null;this._headingDebounce=null;this._selectedHeading=null;this.previewRenderRoot=new ZE.Component;this.previewRenderChildren=new WeakMap;var c,f;this.previewApp=l.app,this.previewMode=(c=l.previewMode)!=null?c:"plain-text",this.displayMode=(f=l.displayMode)!=null?f:"surface",this.previewRenderRoot.load(),this.overlay=this.hostEl.createDiv({cls:"ai3d-annotation-overlay"}),this.setAnnotations(r),this._highlightHandler=d=>{let u=d.detail,h=u==null?void 0:u.pinId;h&&this.pulsePin(h)},activeDocument.addEventListener("ai3d-pin-highlight",this._highlightHandler),this.disposeCallbacks.push(()=>activeDocument.removeEventListener("ai3d-pin-highlight",this._highlightHandler)),this.disposeCallbacks.push(()=>this.previewRenderRoot.unload()),this.startProjectionLoop()}setAnnotations(e){for(let[,t]of this.pinEls)this.removePinElement(t.el);this.pinEls.clear(),this.annotations=[...e];for(let t of e)this.createPinElement(t);this.updateProjections()}addPin(e,t,i){var s;if(this.annotations.length>=KJ)return console.warn(`[AI3D] Pin limit (${KJ}) reached; ignoring new pin.`),this.annotations[this.annotations.length-1];let r={id:hxe(),position:[e.x,e.y,e.z],label:t,color:i!=null?i:wg[this.annotations.length%wg.length],createdAt:new Date().toISOString()};return this.annotations.push(r),this.createPinElement(r),this.updateProjections(),(s=this.onChange)==null||s.call(this,this.annotations),r}removePin(e){var i;let t=this.pinEls.get(e);t&&(this.removePinElement(t.el),this.pinEls.delete(e)),this.annotations=this.annotations.filter(r=>r.id!==e),(i=this.onChange)==null||i.call(this,this.annotations)}updatePin(e,t){var s;let i=this.annotations.find(a=>a.id===e);if(!i)return;Object.assign(i,t);let r=this.pinEls.get(e);if(r){t.position&&(r.worldPos={x:t.position[0],y:t.position[1],z:t.position[2]});let a=r.el.querySelector(".ai3d-pin-label");a&&t.label!==void 0&&(a.textContent=t.label);let o=r.el.querySelector(".ai3d-pin-dot");o&&t.color!==void 0&&o.style.setProperty("--pin-color",t.color),(t.notePath!==void 0||t.headingRef!==void 0||t.label!==void 0)&&this.renderPinDisplay(r.el,i)}this.updateProjections(),(s=this.onChange)==null||s.call(this,this.annotations)}showEditor(e,t,i){this.showEditorInternal(e,t,i)}editPin(e){let t=this.annotations.find(o=>o.id===e);if(!t)return;let i=this.pinEls.get(e);if(!i)return;let r=i.el.getBoundingClientRect(),s=r.left+r.width/2,a=r.top;this.showEditorInternal(s,a,jJ(i.worldPos),t)}getPinPosition(e){let t=this.pinEls.get(e);return t?jJ(t.worldPos):null}getAnnotations(){return this.annotations}showEditorInternal(e,t,i,r){var w,G;this.hideEditor(),this._selectedHeading=null;let s=this.overlay.createDiv({cls:"ai3d-annotation-editor"}),a=s.createDiv({cls:"ai3d-editor-input-wrap"}),o=a.createEl("input",{cls:"ai3d-annotation-editor-input"});o.type="text",o.placeholder=this.headingSearch?"Label or search heading...":"Label...",r&&(o.value=r.label);let l=a.createSpan({cls:"ai3d-editor-binding-tag is-hidden"}),c=l.createEl("button",{cls:"ai3d-editor-binding-clear"});c.textContent="\xD7",c.addEventListener("click",O=>{O.stopPropagation(),this._selectedHeading=null,l.classList.add("is-hidden"),f.classList.add("is-hidden"),f.textContent="",o.value="",o.focus()});let f=s.createDiv({cls:"ai3d-editor-content-preview is-hidden"}),d=s.createDiv({cls:"ai3d-heading-dropdown is-hidden"});this._headingDropdown=d;let u=-1,h=[],m=O=>{let N=d.querySelectorAll(".ai3d-heading-dropdown-item");N.forEach(B=>B.classList.remove("active")),u=O,O>=0&&O<N.length&&(N[O].classList.add("active"),N[O].scrollIntoView({block:"nearest"}))},g=O=>{var V;this._selectedHeading=O,o.value=O.heading;let N=gn(O.notePath);(V=l.querySelector(".ai3d-editor-binding-text"))==null||V.remove();let B=l.createSpan({cls:"ai3d-editor-binding-text"});B.textContent=`\u{1F4C4} ${N}`,l.classList.remove("is-hidden"),p(),o.focus(),this.loadContentPreview(f,O.notePath,O.heading)},p=()=>{d.classList.add("is-hidden"),d.replaceChildren(),u=-1},_=O=>{if(d.replaceChildren(),u=-1,h=O,O.length===0){d.classList.add("is-hidden");return}for(let N=0;N<O.length;N++){let B=O[N],V=d.createDiv({cls:"ai3d-heading-dropdown-item"}),q=V.createSpan({cls:"ai3d-heading-dropdown-heading"});q.textContent=`${"#".repeat(B.level)} ${B.heading}`;let K=V.createSpan({cls:"ai3d-heading-dropdown-note"});K.textContent=gn(B.notePath),V.addEventListener("mousedown",J=>{J.preventDefault(),J.stopPropagation(),g(B)}),V.addEventListener("mouseenter",()=>m(N))}d.classList.remove("is-hidden")};o.addEventListener("input",()=>{if(!this.headingSearch)return;this._headingDebounce&&window.clearTimeout(this._headingDebounce);let O=o.value.trim();if(O.length<1){p();return}this._headingDebounce=window.setTimeout(()=>{let N=this.headingSearch(O);_(N)},150)}),o.addEventListener("keydown",O=>{if(d.classList.contains("is-hidden")){O.key==="Enter"?(O.preventDefault(),R.click()):O.key==="Escape"&&(O.preventDefault(),this.hideEditor());return}let N=d.querySelectorAll(".ai3d-heading-dropdown-item");O.key==="ArrowDown"?(O.preventDefault(),m(Math.min(u+1,N.length-1))):O.key==="ArrowUp"?(O.preventDefault(),m(Math.max(u-1,0))):O.key==="Enter"?(O.preventDefault(),u>=0&&u<N.length?h[u]&&g(h[u]):R.click()):O.key==="Escape"&&(O.preventDefault(),p())}),o.addEventListener("blur",()=>{window.setTimeout(p,150)});let v=s.createDiv({cls:"ai3d-annotation-editor-colors"}),E=(w=r==null?void 0:r.color)==null?void 0:w.trim(),S=E||wg[0],T=E&&!wg.includes(E)?[E,...wg]:wg;for(let O of T){let N=v.createEl("button",{cls:"ai3d-pin-color-swatch"});N.type="button",N.title=O,N.setAttribute("aria-label",Wi("annotation.selectColor",{color:O})),N.style.setProperty("--swatch-color",O),N.style.backgroundColor=O,O===S&&N.classList.add("is-selected"),N.addEventListener("click",B=>{B.stopPropagation(),S=O,v.querySelectorAll(".ai3d-pin-color-swatch").forEach(V=>V.classList.remove("is-selected")),N.classList.add("is-selected")})}let A=s.createDiv({cls:"ai3d-annotation-editor-actions"});if(r){let O=A.createEl("button",{cls:"ai3d-annotation-editor-btn ai3d-annotation-editor-delete"});O.textContent="Delete",O.addEventListener("click",N=>{N.stopPropagation(),this.removePin(r.id),this.hideEditor()})}let R=A.createEl("button",{cls:"ai3d-annotation-editor-btn ai3d-annotation-editor-confirm"});R.textContent=r?"Save":"OK",R.addEventListener("click",O=>{O.stopPropagation();let N=o.value.trim()||"Pin",B=this._selectedHeading;if(r){let V={label:N,color:S};B&&(V.notePath=B.notePath,V.headingRef=B.heading,V.headingLevel=B.level),this.updatePin(r.id,V)}else{let V=this.addPin(i,N,S);B&&this.updatePin(V.id,{notePath:B.notePath,headingRef:B.heading,headingLevel:B.level})}this.hideEditor()});let M=A.createEl("button",{cls:"ai3d-annotation-editor-btn ai3d-annotation-editor-cancel"});M.textContent="Cancel",M.addEventListener("click",O=>{O.stopPropagation(),this.hideEditor()});let I=this.overlay.getBoundingClientRect(),C=e-I.left,L=t-I.top;if(s.style.setProperty("--editor-left",`${Math.max(0,Math.min(C,I.width-220))}px`),s.style.setProperty("--editor-top",`${Math.max(0,Math.min(L-10,I.height-160))}px`),this.editorEl=s,r!=null&&r.notePath&&(r!=null&&r.headingRef)){let O=gn(r.notePath),N=l.createSpan({cls:"ai3d-editor-binding-text"});N.textContent=`\u{1F4C4} ${O}`,l.classList.remove("is-hidden"),this._selectedHeading={notePath:r.notePath,heading:r.headingRef,level:(G=r.headingLevel)!=null?G:2},this.loadContentPreview(f,r.notePath,r.headingRef)}window.requestAnimationFrame(()=>o.focus()),s.addEventListener("pointerdown",O=>O.stopPropagation()),s.addEventListener("mousedown",O=>O.stopPropagation())}hideEditor(){if(this._headingDebounce&&(window.clearTimeout(this._headingDebounce),this._headingDebounce=null),this._headingDropdown=null,this._selectedHeading=null,this.editorEl){let e=this.editorEl.querySelector(".ai3d-editor-content-preview");e&&this.clearRenderedPreview(e),this.editorEl.remove(),this.editorEl=null}}async loadContentPreview(e,t,i){if(!this.noteReader)return;this.clearRenderedPreview(e),e.classList.add("is-hidden");let r=await this.noteReader(t,i);if(!r){e.textContent=H("annotation.sectionEmpty"),e.className="ai3d-editor-content-preview ai3d-editor-content-preview--empty",e.classList.remove("is-hidden");return}await this.renderPreviewContent(e,r,t,"editor")}async showHoverPopover(e,t,i){if(!this.noteReader||!i.notePath||!i.headingRef)return;this.hideHoverPopover();let r=await this.noteReader(i.notePath,i.headingRef);if(!r||e!==this.hoverRequestId||!t.isConnected||!this.hostEl.isConnected)return;let s=createDiv({cls:"ai3d-pin-popover"}),a=s.createDiv({cls:"ai3d-pin-popover-title"});a.textContent=i.headingRef;let o=s.createDiv({cls:"ai3d-pin-popover-body"}),l=t.getBoundingClientRect();s.style.setProperty("--popover-left",`${l.left+l.width/2}px`),s.style.setProperty("--popover-top",`${l.bottom+4}px`),s.addEventListener("mouseenter",()=>this.cancelHoverClose()),s.addEventListener("mouseleave",()=>this.scheduleHoverClose()),activeDocument.body.appendChild(s),this.hoverPopover=s,await this.renderPreviewContent(o,r,i.notePath,"popover"),(e!==this.hoverRequestId||!t.isConnected||!this.hostEl.isConnected)&&(this.clearRenderedPreview(o),this.hoverPopover===s&&(this.hoverPopover=null),s.remove())}hideHoverPopover(){if(this.hoverTimeout&&(window.clearTimeout(this.hoverTimeout),this.hoverTimeout=null),this.hoverCloseTimeout&&(window.clearTimeout(this.hoverCloseTimeout),this.hoverCloseTimeout=null),this.hoverPopover){let e=this.hoverPopover.querySelector(".ai3d-pin-popover-body");e&&this.clearRenderedPreview(e),this.hoverPopover.remove(),this.hoverPopover=null}}cancelHoverClose(){this.hoverCloseTimeout&&(window.clearTimeout(this.hoverCloseTimeout),this.hoverCloseTimeout=null)}scheduleHoverClose(){this.hoverTimeout&&(window.clearTimeout(this.hoverTimeout),this.hoverTimeout=null,this.hoverRequestId++),this.cancelHoverClose(),this.hoverCloseTimeout=window.setTimeout(()=>{this.hoverCloseTimeout=null,this.hoverRequestId++,this.hideHoverPopover()},180)}clearRenderedPreview(e){let t=this.previewRenderChildren.get(e);t&&(this.previewRenderRoot.removeChild(t),this.previewRenderChildren.delete(e)),e.replaceChildren()}removePinElement(e){e.querySelectorAll(".ai3d-rendered-preview").forEach(t=>{this.clearRenderedPreview(t)}),e.remove()}async renderPreviewContent(e,t,i,r){let s=this.previewMode==="markdown"&&!!this.previewApp,a=r==="editor",o=r==="pin-snippet";if(!s){let c=a?300:o?180:1/0,f=t.length>c?t.slice(0,c)+"...":t;e.textContent=f,e.className=a?"ai3d-editor-content-preview":o?"ai3d-pin-snippet ai3d-rendered-preview":"ai3d-pin-popover-body ai3d-rendered-preview",a&&e.classList.remove("is-hidden");return}e.className=a?"ai3d-editor-content-preview ai3d-editor-content-preview--markdown markdown-rendered":o?"ai3d-pin-snippet ai3d-pin-snippet--markdown ai3d-rendered-preview markdown-rendered":"ai3d-pin-popover-body ai3d-pin-popover-body--markdown ai3d-rendered-preview markdown-rendered",a&&e.classList.remove("is-hidden");let l=this.previewRenderRoot.addChild(new ZE.Component);this.previewRenderChildren.set(e,l);try{await ZE.MarkdownRenderer.render(this.previewApp,t,e,i,l)}catch(c){this.previewRenderRoot.removeChild(l),this.previewRenderChildren.delete(e);let f=a?300:o?180:1/0;e.textContent=t.length>f?t.slice(0,f)+"...":t,e.className=a?"ai3d-editor-content-preview":o?"ai3d-pin-snippet ai3d-rendered-preview":"ai3d-pin-popover-body ai3d-rendered-preview",a&&e.classList.remove("is-hidden"),console.warn("[AI3D] Annotation markdown preview fallback:",c)}}pulsePin(e){let t=this.pinEls.get(e);t&&(this._pulseTimeout&&(window.clearTimeout(this._pulseTimeout),this._pulseTimeout=null),t.el.classList.remove("ai3d-pin-pulse"),t.el.offsetWidth,t.el.classList.add("ai3d-pin-pulse"),this._pulseTimeout=window.setTimeout(()=>{t.el.classList.remove("ai3d-pin-pulse"),this._pulseTimeout=null},1200))}destroy(){var e,t,i;this.hoverRequestId++,this.hideHoverPopover(),this._pulseTimeout&&(window.clearTimeout(this._pulseTimeout),this._pulseTimeout=null),this._headingDebounce&&(window.clearTimeout(this._headingDebounce),this._headingDebounce=null),this._headingDropdown=null,this._selectedHeading=null,(e=this.observer)==null||e.remove(),this.observer=null,(t=this.resizeObs)==null||t.disconnect(),this.resizeObs=null;for(let r of this.disposeCallbacks)r();this.disposeCallbacks=[],this.overlay.remove(),this.pinEls.clear(),(i=this.editorEl)==null||i.remove(),this.editorEl=null}createPinElement(e){let t=this.overlay.createDiv({cls:"ai3d-annotation-pin"});if(t.dataset.pinId=e.id,this.renderPinDisplay(t,e),this.mode==="edit"){let i=t.createEl("button",{cls:"ai3d-pin-delete"});i.textContent="\xD7",i.addEventListener("click",r=>{r.stopPropagation(),this.removePin(e.id)}),t.addEventListener("click",r=>{r.target.closest(".ai3d-pin-delete")||(r.stopPropagation(),this.editPin(e.id))})}t.addEventListener("pointerdown",i=>i.stopPropagation()),t.addEventListener("wheel",i=>{i.preventDefault(),i.stopPropagation(),this.provider.canvas.dispatchEvent(new WheelEvent("wheel",{bubbles:!0,cancelable:!0,clientX:i.clientX,clientY:i.clientY,ctrlKey:i.ctrlKey,deltaMode:i.deltaMode,deltaX:i.deltaX,deltaY:i.deltaY,deltaZ:i.deltaZ,metaKey:i.metaKey,shiftKey:i.shiftKey}))},{passive:!1}),e.notePath&&e.headingRef&&this.noteReader&&(t.addEventListener("mouseenter",()=>{this.cancelHoverClose(),this.hoverTimeout&&window.clearTimeout(this.hoverTimeout);let i=++this.hoverRequestId;this.hoverTimeout=window.setTimeout(()=>{this.hoverTimeout=null,i===this.hoverRequestId&&this.showHoverPopover(i,t,e)},300)}),t.addEventListener("mouseleave",()=>{this.scheduleHoverClose()})),this.pinEls.set(e.id,{el:t,worldPos:{x:e.position[0],y:e.position[1],z:e.position[2]}})}renderPinDisplay(e,t){let i=e.querySelector(".ai3d-pin-delete");if(e.querySelectorAll(".ai3d-rendered-preview").forEach(s=>{this.clearRenderedPreview(s)}),e.replaceChildren(),e.className=`ai3d-annotation-pin ai3d-annotation-pin--${this.displayMode}`,e.createDiv({cls:"ai3d-pin-dot"}).style.setProperty("--pin-color",t.color),e.title=t.label,e.setAttribute("aria-label",t.label),this.displayMode!=="dot"){let s=e.createDiv({cls:"ai3d-pin-content"}),a=s.createSpan({cls:"ai3d-pin-label"});if(a.textContent=t.label,this.displayMode==="snippet"&&t.notePath&&t.headingRef&&this.noteReader){let o=s.createDiv({cls:"ai3d-pin-snippet ai3d-rendered-preview"});this.loadPinSnippet(o,t.notePath,t.headingRef)}}i&&e.appendChild(i)}async loadPinSnippet(e,t,i){if(!this.noteReader)return;let r=await this.noteReader(t,i);!r||!e.isConnected||await this.renderPreviewContent(e,r,t,"pin-snippet")}startProjectionLoop(){this.observer=this.provider.observeRender(()=>this.updateProjections()),this.resizeObs=new ResizeObserver(()=>this.updateProjections()),this.resizeObs.observe(this.provider.canvas)}updateProjections(){if(this.pinEls.size===0)return;let{canvas:e}=this.provider;if(!this.hostEl.isConnected||!e.isConnected||e.clientWidth===0||e.clientHeight===0)return;let t=this.provider.getCameraStateKey();t===this.lastCamState?this.idleFrames++:(this.idleFrames=0,this.cameraIdle=!1),this.lastCamState=t,this.idleFrames>=Fg.IDLE_THRESHOLD&&!this.cameraIdle&&(this.cameraIdle=!0),this.frameCount++;let i=this.cameraIdle?1:this.pinEls.size>=12?3:2;if(!this.cameraIdle&&this.frameCount%i!==0)return;let r=Array.from(this.pinEls.values()),s=this.cameraIdle?this.frameCount%dxe===0:this.frameCount%fxe===0,a=this.cameraIdle||r.length<=t3,o=a?0:this.movingOcclusionCursor%r.length,l=o+t3,c=Fg._scratchProjection,f=[];for(let d=0;d<r.length;d++){let u=r[d];if(!this.provider.projectWorldPoint(u.worldPos,c)){this.hidePin(u.el);continue}if(c.depth>1||c.depth<0)this.hidePin(u.el);else{let h=Math.round(c.screenX),m=Math.round(c.screenY);u.el.style.setProperty("--pin-left",`${h}px`),u.el.style.setProperty("--pin-top",`${m}px`),this.updatePinPriority(u.el,c.depth),f.push({el:u.el,screenX:h,screenY:m,depth:c.depth});let g=a||d>=o&&d<l||l>r.length&&d<l%r.length;if(s&&g){let p=this.provider.isWorldPointOccluded(u.worldPos);this.showPin(u.el),u.el.classList.toggle("ai3d-pin-occluded",p)}else s||!this.cameraIdle&&u.el.classList.contains("ai3d-pin-hidden")&&this.showPin(u.el)}}if(s&&!a&&r.length>0&&(this.movingOcclusionCursor=(o+t3)%r.length),this.cameraIdle)this.applyLabelAvoidance(f);else for(let d of f)d.el.style.removeProperty("--pin-offset-y")}updatePinPriority(e,t){let i=Math.max(0,Math.min(1,1-t)),r=this.cameraIdle?0:160,s=e.classList.contains("ai3d-pin-occluded")?80:0;e.style.zIndex=String(100+r+Math.round(i*120)-s)}applyLabelAvoidance(e){if(e.length===0)return;if(e.length>uxe){for(let a of e)a.el.style.removeProperty("--pin-offset-y");return}let i=e.filter(a=>!a.el.classList.contains("ai3d-pin-hidden")&&!a.el.classList.contains("ai3d-pin-occluded")).sort((a,o)=>a.depth-o.depth).map(a=>({pin:a,rect:a.el.getBoundingClientRect()})),r=[],s=[];for(let{pin:a,rect:o}of i){let l=0,c=o;for(let f of r){if(!mxe(c,f,XJ))continue;let d=a.screenY>=f.top+f.height/2?1:-1;l=Math.max(-YJ,Math.min(YJ,l+d*(f.height+XJ)));let u=c.width,h=c.height;c=new DOMRect(c.x,c.y+l,u,h)}r.push(c),s.push({el:a.el,offset:l})}for(let{el:a,offset:o}of s)a.setCssProps({"--pin-offset-y":o===0?"0px":`${o}px`})}hidePin(e){e.classList.remove("ai3d-pin-occluded"),e.classList.add("ai3d-pin-hidden")}showPin(e){e.classList.remove("ai3d-pin-hidden")}};Fg.IDLE_THRESHOLD=15,Fg._scratchProjection={screenX:0,screenY:0,depth:0};i3=Fg});function Jl(n){return n.replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g,"$2").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/[*_~`]+/g,"").replace(/==([^=]+)==/g,"$1").replace(/\s+/g," ").trim()}var qE=y(()=>{"use strict"});var u0={};Be(u0,{createHeadingSearch:()=>pxe,createNoteReader:()=>gxe,normalizeHeadingText:()=>Jl,readHeadingSection:()=>QJ,searchVaultHeadings:()=>qJ});function qJ(n,e){let t=e.toLowerCase().trim();if(!t)return[];let i=[],r=n.vault.getMarkdownFiles();for(let s of r){let a=n.metadataCache.getFileCache(s);if(a!=null&&a.headings)for(let o of a.headings)o.heading.toLowerCase().includes(t)&&i.push({notePath:s.path,heading:o.heading,level:o.level})}return i.slice(0,15)}function pxe(n){return e=>qJ(n,e)}async function QJ(n,e,t){try{let i=n.vault.getAbstractFileByPath(e);if(!(i instanceof ZJ.TFile))return null;let s=(await n.vault.cachedRead(i)).split(`
`),a=-1,o=0,l=Jl(t);for(let f=0;f<s.length;f++){let d=s[f].match(/^(#{1,6})\s+(.+)/);if(d){let u=d[2].trim();if(u===t||Jl(u)===l){a=f+1,o=d[1].length;break}}}if(a<0)return null;let c=[];for(let f=a;f<s.length;f++){let d=s[f].match(/^(#{1,6})\s/);if(d&&d[1].length<=o)break;c.push(s[f])}return c.join(`
`).trim()||null}catch(i){return null}}function gxe(n){return(e,t)=>QJ(n,e,t)}var ZJ,h0=y(()=>{"use strict";ZJ=require("obsidian");qE();qE()});var a3={};Be(a3,{LOCAL_ANALYSIS_VERSION:()=>yh,buildLocalAnalysisResult:()=>s3,buildPartRecordsFromEvidence:()=>iee,inferModelAssetFormat:()=>pf,normalizeModelLoadStrategy:()=>Mh});function tee(){return typeof performance!="undefined"?performance.now():Date.now()}function jd(n,e,t=`${e}s`){return`${n.toLocaleString()} ${n===1?e:t}`}function Txe(n){return{stage:"reason",durationMs:Math.max(0,Math.round(tee()-n)),status:"success"}}function Axe(n,e){let t=n[0]-e[0],i=n[1]-e[1],r=n[2]-e[2];return Math.sqrt(t*t+i*i+r*r)}function n3(n){return Nh([n.x,n.y,n.z])}function $J(n,e){return n.filter(t=>t.trim().length>0).slice(0,e)}function JJ(n){return n.trim().replace(/[\\/:*?"<>|#[\]^]+/g,"-").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,96)}function xxe(n,e,t,i){var c,f;let r=JJ(gn(n)||"model")||"model",s=(f=(c=e.occurrenceId)!=null?c:e.componentId)!=null?f:e.partNumber,a=s?`${r}:component:${JJ(s)||t+1}`:`${r}:part:${t+1}`,o=a,l=2;for(;i.has(o);)o=`${a}:${l}`,l++;return i.add(o),o}function QE(n){return(n!=null?n:"").toLowerCase().replace(/[_\-./\\]+/g," ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}function m0(n){return new Set(QE(n).split(" ").filter(e=>e.length>=2))}function eee(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let i of n)e.has(i)&&(t+=1);return t/Math.max(n.size,e.size)}function Rxe(n,e){if(!n||!e||n.length<3||e.length<3)return 0;let t=[...n].slice(0,3).map(s=>Math.max(1e-4,Math.abs(s))).sort((s,a)=>s-a),i=[...e].slice(0,3).map(s=>Math.max(1e-4,Math.abs(s))).sort((s,a)=>s-a),r=0;for(let s=0;s<3;s++)r+=Math.min(t[s],i[s])/Math.max(t[s],i[s]);return r/3}function bxe(n,e){let t=QE(n),i=QE(e);return!!t&&!!i&&t===i}function r3(n,e){let t=QE(n),i=QE(e);return!!t&&!!i&&t===i}function Mxe(n){return n.map(e=>({part:e,nameTokens:m0(e.name),meshTokens:m0(e.meshRefs.join(" "))}))}function yxe(n,e){let t=m0(n.name),i=m0(n.meshRefs.join(" "));return e.filter(s=>s.part.assetId!==n.assetId||s.part.partId!==n.partId).flatMap(s=>{let a=s.part,o=[],l=eee(t,s.nameTokens),c=eee(i,s.meshTokens),f=Rxe(n.bbox,a.bbox),d=!!n.category&&!!a.category&&n.category===a.category,u=bxe(n.materialName,a.materialName),h=r3(n.componentId,a.componentId),m=r3(n.partNumber,a.partNumber),g=r3(n.occurrenceId,a.occurrenceId),p=l*.38+c*.22+f*.22;return h&&(p+=.5),m&&(p+=.4),g&&(p+=.25),d&&(p+=.1),u&&(p+=.08),h&&o.push(`same component id: ${n.componentId}`),m&&o.push(`same part number: ${n.partNumber}`),g&&o.push("same occurrence id"),l>=.5&&o.push("similar part name"),c>=.5&&o.push("similar mesh names"),f>=.72&&o.push("similar bounding size"),d&&o.push(`same category: ${n.category}`),u&&n.materialName&&o.push(`same material: ${n.materialName}`),p=Math.min(1,p),p<vxe||o.length===0?[]:[{sourceAssetId:a.assetId,sourcePartId:a.partId,sourcePartName:a.name,sourceNotePath:a.notePath,sourceCategory:a.category,sourceModelPath:a.assetId,matchScore:Number(p.toFixed(3)),confidence:Math.max(.35,Math.min(.9,Number(p.toFixed(3)))),reasons:o}]}).sort((s,a)=>a.matchScore-s.matchScore).slice(0,_xe)}function Ixe(n,e){if(e.length===0)return n.map(i=>({...i}));let t=Mxe(e);return n.map(i=>{let r=yxe(i,t);return r.length>0?{...i,registeredMatches:r}:{...i}})}function Cxe(n){var t;let e=n.name.toLowerCase();return n.source==="component"?"component":n.source==="group"?"group":n.source==="detail-cluster"?"detail-cluster":e.includes("wheel")||e.includes("gear")||e.includes("axle")?"mechanical":e.includes("shell")||e.includes("case")||e.includes("cover")||e.includes("housing")?"enclosure":e.includes("button")||e.includes("key")||e.includes("switch")?"control":e.includes("glass")||e.includes("screen")||e.includes("lens")?"surface":(t=n.materialName)!=null&&t.toLowerCase().includes("metal")?"material-driven":"unclassified"}function Pxe(n){var t,i,r,s,a,o,l,c,f,d,u,h;let e=[];if(n.source==="group"&&e.push(`Registered from model group with ${jd((r=(i=n.childCount)!=null?i:(t=n.meshNames)==null?void 0:t.length)!=null?r:0,"child mesh","child meshes")}.`),n.source==="component"&&e.push(`Registered from model component metadata with ${jd((o=(a=n.childCount)!=null?a:(s=n.meshNames)==null?void 0:s.length)!=null?o:1,"child mesh","child meshes")}.`),n.source==="detail-cluster"&&e.push(`Merged from ${jd((f=(c=n.childCount)!=null?c:(l=n.meshNames)==null?void 0:l.length)!=null?f:0,"generic tiny mesh","generic tiny meshes")} to avoid over-splitting renderer fragments.`),n.componentId&&e.push(`Component ID: ${n.componentId}.`),n.occurrenceId&&e.push(`Occurrence ID: ${n.occurrenceId}.`),n.partNumber&&e.push(`Part number: ${n.partNumber}.`),n.componentPath&&e.push(`Component path: ${n.componentPath}.`),n.sourceFormat||n.effectiveFormat||n.loadStrategy){let m=(u=(d=n.sourceFormat)!=null?d:n.effectiveFormat)!=null?u:"glb",g=(h=n.effectiveFormat)!=null?h:m,p=Mh(n.loadStrategy,m,g);e.push(`Format lineage: ${m.toUpperCase()}${g!==m?` -> ${g.toUpperCase()}`:""} (${p}).`)}return e.push(`${jd(n.triangleCount,"triangle")} and ${jd(n.vertexCount,"vertex")}.`,`Bounding size ${n.boundingSize.x.toFixed(3)} x ${n.boundingSize.y.toFixed(3)} x ${n.boundingSize.z.toFixed(3)}.`),n.materialName&&e.push(`Uses material "${n.materialName}".`),e}function Lxe(n,e,t){var o,l,c,f,d;let i=pf(n),r=(l=(o=e.sourceFormat)!=null?o:t==null?void 0:t.sourceFormat)!=null?l:i,s=(f=(c=e.effectiveFormat)!=null?c:t==null?void 0:t.effectiveFormat)!=null?f:r,a=Mh((d=e.loadStrategy)!=null?d:t==null?void 0:t.loadStrategy,r,s);return{sourceFormat:r,effectiveFormat:s,loadStrategy:a}}function Dxe(n){return n.source==="component"?.82:n.source==="group"?.72:n.source==="detail-cluster"?.48:n.name?.55:.35}function iee(n,e,t){let i=new Set;return e.map((r,s)=>{var l;let a=Lxe(n,r,t),o={...r,sourceFormat:a.sourceFormat,effectiveFormat:a.effectiveFormat,loadStrategy:a.loadStrategy};return{partId:xxe(n,r,s,i),assetId:n,name:r.name||`Part ${s+1}`,source:r.source,componentId:r.componentId,occurrenceId:r.occurrenceId,partNumber:r.partNumber,componentPath:r.componentPath,category:Cxe(r),meshRefs:$J((l=r.meshNames)!=null&&l.length?r.meshNames:[r.name||`mesh-${s+1}`],Exe),childCount:r.childCount,materialRefs:$J(r.materialName?[r.materialName]:[],Sxe),bbox:n3(r.boundingSize),center:n3(r.center),triangleCount:r.triangleCount,vertexCount:r.vertexCount,materialName:r.materialName,sourceFormat:a.sourceFormat,effectiveFormat:a.effectiveFormat,loadStrategy:a.loadStrategy,confidence:Dxe(r),observations:Pxe(o),inferredFunctions:[],knowledgeTags:[],reviewed:!1}})}function Oxe(n,e,t,i,r){var o;let s=[],a=t==null?void 0:t.summary;a&&s.push({id:`${n}:geometry`,title:"Geometry overview",domain:"geometry",summary:`${jd(a.meshCount,"mesh")}, ${jd(a.triangleCount,"triangle")}, ${jd(a.materialCount,"material slot")}.`,relatedPartIds:i.slice(0,12).map(l=>l.partId),relatedAssetIds:[n],confidence:.72,source:"rule"});for(let l of(o=e==null?void 0:e.annotations)!=null?o:[]){let c=r.find(f=>f.annotationId===l.id);s.push({id:`${n}:annotation:${l.id}`,title:l.label||"Annotation focus",domain:"assembly",summary:[l.headingRef?`Pinned focus area linked to heading "${l.headingRef}".`:"Pinned focus area marked by the user for follow-up analysis.",c!=null&&c.nearestPartName?`Nearest part candidate: ${c.nearestPartName}.`:""].filter(Boolean).join(" "),relatedPartIds:c!=null&&c.nearestPartId?[c.nearestPartId]:[],relatedAssetIds:[n],confidence:.8,source:"user"})}return s}function Nxe(n,e){var i;return((i=n==null?void 0:n.annotations)!=null?i:[]).map(r=>{let s=r.position,a=null,o=Number.POSITIVE_INFINITY;for(let c of e){if(!c.center)continue;let f=Axe(s,c.center);f<o&&(o=f,a=c)}let l=a&&Number.isFinite(o)?Math.max(.2,Math.min(.85,1/(1+o))):.25;return{annotationId:r.id,label:r.label||"Untitled pin",position:s,notePath:r.notePath,headingRef:r.headingRef,nearestPartId:a==null?void 0:a.partId,nearestPartName:a==null?void 0:a.name,distance:Number.isFinite(o)?o:void 0,confidence:l}})}function wxe(n){var s,a,o,l,c,f,d,u,h,m;let e=gn(n.modelPath)||n.modelPath,t=(a=(s=n.formatLineage)==null?void 0:s.sourceFormat)!=null?a:pf(n.modelPath),i=(l=(o=n.formatLineage)==null?void 0:o.effectiveFormat)!=null?l:t,r=Mh((c=n.formatLineage)==null?void 0:c.loadStrategy,t,i);return{task:"Draft an Obsidian knowledge note grounded only in the provided model evidence, annotations, and preview images. Do not invent part functions unless evidence or user notes support them.",model:{path:n.modelPath,title:e,format:t,effectiveFormat:i,loadStrategy:r,summary:(f=n.preview)!=null?f:void 0,tags:(u=(d=n.profile)==null?void 0:d.tags)!=null?u:[],notes:(m=(h=n.profile)==null?void 0:h.notes)!=null?m:""},evidence:{rawModelIncluded:!1,previewImages:[...n.previewImages],warnings:[...n.warnings],generatedAt:new Date().toISOString()},partCandidates:n.parts.slice(0,64).map(g=>{var p;return{partId:g.partId,name:g.name,notePath:g.notePath,source:g.source,componentId:g.componentId,occurrenceId:g.occurrenceId,partNumber:g.partNumber,componentPath:g.componentPath,category:g.category,sourceFormat:g.sourceFormat,effectiveFormat:g.effectiveFormat,loadStrategy:g.loadStrategy,meshRefs:[...g.meshRefs],childCount:g.childCount,triangleCount:g.triangleCount,materialName:g.materialName,registeredMatches:(p=g.registeredMatches)==null?void 0:p.map(_=>({..._,reasons:[..._.reasons]})),observations:g.observations}}),annotationLinks:[...n.annotationLinks],knowledgeNodes:[...n.knowledgeNodes]}}function Fxe(n,e){var t,i;return Array.from(new Set([...(t=n==null?void 0:n.resourceWarnings)!=null?t:[],...(i=e==null?void 0:e.resourceWarnings)!=null?i:[]]))}function s3(n){var m,g,p,_,v,E,S,T,A,R,M,I,C;let e=(m=n.startedAt)!=null?m:tee(),t=(p=(g=n.evidence)==null?void 0:g.summary)!=null?p:n.preview,i=pf(n.modelPath),r=(_=n.evidence)==null?void 0:_.formatLineage,s=(v=r==null?void 0:r.effectiveFormat)!=null?v:i,a=Mh(r==null?void 0:r.loadStrategy,(E=r==null?void 0:r.sourceFormat)!=null?E:i,s),o=Ixe(iee(n.modelPath,(T=(S=n.evidence)==null?void 0:S.parts)!=null?T:[],r),(A=n.registeredParts)!=null?A:[]),l=new Date().toISOString(),c=Fxe(n.preview,n.evidence),f=Nxe(n.profile,o),d=Oxe(n.modelPath,n.profile,n.evidence,o,f),u=(R=n.previewImages)!=null?R:[],h=wxe({modelPath:n.modelPath,profile:n.profile,preview:t,formatLineage:r,parts:o,knowledgeNodes:d,annotationLinks:f,previewImages:u,warnings:c});return{asset:{assetId:n.modelPath,title:gn(n.modelPath)||n.modelPath,sourcePath:n.modelPath,format:i,effectiveFormat:s,loadStrategy:a,importedAt:l,updatedAt:l,status:t?"ready":"processing",vertexCount:t==null?void 0:t.vertexCount,triangleCount:t==null?void 0:t.triangleCount,materialCount:t==null?void 0:t.materialCount,boundingBox:t?n3(t.boundingSize):void 0,analysisVersion:yh},parts:o,knowledgeNodes:d,previewImages:u,annotationLinks:f,draftingInput:h,evidence:(M=n.evidence)!=null?M:void 0,warnings:c,pipeline:[{stage:"stats",durationMs:0,status:t?"success":"skipped"},{stage:"split",durationMs:0,status:(C=(I=n.evidence)==null?void 0:I.parts)!=null&&C.length?"success":"skipped"},{stage:"map",durationMs:0,status:f.length>0?"success":"skipped"},Txe(e)]}}var yh,_xe,vxe,Exe,Sxe,p0=y(()=>{"use strict";As();dS();jy();jy();yh="local-evidence-v1",_xe=3,vxe=.58,Exe=16,Sxe=16});function Ih(n){let e=n.trim();return e.length>ree?Hi(e.slice(0,ree))+"\u2026":Hi(e)}function nee(n){if(!n||typeof n!="object")return null;let e=n,t=typeof e.summary=="string"?e.summary.trim():"",i=Ih(t);if(!i)return null;let r=Array.isArray(e.sections)?e.sections.flatMap(o=>{if(!o||typeof o!="object")return[];let l=o,c=typeof l.heading=="string"?l.heading.trim():"",f=typeof l.body=="string"?l.body.trim():"",d=Ih(c),u=Ih(f);return d&&u?[{heading:d,body:u}]:[]}):void 0,s=Array.isArray(e.suggestedTags)?e.suggestedTags.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>Ih(o)):void 0,a=Array.isArray(e.warnings)?e.warnings.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>Ih(o)):void 0;return{title:typeof e.title=="string"?Ih(e.title):void 0,summary:i,sections:r,suggestedTags:s,warnings:a,model:typeof e.model=="string"?Ih(e.model):void 0}}var ree,see=y(()=>{"use strict";XA();ree=8e3});function Uxe(n){let e=n.trim().replace(/\/+$/,"");if(!e)return"";let t=/^[a-z][a-z\d+\-.]*:\/\//i.test(e)?e:`http://${e}`;try{let i=new URL(t);return i.protocol!=="http:"&&i.protocol!=="https:"||i.search||i.hash?null:i.toString().replace(/\/+$/,"")}catch(i){return null}}function Vxe(n){return{...n,evidence:{...n.evidence,previewImages:[]}}}function Gxe(n){return{...n,model:{...n.model,summary:void 0},partCandidates:[],annotationLinks:n.annotationLinks.map(e=>({...e,notePath:void 0,position:[0,0,0],nearestPartId:void 0,nearestPartName:void 0,distance:void 0,confidence:Math.min(e.confidence,.25)})),knowledgeNodes:n.knowledgeNodes.map(e=>({...e,summary:"Geometry details were withheld by privacy settings.",relatedPartIds:[]}))}}function kxe(n,e){let t=e;return n.sendPreviewImagesToRemote||(t=Vxe(t)),n.sendGeometrySummaryToRemote||(t=Gxe(t)),{...t,evidence:{...t.evidence,rawModelIncluded:!1}}}function oee(n,e,t){if(n.analysisMode==="local")return{enabled:!1,reason:"analysisMode=local"};let i=Uxe(n.serviceBaseUrl);return i===""?{enabled:!1,reason:"serviceBaseUrl is empty"}:i===null?{enabled:!1,reason:"serviceBaseUrl must be a valid http(s) URL"}:n.sendRawModelToRemote?{enabled:!1,reason:"raw model upload is not supported by this draft client"}:e?{enabled:!0,endpoint:`${i}/draft-note`,request:{analysisVersion:t,draftingInput:kxe(n,e)}}:{enabled:!1,reason:"drafting input is unavailable"}}function zxe(n){return Number.isFinite(n)&&Number(n)>0?Math.floor(Number(n)):Bxe}async function Wxe(n,e,t){let i=null,r=new Promise((s,a)=>{i=window.setTimeout(()=>{a(new o3(e,t))},e)});try{return await Promise.race([n,r])}finally{i!==null&&window.clearTimeout(i)}}async function lee(n,e={}){if(!n.enabled||!n.endpoint||!n.request)return null;let t=zxe(e.timeoutMs),i=await Wxe((0,aee.requestUrl)({url:n.endpoint,method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n.request)}),t,n.endpoint);if(i.status<200||i.status>=300)throw new Error(`Remote draft request failed: HTTP ${i.status}`);return nee(i.json)}var aee,Bxe,o3,cee=y(()=>{"use strict";aee=require("obsidian");see();Bxe=15e3,o3=class extends Error{constructor(e,t){super(`Remote draft request timed out after ${e}ms: ${t}`),this.name="RemoteDraftTimeoutError"}}});var g0={};Be(g0,{buildKnowledgeIndexContent:()=>Cee,buildKnowledgeIndexManagedSection:()=>E3,buildKnowledgeNoteContent:()=>Ree,collectRegisteredPartsFromProfiles:()=>yee,generateKnowledgeNote:()=>ARe,replaceManagedSection:()=>Iee,stripTransientRegisteredPartData:()=>v3});function l3(n){var e,t,i;return{modelPath:n.modelPath,reportNotePath:n.reportNotePath,analysisSidecarPath:n.analysisSidecarPath,knowledgeIndexPath:n.knowledgeIndexPath,partNoteCount:(e=n.partNoteCount)!=null?e:0,previewImageCount:(t=n.previewImageCount)!=null?t:0,generatedAt:new Date().toISOString(),status:n.status,warningCount:(i=n.warningCount)!=null?i:0}}function vee(n){var t;let e=(t=n.split(".").pop())==null?void 0:t.trim().toLowerCase();return e&&e.length>0?e:"unknown"}function u3(n){return n.filter(e=>e.length>0).join(", ")}function c3(n){return Array.from(new Set(n.map(e=>e.trim()).filter(Boolean)))}function g3(n){return n.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"").trim()}function h3(n,e){return n.replace(/[\\/:*?"<>|#[\]^]/g," ").replace(/\s+/g," ").trim().slice(0,80)||e}function m3(n){var e;return(e=n==null?void 0:n.map(t=>t.toFixed(2)).join(", "))!=null?e:"-"}function Yxe(n,e=12){if(n.length===0)return"-";let t=n.slice(0,e).join(", "),i=n.length-e;return i>0?`${t}, +${i.toLocaleString()} more`:t}function Eee(n){var e,t;return n.source==="component"?n.childCount&&n.childCount>1?`component (${n.childCount})`:"component":n.source==="group"?`group (${(e=n.childCount)!=null?e:n.meshRefs.length})`:n.source==="detail-cluster"?`detail cluster (${(t=n.childCount)!=null?t:n.meshRefs.length})`:"mesh"}function p3(n){var a,o,l;if(!n.sourceFormat&&!n.effectiveFormat&&!n.loadStrategy)return null;let e=(a=n.sourceFormat)!=null?a:n.effectiveFormat,t=(o=n.effectiveFormat)!=null?o:e,i=(l=n.loadStrategy)!=null?l:e&&t&&e!==t?"convert":"direct",r=e?e.toUpperCase():"unknown",s=t&&t!==e?` -> ${t.toUpperCase()}`:"";return`${r}${s} (${i})`}function Kxe(n){let e=n.sourceNotePath?`[[${n.sourceNotePath}|${n.sourcePartName}]]`:n.sourcePartName,t=n.reasons.length>0?` - ${n.reasons.join(", ")}`:"";return`${e} (${Math.round(n.confidence*100)}%${t})`}function See(n){var t;let e=[];if(n.headingRef&&e.push(`heading: ${Hi(n.headingRef)}`),n.notePath){let i=(t=Qs(n.notePath))!=null?t:n.notePath;e.push(`note: [[${n.notePath}|${i}]]`)}return e}function jxe(n){return[{axis:"x",value:Math.max(0,n.boundingSize.x)},{axis:"y",value:Math.max(0,n.boundingSize.y)},{axis:"z",value:Math.max(0,n.boundingSize.z)}].sort((e,t)=>t.value-e.value)}function Tee(n){let[e,t,i]=jxe(n);if(!e||e.value<=0)return"Bounding information is incomplete, so scale and orientation still need manual review.";let r=i.value>0?e.value/i.value:Number.POSITIVE_INFINITY,s=e.value>0?t.value/e.value:0;return(e.value>0?i.value/e.value:0)<=.18&&s>=.45?`The bounding box is strongly planar, with a thin ${i.axis.toUpperCase()} dimension compared with ${e.axis.toUpperCase()}.`:r>=3&&s<=.55?`The model is strongly elongated along ${e.axis.toUpperCase()}, which suggests a directional or axial structure.`:"The overall bounding volume is fairly balanced, so semantic grouping is more likely to come from mesh and material boundaries than from one dominant axis."}function Aee(n){if(n.splatCount!==void 0)return`This is a splat-based asset with ${n.splatCount.toLocaleString()} splats; review should focus on capture coverage, density, and viewpoint clarity instead of triangle topology.`;let e=0;return n.triangleCount>=5e5?e+=3:n.triangleCount>=1e5?e+=2:n.triangleCount>=2e4&&(e+=1),n.meshCount>=100?e+=2:n.meshCount>=25&&(e+=1),n.materialCount>=8&&(e+=1),e>=5?"The mesh and material counts point to a high-complexity asset; expect semantic cleanup, regrouping, or naming review before turning it into stable knowledge notes.":e>=3?"The asset sits in a medium-complexity range: it already contains useful structure, but some meshes or materials may still reflect export convenience rather than real-world parts.":"The asset is structurally compact, so a lightweight local pass can usually produce usable first-draft notes without a heavier analysis pipeline."}function Zxe(n){var t;let e=(t=n==null?void 0:n.tags)!=null?t:[];return e.length===0?"No knowledge tags are stored yet, so the note should establish the first stable vocabulary for this model.":`Current tags already suggest a working taxonomy: ${u3(e)}.`}function fee(n){var t;let e=(t=n==null?void 0:n.annotations)!=null?t:[];return e.length===0?"No annotation pins are stored yet, so the next useful pass is to mark semantically important regions before splitting the model into part notes.":e.length===1?"There is 1 saved annotation pin, which already gives this report a concrete user-selected focus area.":`There are ${e.length} saved annotation pins, which provide a useful first-pass map of user-relevant regions.`}function qxe(n,e){var r;if(!n)return["Preview statistics were not available when this note was generated, so the next step is to reload the model and regenerate the report.",fee(e)];let t=[`${n.meshCount.toLocaleString()} mesh(es), ${((r=n.splatCount)!=null?r:n.triangleCount).toLocaleString()} ${n.splatCount!==void 0?"splats":"triangles"}, and ${n.materialCount.toLocaleString()} material slot(s) are currently visible in the preview pipeline.`,Aee(n),Tee(n),fee(e)],i=Zxe(e);return i&&t.push(i),t}function Qxe(n){var i;let e=(i=n==null?void 0:n.annotations)!=null?i:[];if(e.length===0)return["## Focus Areas","","- No focus areas have been pinned yet.",""];let t=["## Focus Areas",""];for(let r of e){let s=See(r),a=s.length>0?` (${s.join("; ")})`:"";t.push(`- **${Hi(r.label||"Untitled pin")}**${a}`)}return t.push(""),t}function $xe(n){var i,r;let e=(i=n==null?void 0:n.annotationLinks)!=null?i:[];if(e.length===0)return["## Annotation Links","","- No annotation-to-part links were produced in this pass.",""];let t=["## Annotation Links","","| Annotation | Nearest Part | Linked Note | Distance | Confidence |","|------------|--------------|-------------|----------|------------|"];for(let s of e){let a=s.notePath?`[[${s.notePath}]]`:"-";t.push(`| ${ka(s.label)} | ${ka((r=s.nearestPartName)!=null?r:"-")} | ${ka(a)} | ${s.distance===void 0?"-":s.distance.toFixed(3)} | ${Math.round(s.confidence*100)}% |`)}return t.push(""),t}function Jxe(n){var i,r,s,a;let e=((i=n==null?void 0:n.parts)!=null?i:[]).filter(o=>o.notePath);if(e.length===0)return["## Suggested Part Notes","","- No part note drafts were created in this pass.",""];let t=["## Suggested Part Notes",""];for(let o of e.slice(0,gee)){let l=Hi((s=Qs((r=o.notePath)!=null?r:""))!=null?s:o.name),c=[(a=o.category)!=null?a:"unclassified",sl(o.triangleCount,"triangle"),o.materialName?`material ${Hi(o.materialName)}`:""].filter(Boolean).join(", ");t.push(`- [[${o.notePath}|${l}]] - ${Hi(o.name)} (${c})`)}return t.push(""),t}function sl(n,e){return`${(n!=null?n:0).toLocaleString()} ${e}${n===1?"":"s"}`}function eRe(n){return n.length===0?"No per-part evidence was captured yet, so the first useful editing pass is to reload the model and regenerate this note from the workbench.":n.slice(0,6).map((e,t)=>{var r;let i=e.materialName?`, material ${Hi(e.materialName)}`:"";return`${t+1}. ${Hi(e.name)} (${(r=e.category)!=null?r:"unclassified"}, ${sl(e.triangleCount,"triangle")}${i})`}).join(`
`)}function tRe(n){let e=n.filter(t=>{var i;return(i=t.registeredMatches)==null?void 0:i.length});return e.length===0?"No previously registered parts were matched across other analyzed models in this pass.":e.slice(0,6).map(t=>{var r;let i=(r=t.registeredMatches)==null?void 0:r[0];return i?`- ${Hi(t.name)}: possible reuse of ${Hi(i.sourcePartName)} from ${Hi(i.sourceAssetId)} (${Math.round(i.confidence*100)}% confidence).`:""}).filter(Boolean).join(`
`)}function xee(n){var p,_,v,E,S,T,A,R,M;let e=vee(n.sourcePath).toUpperCase(),t=n.preview,i=[...(_=(p=n.analysis)==null?void 0:p.parts)!=null?_:[]].sort((I,C)=>{var L,w;return((L=C.triangleCount)!=null?L:0)-((w=I.triangleCount)!=null?w:0)}),r=(E=(v=n.profile)==null?void 0:v.annotations)!=null?E:[],s=(T=(S=n.analysis)==null?void 0:S.annotationLinks)!=null?T:[],a=c3(i.map(I=>{var C;return(C=I.category)!=null?C:"unclassified"})).slice(0,6),o=c3(i.flatMap(I=>I.materialName?[Hi(I.materialName)]:[])).slice(0,6),l=eRe(i),c=tRe(i),f=t?Tee(t):"Geometry statistics are not available yet, so this draft should stay provisional.",d=t?Aee(t):"Reload the preview to capture mesh, triangle, vertex, and material evidence.",u=(A=n.profile)==null?void 0:A.notes.trim(),h=t?`${n.baseName} is a ${e} asset with ${sl(t.meshCount,"mesh")}, ${sl(t.triangleCount,"triangle")}, ${sl(t.vertexCount,"vertex")}, and ${sl(t.materialCount,"material slot")}.`:`${n.baseName} is a ${e} asset that still needs a refreshed preview pass before its geometry can be summarized confidently.`,m=r.length>0?r.map(I=>{let C=s.find(G=>G.annotationId===I.id),L=C!=null&&C.nearestPartName?` Nearest captured part: ${Hi(C.nearestPartName)}.`:"",w=I.headingRef?` Linked heading: ${Hi(I.headingRef)}.`:"";return`- ${Hi(I.label||"Untitled pin")}.${L}${w}`}).join(`
`):"- No pins are saved yet. Add pins for the regions that should become standalone notes, questions, or review checkpoints.",g=[i.length>0?"Rename the strongest part candidates so their mesh names match real semantic parts.":"Regenerate after the model preview has captured per-part evidence.",r.length>0?"Turn each saved pin into a short linked note or heading-level review item.":"Place at least one pin on the most important region before treating this as a finished note.","Review scale, orientation, materials, and whether mesh boundaries represent real assembly boundaries."];return{title:`${n.baseName} local knowledge draft`,summary:[h,f,u?`User notes add this context: ${u}`:"No user notes are stored yet, so the draft stays grounded in renderer evidence and saved pins."].join(" "),sections:[{heading:"Evidence-backed description",body:[d,a.length>0?`Detected part categories: ${u3(a)}.`:"No part categories were inferred yet.",o.length>0?`Visible materials include ${u3(o)}.`:"No material names were captured from the renderer evidence."].join(" ")},{heading:"Candidate structure",body:l},{heading:"Registered part reuse",body:c},{heading:"Focus areas",body:m},{heading:"Suggested note shape",body:[`Start with a short purpose paragraph for ${n.baseName}.`,"Then split the note into geometry evidence, meaningful part candidates, saved focus areas, and unresolved review questions.","Only promote a mesh into a standalone part note after a human confirms its function or assembly role."].join(" ")}],suggestedTags:c3([...(M=(R=n.profile)==null?void 0:R.tags)!=null?M:[],`format/${e.toLowerCase()}`,...a.map(I=>`part/${I}`)]).slice(0,12),nextActions:g,generatedAt:new Date().toISOString()}}function iRe(n){var i,r;let e=(r=(i=n.analysis)==null?void 0:i.localDraft)!=null?r:xee(n),t=["## Local Draft Metadata","",`- Generated at: ${e.generatedAt}`,`- Sections: ${e.sections.length.toLocaleString()}`];return e.suggestedTags.length>0&&t.push("Suggested tags:","",...e.suggestedTags.map(s=>`- ${Hi(s)}`),""),e.nextActions.length>0&&t.push("Next actions:","",...e.nextActions.map(s=>`- ${Hi(s)}`),""),t}function fn(n){return JSON.stringify(n)}function rRe(n){return n!=null&&n.draftingInput?["## AI Drafting Input","","- Grounded drafting input is available in the sidecar JSON under `draftingInput`.",`- Part candidates included: ${n.draftingInput.partCandidates.length.toLocaleString()}`,`- Annotation links included: ${n.draftingInput.annotationLinks.length.toLocaleString()}`,"- Raw model included: false",""]:["## AI Drafting Input","","- No drafting input was prepared in this pass.",""]}function nRe(n){var i,r,s,a;let e=n==null?void 0:n.remoteDraft;if(!e)return["## Remote Draft","","- No remote draft was requested or returned for this pass.",""];let t=["## Remote Draft","",e.title?`### ${e.title}`:"### Draft Summary","",e.summary,""];for(let o of(i=e.sections)!=null?i:[])t.push(`### ${o.heading}`,"",o.body,"");(r=e.suggestedTags)!=null&&r.length&&t.push("Suggested tags:","",...e.suggestedTags.map(o=>`- ${o}`),"");for(let o of(s=e.warnings)!=null?s:[])t.push(`- Remote warning: ${o}`);return(a=e.warnings)!=null&&a.length&&t.push(""),t}function sRe(n){var i,r;let e=(i=n==null?void 0:n.remoteDraft)!=null?i:n==null?void 0:n.localDraft;if(!e)return["## Editable Draft","","- No draft body was produced in this pass.",""];let t=["## Editable Draft","",n!=null&&n.remoteDraft?"- Source: optional remote draft, grounded by the local evidence sidecar.":"- Source: local evidence draft, generated without a remote service.","",e.summary,""];for(let s of(r=e.sections)!=null?r:[])t.push(`### ${s.heading}`,"",s.body,"");return t}function aRe(n){var t;let e=(t=n==null?void 0:n.previewImages)!=null?t:[];return e.length===0?["## Evidence Snapshots","","- No preview snapshot was captured for this generation pass.",""]:["## Evidence Snapshots","",...e.map(i=>`![[${i}]]`),""]}function oRe(n){var i,r,s,a;let e=(i=n==null?void 0:n.parts)!=null?i:[];if(e.length===0)return["## Part Candidates","","- No per-mesh evidence was available. Reload the model in the workbench and regenerate the note to capture part candidates.",""];let t=["## Part Candidates","","| # | Part | Part Note | Source | Category | Triangles | Material | Center | Evidence |","|---|------|-----------|--------|----------|-----------|----------|--------|----------|"];for(let[o,l]of e.slice(0,32).entries()){let c=m3(l.center),f=l.observations.slice(0,2).join(" "),d=l.notePath?`[[${l.notePath}]]`:"-",u=p3(l),h=[Eee(l),u].filter(Boolean).join("; ");t.push(`| ${o+1} | ${ka(l.name)} | ${ka(d)} | ${ka(h)} | ${ka((r=l.category)!=null?r:"unclassified")} | ${((s=l.triangleCount)!=null?s:0).toLocaleString()} | ${ka((a=l.materialName)!=null?a:"-")} | ${c} | ${ka(f)} |`)}return e.length>32&&t.push(`| ... | ${e.length-32} more candidate parts omitted from this note | - | - | - | - | - | - | See sidecar JSON |`),t.push(""),t}function lRe(n){var i,r;let e=((i=n==null?void 0:n.parts)!=null?i:[]).filter(s=>{var a;return(a=s.registeredMatches)==null?void 0:a.length});if(e.length===0)return["## Registered Part Matches","","- No previously registered parts were matched across other analyzed models in this pass.",""];let t=["## Registered Part Matches","","| Current Part | Best Existing Part | Source Model | Confidence | Reasons |","|--------------|--------------------|--------------|------------|---------|"];for(let s of e.slice(0,32)){let a=(r=s.registeredMatches)==null?void 0:r[0];if(!a)continue;let o=a.sourceNotePath?`[[${a.sourceNotePath}|${a.sourcePartName}]]`:a.sourcePartName;t.push(`| ${ka(s.name)} | ${ka(o)} | ${ka(a.sourceAssetId)} | ${Math.round(a.confidence*100)}% | ${ka(a.reasons.join(", "))} |`)}return e.length>32&&t.push(`| ... | ${e.length-32} more matched parts omitted | - | - | See sidecar JSON |`),t.push(""),t}function cRe(n){var i;let e=(i=n==null?void 0:n.knowledgeNodes)!=null?i:[];if(e.length===0)return["## Knowledge Nodes","","- No knowledge nodes were produced in this pass.",""];let t=["## Knowledge Nodes",""];for(let r of e)t.push(`- **${Hi(r.title)}** (${r.domain}, ${Math.round(r.confidence*100)}%, ${r.source}): ${Hi(r.summary)}`);return t.push(""),t}function fRe(n,e){var i,r;let t=["## Evidence Health","",`- Analysis version: ${yh}`,e?`- Sidecar: [[${e}|Analysis JSON]]`:"- Sidecar: not written",n!=null&&n.knowledgeIndexPath?`- Knowledge index: [[${n.knowledgeIndexPath}|Model index]]`:"- Knowledge index: not written"];for(let s of(i=n==null?void 0:n.warnings)!=null?i:[])t.push(`- Warning: ${s}`);return((r=n==null?void 0:n.warnings)!=null?r:[]).length===0&&t.push("- Warnings: none"),t.push(""),t}function dRe(n,e){var r;let t=(r=e==null?void 0:e.annotations)!=null?r:[],i=["## Draft Knowledge Points",""];if(n?(i.push(`- Geometry overview: explain how ${n.meshCount.toLocaleString()} mesh(es) and ${n.materialCount.toLocaleString()} material slot(s) map to real semantic parts instead of export-only fragments.`),n.splatCount!==void 0?i.push(`- Capture quality: review whether the ${n.splatCount.toLocaleString()} splats preserve enough silhouette and depth detail for note-taking from multiple angles.`):i.push(`- Structural density: verify whether ${(n.triangleCount/Math.max(n.meshCount,1)).toLocaleString(void 0,{maximumFractionDigits:0})} average triangles per mesh reflects deliberate detail or accidental over-segmentation.`)):i.push("- Geometry overview: reload the model and capture preview statistics before turning this into a stable knowledge note."),t.length>0)for(let s of t.slice(0,8)){let a=See(s),o=a.length>0?` (${a.join("; ")})`:"";i.push(`- **${Hi(s.label||"Untitled pin")}**${o}: describe what this region does, why it matters, and whether it deserves its own linked part note.`)}else i.push("- Focus mapping: add pins for the regions that should become standalone part notes or review checkpoints.");return i.push("- Review pass: confirm scale, orientation, and whether material boundaries reflect actual function, assembly, or simply renderer setup."),i.push(""),i}function Ree(n){var c,f,d,u;let e=n.profile,t=n.preview,i=n.analysis,r=vee(n.sourcePath),s=(c=e==null?void 0:e.tags)!=null?c:[],a=(f=e==null?void 0:e.annotations)!=null?f:[],o=(d=i==null?void 0:i.previewImages)!=null?d:[];return[["---",`source_model: ${fn(n.sourcePath)}`,`format: ${r}`,"status: ready","analysis_mode: local",`analysis_version: ${yh}`,`report_note_path: ${fn(n.notePath)}`,...n.analysisSidecarPath?[`analysis_sidecar_path: ${fn(n.analysisSidecarPath)}`]:[],...n.knowledgeIndexPath?[`knowledge_index_path: ${fn(n.knowledgeIndexPath)}`]:[],`annotation_count: ${a.length}`,`updated_at: ${new Date().toISOString()}`,...o.length>0?["preview_images:",...o.map(h=>` - ${fn(h)}`)]:[],...s.length>0?["knowledge_tags:",...s.map(h=>` - ${fn(h)}`)]:[],"---"].join(`
`),"",`# ${Hi(n.baseName)}`,"","## Summary","",...t?[...dV(t,{decimals:2}),""]:["(No preview data available)",""],...sRe(i),...iRe(n),...n.knowledgeIndexPath?["## Knowledge Index","",`- [[${n.knowledgeIndexPath}|Open model knowledge index]]`,""]:[],"## Local Observations","",...qxe(t,e).map(h=>`- ${h}`),"",...fRe(i,n.analysisSidecarPath),...aRe(i),...Qxe(e),...$xe(i),...Jxe(i),...oRe(i),...lRe(i),...cRe(i),...rRe(i),...nRe(i),...dRe(t,e),"## Review Notes","",(u=e==null?void 0:e.notes)!=null&&u.trim()?Hi(e.notes.trim()):"-",""].join(`
`)}function ka(n){return Hi(n).replace(/\|/g,"\\|").replace(/\r?\n/g," ")}function uRe(n){let[,e=""]=n.split(",",2),t=atob(e),i=new Uint8Array(t.length);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return i.buffer}async function _3(n,e){let t=g3(e);if(!t)return;let i="";for(let r of t.split("/"))i=i?`${i}/${r}`:r,n.vault.getAbstractFileByPath(i)||await n.vault.createFolder(i).catch(s=>{Hxe.warn("Failed to create vault folder",{path:i,error:String(s)})})}async function bee(n,e,t){let i=n.vault.getAbstractFileByPath(e);if(i instanceof ec.TFile)return i;try{return await n.vault.create(e,t)}catch(r){let s=n.vault.getAbstractFileByPath(e);return s instanceof ec.TFile?s:null}}async function dee(n,e,t){let i=n.vault.getAbstractFileByPath(e);if(i instanceof ec.TFile)return await n.vault.modify(i,t),i;try{return await n.vault.create(e,t)}catch(r){let s=n.vault.getAbstractFileByPath(e);if(s instanceof ec.TFile)return await n.vault.modify(s,t),s}return null}async function hRe(n,e,t,i){var s;let r=(s=e==null?void 0:e.captureSnapshot)==null?void 0:s.call(e);if(!(r!=null&&r.startsWith("data:image/png;base64,")))return{paths:[]};try{await _3(n,t);let a=`${t}/${i}_evidence_${Date.now()}.png`;return await n.vault.createBinary(a,uRe(r)),{paths:[a]}}catch(a){let o=a instanceof Error?a.message:String(a);return{paths:[],warning:`Evidence snapshot failed: ${o}`}}}function Mee(n){return!!n&&typeof n=="object"}function $E(n,e=Number.POSITIVE_INFINITY){let t=Array.isArray(n)?n.filter(i=>typeof i=="string"):[];return Number.isFinite(e)?t.slice(0,e):t}function uee(n){if(!Array.isArray(n)||n.length<3)return;let e=n.slice(0,3).map(t=>Number(t));return e.every(Number.isFinite)?Nh(e):void 0}function mRe(n){return n==="group"||n==="mesh"||n==="component"||n==="detail-cluster"?n:void 0}function hee(n){return n==="glb"||n==="gltf"||n==="stl"||n==="obj"||n==="splat"||n==="ply"||n==="fbx"||n==="step"||n==="stp"||n==="iges"||n==="igs"||n==="brep"||n==="sldprt"||n==="3mf"||n==="dae"?n:void 0}function pRe(n){return n==="direct"||n==="convert"?n:void 0}function gRe(n,e){if(!Mee(n))return null;let t=typeof n.partId=="string"?n.partId:"",i=typeof n.name=="string"?n.name:"";if(!t||!i)return null;let r=typeof n.assetId=="string"&&n.assetId?n.assetId:e;return{partId:t,assetId:r,parentPartId:typeof n.parentPartId=="string"?n.parentPartId:void 0,name:i,source:mRe(n.source),componentId:typeof n.componentId=="string"?n.componentId:void 0,occurrenceId:typeof n.occurrenceId=="string"?n.occurrenceId:void 0,partNumber:typeof n.partNumber=="string"?n.partNumber:void 0,componentPath:typeof n.componentPath=="string"?n.componentPath:void 0,category:typeof n.category=="string"?n.category:void 0,meshRefs:$E(n.meshRefs,16),childCount:Number.isFinite(n.childCount)?Number(n.childCount):void 0,materialRefs:$E(n.materialRefs,32),bbox:uee(n.bbox),center:uee(n.center),triangleCount:Number.isFinite(n.triangleCount)?Number(n.triangleCount):void 0,vertexCount:Number.isFinite(n.vertexCount)?Number(n.vertexCount):void 0,materialName:typeof n.materialName=="string"?n.materialName:null,sourceFormat:hee(n.sourceFormat),effectiveFormat:hee(n.effectiveFormat),loadStrategy:pRe(n.loadStrategy),confidence:Number.isFinite(n.confidence)?Number(n.confidence):.5,observations:$E(n.observations,16),inferredFunctions:$E(n.inferredFunctions),knowledgeTags:$E(n.knowledgeTags),notePath:typeof n.notePath=="string"?n.notePath:void 0,registeredMatches:void 0,reviewed:n.reviewed===!0}}function mee(n){return n.reviewed||n.notePath?0:n.source==="component"?1:n.source==="group"?2:n.source==="detail-cluster"?3:4}function pee(n){return[...n].sort((e,t)=>{var s,a,o,l;let i=mee(e)-mee(t);if(i!==0)return i;let r=((s=t.confidence)!=null?s:0)-((a=e.confidence)!=null?a:0);return r!==0?r:((o=t.childCount)!=null?o:0)-((l=e.childCount)!=null?l:0)})}function v3(n){return wh(n)}async function yee(n,e,t,i={}){var c,f,d;let r=[],s=new Set,a=(c=i.includeSidecars)!=null?c:!0,o=(f=i.perProfileLimit)!=null?f:Xxe,l=(u,h)=>{let m=gRe(u,h);if(!m)return;let g=`${m.assetId}:${m.partId}`;s.has(g)||(s.add(g),r.push(v3(m)))};for(let[u,h]of Object.entries(e)){if(u===t)continue;if(a&&h.analysisSidecarPath){let g=n.vault.getAbstractFileByPath(h.analysisSidecarPath);if(g instanceof ec.TFile)try{let p=await n.vault.read(g),_=JSON.parse(p);if(Mee(_)&&Array.isArray(_.parts))for(let v of _.parts)l(v,u)}catch(p){console.warn("[AI3D] Failed to read registered part sidecar:",h.analysisSidecarPath,p)}}let m=pee((d=h.registeredParts)!=null?d:[]).slice(0,o);for(let g of m)l(g,u)}return typeof i.maxParts=="number"&&i.maxParts>0?pee(r).slice(0,i.maxParts):r}function _Re(n){var t;let e=new Set(((t=n.annotationLinks)!=null?t:[]).flatMap(i=>i.nearestPartId?[i.nearestPartId]:[]));return new Set([...n.parts].filter(i=>{var r;return i.source!=="detail-cluster"||e.has(i.partId)||!!((r=i.registeredMatches)!=null&&r.length)}).sort((i,r)=>{var c,f,d,u;let s=e.has(i.partId)?1:0,a=e.has(r.partId)?1:0;if(s!==a)return a-s;let o=(c=i.registeredMatches)!=null&&c.length?1:0,l=(f=r.registeredMatches)!=null&&f.length?1:0;return o!==l?l-o:((d=r.triangleCount)!=null?d:0)-((u=i.triangleCount)!=null?u:0)}).slice(0,gee).map(i=>i.partId))}function vRe(n,e,t,i){let r=g3(n)||"Parts/3D Components",s=h3(e,"model"),a=h3(t.name,`Part ${i+1}`);return`${r}/${s}/${String(i+1).padStart(2,"0")} ${a}.md`}function ERe(n){var i,r,s,a,o,l;let e=((i=n.analysis.annotationLinks)!=null?i:[]).filter(c=>c.nearestPartId===n.part.partId);return[["---",`source_model: ${fn(n.sourcePath)}`,`parent_report: ${fn(n.notePath)}`,`part_id: ${fn(n.part.partId)}`,`asset_id: ${fn(n.part.assetId)}`,...n.part.componentId?[`component_id: ${fn(n.part.componentId)}`]:[],...n.part.occurrenceId?[`occurrence_id: ${fn(n.part.occurrenceId)}`]:[],...n.part.partNumber?[`part_number: ${fn(n.part.partNumber)}`]:[],...n.part.sourceFormat?[`source_format: ${fn(n.part.sourceFormat)}`]:[],...n.part.effectiveFormat?[`effective_format: ${fn(n.part.effectiveFormat)}`]:[],...n.part.loadStrategy?[`load_strategy: ${fn(n.part.loadStrategy)}`]:[],`category: ${fn((r=n.part.category)!=null?r:"unclassified")}`,"status: draft","generated_by: ai-model-workbench",`updated_at: ${new Date().toISOString()}`,"---"].join(`
`),"",`# ${Hi(n.part.name)}`,"","## Evidence","",`- Source model: [[${n.sourcePath}|${n.baseName}]]`,`- Parent report: [[${n.notePath}|${n.baseName} Report]]`,`- Source: ${Eee(n.part)}`,...p3(n.part)?[`- Format lineage: ${p3(n.part)}`]:[],`- Category: ${(s=n.part.category)!=null?s:"unclassified"}`,...n.part.componentId?[`- Component ID: ${n.part.componentId}`]:[],...n.part.occurrenceId?[`- Occurrence ID: ${n.part.occurrenceId}`]:[],...n.part.partNumber?[`- Part number: ${n.part.partNumber}`]:[],...n.part.componentPath?[`- Component path: ${n.part.componentPath}`]:[],...n.part.source==="group"||n.part.source==="component"||n.part.source==="detail-cluster"?[`- Child meshes: ${Yxe(n.part.meshRefs)}`]:[],`- Triangles: ${((a=n.part.triangleCount)!=null?a:0).toLocaleString()}`,`- Vertices: ${((o=n.part.vertexCount)!=null?o:0).toLocaleString()}`,`- Material: ${n.part.materialName?Hi(n.part.materialName):"-"}`,`- Bounding size: ${m3(n.part.bbox)}`,`- Center: ${m3(n.part.center)}`,...(l=n.part.registeredMatches)!=null&&l.length?[`- Possible registered match: ${Kxe(n.part.registeredMatches[0])}`]:[],"","## Renderer Observations","",...n.part.observations.length>0?n.part.observations.map(c=>`- ${c}`):["- No renderer observations were captured for this part."],"","## Linked Focus Areas","",...e.length>0?e.map(c=>`- ${c.label} (${Math.round(c.confidence*100)}% confidence, distance ${c.distance===void 0?"-":c.distance.toFixed(3)})`):["- No saved annotation pin is linked to this part yet."],"","## Working Notes","","- ",""].join(`
`)}async function SRe(n){var a;let e=_Re(n.analysis);if(e.size===0)return n.analysis.pipeline.push({stage:"partNotes",durationMs:0,status:"skipped"}),[];let t=[],i=typeof performance!="undefined"?performance.now():Date.now(),s=`${g3(n.partFolder)||"Parts/3D Components"}/${h3(n.baseName,"model")}`;await _3(n.app,s);for(let[o,l]of n.analysis.parts.entries()){if(!e.has(l.partId))continue;let c=vRe(n.partFolder,n.baseName,l,o),f={...l,notePath:c},d=ERe({baseName:n.baseName,notePath:n.notePath,sourcePath:n.sourcePath,part:f,analysis:n.analysis}),u=await bee(n.app,c,d);u&&(l.notePath=u.path,t.push(u.path))}n.analysis.partNotePaths=t;for(let o of(a=n.analysis.annotationLinks)!=null?a:[]){let l=n.analysis.parts.find(c=>c.partId===o.nearestPartId);l!=null&&l.notePath&&!o.notePath&&(o.notePath=l.notePath)}return n.analysis.pipeline.push({stage:"partNotes",durationMs:Math.max(0,Math.round((typeof performance!="undefined"?performance.now():Date.now())-i)),status:t.length>0?"success":"skipped"}),t}function E3(n){var r,s,a,o,l,c;let e=((r=n.analysis.parts)!=null?r:[]).filter(f=>f.notePath),t=(a=(s=n.profile)==null?void 0:s.annotations)!=null?a:[],i=(l=(o=n.analysis.localDraft)==null?void 0:o.nextActions)!=null?l:[];return[_ee,"","## Entry Points","",`- Model report: [[${n.notePath}|${n.baseName} Report]]`,`- Analysis sidecar: [[${n.analysisSidecarPath}|Analysis JSON]]`,`- Source model: [[${n.sourcePath}|${n.baseName}]]`,"","## Model Snapshot","",n.preview?`- ${sl(n.preview.meshCount,"mesh")}, ${sl(n.preview.triangleCount,"triangle")}, ${sl(n.preview.vertexCount,"vertex")}, ${sl(n.preview.materialCount,"material slot")}.`:"- No preview statistics were available for this index.",`- Evidence images: ${((c=n.analysis.previewImages)!=null?c:[]).length.toLocaleString()}`,`- Part drafts: ${e.length.toLocaleString()}`,`- Saved annotations: ${t.length.toLocaleString()}`,"","## Part Notes","",...e.length>0?e.map(f=>{var h,m;let d=(h=f.registeredMatches)==null?void 0:h[0],u=d?`, matches ${Hi(d.sourcePartName)} (${Math.round(d.confidence*100)}%)`:"";return`- [[${f.notePath}|${Hi(f.name)}]] - ${(m=f.category)!=null?m:"unclassified"}, ${sl(f.triangleCount,"triangle")}${u}`}):["- No part note drafts were created in this pass."],"","## Evidence Images","",...n.analysis.previewImages.length>0?n.analysis.previewImages.map(f=>`- ![[${f}]]`):["- No evidence image was captured in this pass."],"","## Focus Areas","",...t.length>0?t.map(f=>{var h;let d=(h=n.analysis.annotationLinks)==null?void 0:h.find(m=>m.annotationId===f.id),u=d!=null&&d.notePath?` -> [[${d.notePath}|part note]]`:"";return`- ${f.label||"Untitled pin"}${u}`}):["- No saved annotation pins yet."],"","## Next Actions","",...i.length?i.map(f=>`- ${f}`):["- Review generated part drafts and promote confirmed components into stable notes."],"",d3,""].join(`
`)}function Iee(n,e){let t=n.indexOf(_ee),i=n.indexOf(d3);if(t>=0&&i>t){let r=n.slice(0,t).replace(/\s+$/,""),s=n.slice(i+d3.length).replace(/^\s+/,"");return[r,e.trim(),s].filter(Boolean).join(`
`)+`
`}return`${n.replace(/\s+$/,"")}
${e.trim()}
`}function Cee(n){var r;let e=E3(n),t=((r=n.analysis.parts)!=null?r:[]).filter(s=>s.notePath).length;return[["---",`source_model: ${fn(n.sourcePath)}`,`report_note_path: ${fn(n.notePath)}`,`analysis_sidecar_path: ${fn(n.analysisSidecarPath)}`,`part_note_count: ${t}`,"status: index","generated_by: ai-model-workbench",`updated_at: ${new Date().toISOString()}`,"---"].join(`
`),"",`# ${n.baseName} Knowledge Index`,"","## User Notes","","- ","",e].join(`
`)}async function TRe(n){let e=typeof performance!="undefined"?performance.now():Date.now(),t=n.app.vault.getAbstractFileByPath(n.indexPath),i=null;if(t instanceof ec.TFile){let r=await n.app.vault.read(t),s=E3(n);await n.app.vault.modify(t,Iee(r,s)),i=t}else i=await bee(n.app,n.indexPath,Cee(n));return i&&(n.analysis.knowledgeIndexPath=i.path),n.analysis.pipeline.push({stage:"index",durationMs:Math.max(0,Math.round((typeof performance!="undefined"?performance.now():Date.now())-e)),status:i?"success":"failed"}),i}async function ARe(n,e,t={}){var o,l,c,f,d,u,h,m,g,p,_;if(f3!==null)return;let i;f3=new Promise(v=>{i=v});let r=null,s=null,a=0;try{let v=e.store.getState(),E=v.currentModelPath;if(!E)return;let S=v.modelAssetProfiles[E],T=v.modelPreview,A=gn(E)||"model",R=v.settings.reportFolder,M=`${R}/${A} Report.md`,I=`${R}/${A} Analysis.json`,C=`${R}/${A} Index.md`,L=((o=v.lastKnowledgeGeneration)==null?void 0:o.status)==="pending"?`Previous knowledge generation for ${v.lastKnowledgeGeneration.modelPath} did not complete. This run can replace the pending marker if it finishes.`:null;L&&new ec.Notice(L),r=l3({modelPath:E,reportNotePath:M,analysisSidecarPath:I,knowledgeIndexPath:C,status:"pending"}),e.setLastKnowledgeGeneration(r);let w=(f=(c=(l=t.preview)==null?void 0:l.getModelEvidence)==null?void 0:c.call(l))!=null?f:null,G=await hRe(n,t.preview,v.settings.previewFolder,A);a=G.paths.length;let O=await yee(n,v.modelAssetProfiles,E);s=s3({modelPath:E,profile:S,preview:T,evidence:w,previewImages:G.paths,registeredParts:O}),L&&(s.warnings=[...s.warnings,L]);let N=s;G.warning&&(N.warnings=[...N.warnings,G.warning],N.draftingInput&&(N.draftingInput={...N.draftingInput,evidence:{...N.draftingInput.evidence,warnings:[...N.draftingInput.evidence.warnings,G.warning]}})),N.localDraft=xee({baseName:A,sourcePath:E,profile:S,preview:T,analysis:N}),N.pipeline.push({stage:"draft",durationMs:0,status:"success"}),await SRe({app:n,partFolder:v.settings.partFolder,baseName:A,notePath:M,sourcePath:E,analysis:N}),N.draftingInput&&(N.draftingInput={...N.draftingInput,partCandidates:N.draftingInput.partCandidates.map(Y=>{let j=N.parts.find(ue=>ue.partId===Y.partId);return j!=null&&j.notePath?{...Y,notePath:j.notePath}:Y}),annotationLinks:[...(d=N.annotationLinks)!=null?d:[]]});let B=oee(v.settings,N.draftingInput,yh);if(B.enabled)try{let Y=await lee(B);Y?(N.remoteDraft=Y,N.pipeline.push({stage:"remoteDraft",durationMs:0,status:"success"})):N.pipeline.push({stage:"remoteDraft",durationMs:0,status:"skipped"})}catch(Y){let j=Y instanceof Error?Y.message:String(Y);N.warnings=[...N.warnings,`Remote draft failed: ${j}`],N.pipeline.push({stage:"remoteDraft",durationMs:0,status:"failed"})}else N.pipeline.push({stage:"remoteDraft",durationMs:0,status:"skipped"});if(await _3(n,R),!await TRe({app:n,baseName:A,notePath:M,sourcePath:E,analysisSidecarPath:I,indexPath:C,analysis:N,preview:T,profile:S}))throw new Error(`Unable to write knowledge index: ${C}`);let q=Ree({baseName:A,notePath:M,sourcePath:E,profile:S,preview:T,analysis:N,analysisSidecarPath:I,knowledgeIndexPath:N.knowledgeIndexPath});if(!await dee(n,I,`${JSON.stringify(N,null,2)}
`))throw new Error(`Unable to write analysis sidecar: ${I}`);let J=await dee(n,M,q);if(!J)throw new Error(`Unable to write knowledge report: ${M}`);e.updateModelProfile(E,Y=>({analysisVersion:yh,registeredParts:N.parts.map(v3),reportNotePath:J.path,analysisSidecarPath:I,knowledgeIndexPath:N.knowledgeIndexPath,previewImagePaths:G.paths})),e.setLastKnowledgeGeneration(l3({modelPath:E,reportNotePath:J.path,analysisSidecarPath:I,knowledgeIndexPath:N.knowledgeIndexPath,partNoteCount:(h=(u=N.partNotePaths)==null?void 0:u.length)!=null?h:0,previewImageCount:N.previewImages.length,status:"success",warningCount:N.warnings.length})),await n.workspace.getLeaf(!0).openFile(J,{active:!0}),new ec.Notice(`Knowledge note updated: ${J.path}`)}catch(v){throw r&&e.setLastKnowledgeGeneration(l3({...r,partNoteCount:(g=(m=s==null?void 0:s.partNotePaths)==null?void 0:m.length)!=null?g:0,previewImageCount:(p=s==null?void 0:s.previewImages.length)!=null?p:a,status:"failed",warningCount:Math.max(1,(_=s==null?void 0:s.warnings.length)!=null?_:0)})),v}finally{i(),f3=null}}var ec,Hxe,gee,Xxe,_ee,d3,f3,_0=y(()=>{"use strict";ec=require("obsidian");qA();XA();zn();As();dS();uS();p0();cee();Hxe=er("knowledge-note"),gee=8,Xxe=256,_ee="<!-- AI3D_INDEX_START -->",d3="<!-- AI3D_INDEX_END -->";f3=null});var Pee={};Be(Pee,{renderRegisteredPartMatchRow:()=>RRe});function xRe(n){if(!n)return"";let e=n.split("/");return e[e.length-1]||n}function RRe(n,e,t){var o,l;let i=n.createDiv({cls:"ai3d-direct-workbench-match"}),r=i.createDiv({cls:"ai3d-direct-workbench-match-main"});r.createDiv({cls:"ai3d-direct-workbench-match-title",text:e}),r.createDiv({cls:"ai3d-direct-workbench-match-source",text:t.sourcePartName||t.sourcePartId}),t.sourceModelPath&&r.createDiv({cls:"ai3d-direct-workbench-match-model",text:Wi("directWorkbench.registeredSourceModel",{model:xRe(t.sourceModelPath)})}),r.createDiv({cls:"ai3d-direct-workbench-match-target",text:t.sourceNotePath?H("directWorkbench.registeredTargetPartNote"):t.sourceModelPath?H("directWorkbench.registeredTargetSourceModel"):H("directWorkbench.registeredTargetUnavailable")}),t.reasons.length>0&&r.createDiv({cls:"ai3d-direct-workbench-match-reasons",text:t.reasons.slice(0,2).join(" / ")});let s=i.createDiv({cls:"ai3d-direct-workbench-match-side"});s.createDiv({cls:"ai3d-direct-workbench-match-score",text:`${Math.round(t.matchScore*100)}%`});let a=s.createEl("button",{cls:"ai3d-direct-workbench-action ai3d-direct-workbench-match-open",text:t.sourceNotePath?H("directWorkbench.registeredOpenNote"):H("directWorkbench.registeredOpenModel"),attr:{type:"button","data-ai3d-action":"open-registered-part","data-ai3d-target-path":(l=(o=t.sourceNotePath)!=null?o:t.sourceModelPath)!=null?l:""}});return a.disabled=!t.sourceNotePath&&!t.sourceModelPath,i}var Lee=y(()=>{"use strict";xn()});var Uee={};Be(Uee,{DirectModelView:()=>S3});function ORe(n){return n instanceof Error&&n.message.includes("Missing external model resource:")}function Nee(n){var i,r,s;let e=(r=(i=n.occurrenceId)!=null?i:n.componentId)!=null?r:n.partNumber;if(e!=null&&e.trim())return`component:${e.trim().toLowerCase()}`;let t=n.meshRefs.map(a=>a.trim().toLowerCase()).filter(Boolean).sort().join("|");return`${(s=n.source)!=null?s:"mesh"}:${n.name.trim().toLowerCase()}:${t}`}function NRe(n,e){return n?{...e,notePath:n.notePath,reviewed:n.reviewed,observations:n.reviewed||n.notePath?n.observations:e.observations,inferredFunctions:n.inferredFunctions.length>0?n.inferredFunctions:e.inferredFunctions,knowledgeTags:n.knowledgeTags.length>0?n.knowledgeTags:e.knowledgeTags}:e}function wee(n){return n.reviewed||n.notePath?0:n.source==="component"?1:n.source==="group"?2:n.source==="detail-cluster"?3:4}function wRe(n){return n.length<=Dee?n:[...n].sort((e,t)=>{var s,a,o,l;let i=wee(e)-wee(t);if(i!==0)return i;let r=((s=t.confidence)!=null?s:0)-((a=e.confidence)!=null?a:0);return r!==0?r:((o=t.childCount)!=null?o:0)-((l=e.childCount)!=null?l:0)}).slice(0,Dee)}function Fee(n){return{partId:n.partId,assetId:n.assetId,parentPartId:n.parentPartId,name:n.name,source:n.source,componentId:n.componentId,occurrenceId:n.occurrenceId,partNumber:n.partNumber,componentPath:n.componentPath,category:n.category,meshRefs:n.meshRefs,childCount:n.childCount,materialRefs:n.materialRefs,bbox:n.bbox,center:n.center,triangleCount:n.triangleCount,vertexCount:n.vertexCount,materialName:n.materialName,sourceFormat:n.sourceFormat,effectiveFormat:n.effectiveFormat,loadStrategy:n.loadStrategy,confidence:n.confidence,observations:n.observations,inferredFunctions:n.inferredFunctions,knowledgeTags:n.knowledgeTags,notePath:n.notePath,reviewed:n.reviewed}}function FRe(n=[],e=[]){return n.length!==e.length?!1:JSON.stringify(n.map(Fee))===JSON.stringify(e.map(Fee))}function T3(n){return n==="extreme"?3:n==="heavy"?2:n==="medium"?1:0}function BRe(n){let e=T3(n.performanceTier);return e>=2?yRe:e===1?MRe:bRe}function URe(n){return T3(n.performanceTier)<2&&n.meshCount<=IRe&&n.triangleCount<=CRe}function VRe(n){let e=T3(n.performanceTier);return e>=2?null:e===1?DRe:LRe}function Bee(n){return n.source==="component"?0:n.source==="group"?1:n.source==="detail-cluster"?2:3}function GRe(n){return n.parts.length<=Oee?n:{...n,parts:[...n.parts].sort((e,t)=>{var s,a;let i=Bee(e)-Bee(t);if(i!==0)return i;let r=((s=t.childCount)!=null?s:0)-((a=e.childCount)!=null?a:0);return r!==0?r:t.triangleCount-e.triangleCount}).slice(0,Oee)}}function kRe(n){return{sourcePath:n.sourcePath,sourceFormat:pf(n.sourceExt||n.sourcePath),effectiveFormat:pf(n.ext||n.path),loadStrategy:n.strategy}}function zRe(n,e,t=[]){if(!e&&t.length===0)return n;let i=e!=null?e:n.formatLineage,r=Array.from(new Set([...n.resourceWarnings,...t]));return{...n,formatLineage:i,resourceWarnings:r,parts:n.parts.map(s=>{var a,o,l;return{...s,sourceFormat:(a=s.sourceFormat)!=null?a:i==null?void 0:i.sourceFormat,effectiveFormat:(o=s.effectiveFormat)!=null?o:i==null?void 0:i.effectiveFormat,loadStrategy:(l=s.loadStrategy)!=null?l:i==null?void 0:i.loadStrategy}})}}var Bg,v0,bRe,MRe,yRe,Dee,IRe,CRe,Oee,PRe,LRe,DRe,S3,Vee=y(()=>{"use strict";Bg=require("obsidian");Cy();ev();w1();Xy();F1();As();e_();Yy();Ky();yg();xn();KE();Ma();zn();uS();jy();mJ();W0();gJ();EJ();pS();Jy();G0();v0=er("direct-view"),bRe=450,MRe=1200,yRe=1500,Dee=256,IRe=500,CRe=15e5,Oee=64,PRe=512,LRe=250,DRe=1e3;S3=class extends Bg.FileView{constructor(t,i,r,s){super(t);this.preview=null;this.annotationMgr=null;this.annotationMode=!1;this.loadGeneration=0;this.activeLoadController=null;this.escHandler=null;this.workbenchPanel=null;this.workbenchSummary=null;this.workbenchRoute=null;this.workbenchModelPath=null;this.workbenchEvidenceLineage=null;this.workbenchSourceWarnings=[];this.workbenchEvidenceModelPath=null;this.workbenchEvidence=null;this.evidenceRegistrationTimer=null;this.registeredMatchPreviewTimer=null;this.sidebarContent=null;this.getSettings=i,this.convertedAssetCache=r,this.ps=s}getViewType(){return Qd}getDisplayText(){var t,i;return(i=(t=this.file)==null?void 0:t.name)!=null?i:H("workbench.modelTitle")}getIcon(){return"box"}async onOpen(){this.contentEl.empty(),$d(this.contentEl),this.file&&await this.loadModel(this.file)}async onLoadFile(t){this.contentEl.empty(),$d(this.contentEl),await this.loadModel(t)}onClose(){var t,i,r;return gS(this.contentEl),this.loadGeneration++,(t=this.activeLoadController)==null||t.abort(),this.activeLoadController=null,this.clearDeferredEvidenceRegistration(),this.clearRegisteredMatchPreview(),this.escHandler&&(activeDocument.removeEventListener("keydown",this.escHandler),this.escHandler=null),(i=this.annotationMgr)==null||i.destroy(),this.annotationMgr=null,(r=this.preview)==null||r.destroy(),this.preview=null,Promise.resolve()}async loadModel(t){var S,T,A,R,M,I;$d(this.contentEl),(S=this.activeLoadController)==null||S.abort();let i=new AbortController;this.activeLoadController=i;let r=++this.loadGeneration,s={signal:i.signal,isCurrent:()=>this.loadGeneration===r&&this.activeLoadController===i&&!i.signal.aborted},a=Rr();this.clearDeferredEvidenceRegistration(),this.clearRegisteredMatchPreview(),(T=this.annotationMgr)==null||T.destroy(),this.annotationMgr=null,this.workbenchPanel=null,this.workbenchSummary=null,this.workbenchRoute=null,this.workbenchModelPath=null,this.workbenchEvidenceLineage=null,this.workbenchSourceWarnings=[],this.workbenchEvidenceModelPath=null,this.workbenchEvidence=null,this.sidebarContent=null,(A=this.preview)==null||A.destroy(),this.preview=null,this.ps.setCurrentModel(t.path,null);let{workspace:o,topTrack:l,mainArea:c,hHandle:f,host:d,canvas:u,modeOverlay:h,sidebarContent:m,vHandle:g,workbenchPanel:p}=hJ({contentEl:this.contentEl,filePath:t.path,mobile:a,getPreview:()=>this.preview}),_=null,v=C=>{var L;this.annotationMode=C,a&&C&&(_==null||_.setMobileInteractionMode(!0)),(L=this.annotationMgr)==null||L.hideEditor(),h.classList.toggle("is-hidden",!C)};this.escHandler&&activeDocument.removeEventListener("keydown",this.escHandler),this.escHandler=C=>{C.key==="Escape"&&this.annotationMode&&v(!1)},activeDocument.addEventListener("keydown",this.escHandler),_=kE(c,d,this.app,()=>this.preview,()=>t.path,()=>{this.leaf.detach()},this.getSettings,()=>(v(!this.annotationMode),this.annotationMode),C=>{!C&&this.annotationMode&&v(!1)}),this.sidebarContent=m,this.workbenchPanel=p,this.setupResizeHandles(f,g,l,o);let E=bh(d);try{let C=this.getSettings(),L=(R=Ec(this.app,t.path))!=null?R:void 0,w=Rh(this.app,C);E.setPhaseKey("loading.preparingModel");let G=await Ig({path:t.path,absolutePath:L,preferConversionExts:vf(C),conversionManager:async()=>{let{createConversionManager:J}=await Promise.resolve().then(()=>(c0(),l0));return J(C)},convertedAssetCache:this.convertedAssetCache,conversionOutputRoot:w});xi(s);let O=HE(G);this.workbenchEvidenceLineage=kRe(O),this.workbenchSourceWarnings=[...O.warnings];let N=vJ(C,O);_==null||_.syncCapabilities(),E.setPhaseKey("loading.loadingModel");let B=Po(this.app,O.path,{signal:i.signal}),V=Ng(this.app,O.path,C);B.catch(()=>{}),V.catch(()=>{});let q=await this.createPreviewWithFallback(u,B,V,O,N,t.path,s);xi(s),this.preview=q.preview,d.dataset.ai3dBackend=q.route.backend,d.dataset.ai3dRouteReason=q.route.reason,_==null||_.syncCapabilities();let K=q.summary;this.applyLargeModelRenderBudget(q.preview,C,K),_==null||_.syncCapabilities(),YE(d,K),this.workbenchPanel=p,this.workbenchSummary=K,this.workbenchRoute=q.route,this.workbenchModelPath=t.path,this.renderWorkbenchPanel(p,K,q.route,t.path),this.renderSidebarContent(t.path,K),this.ps.setCurrentModel(t.path,K),v0.info("direct view model loaded",{path:t.path,effectivePath:O.path,effectiveExt:O.ext,strategy:O.strategy,backend:q.route.backend,routeReason:q.route.reason,meshCount:K.meshCount,triangleCount:K.triangleCount}),E.setProgress(100),E.hide(),this.setupAnnotationManager(t.path,r,d,_),this.scheduleDeferredEvidenceRegistration(t.path,r,K)}catch(C){if(Vf(C)||r!==this.loadGeneration)return;E.hide(),(M=this.preview)==null||M.destroy(),this.preview=null,d.replaceChildren(),(I=this.workbenchPanel)==null||I.addClass("is-hidden");let L=WE(C);zE(C)?console.warn("[AI3D] Direct view blocked by converter settings:",L.message):console.error("[AI3D] Direct view failed:",C),this.ps.store.getState().currentModelPath===t.path&&this.ps.clearModelPreview(),XE(d,L)}finally{this.activeLoadController===i&&(this.activeLoadController=null),E.hide()}}async setupAnnotationManager(t,i,r,s){var l;let a=this.preview;if(!a)return;let o=a.getAnnotationProvider();if(o.canvas)try{let[{AnnotationManager:c},{createHeadingSearch:f,createNoteReader:d}]=await Promise.all([Promise.resolve().then(()=>(d0(),f0)),Promise.resolve().then(()=>(h0(),u0))]);if(i!==this.loadGeneration||this.preview!==a||this.workbenchModelPath!==t||!r.isConnected)return;let u=this.ps.store.getState().modelAssetProfiles[t],h=(l=u==null?void 0:u.annotations)!=null?l:[],m=d(this.app),g=f(this.app);this.annotationMgr=new c(o,r,"edit",h,p=>{this.ps.updateModelProfile(t,_=>({annotations:p})),s==null||s.updateAnnotationBadge(p.length)},m,g,{app:this.app,previewMode:this.getSettings().annotationPreviewMode,displayMode:this.getSettings().annotationDisplayMode}),s==null||s.showAnnotateButton(),s==null||s.updateAnnotationBadge(h.length),a.onPick(p=>{var S,T;if(!this.annotationMode||!this.annotationMgr)return;let _=p.screenX,v=p.screenY,E=(T=(S=this.preview)==null?void 0:S.getPickWorldPoint(p))!=null?T:null;E&&this.annotationMgr.showEditor(_,v,E)})}catch(c){console.warn("[AI3D] Direct view annotation runtime failed to load:",c)}}async registerModelPartsFromEvidence(t,i){var f,d;if(!(i!=null&&i.parts.length))return;let{buildPartRecordsFromEvidence:r}=await Promise.resolve().then(()=>(p0(),a3)),s=r(t,i.parts,i.formatLineage);if(s.length===0)return;let o=(f=this.ps.store.getState().modelAssetProfiles[t])!=null?f:V0(),l=new Map(((d=o.registeredParts)!=null?d:[]).map(u=>[Nee(u),u])),c=wRe(s.map(u=>NRe(l.get(Nee(u)),u))).map(wh);FRe(o.registeredParts,c)||this.ps.updateModelProfile(t,u=>({registeredParts:c}))}clearDeferredEvidenceRegistration(){this.evidenceRegistrationTimer!==null&&(window.clearTimeout(this.evidenceRegistrationTimer),this.evidenceRegistrationTimer=null)}clearRegisteredMatchPreview(){this.registeredMatchPreviewTimer!==null&&(window.clearTimeout(this.registeredMatchPreviewTimer),this.registeredMatchPreviewTimer=null)}scheduleDeferredEvidenceRegistration(t,i,r){if(this.clearDeferredEvidenceRegistration(),!URe(r)){this.workbenchEvidenceModelPath=t,this.workbenchEvidence=null,this.refreshWorkbenchPanel(),v0.info("skip automatic evidence capture for very large model",{modelPath:t,performanceTier:r.performanceTier,meshCount:r.meshCount,triangleCount:r.triangleCount});return}this.evidenceRegistrationTimer=window.setTimeout(()=>{this.evidenceRegistrationTimer=null,!(i!==this.loadGeneration||this.workbenchModelPath!==t)&&(async()=>{let s=this.getCurrentModelEvidence();await this.registerModelPartsFromEvidence(t,s),i===this.loadGeneration&&this.workbenchModelPath===t&&this.refreshWorkbenchPanel()})().catch(s=>{console.warn("[AI3D] Deferred model evidence capture failed:",s)})},BRe(r))}getCurrentModelEvidence(){var s,a,o;let t=this.workbenchModelPath;if(t&&this.workbenchEvidenceModelPath===t)return this.workbenchEvidence;let i=(o=(a=(s=this.preview)==null?void 0:s.getModelEvidence)==null?void 0:a.call(s))!=null?o:null,r=i?zRe(i,this.workbenchEvidenceLineage,this.workbenchSourceWarnings):null;return t&&(this.workbenchEvidenceModelPath=t,this.workbenchEvidence=r),r}getCachedModelEvidence(t){return this.workbenchEvidenceModelPath===t?this.workbenchEvidence:null}createKnowledgePreviewAdapter(){return this.preview?{captureSnapshot:()=>{var t,i;return(i=(t=this.preview)==null?void 0:t.captureSnapshot())!=null?i:null},getModelEvidence:()=>this.getCurrentModelEvidence()}:null}renderWorkbenchPanel(t,i,r,s){var a,o;pJ({panel:t,summary:i,route:r,registeredPartCount:(o=(a=this.ps.store.getState().modelAssetProfiles[s])==null?void 0:a.registeredParts)==null?void 0:o.length})}renderSidebarContent(t,i){this.sidebarContent&&(this.clearRegisteredMatchPreview(),this.sidebarContent.empty(),this.renderKnowledgeControls(this.sidebarContent,t),this.renderRegisteredPartMatches(this.sidebarContent,t,i))}refreshWorkbenchPanel(){!this.workbenchPanel||!this.workbenchSummary||!this.workbenchRoute||!this.workbenchModelPath||(this.renderWorkbenchPanel(this.workbenchPanel,this.workbenchSummary,this.workbenchRoute,this.workbenchModelPath),this.renderSidebarContent(this.workbenchModelPath,this.workbenchSummary))}setupResizeHandles(t,i,r,s){let a=(c,f,d)=>{let u=0,h=0,m=p=>{f(p.clientX-u,p.clientY-h),u=p.clientX,h=p.clientY},g=()=>{activeDocument.removeEventListener("mousemove",m),activeDocument.removeEventListener("mouseup",g),d()};c.addEventListener("mousedown",p=>{p.preventDefault(),u=p.clientX,h=p.clientY,activeDocument.addEventListener("mousemove",m),activeDocument.addEventListener("mouseup",g)})},o=200;a(t,c=>{o=Math.max(48,Math.min(400,o-c)),r.style.gridTemplateColumns=`1fr 4px ${o}px`},()=>{});let l=220;a(i,(c,f)=>{l=Math.max(120,Math.min(500,l-f)),s.style.gridTemplateRows=`1fr 4px ${l}px`},()=>{})}renderKnowledgeControls(t,i){let r=this.ps.store.getState().modelAssetProfiles[i],s=t.createDiv({cls:"ai3d-direct-workbench-control ai3d-direct-workbench-knowledge"});s.createDiv({cls:"ai3d-direct-workbench-label",text:H("directWorkbench.knowledgeTitle")}),s.createDiv({cls:"ai3d-direct-workbench-value",text:r!=null&&r.knowledgeIndexPath?H("workbench.indexReady"):r!=null&&r.reportNotePath?H("workbench.noteReady"):H("workbench.noReportYet")});let a=s.createDiv({cls:"ai3d-direct-workbench-actions"}),o=a.createEl("button",{cls:"ai3d-direct-workbench-action",text:H("workbench.generateNoteAction"),attr:{type:"button","data-ai3d-action":"generate-note"}});o.addEventListener("click",()=>{o.disabled=!0,Promise.resolve().then(()=>(_0(),g0)).then(({generateKnowledgeNote:f})=>f(this.app,this.ps,{preview:this.createKnowledgePreviewAdapter()})).catch(f=>{console.error("[AI3D] Generate knowledge note failed:",f)}).finally(()=>{o.disabled=!1,this.refreshWorkbenchPanel()})});let l=a.createEl("button",{cls:"ai3d-direct-workbench-action",text:H("workbench.openNoteAction"),attr:{type:"button","data-ai3d-action":"open-note"}});l.disabled=!(r!=null&&r.reportNotePath),l.addEventListener("click",()=>{var u;let f=(u=this.ps.store.getState().modelAssetProfiles[i])==null?void 0:u.reportNotePath;if(!f)return;let d=this.app.vault.getAbstractFileByPath(f);d instanceof Bg.TFile&&this.app.workspace.getLeaf(!0).openFile(d,{active:!0})});let c=a.createEl("button",{cls:"ai3d-direct-workbench-action",text:H("workbench.openIndexAction"),attr:{type:"button","data-ai3d-action":"open-index"}});c.disabled=!(r!=null&&r.knowledgeIndexPath),c.addEventListener("click",()=>{var u;let f=(u=this.ps.store.getState().modelAssetProfiles[i])==null?void 0:u.knowledgeIndexPath;if(!f)return;let d=this.app.vault.getAbstractFileByPath(f);d instanceof Bg.TFile&&this.app.workspace.getLeaf(!0).openFile(d,{active:!0})})}renderRegisteredPartMatches(t,i,r){let s=this.loadGeneration,a=t.createDiv({cls:"ai3d-direct-workbench-control ai3d-direct-workbench-registered"}),o=a.createDiv({cls:"ai3d-direct-workbench-control-head"});o.createSpan({cls:"ai3d-direct-workbench-label",text:H("directWorkbench.registeredTitle")});let l=o.createSpan({cls:"ai3d-direct-workbench-value",text:H("directWorkbench.registeredLoading")}),c=a.createDiv({cls:"ai3d-direct-workbench-registered-body"}),f=m=>{l.setText(""),c.empty(),c.createDiv({cls:"ai3d-direct-workbench-empty",text:H(m)})},d=this.getCachedModelEvidence(i),u=d?GRe(d):null;if(!(u!=null&&u.parts.length)){this.workbenchEvidenceModelPath===i?f("directWorkbench.registeredUnavailable"):c.createDiv({cls:"ai3d-direct-workbench-empty",text:H("directWorkbench.registeredLoading")});return}let h=VRe(r);if(h===null){f("directWorkbench.registeredUnavailable");return}this.registeredMatchPreviewTimer=window.setTimeout(()=>{this.registeredMatchPreviewTimer=null,!(s!==this.loadGeneration||this.workbenchModelPath!==i||!a.isConnected)&&Promise.all([Promise.resolve().then(()=>(_0(),g0)),Promise.resolve().then(()=>(p0(),a3)),Promise.resolve().then(()=>(Lee(),Pee))]).then(async([{collectRegisteredPartsFromProfiles:m},{buildLocalAnalysisResult:g},{renderRegisteredPartMatchRow:p}])=>{var R;let _=this.ps.store.getState(),v=await m(this.app,_.modelAssetProfiles,i,{includeSidecars:!1,maxParts:PRe});if(s!==this.loadGeneration||this.workbenchModelPath!==i||!a.isConnected)return;if(v.length===0){f("directWorkbench.registeredEmpty");return}let E=this.ps.store.getState().modelAssetProfiles[i],T=g({modelPath:i,profile:E,preview:r,evidence:u,registeredParts:v}).parts.filter(M=>{var I;return(I=M.registeredMatches)==null?void 0:I.length}).sort((M,I)=>{var C,L,w,G,O,N;return((w=(L=(C=I.registeredMatches)==null?void 0:C[0])==null?void 0:L.matchScore)!=null?w:0)-((N=(O=(G=M.registeredMatches)==null?void 0:G[0])==null?void 0:O.matchScore)!=null?N:0)}).slice(0,5);if(T.length===0){f("directWorkbench.registeredEmpty");return}l.setText(Wi("directWorkbench.registeredCount",{count:String(T.length)})),c.empty();let A=c.createDiv({cls:"ai3d-direct-workbench-match-list"});for(let M of T){let I=(R=M.registeredMatches)==null?void 0:R[0];if(!I)continue;let L=p(A,M.name,I).querySelector("[data-ai3d-action='open-registered-part']");L instanceof HTMLButtonElement&&L.addEventListener("click",()=>{let w=L.getAttribute("data-ai3d-target-path")||void 0;if(!w)return;let G=this.app.vault.getAbstractFileByPath(w);G instanceof Bg.TFile&&this.app.workspace.getLeaf(!0).openFile(G,{active:!0})})}}).catch(m=>{console.warn("[AI3D] Registered part match preview failed:",m),s===this.loadGeneration&&this.workbenchModelPath===i&&a.isConnected&&f("directWorkbench.registeredUnavailable")})},h)}async createPreviewWithFallback(t,i,r,s,a,o,l){xi(l);let c=await bg(v0,{surface:"direct-view",modelPath:o},t,a);try{xi(l)}catch(u){throw c.preview.destroy(),u}let f;try{f=await r,xi(l)}catch(u){throw c.preview.destroy(),u}this.applyRenderBudget(c.preview,f);let d;try{d=await i,xi(l)}catch(u){throw c.preview.destroy(),u}try{let u=await c.preview.loadModel(d,s.ext,h=>Po(this.app,h,{signal:l.signal}),s.path,l);return xi(l),{preview:c.preview,summary:u,route:c.route}}catch(u){if(c.preview.destroy(),Vf(u)||c.route.backend!=="three")throw u;xi(l),console.warn("[AI3D] Three direct view failed; falling back to Babylon:",u);let h={...a,allowWorkbenchFeaturesOnThree:!1,rendererRollout:"babylon-safe",useThreeRenderer:!1},m=await bg(v0,{surface:"direct-view-fallback",modelPath:o},t,h);this.applyRenderBudget(m.preview,f);try{xi(l);let g=await m.preview.loadModel(d,s.ext,p=>Po(this.app,p,{signal:l.signal}),s.path,l);return xi(l),{preview:m.preview,summary:g,route:m.route}}catch(g){throw m.preview.destroy(),Vf(g)?g:ORe(u)?u:g}}}applyRenderBudget(t,i){var r;(r=t.setRenderQuality)==null||r.call(t,i.renderQuality,i.renderScale)}applyLargeModelRenderBudget(t,i,r){var a;let s=xJ(i,r);(a=t.setRenderQuality)==null||a.call(t,s.renderQuality,s.renderScale)}}});var kee={};Be(kee,{AI3DSettingTab:()=>x3});function HRe(){switch(A3==null?void 0:A3.platform){case"win32":return{python:"Path to python executable",freecad:"Path to FreeCADCmd.exe",obj2gltf:"Path to obj2gltf.cmd",fbx2gltf:"Path to FBX2glTF.exe"};case"darwin":return{python:"Path to python3",freecad:"Path to FreeCADCmd",obj2gltf:"Path to obj2gltf",fbx2gltf:"Path to FBX2glTF"};case"linux":return{python:"Path to python3",freecad:"Path to freecadcmd",obj2gltf:"Path to obj2gltf",fbx2gltf:"Path to FBX2glTF"};default:return{python:"Path to python executable",freecad:"Path to FreeCAD command",obj2gltf:"Path to obj2gltf",fbx2gltf:"Path to FBX2glTF"}}}var ei,A3,x3,zee=y(()=>{"use strict";ei=require("obsidian");w0();xn();Ma();hr();A3=Dm();x3=class extends ei.PluginSettingTab{constructor(t,i){super(t,i);this.diagnosticsRunId=0;this.diagnosticsEl=null;this.plugin=i}display(){let{containerEl:t}=this;t.empty(),Fh(this.plugin.getSettings().locale),this.diagnosticsEl=null,this.addTitle(t),this.buildLanguageSection(t),this.buildFoldersSection(t),this.buildBehaviorSection(t),this.buildKnowledgeGenerationSection(t),this.buildConvertersSection(t),this.buildPerformanceSection(t)}addTitle(t){new ei.Setting(t).setName(H("settings.title")).setHeading()}createSecondaryMenu(t,i,r){let s=t.createEl("details",{cls:"ai3d-settings-secondary-menu"});s.createEl("summary",{cls:"ai3d-settings-secondary-menu-summary",text:i});let a=s.createDiv({cls:"ai3d-settings-secondary-menu-body"});return a.createEl("p",{cls:"setting-item-description",text:r}),a}resetCommandDiagnostics(){this.diagnosticsEl&&(this.diagnosticsRunId++,this.diagnosticsEl.empty(),this.diagnosticsEl.createEl("p",{text:H("settings.diagnostics.idle")}))}buildLanguageSection(t){new ei.Setting(t).setName(H("settings.language")).setDesc(H("settings.language.desc")).addDropdown(i=>i.addOption("en",H("settings.language.englishName")).addOption("zh-CN",H("settings.language.chineseName")).setValue(this.plugin.getSettings().locale).onChange(r=>{let s=r;this.plugin.updateSettings({locale:s}),Fh(s),this.display()}))}buildFoldersSection(t){new ei.Setting(t).setName(H("settings.folders")).setHeading(),new ei.Setting(t).setName(H("settings.sourceModelFolder")).setDesc(H("settings.sourceModelFolder.desc")).addText(i=>i.setPlaceholder(_f.sourceModelFolder).setValue(this.plugin.getSettings().sourceModelFolder).onChange(r=>{this.plugin.updateSettings({sourceModelFolder:r})})),new ei.Setting(t).setName(H("settings.auxiliaryFileFolder")).setDesc(H("settings.auxiliaryFileFolder.desc")).addText(i=>i.setPlaceholder(H("settings.auxiliaryFileFolder.placeholder")).setValue(this.plugin.getSettings().auxiliaryFileFolder).onChange(r=>{this.plugin.updateSettings({auxiliaryFileFolder:r})})),new ei.Setting(t).setName(H("settings.reportFolder")).setDesc(H("settings.reportFolder.desc")).addText(i=>i.setPlaceholder(_f.reportFolder).setValue(this.plugin.getSettings().reportFolder).onChange(r=>{this.plugin.updateSettings({reportFolder:r})})),new ei.Setting(t).setName(H("settings.partFolder")).setDesc(H("settings.partFolder.desc")).addText(i=>i.setPlaceholder(_f.partFolder).setValue(this.plugin.getSettings().partFolder).onChange(r=>{this.plugin.updateSettings({partFolder:r})})),new ei.Setting(t).setName(H("settings.snapshotFolder")).setDesc(H("settings.snapshotFolder.desc")).addText(i=>i.setPlaceholder(_f.snapshotFolder).setValue(this.plugin.getSettings().snapshotFolder).onChange(r=>{this.plugin.updateSettings({snapshotFolder:r})}))}buildBehaviorSection(t){new ei.Setting(t).setName(H("settings.behavior")).setHeading(),new ei.Setting(t).setName(H("settings.autoGenerateKnowledgeNotes")).setDesc(H("settings.autoGenerateKnowledgeNotes.desc")).addToggle(i=>i.setValue(this.plugin.getSettings().autoGenerateKnowledgeNotes).onChange(r=>{this.plugin.updateSettings({autoGenerateKnowledgeNotes:r})})),new ei.Setting(t).setName(H("settings.annotationPreviewMode")).setDesc(H("settings.annotationPreviewMode.desc")).addDropdown(i=>i.addOption("plain-text",H("settings.annotationPreviewMode.plainText")).addOption("markdown",H("settings.annotationPreviewMode.markdown")).setValue(this.plugin.getSettings().annotationPreviewMode).onChange(r=>{this.plugin.updateSettings({annotationPreviewMode:r})})),new ei.Setting(t).setName(H("settings.annotationDisplayMode")).setDesc(H("settings.annotationDisplayMode.desc")).addDropdown(i=>i.addOption("snippet",H("settings.annotationDisplayMode.snippet")).addOption("surface",H("settings.annotationDisplayMode.surface")).addOption("dot",H("settings.annotationDisplayMode.dot")).setValue(this.plugin.getSettings().annotationDisplayMode).onChange(r=>{this.plugin.updateSettings({annotationDisplayMode:r})})),new ei.Setting(t).setName(H("settings.previewRendererRollout")).setDesc(H("settings.previewRendererRollout.desc")).addDropdown(i=>i.addOption("babylon-safe",H("settings.previewRendererRollout.babylonSafe")).addOption("three-readonly-glb",H("settings.previewRendererRollout.readonly")).addOption("three-direct-glb",H("settings.previewRendererRollout.direct")).setValue(this.plugin.getSettings().previewRendererRollout).onChange(r=>{this.plugin.updateSettings({previewRendererRollout:r})})),new ei.Setting(t).setName(H("settings.useThreeRenderer")).setDesc(H("settings.useThreeRenderer.desc")).addToggle(i=>i.setValue(this.plugin.getSettings().useThreeRenderer).onChange(r=>{this.plugin.updateSettings({useThreeRenderer:r})})),new ei.Setting(t).setName(H("settings.useThreeForConvertedDirectView")).setDesc(H("settings.useThreeForConvertedDirectView.desc")).addToggle(i=>i.setValue(this.plugin.getSettings().useThreeForConvertedDirectView).onChange(r=>{this.plugin.updateSettings({useThreeForConvertedDirectView:r})})),new ei.Setting(t).setName(H("settings.experimentalThreeWorkbench")).setDesc(H("settings.experimentalThreeWorkbench.desc")).addToggle(i=>i.setValue(this.plugin.getSettings().experimentalThreeWorkbench).onChange(r=>{this.plugin.updateSettings({experimentalThreeWorkbench:r})})),new ei.Setting(t).setName(H("settings.autoRotateDefault")).setDesc(H("settings.autoRotateDefault.desc")).addToggle(i=>i.setValue(this.plugin.getSettings().autoRotateDefault).onChange(r=>{this.plugin.updateSettings({autoRotateDefault:r})})),new ei.Setting(t).setName(H("settings.snapshotNaming")).setDesc(H("settings.snapshotNaming.desc")).addDropdown(i=>i.addOption("model-name",H("settings.snapshotNaming.modelName")).addOption("timestamp",H("settings.snapshotNaming.timestamp")).setValue(this.plugin.getSettings().snapshotNaming).onChange(r=>{this.plugin.updateSettings({snapshotNaming:r})})),new ei.Setting(t).setName(H("settings.logLevel")).setDesc(H("settings.logLevel.desc")).addDropdown(i=>i.addOption("debug","Debug").addOption("info","Info").addOption("warn","Warn").addOption("error","Error").setValue(this.plugin.getSettings().logLevel).onChange(r=>{this.plugin.updateSettings({logLevel:r})}))}buildKnowledgeGenerationSection(t){new ei.Setting(t).setName(H("settings.knowledgeGeneration")).setHeading(),new ei.Setting(t).setName(H("settings.analysisMode")).setDesc(H("settings.analysisMode.desc")).addDropdown(i=>i.addOption("local",H("settings.analysisMode.local")).addOption("hybrid",H("settings.analysisMode.hybrid")).addOption("remote",H("settings.analysisMode.remote")).setValue(this.plugin.getSettings().analysisMode).onChange(r=>{this.plugin.updateSettings({analysisMode:r})})),new ei.Setting(t).setName(H("settings.serviceBaseUrl")).setDesc(H("settings.serviceBaseUrl.desc")).addText(i=>i.setPlaceholder("Local draft service URL").setValue(this.plugin.getSettings().serviceBaseUrl).onChange(r=>{this.plugin.updateSettings({serviceBaseUrl:r.trim()})})),new ei.Setting(t).setName(H("settings.sendGeometrySummaryToRemote")).setDesc(H("settings.sendGeometrySummaryToRemote.desc")).addToggle(i=>i.setValue(this.plugin.getSettings().sendGeometrySummaryToRemote).onChange(r=>{this.plugin.updateSettings({sendGeometrySummaryToRemote:r})})),new ei.Setting(t).setName(H("settings.sendPreviewImagesToRemote")).setDesc(H("settings.sendPreviewImagesToRemote.desc")).addToggle(i=>i.setValue(this.plugin.getSettings().sendPreviewImagesToRemote).onChange(r=>{this.plugin.updateSettings({sendPreviewImagesToRemote:r})})),new ei.Setting(t).setName(H("settings.sendRawModelToRemote")).setDesc(H("settings.sendRawModelToRemote.desc")).addToggle(i=>i.setValue(this.plugin.getSettings().sendRawModelToRemote).onChange(r=>{this.plugin.updateSettings({sendRawModelToRemote:r})}))}buildConvertersSection(t){if(new ei.Setting(t).setName(H("settings.converters")).setHeading(),Rr()){t.createEl("p",{cls:"setting-item-description",text:H("settings.mobileSupport.desc")});return}let i=this.createSecondaryMenu(t,H("settings.converterMenu"),H("settings.converterMenu.desc"));this.buildConverterToggles(i);let r=this.createSecondaryMenu(t,H("settings.environmentInspector"),H("settings.environmentInspector.desc"));this.buildConverterPaths(r),this.buildDiagnostics(r)}buildConverterToggles(t){new ei.Setting(t).setName(H("settings.enableCad")).setDesc(H("settings.enableCad.desc")).addToggle(i=>{let r=this.plugin.getSettings().enabledConverterIds.includes("freecad");return i.setValue(r).onChange(s=>{let a=this.plugin.getSettings().enabledConverterIds,o=s?Array.from(new Set([...a,"freecad"])):a.filter(l=>l!=="freecad");this.plugin.updateSettings({enabledConverterIds:o})})}),new ei.Setting(t).setName(H("settings.enableObj2gltf")).setDesc(H("settings.enableObj2gltf.desc")).addToggle(i=>{let r=this.plugin.getSettings().enabledConverterIds.includes("obj2gltf");return i.setValue(r).onChange(s=>{let a=this.plugin.getSettings().enabledConverterIds,o=s?Array.from(new Set([...a,"obj2gltf"])):a.filter(l=>l!=="obj2gltf");this.plugin.updateSettings({enabledConverterIds:o})})}),new ei.Setting(t).setName(H("settings.preferObj2gltf")).setDesc(H("settings.preferObj2gltf.desc")).addToggle(i=>i.setValue(this.plugin.getSettings().preferObj2gltfForObj).onChange(r=>{this.plugin.updateSettings({preferObj2gltfForObj:r})})),new ei.Setting(t).setName(H("settings.enableFbx2gltf")).setDesc(H("settings.enableFbx2gltf.desc")).addToggle(i=>{let r=this.plugin.getSettings().enabledConverterIds.includes("fbx2gltf");return i.setValue(r).onChange(s=>{let a=this.plugin.getSettings().enabledConverterIds,o=s?Array.from(new Set([...a,"fbx2gltf"])):a.filter(l=>l!=="fbx2gltf");this.plugin.updateSettings({enabledConverterIds:o})})}),new ei.Setting(t).setName(H("settings.enableMesh")).setDesc(H("settings.enableMesh.desc")).addToggle(i=>{let r=this.plugin.getSettings().enabledConverterIds.includes("assimp");return i.setValue(r).onChange(s=>{let a=this.plugin.getSettings().enabledConverterIds,o=s?Array.from(new Set([...a,"assimp"])):a.filter(l=>l!=="assimp");this.plugin.updateSettings({enabledConverterIds:o})})}),new ei.Setting(t).setName(H("settings.enableSldprt")).setDesc(H("settings.enableSldprt.desc")).addToggle(i=>{let r=this.plugin.getSettings().enabledConverterIds.includes("sldprt");return i.setValue(r).onChange(s=>{let a=this.plugin.getSettings().enabledConverterIds,o=s?Array.from(new Set([...a,"sldprt"])):a.filter(l=>l!=="sldprt");this.plugin.updateSettings({enabledConverterIds:o})})})}buildConverterPaths(t){let i=HRe();new ei.Setting(t).setName(H("settings.paths")).setHeading(),new ei.Setting(t).setName(H("settings.pythonCmd")).setDesc(H("settings.pythonCmd.desc")).addText(r=>r.setPlaceholder(i.python).setValue(this.plugin.getSettings().freecadCommand).onChange(s=>{this.plugin.updateSettings({freecadCommand:s.trim()}),this.resetCommandDiagnostics()})),new ei.Setting(t).setName(H("settings.freecadCmd")).setDesc(H("settings.freecadCmd.desc")).addText(r=>r.setPlaceholder(i.freecad).setValue(this.plugin.getSettings().freecadcmdCommand).onChange(s=>{this.plugin.updateSettings({freecadcmdCommand:s.trim()}),this.resetCommandDiagnostics()})),new ei.Setting(t).setName(H("settings.obj2gltfCmd")).setDesc(H("settings.obj2gltfCmd.desc")).addText(r=>r.setPlaceholder(i.obj2gltf).setValue(this.plugin.getSettings().obj2gltfCommand).onChange(s=>{this.plugin.updateSettings({obj2gltfCommand:s.trim()}),this.resetCommandDiagnostics()})),new ei.Setting(t).setName(H("settings.fbx2gltfCmd")).setDesc(H("settings.fbx2gltfCmd.desc")).addText(r=>r.setPlaceholder(i.fbx2gltf).setValue(this.plugin.getSettings().fbx2gltfCommand).onChange(s=>{this.plugin.updateSettings({fbx2gltfCommand:s.trim()}),this.resetCommandDiagnostics()})),new ei.Setting(t).setName(H("settings.assimpCmd")).setDesc(H("settings.assimpCmd.desc")).addText(r=>r.setPlaceholder(i.python).setValue(this.plugin.getSettings().assimpCommand).onChange(s=>{this.plugin.updateSettings({assimpCommand:s.trim()}),this.resetCommandDiagnostics()}))}buildDiagnostics(t){new ei.Setting(t).setName(H("settings.diagnostics")).setDesc(H("settings.diagnostics.desc")).addButton(r=>r.setButtonText(H("settings.diagnostics.checkNow")).onClick(async()=>{r.setDisabled(!0),r.setButtonText(H("settings.diagnostics.checking")),this.diagnosticsEl&&await this.renderCommandDiagnostics(this.diagnosticsEl),r.setButtonText(H("settings.diagnostics.checkNow")),r.setDisabled(!1),new ei.Notice(H("settings.diagnostics.refreshed"))})),this.diagnosticsEl=t.createDiv({cls:"ai3d-settings-diagnostics"}),this.resetCommandDiagnostics()}buildPerformanceSection(t){new ei.Setting(t).setName(H("settings.performance")).setHeading(),new ei.Setting(t).setName(H("settings.canvasHeight")).setDesc(H("settings.canvasHeight.desc")).addSlider(i=>i.setLimits(200,800,25).setValue(this.plugin.getSettings().defaultCanvasHeight).setDynamicTooltip().onChange(r=>{this.plugin.updateSettings({defaultCanvasHeight:r})})),new ei.Setting(t).setName(H("settings.autoRotateSpeed")).setDesc(H("settings.autoRotateSpeed.desc")).addSlider(i=>i.setLimits(.1,2,.1).setValue(this.plugin.getSettings().autoRotateSpeed).setDynamicTooltip().onChange(r=>{this.plugin.updateSettings({autoRotateSpeed:r})})),new ei.Setting(t).setName(H("settings.renderQuality")).setDesc(H("settings.renderQuality.desc")).addDropdown(i=>i.addOption("low","Low").addOption("medium","Medium").addOption("high","High").setValue(this.plugin.getSettings().renderQuality).onChange(r=>{this.plugin.updateSettings({renderQuality:r})})),new ei.Setting(t).setName(H("settings.renderScale")).setDesc(H("settings.renderScale.desc")).addSlider(i=>i.setLimits(.25,2,.25).setValue(this.plugin.getSettings().renderScale).setDynamicTooltip().onChange(r=>{this.plugin.updateSettings({renderScale:r})}))}async renderCommandDiagnostics(t){let i=++this.diagnosticsRunId;t.empty(),t.createEl("p",{text:H("settings.diagnostics.checkingAvailability")});let{describeConverterCommandSource:r,inspectAllConverterCommands:s}=await Promise.resolve().then(()=>(Kd(),Q1)),a=await s(this.plugin.getSettings());if(i===this.diagnosticsRunId){t.empty();for(let o of a)this.renderCommandStatus(t,o,r)}}renderCommandStatus(t,i,r){var o;let s=t.createDiv({cls:"ai3d-settings-status-block"});s.createEl("strong",{text:`${i.label}: ${i.available?H("settings.diagnostics.available"):H("settings.diagnostics.notFound")}`});let a=[`${H("settings.diagnostics.sourceLabel")}: ${r(i.source)}`,`${H("settings.diagnostics.commandLabel")}: ${i.command}`,i.resolvedPath&&i.resolvedPath!==i.command?`${H("settings.diagnostics.resolvedPathLabel")}: ${i.resolvedPath}`:"",i.detail].filter(Boolean);for(let l of a)s.createDiv({text:l});for(let l of(o=i.dependencyChecks)!=null?o:[])this.renderDependencyCheck(s,l)}renderDependencyCheck(t,i){var a;let r=(a=i.label)!=null?a:(()=>{switch(i.kind){case"cad-python":return H("settings.diagnostics.cadPythonCheck");case"mesh-python":return H("settings.diagnostics.meshPythonCheck");case"freecadcmd-cli":return H("settings.diagnostics.freecadCmdCheck");case"obj2gltf-cli":return H("settings.diagnostics.obj2gltfCheck");case"fbx2gltf-cli":return H("settings.diagnostics.fbx2gltfCheck")}})(),s=i.ok?H("settings.diagnostics.selfCheckOk"):H("settings.diagnostics.selfCheckFailed");t.createDiv({text:`${H("settings.diagnostics.selfCheckLabel")}: ${r} - ${s}`}),i.detail&&t.createDiv({text:i.detail})}}});function Hee(n){let e=new Map;for(let[t,i]of Object.entries(n))for(let r of i.annotations)if(r.headingRef&&r.id){let s=Jl(r.headingRef);if(!s)continue;let a=e.get(s);a||(a=[],e.set(s,a)),a.push({pinId:r.id,modelPath:t,color:r.color})}return e}function Xee(n){for(let e of Object.values(n))for(let t of e.annotations)if(typeof t.headingRef=="string"&&Jl(t.headingRef))return!0;return!1}var R3=y(()=>{"use strict";qE()});function al(n,e,t=2.5){var i;if(typeof n=="string"){let r=(i=b3[n])!=null?i:b3.iso;return{alpha:r.alpha,beta:r.beta,radiusMultiplier:t}}return{alpha:n,beta:e!=null?e:Math.PI/3,radiusMultiplier:t}}function tc(n,e,t=.02){let i=(1-t*(n+1))/n,r=(1-t*(e+1))/e,s=[];for(let a=0;a<e;a++)for(let o=0;o<n;o++)s.push({x:t+o*(i+t),y:t+(e-1-a)*(r+t),w:i,h:r});return s}function M3(n,e=.02){return tc(n,1,e)}function JE(n,e){let t=(n.length-1)*e;return n.map((i,r)=>({path:i.path,position:[-t/2+r*e,0,0],color:i.color,wireframe:i.wireframe}))}function y3(n,e){return n.map((t,i)=>{let r=2*Math.PI*i/n.length;return{path:t.path,position:[Math.cos(r)*e,0,Math.sin(r)*e],color:t.color,wireframe:t.wireframe}})}var b3,Ch=y(()=>{"use strict";b3={iso:{alpha:Math.PI/4,beta:Math.PI/3},front:{alpha:0,beta:Math.PI/2},side:{alpha:Math.PI/2,beta:Math.PI/2},top:{alpha:0,beta:.01},back:{alpha:Math.PI,beta:Math.PI/2},"3/4":{alpha:Math.PI/6,beta:Math.PI/3.5}}});var Yee,Kee=y(()=>{"use strict";Ch();Yee={name:"compare",description:"Side-by-side model comparison (2-4 models)",minModels:2,maxModels:4,compute(n,e){if(n.length<2||n.length>4)return null;let t=Number(e.spacing)||6,i=e.angle||"iso",r=JE(n,t),s=n.length<=3?n.length:2,a=Math.ceil(n.length/s),o=tc(s,a),l=n.map((c,f)=>({modelIndex:f,camera:al(i),viewport:o[f]}));return{placements:r,cells:l}}}});var jee,Zee=y(()=>{"use strict";Ch();jee={name:"showcase",description:"Single model viewed from multiple angles",minModels:1,maxModels:1,compute(n,e){if(n.length<1)return null;let t=Number(e.angles)||4,i=Number(e.radius)||2.5,r=[{path:n[0].path,position:[0,0,0],color:n[0].color,wireframe:n[0].wireframe}],s=t>=6?["front","side","top","back","iso","3/4"]:["iso","front","side","top"],a=s.length<=4?2:3,o=Math.ceil(s.length/a),l=tc(a,o),c=s.map((f,d)=>({modelIndex:0,camera:al(f,void 0,i),viewport:l[d]}));return{placements:r,cells:c}}}});var qee,Qee=y(()=>{"use strict";Ch();qee={name:"explode",description:"Spatial arrangement of parts (3-8 models in a ring)",minModels:3,maxModels:8,compute(n,e){if(n.length<3||n.length>8)return null;let t=Number(e.radius)||8,i=e.angle||"iso",r=y3(n,t),s=Math.min(n.length,4),a=Math.ceil(n.length/s),o=tc(s,a),l=n.map((c,f)=>({modelIndex:f,camera:al(i),viewport:o[f]}));return{placements:r,cells:l}}}});var $ee,Jee=y(()=>{"use strict";Ch();$ee={name:"timeline",description:"Horizontal progression of models (2-6 models in a strip)",minModels:2,maxModels:6,compute(n,e){if(n.length<2||n.length>6)return null;let t=Number(e.spacing)||6,i=e.angle||"3/4",r=JE(n,t),s=M3(n.length),a=n.map((o,l)=>({modelIndex:l,camera:al(i),viewport:s[l]}));return{placements:r,cells:a}}}});function I3(n,e,t,i,r){var f,d;if(!n||n.length===0)return null;let s=n.reduce((u,h)=>{var m;return u+((m=h.weight)!=null?m:1)},0);if(s<=0)return null;let a=[],o=0;for(let u of n){let m=((f=u.weight)!=null?f:1)/s*(1-t*(n.length+1));e==="horizontal"?a.push({x:t+o,y:t,w:m,h:1-2*t}):a.push({x:t,y:t+o,w:1-2*t,h:m}),o+=m+t}let l=[],c=[];for(let u=0;u<n.length;u++){let h=n[u],m=r(h.preset);if(!m){console.warn(`[AI3D Compose] Unknown preset: "${h.preset}"`);continue}let g=[];for(let E of h.models){let S=i(E);if(!S){console.warn(`[AI3D Compose] Model not found: ${typeof E=="string"?E:E.path}`);continue}g.push(S)}if(g.length<m.minModels)continue;let p=m.compute(g,(d=h.params)!=null?d:{});if(!p)continue;let _=l.length;for(let E of p.placements)l.push(E);let v=a[u];for(let E of p.cells)c.push({modelIndex:E.modelIndex+_,camera:E.camera,viewport:XRe(E.viewport,v)})}return c.length===0?null:{placements:l,cells:c}}function XRe(n,e){return{x:e.x+n.x*e.w,y:e.y+n.y*e.h,w:n.w*e.w,h:n.h*e.h}}var ete,C3=y(()=>{"use strict";ete={name:"compose",description:"Combine multiple presets into one layout",minModels:1,maxModels:32,compute(n,e,t){return null}}});var tte,ite=y(()=>{"use strict";Ch();tte={name:"gallery",description:"All models in one scene, single camera (no cell limit)",minModels:1,maxModels:32,compute(n,e){if(n.length===0)return null;let t=Number(e.spacing)||6,i=e.angle||"iso",r=Number(e.cols)||0,s=r>0?r:Math.ceil(Math.sqrt(n.length)),a=Math.ceil(n.length/s),o=n.map((f,d)=>{let u=d%s,h=Math.floor(d/s),m=(u-(s-1)/2)*t,g=(h-(a-1)/2)*t;return{path:f.path,position:[m,0,g],color:f.color,wireframe:f.wireframe}}),l=tc(1,1,0),c=[{modelIndex:0,camera:al(i,void 0,3+Math.max(s,a)*.5),viewport:l[0]}];return{placements:o,cells:c}}}});function Ug(n){rte.set(n.name,n)}function P3(n){return rte.get(n)}var rte,nte=y(()=>{"use strict";Kee();Zee();Qee();Jee();C3();ite();Ch();C3();rte=new Map;Ug(Yee);Ug(jee);Ug(qee);Ug($ee);Ug(ete);Ug(tte)});function YRe(){return typeof activeWindow=="undefined"?window:activeWindow}function eS(n){return jRe.schedule(n)}var L3,KRe,jRe,D3=y(()=>{"use strict";L3=class{constructor(e=1,t=0){this.maxActive=e;this.settleDelayMs=t;this.active=0;this.drainTimer=null;this.queue=[]}get activeCount(){return this.active}get queuedCount(){return this.queue.length}schedule(e){return new Promise((t,i)=>{this.queue.push({run:e,resolve:t,reject:i}),this.drain()})}drain(){if(this.drainTimer===null)for(;this.active<this.maxActive&&this.queue.length>0;){let e=this.queue.shift();if(!e)return;this.active+=1,Promise.resolve().then(e.run).then(e.resolve,e.reject).finally(()=>{this.active-=1,this.scheduleNextDrain()})}}scheduleNextDrain(){if(this.queue.length!==0){if(this.settleDelayMs<=0){this.drain();return}this.drainTimer===null&&(this.drainTimer=YRe().setTimeout(()=>{this.drainTimer=null,this.drain()},this.settleDelayMs))}}},KRe=75,jRe=new L3(1,KRe)});var cte={};Be(cte,{registerCodeBlockProcessor:()=>qRe,registerGridCodeBlockProcessor:()=>$Re});async function ate(n){let{createConversionManager:e}=await Promise.resolve().then(()=>(c0(),l0));return e(n)}async function ote(n,e,t,i){var d,u,h;let r=typeof e=="string"?{path:e}:e,s=Uf(n,r.path);if(!s)throw new Error(Wi("workbench.fileNotFound",{path:r.path}));let a=(u=(d=s.split(".").pop())==null?void 0:d.toLowerCase())!=null?u:"";if(!_o(a))throw jg(a)?new Error(H("codeBlock.splatDisabled")):new Error(Wi("codeBlock.unsupportedFormat",{ext:`.${a}`,formats:sc().join(", ")}));let o=(h=Ec(n,s))!=null?h:void 0,l=Rh(n,t),c=await Ig({path:s,absolutePath:o,preferConversionExts:vf(t),conversionManager:()=>ate(t),convertedAssetCache:i,conversionOutputRoot:l}),f=HE(c);return{sourcePath:s,effectivePath:f.path,effectiveExt:f.ext,warnings:f.warnings,model:{...r,path:f.path}}}async function ZRe(n,e,t,i){let r=[];for(let s of e.models){let a=await ote(n,s,t,i);r.push(a.model)}return{...e,models:r}}function lte(n){Rr()&&n.createDiv({cls:"ai3d-mobile-mode-hint ai3d-mobile-mode-hint--inline",text:H("codeBlock.mobileHint")})}function qRe(n,e,t,i){return{id:"3d",handler:(r,s,a)=>{var I,C;let o=r.trim();if(!o){s.createDiv({cls:"ai3d-inline-empty",text:H("codeBlock.noModelPathOrConfig")});return}let l;if(o.startsWith("{")||o.startsWith("["))try{let L=JSON.parse(o);l=QRe(L)}catch(L){let w=s.createDiv({cls:"ai3d-json-error"}),G=String(L).match(/position\s+(\d+)/),O=Wi("codeBlock.jsonParseError",{error:String(L)});if(G){let N=parseInt(G[1],10),B=o.substring(0,N).split(`
`);O+=Wi("codeBlock.jsonParseLine",{line:String(B.length)})}w.createEl("pre",{text:O});return}else l={models:[{path:o}]};if(!l.models||l.models.length===0){s.createDiv({cls:"ai3d-inline-empty",text:H("codeBlock.noModelsInConfig")});return}l.models.length>1&&console.warn(`[AI3D] \`\`\`3d only supports one model; ${l.models.length-1} additional models ignored. Use \`\`\`3dgrid for multi-model.`);let f=l.models[0],d=Uf(n,f.path);if(!d){s.createDiv({cls:"ai3d-inline-empty",text:Wi("workbench.fileNotFound",{path:f.path})});return}let u=(C=(I=d.split(".").pop())==null?void 0:I.toLowerCase())!=null?C:"";if(!_o(u)){s.createDiv({cls:"ai3d-inline-empty",text:jg(u)?H("codeBlock.splatDisabled"):Wi("codeBlock.unsupportedFormat",{ext:`.${u}`,formats:sc().join(", ")})});return}let h=e(),m=s.createDiv({cls:"ai3d-preview-host"});l.height&&m.style.setProperty("--min-height",typeof l.height=="number"?`${l.height}px`:l.height),l.width&&m.style.setProperty("--max-width",typeof l.width=="number"?`${l.width}px`:l.width);let g=m.createEl("canvas",{cls:"ai3d-canvas-full"});Cg(g,"inline",d),m.appendChild(g);let p=null,_=null,v=!0,E=!1,S=!1;Pg(g,()=>E?null:p);let T=kE(s,m,n,()=>p,()=>d,()=>{E||(E=!0,A.disconnect(),M.disconnect(),_==null||_.destroy(),_=null,p==null||p.destroy(),p=null,m.remove())},e,()=>{if(v=!v,_){let L=m.querySelector(".ai3d-annotation-overlay");L&&L.classList.toggle("is-hidden",!v)}return v},void 0,{labelKey:"helper.toggleAnnotationsVisibilityLabel",activeTooltipKey:"helper.annotationsVisible",inactiveTooltipKey:"helper.annotationsHidden"});lte(s);let A=new MutationObserver(()=>{E||s.contains(m)||(E=!0,A.disconnect(),M.disconnect(),_==null||_.destroy(),_=null,p==null||p.destroy(),p=null)});A.observe(s,{childList:!0});async function R(){if(S||E||!d)return;S=!0;let L=bh(m),w=async(G,O)=>{if(O.length===0||!Oy(G))return;let N=G.getAnnotationProvider();if(N.canvas)try{let[{AnnotationManager:B},{createNoteReader:V}]=await Promise.all([Promise.resolve().then(()=>(d0(),f0)),Promise.resolve().then(()=>(h0(),u0))]);if(E||p!==G||!m.isConnected)return;_=new B(N,m,"readonly",O,void 0,V(n),void 0,{app:n,previewMode:h.annotationPreviewMode,displayMode:h.annotationDisplayMode}),T.showAnnotateButton(),T.updateAnnotationBadge(O.length)}catch(B){console.warn("[AI3D] Inline annotation runtime failed to load:",B)}};try{L.setPhaseKey("loading.preparingModel"),await eS(async()=>{var se,ve,ne,me,Le,de,be;if(E||!m.isConnected){L.hide();return}let G=(se=Ec(n,d))!=null?se:void 0,O=Rh(n,h);L.setPhaseKey("loading.preparingModel");let N=await Ig({path:d,absolutePath:G,preferConversionExts:vf(h),conversionManager:()=>ate(h),convertedAssetCache:t,conversionOutputRoot:O}),B=HE(N),V=Ng(n,B.path,h),q=Po(n,B.path);V.catch(()=>{}),q.catch(()=>{});let K=(ve=i==null?void 0:i(d))!=null?ve:[],J={ext:B.ext,annotationMode:K.length>0?"readonly":"none",rendererRollout:h.previewRendererRollout,useThreeRenderer:h.useThreeRenderer},{preview:Y}=await bg(ste,{surface:"code-block",modelPath:d},g,J);p=Y;let j=await V;(ne=p.setRenderQuality)==null||ne.call(p,j.renderQuality,j.renderScale),T.syncCapabilities(),L.setPhaseKey("loading.loadingModel");let ue=await q,Ee=async we=>Po(n,we);if(E){L.hide();return}let Ue=await p.loadModel(ue,B.ext,Ee,B.path);if(L.setProgress(100),YE(m,Ue),E){L.hide();return}((me=l.scene)==null?void 0:me.autoRotate)===void 0&&h.autoRotateDefault&&(l.scene={...l.scene,autoRotate:!0,autoRotateSpeed:h.autoRotateSpeed}),p.applyConfig(l),T.syncCapabilities(),u==="stl"&&f.color&&((Le=p.setSTLColor)==null||Le.call(p,f.color)),u==="stl"&&f.wireframe!==void 0&&((de=p.setWireframe)==null||de.call(p,f.wireframe)),(be=p.hasAnimations)!=null&&be.call(p)&&T.showAnimButton(),L.hide(),w(p,K)})}catch(G){E=!0,A.disconnect(),M.disconnect(),L.hide(),p==null||p.destroy(),p=null,m.replaceChildren();let O=WE(G);zE(G)?console.warn("[AI3D] Inline preview blocked by converter settings:",O.message):console.error("[AI3D] Inline preview failed:",G),XE(m,O)}}let M=new IntersectionObserver(L=>{for(let w of L)w.isIntersecting&&(M.disconnect(),R())},{rootMargin:"200px"});M.observe(m)}}}function QRe(n){if(typeof n=="string")return{models:[{path:n}]};if(typeof n!="object"||n===null)return{models:[]};let e=n;return typeof e.path=="string"?{models:[{path:e.path,color:e.color,wireframe:e.wireframe}],camera:e.camera,lights:e.lights,scene:e.scene,stl:e.stl,width:e.width,height:e.height}:{models:Array.isArray(e.models)?e.models.filter(i=>{let r=typeof i=="string"?i:i&&typeof i=="object"&&"path"in i?i.path:void 0;return typeof r=="string"&&r.length>0}).map(i=>{if(typeof i=="string")return{path:i};let r=i;return{path:r.path,color:r.color,wireframe:r.wireframe}}):[],camera:e.camera,lights:e.lights,scene:e.scene,stl:e.stl,width:e.width,height:e.height}}function $Re(n,e,t){return{id:"3dgrid",handler:(i,r,s)=>{var R,M,I,C,L,w,G,O;let a=i.trim();if(!a){r.createDiv({cls:"ai3d-inline-empty",text:H("codeBlock.noConfigSpecified")});return}let o;try{o=JSON.parse(a)}catch(N){r.createDiv({cls:"ai3d-json-error"}).createEl("pre",{text:`JSON parse error: ${String(N)}`});return}if(o.preset!=="compose"&&(!o.models||o.models.length===0)){r.createDiv({cls:"ai3d-inline-empty",text:H("codeBlock.noModelsSpecified")});return}let l=o.preset==="compose"?1:Math.max(1,(M=(R=o.models)==null?void 0:R.length)!=null?M:1),c=(w=(I=o.models)==null?void 0:I[0])!=null?w:(L=(C=o.sections)==null?void 0:C[0])==null?void 0:L.models[0],f=typeof c=="string"?c:(G=c==null?void 0:c.path)!=null?G:"",d=r.createDiv({cls:"ai3d-grid-host"}),u=d.createEl("canvas");if(fJ(u),d.appendChild(u),typeof o.rowHeight=="number"){let N=o.preset==="compose"?1:Math.ceil(l/((O=o.columns)!=null?O:Math.min(l,3)));d.style.setProperty("--grid-height",`${o.rowHeight*N}px`)}let h=null,m=!1,g=!1,p=!1,_=0,v=null,E=null;dJ(u,()=>m?null:h);let S=kE(r,d,n,()=>h,()=>f,()=>{m||(m=!0,v==null||v.disconnect(),E==null||E.disconnect(),T(),d.remove())},e);lte(r);function T(){_+=1,p=!1,g=!1,h==null||h.destroy(),h=null,S.syncCapabilities()}v=new MutationObserver(()=>{m||r.contains(d)||(m=!0,v==null||v.disconnect(),E==null||E.disconnect(),T())}),v.observe(r,{childList:!0});async function A(){if(g||p||m)return;p=!0;let N=++_,B=bh(d);B.setPhaseKey("codeBlock.renderingGrid"),B.setProgress(-1);try{await eS(async()=>{var ue,Ee,Ue,se,ve,ne,me,Le,de,be;if(m||N!==_||!d.isConnected){B.hide();return}let V=e(),q=[];for(let we of(ue=o.models)!=null?ue:[]){let dt=await ote(n,we,V,t);q.push(dt)}let K=q.map(we=>we.model);f=(Ue=(Ee=q[0])==null?void 0:Ee.sourcePath)!=null?Ue:f;let{renderer:J}=await C1(ste,{surface:"3dgrid",preset:(se=o.preset)!=null?se:"compare",modelCount:(ne=(ve=o.models)==null?void 0:ve.length)!=null?ne:0},u);if(m||N!==_||!d.isConnected){J.destroy(),B.hide();return}h=J,h.setRenderScale(V.renderScale),S.syncCapabilities();let Y=h,j=async we=>Po(n,we);if(o.preset==="compose"){if(!o.sections||o.sections.length===0){B.hide(),d.createDiv({cls:"ai3d-inline-empty",text:H("codeBlock.composeRequiresSections")}),h.destroy(),h=null;return}let we=[];for(let Ve of o.sections)try{if(!f){let Kt=Ve.models[0];if(Kt){let Bt=typeof Kt=="string"?Kt:Kt.path;f=(me=Uf(n,Bt))!=null?me:Bt}}let Ze=await ZRe(n,Ve,V,t);we.push(Ze)}catch(Ze){B.hide(),d.createDiv({cls:"ai3d-inline-empty",text:Ze instanceof Error?Ze.message:String(Ze)}),Y.destroy(),h=null;return}let dt=I3(we,(Le=o.direction)!=null?Le:"horizontal",Number((de=o.params)==null?void 0:de.gap)||.02,Ve=>typeof Ve=="string"?null:Ve,P3);if(!dt){B.hide(),d.createDiv({cls:"ai3d-inline-empty",text:H("codeBlock.composeNoValidSections")}),Y.destroy(),h=null;return}await Y.loadWithPreset(dt,j)}else if(o.preset){let we=P3(o.preset);if(!we){B.hide(),d.createDiv({cls:"ai3d-inline-empty",text:Wi("codeBlock.unknownPreset",{preset:o.preset})}),Y.destroy(),h=null;return}let dt=we.compute(K,(be=o.params)!=null?be:{});if(!dt){B.hide(),d.createDiv({cls:"ai3d-inline-empty",text:Wi("codeBlock.presetRequiresModels",{preset:o.preset,min:String(we.minModels),max:String(we.maxModels),count:String(K.length)})}),Y.destroy(),h=null;return}await Y.loadWithPreset(dt,j)}else await Y.loadModels(K,o,j);if(m||N!==_){B.hide();return}g=!0,B.hide()})}catch(V){if(N!==_||m){B.hide();return}m=!0,v==null||v.disconnect(),E==null||E.disconnect(),B.hide(),h==null||h.destroy(),h=null,console.error("[AI3D Grid] Failed:",V),d.createDiv({cls:"ai3d-inline-empty",text:V instanceof Error?V.message:Wi("codeBlock.gridFailed",{reason:String(V)})})}finally{N===_&&(p=!1)}}E=new IntersectionObserver(N=>{N.some(V=>V.isIntersecting||V.intersectionRatio>0)?A():(g||p)&&T()},{rootMargin:"200px"}),E.observe(d)}}}var ste,fte=y(()=>{"use strict";Wa();Cy();Ah();As();nte();w1();Xy();F1();e_();Yy();Ky();yg();xn();KE();Ma();zn();Zy();D3();Jy();ste=er("inline-code-block")});var hte={};Be(hte,{registerLazyCodeBlockProcessor:()=>ebe,registerLazyGridCodeBlockProcessor:()=>tbe});function dte(){return T0!=null||(T0=Promise.resolve().then(()=>(fte(),cte))),T0}function ute(n){return(e,t,i)=>{let r=Ml("ai3d-preview-host ai3d-code-block-lazy");r.setAttribute("aria-busy","true"),t.appendChild(r);let s=async()=>{if(r.isConnected)try{let o=await n();if(!r.isConnected)return;r.remove(),await o(e,t,i)}catch(o){console.warn("[AI3D] Failed to load inline code block runtime:",o);let l=r.isConnected?r:Ml();r.isConnected||t.appendChild(l),l.classList.remove("ai3d-preview-host"),l.classList.add("ai3d-inline-empty"),l.removeAttribute("aria-busy"),l.textContent="Ai3d inline preview failed to load."}};if(typeof IntersectionObserver=="undefined"){s();return}let a=new IntersectionObserver(o=>{o.some(l=>l.isIntersecting||l.intersectionRatio>0)&&(a.disconnect(),s())},{rootMargin:JRe});a.observe(r)}}function ebe(n,e,t,i){let r=null;return{id:"3d",handler:ute(async()=>(r!=null||(r=dte().then(a=>a.registerCodeBlockProcessor(n,e,t,i).handler)),r))}}function tbe(n,e,t){let i=null;return{id:"3dgrid",handler:ute(async()=>(i!=null||(i=dte().then(s=>s.registerGridCodeBlockProcessor(n,e,t).handler)),i))}}var T0,JRe,mte=y(()=>{"use strict";Fm();T0=null,JRe="240px"});var pte={};Be(pte,{setupHeadingPinObserver:()=>rbe});function ibe(n){if(n.length===0)return"var(--interactive-accent)";if(n.length===1)return n[0];let e=100/n.length;return`linear-gradient(135deg, ${n.map((t,i)=>{let r=Math.round(i*e),s=Math.round((i+1)*e);return`${t} ${r}% ${s}%`}).join(", ")})`}function O3(n){return n.map(e=>`${e.pinId}:${e.modelPath}:${e.color}`).sort().join("|")}function A0(n){return Array.from(n.entries()).map(([e,t])=>`${e}=>${O3(t)}`).sort().join("||")}function rbe(n){let e=new Map,t=null,i=new Map,r="",s=!1,a=null,o=new Set,l=0,c=O=>{var V;if(O===t)return!1;let N=new Map,B=t===null;for(let[q,K]of Object.entries(O)){let J=(V=K.annotations)!=null?V:[];N.set(q,J),i.get(q)!==J&&(B=!0)}return N.size!==i.size&&(B=!0),t=O,i=N,B},f=(O=n.getModelAssetProfiles())=>Hee(O),d=O=>Jl(Array.from(O.childNodes).map(N=>{var B;return N.instanceOf(Element)&&N.classList.contains("ai3d-heading-pin-badge")?"":(B=N.textContent)!=null?B:""}).join(" ")),u=O=>{let N=e.get(O);N&&(O.removeEventListener("mouseover",N.handler),N.badge.remove(),delete O.dataset.pinBound,e.delete(O))},h=(O,N)=>{if(N.length===0){u(O);return}let B=O3(N),V=e.get(O);if((V==null?void 0:V.signature)===B)return;V&&u(O),O.dataset.pinBound=B;let q=O.createSpan({cls:"ai3d-heading-pin-badge"}),K=[...new Set(N.map(Ee=>Ee.color).filter(Boolean))],J=q.createSpan({cls:"ai3d-heading-pin-badge-swatch"});if(J.style.background=ibe(K),J.title=N.length>1?H("headingPin.showMultiple"):H("headingPin.showSingle"),J.setAttribute("role","button"),J.setAttribute("tabindex","0"),N.length>1){let Ee=q.createSpan({cls:"ai3d-heading-pin-badge-count"});Ee.textContent=`\xD7${N.length}`}let Y=[...new Set(N.map(Ee=>gn(Ee.modelPath)))];q.title=Wi("headingPin.linkedTo",{models:Y.join(", ")});let j=Ee=>{Ee==null||Ee.stopPropagation(),Ee==null||Ee.preventDefault();for(let Ue of N)activeDocument.dispatchEvent(new CustomEvent("ai3d-pin-highlight",{detail:{pinId:Ue.pinId}}))};J.addEventListener("click",Ee=>{j(Ee)}),J.addEventListener("keydown",Ee=>{Ee.instanceOf(KeyboardEvent)&&(Ee.key!=="Enter"&&Ee.key!==" "||j(Ee))}),q.addEventListener("click",Ee=>{Ee.stopPropagation()}),O.appendChild(q);let ue=()=>{for(let Ee of N)activeDocument.dispatchEvent(new CustomEvent("ai3d-pin-highlight",{detail:{pinId:Ee.pinId}}))};O.addEventListener("mouseover",ue),e.set(O,{badge:q,handler:ue,signature:B})},m=(O,N)=>{var V;let B=d(O);h(O,(V=N.get(B))!=null?V:[])},g=O=>{var N;for(let[B,V]of Array.from(e.entries())){if(!B.isConnected){u(B);continue}let q=(N=O.get(d(B)))!=null?N:[],K=O3(q);(q.length===0||V.signature!==K)&&h(B,q)}},p=(O,N)=>{O.querySelectorAll(iS).forEach(B=>m(B,N))},_=()=>{let O=n.getModelAssetProfiles();c(O);let N=f(O);if(r=A0(N),s=N.size>0,!s){g(N),L();return}C(),g(N),activeDocument.querySelectorAll(tS).forEach(V=>p(V,N))},v=0,E=(O=0)=>{v&&window.clearTimeout(v),v=window.setTimeout(()=>{v=0,_()},O)},S=n.subscribeStore(()=>{let O=n.getModelAssetProfiles();if(!c(O))return;let N=f(O),B=A0(N);if(B!==r){if(r=B,s=N.size>0,!s){g(N),L();return}C(),E()}});n.onLayoutChange(()=>{!s&&f().size===0||E(200)});let T=O=>O.matches(tS)||O.matches(iS)?!0:!!O.querySelector(tS)||!!O.querySelector(iS),A=O=>O.isConnected&&T(O),R=O=>T(O),M=()=>{var B,V,q,K,J,Y;let O=Array.from(o);o.clear(),l=0;let N=f();g(N);for(let j of O)j.isConnected&&((B=j.matches)!=null&&B.call(j,iS)&&m(j,N),(q=(V=j.querySelectorAll)==null?void 0:V.call(j,iS))==null||q.forEach(ue=>m(ue,N)),(K=j.matches)!=null&&K.call(j,tS)&&p(j,N),(Y=(J=j.querySelectorAll)==null?void 0:J.call(j,tS))==null||Y.forEach(ue=>p(ue,N)));r=A0(N),s=N.size>0,s||L()},I=O=>{if(!s)return;let N=!1;for(let B of O){for(let V of Array.from(B.addedNodes))V.instanceOf(HTMLElement)&&A(V)&&(o.add(V),N=!0);for(let V of Array.from(B.removedNodes))V.instanceOf(HTMLElement)&&R(V)&&(N=!0)}N&&!l&&(l=window.setTimeout(M,100))};function C(){a||(a=new MutationObserver(I),a.observe(activeDocument.body,{childList:!0,subtree:!0}))}function L(){a==null||a.disconnect(),a=null,o.clear(),l&&(window.clearTimeout(l),l=0)}n.registerCleanup(()=>{S(),L(),l&&(window.clearTimeout(l),l=0),v&&(window.clearTimeout(v),v=0);for(let O of Array.from(e.keys()))u(O)});let w=n.getModelAssetProfiles();c(w);let G=f(w);r=A0(G),s=G.size>0,s&&(C(),E(500))}var tS,iS,gte=y(()=>{"use strict";xn();qE();As();R3();tS=".markdown-preview-view, .markdown-source-view",iS=[".markdown-preview-view h1",".markdown-preview-view h2",".markdown-preview-view h3",".markdown-preview-view h4",".markdown-preview-view h5",".markdown-preview-view h6",".cm-heading-1",".cm-heading-2",".cm-heading-3",".cm-heading-4",".cm-heading-5",".cm-heading-6",".cm-header-1",".cm-header-2",".cm-header-3",".cm-header-4",".cm-header-5",".cm-header-6"].join(", ")});function nbe(n){return n.includes("![[")}function x0(n){let e="";for(let t of n.iter()){if(!t)continue;let i=e?e+t:t;if(i.includes("![["))return!0;e=i.slice(-2)}return!1}function _te(n,e){return Math.max(0,Math.min(e,n.length))}function vte(n,e,t){if(n.length===0)return!1;let i=n.lineAt(_te(n,e)),r=n.lineAt(_te(n,t));for(let s=i.number;s<=r.number;s++)if(nbe(n.line(s).text))return!0;return!1}function R0(n){if(!n.docChanged)return!1;let e=!1;return n.changes.iterChanges((t,i,r,s)=>{e||(e=vte(n.startState.doc,t,i)||vte(n.state.doc,r,s))}),e}var N3=y(()=>{"use strict"});function Ete(n,e,t=512){let i=new Map;return{resolve(r){var a;if(i.has(r))return(a=i.get(r))!=null?a:null;let s=e(n,r);if(i.set(r,s),i.size>t){let o=i.keys().next();o.done||i.delete(o.value)}return s},clear(){i.clear()}}}var Ste=y(()=>{"use strict"});var xte={};Be(xte,{ModelEmbedWidget:()=>b0,registerLivePreviewExtension:()=>abe});function Tte(n,e,t,i,r,s,a,o,l,c,f,d,u,h,m,g,p,_,v){var A,R;let E="state"in n?n.state.doc:n.doc,S=[];if(!x0(E))return S;let T=0;for(let M of E.iterLines()){let I=T+M.length+1;if(!M.includes("![[")){T=I;continue}let C=0;for(;C<M.length;){let L=M.indexOf("![[",C);if(L===-1)break;if(L>0&&M[L-1]==="\\"){C=L+"![[".length;continue}let w=M.indexOf("]]",L+"![[".length);if(w===-1)break;let O=M.slice(L+"![[".length,w).split("|"),N=O[0].trim(),B=(R=(A=N.split(".").pop())==null?void 0:A.toLowerCase())!=null?R:"";if(!_o(B)){C=w+2;continue}let V=400,q=300;if(O.length>1){let J=O[1].trim().match(/^(\d+)\s*x\s*(\d+)$/);J&&(V=parseInt(J[1],10),q=parseInt(J[2],10))}let K=Uf(e,N);if(!K){C=w+2;continue}S.push(Vg.Decoration.replace({widget:new b0(e,K,V,q,t,i,r,s,a,o,l,c,f,d,u,h,m,g,p,_,v),block:!0}).range(T+L,T+w+2)),C=w+2}T=I}return S}function Ate(n){return n.length===0?Ph.RangeSet.empty:Ph.RangeSet.of(n,!0)}function abe(n,e,t,i){let r=Ph.StateField.define({create(s){let a=e(),o=Tte(s,n,a.autoRotateDefault,a.enabledConverterIds,a.freecadCommand,a.obj2gltfCommand,a.fbx2gltfCommand,a.freecadcmdCommand,a.preferObj2gltfForObj,a.preferFbx2gltfForFbx,a.annotationPreviewMode,a.annotationDisplayMode,a.previewRendererRollout,a.useThreeRenderer,a.auxiliaryFileFolder,a.renderQuality,a.renderScale,t,i);return Ate(o)},update(s,a){if(a.docChanged){if(!R0(a))return s.map(a.changes);let o=e(),l=Tte(a.state,n,o.autoRotateDefault,o.enabledConverterIds,o.freecadCommand,o.obj2gltfCommand,o.fbx2gltfCommand,o.freecadcmdCommand,o.preferObj2gltfForObj,o.preferFbx2gltfForFbx,o.annotationPreviewMode,o.annotationDisplayMode,o.previewRendererRollout,o.useThreeRenderer,o.auxiliaryFileFolder,o.renderQuality,o.renderScale,t,i);return Ate(l)}return s.map(a.changes)},provide:s=>Vg.EditorView.decorations.from(s)});return[Ph.Prec.highest(r)]}var Vg,Ph,sbe,b0,Rte=y(()=>{"use strict";Vg=require("@codemirror/view"),Ph=require("@codemirror/state");Wa();As();Yy();Ky();Fm();Ma();xn();zn();Zy();L1();N3();D3();Jy();sbe=er("inline-live-preview"),b0=class extends Vg.WidgetType{constructor(t,i,r,s,a,o,l,c,f,d,u,h,m,g,p,_,v,E,S,T,A){super();this.app=t;this.modelPath=i;this.width=r;this.height=s;this.autoRotate=a;this.enabledConverterIds=o;this.freecadCommand=l;this.obj2gltfCommand=c;this.fbx2gltfCommand=f;this.freecadcmdCommand=d;this.preferObj2gltfForObj=u;this.preferFbx2gltfForFbx=h;this.annotationPreviewMode=m;this.annotationDisplayMode=g;this.previewRendererRollout=p;this.useThreeRenderer=_;this.auxiliaryFileFolder=v;this.renderQuality=E;this.renderScale=S;this.convertedAssetCache=T;this.getAnnotations=A;this.preview=null;this.annotationMgr=null;this.readyObs=null;this.viewportObs=null;this.pollId=0;this.initStarted=!1;this.destroyed=!1;this.initGeneration=0;this.viewportReady=!1;this.zoomControl=null}eq(t){return this.modelPath===t.modelPath&&this.width===t.width&&this.height===t.height&&this.autoRotate===t.autoRotate&&this.enabledConverterIds.join("|")===t.enabledConverterIds.join("|")&&this.freecadCommand===t.freecadCommand&&this.obj2gltfCommand===t.obj2gltfCommand&&this.fbx2gltfCommand===t.fbx2gltfCommand&&this.freecadcmdCommand===t.freecadcmdCommand&&this.preferObj2gltfForObj===t.preferObj2gltfForObj&&this.preferFbx2gltfForFbx===t.preferFbx2gltfForFbx&&this.annotationPreviewMode===t.annotationPreviewMode&&this.annotationDisplayMode===t.annotationDisplayMode&&this.previewRendererRollout===t.previewRendererRollout&&this.useThreeRenderer===t.useThreeRenderer&&this.auxiliaryFileFolder===t.auxiliaryFileFolder&&this.renderQuality===t.renderQuality&&this.renderScale===t.renderScale&&this.convertedAssetCache===t.convertedAssetCache}toDOM(){let t=Rr(),i=Ml("ai3d-embed-preview ai3d-cm-widget");i.setAttribute("contenteditable","false"),t&&i.classList.add("is-mobile","is-mobile-scroll-mode");let r=Cu("canvas","ai3d-embed-canvas"),s=t?Math.min(this.height,220):this.height;r.style.setProperty("--ai3d-embed-height",`${s}px`),Cg(r,"live-preview",this.modelPath),Pg(r,()=>this.destroyed?null:this.preview),i.appendChild(r),this.zoomControl=Vy(i,()=>this.preview);let a=bh(i),o=Ml("ai3d-embed-error is-hidden");if(i.appendChild(o),t){let f=!1,d=Ml("ai3d-mobile-mode-bar"),u=Ml("ai3d-mobile-mode-hint");u.textContent=H("livePreview.mobileHint");let h=Cu("button","ai3d-mobile-mode-btn");h.type="button";let m=()=>{i.classList.toggle("is-mobile-interactive",f),i.classList.toggle("is-mobile-scroll-mode",!f),h.textContent=f?H("helper.scrollAction"):H("helper.interactAction"),h.classList.toggle("ai3d-btn-active",f),h.setAttribute("aria-label",f?H("helper.disableInteractionLabel"):H("helper.enableInteractionLabel"))};h.addEventListener("click",()=>{f=!f,m()}),m(),d.append(u,h),i.appendChild(d)}let l=()=>{this.destroyed||this.initStarted||this.viewportReady&&(!i.isConnected||r.clientWidth<=0||r.clientHeight<=0||(this.initStarted=!0,this.stopReadyPoll(),this.stopReadyWatch(),this.stopViewportWatch(),this.initPreview(i,r,a,o,++this.initGeneration)))};this.readyObs=new ResizeObserver(()=>l()),this.readyObs.observe(i),this.readyObs.observe(r);let c=()=>{if(this.pollId||this.destroyed||this.initStarted)return;let f=0,d=()=>{this.pollId=0,!(this.destroyed||this.initStarted)&&(l(),!this.initStarted&&(++f>240||(this.pollId=window.requestAnimationFrame(d))))};this.pollId=window.requestAnimationFrame(d)};return typeof IntersectionObserver=="undefined"?(this.viewportReady=!0,c(),l()):(this.viewportObs=new IntersectionObserver(f=>{this.destroyed||this.initStarted||f.some(d=>d.isIntersecting||d.intersectionRatio>0)&&(this.viewportReady=!0,this.stopViewportWatch(),c(),l())},{rootMargin:"200px"}),this.viewportObs.observe(i)),i}stopReadyPoll(){this.pollId&&(window.cancelAnimationFrame(this.pollId),this.pollId=0)}async initPreview(t,i,r,s,a){var o;try{r.setPhaseKey("loading.preparingModel"),await eS(async()=>{var C,L,w,G,O,N,B,V,q,K;if(this.destroyed||a!==this.initGeneration||!t.isConnected){r.hide();return}let[{prepareModelInput:l},{listPreferredConversionExts:c},{createLoggedModelPreview:f},{supportsAnnotationPreview:d},{AnnotationManager:u},{createNoteReader:h},{renderModelPerformanceFeedback:m}]=await Promise.all([Promise.resolve().then(()=>(Xy(),aJ)),Promise.resolve().then(()=>(e_(),cB)),Promise.resolve().then(()=>(Cy(),G$)),Promise.resolve().then(()=>(Ah(),H$)),Promise.resolve().then(()=>(d0(),f0)),Promise.resolve().then(()=>(h0(),u0)),Promise.resolve().then(()=>(KE(),B1))]),g=(C=Ec(this.app,this.modelPath))!=null?C:void 0;r.setPhaseKey("loading.preparingModel");let p=Rh(this.app,{auxiliaryFileFolder:this.auxiliaryFileFolder}),_=await l({path:this.modelPath,absolutePath:g,preferConversionExts:c({preferObj2gltfForObj:this.preferObj2gltfForObj,preferFbx2gltfForFbx:this.preferFbx2gltfForFbx}),conversionManager:async()=>{let{createConversionManager:J}=await Promise.resolve().then(()=>(c0(),l0));return J({enabledConverterIds:this.enabledConverterIds,freecadCommand:this.freecadCommand,obj2gltfCommand:this.obj2gltfCommand,fbx2gltfCommand:this.fbx2gltfCommand,freecadcmdCommand:this.freecadcmdCommand})},convertedAssetCache:this.convertedAssetCache,conversionOutputRoot:p}),v=(w=(L=this.getAnnotations)==null?void 0:L.call(this,this.modelPath))!=null?w:[],E={ext:_.effectiveExt,annotationMode:v.length>0?"readonly":"none",rendererRollout:this.previewRendererRollout,useThreeRenderer:this.useThreeRenderer},S=Ng(this.app,_.effectivePath,{renderQuality:this.renderQuality,renderScale:this.renderScale}),T=Po(this.app,_.effectivePath);S.catch(()=>{}),T.catch(()=>{});let{preview:A}=await f(sbe,{surface:"live-preview",modelPath:this.modelPath},i,E);if(this.destroyed||a!==this.initGeneration){A.destroy();return}this.preview=A,(G=this.zoomControl)==null||G.sync();let R=await S;(N=(O=this.preview).setRenderQuality)==null||N.call(O,R.renderQuality,R.renderScale),r.setPhaseKey("loading.loadingModel");let M=await T;if(this.destroyed||a!==this.initGeneration){(B=this.preview)==null||B.destroy(),this.preview=null;return}let I=await this.preview.loadModel(M,_.effectiveExt,J=>Po(this.app,J),_.effectivePath);if(this.destroyed||a!==this.initGeneration){(V=this.preview)==null||V.destroy(),this.preview=null,(q=this.zoomControl)==null||q.sync();return}if(m(t,I),(K=this.zoomControl)==null||K.sync(),this.autoRotate&&this.preview.applyConfig({models:[],scene:{autoRotate:!0,autoRotateSpeed:.5}}),v.length>0&&d(this.preview)){let J=this.preview.getAnnotationProvider();J.canvas&&(this.annotationMgr=new u(J,t,"readonly",v,void 0,h(this.app),void 0,{app:this.app,previewMode:this.annotationPreviewMode,displayMode:this.annotationDisplayMode}))}r.setProgress(100),r.hide()})}catch(l){if(this.destroyed||a!==this.initGeneration)return;(o=this.preview)==null||o.destroy(),this.preview=null,r.hide(),s.remove(),t.replaceChildren();let[{describeModelLoadFailure:c,isMissingConverterError:f},{renderModelLoadFailure:d}]=await Promise.all([Promise.resolve().then(()=>(yg(),eJ)),Promise.resolve().then(()=>(KE(),B1))]),u=c(l);f(l)?console.warn("[AI3D] Live Preview blocked by converter settings:",u.message):console.error("[AI3D] Live Preview failed:",l),d(t,u)}finally{r.hide()}}destroy(){var t,i;this.destroyed=!0,this.stopReadyPoll(),this.stopReadyWatch(),this.stopViewportWatch(),(t=this.annotationMgr)==null||t.destroy(),this.annotationMgr=null,(i=this.zoomControl)==null||i.destroy(),this.zoomControl=null,this.preview&&(this.preview.destroy(),this.preview=null),this.initStarted=!1,this.viewportReady=!1}stopReadyWatch(){var t;(t=this.readyObs)==null||t.disconnect(),this.readyObs=null}stopViewportWatch(){var t;(t=this.viewportObs)==null||t.disconnect(),this.viewportObs=null}ignoreEvent(){return!0}}});var yte={};Be(yte,{registerLazyLivePreviewExtension:()=>lbe});function obe(){return M0!=null||(M0=Promise.resolve().then(()=>(Rte(),xte))),M0}function bte(n,e,t,i,r,s,a,o,l,c,f,d,u,h,m,g,p,_,v,E){var R,M;let S="state"in n?n.state.doc:n.doc,T=[];if(!x0(S))return T;let A=0;for(let I of S.iterLines()){let C=A+I.length+1;if(!I.includes("![[")){A=C;continue}let L=0;for(;L<I.length;){let w=I.indexOf("![[",L);if(w===-1)break;if(w>0&&I[w-1]==="\\"){L=w+"![[".length;continue}let G=I.indexOf("]]",w+"![[".length);if(G===-1)break;let N=I.slice(w+"![[".length,G).split("|"),B=N[0].trim(),V=(M=(R=B.split(".").pop())==null?void 0:R.toLowerCase())!=null?M:"";if(!_o(V)){L=G+2;continue}let q=400,K=300;if(N.length>1){let Y=N[1].trim().match(/^(\d+)\s*x\s*(\d+)$/);Y&&(q=parseInt(Y[1],10),K=parseInt(Y[2],10))}let J=v.resolve(B);if(!J){L=G+2;continue}T.push(Gg.Decoration.replace({widget:new w3(e,J,q,K,t,i,r,s,a,o,l,c,f,d,u,h,m,g,p,_,E),block:!0}).range(A+w,A+G+2)),L=G+2}A=C}return T}function Mte(n){return n.length===0?Lh.RangeSet.empty:Lh.RangeSet.of(n,!0)}function lbe(n,e,t,i,r){let s=Ete(n,Uf),a=()=>s.clear(),o=[n.vault.on("create",a),n.vault.on("delete",a),n.vault.on("rename",a)];r==null||r(()=>{for(let c of o)n.vault.offref(c)});let l=Lh.StateField.define({create(c){let f=e(),d=bte(c,n,f.autoRotateDefault,f.enabledConverterIds,f.freecadCommand,f.obj2gltfCommand,f.fbx2gltfCommand,f.freecadcmdCommand,f.preferObj2gltfForObj,f.preferFbx2gltfForFbx,f.annotationPreviewMode,f.annotationDisplayMode,f.previewRendererRollout,f.useThreeRenderer,f.auxiliaryFileFolder,f.renderQuality,f.renderScale,t,s,i);return Mte(d)},update(c,f){if(f.docChanged){if(!R0(f))return c.map(f.changes);let d=e(),u=bte(f.state,n,d.autoRotateDefault,d.enabledConverterIds,d.freecadCommand,d.obj2gltfCommand,d.fbx2gltfCommand,d.freecadcmdCommand,d.preferObj2gltfForObj,d.preferFbx2gltfForFbx,d.annotationPreviewMode,d.annotationDisplayMode,d.previewRendererRollout,d.useThreeRenderer,d.auxiliaryFileFolder,d.renderQuality,d.renderScale,t,s,i);return Mte(u)}return c.map(f.changes)},provide:c=>Gg.EditorView.decorations.from(c)});return[Lh.Prec.highest(l)]}var Gg,Lh,M0,w3,Ite=y(()=>{"use strict";Gg=require("@codemirror/view"),Lh=require("@codemirror/state");Wa();As();N3();Ste();Fm();M0=null;w3=class extends Gg.WidgetType{constructor(t,i,r,s,a,o,l,c,f,d,u,h,m,g,p,_,v,E,S,T,A){super();this.app=t;this.modelPath=i;this.width=r;this.height=s;this.autoRotate=a;this.enabledConverterIds=o;this.freecadCommand=l;this.obj2gltfCommand=c;this.fbx2gltfCommand=f;this.freecadcmdCommand=d;this.preferObj2gltfForObj=u;this.preferFbx2gltfForFbx=h;this.annotationPreviewMode=m;this.annotationDisplayMode=g;this.previewRendererRollout=p;this.useThreeRenderer=_;this.auxiliaryFileFolder=v;this.renderQuality=E;this.renderScale=S;this.convertedAssetCache=T;this.getAnnotations=A;this.mountedWidget=null;this.mountedDom=null;this.viewportObs=null;this.destroyed=!1}eq(t){return this.modelPath===t.modelPath&&this.width===t.width&&this.height===t.height&&this.autoRotate===t.autoRotate&&this.enabledConverterIds.join("|")===t.enabledConverterIds.join("|")&&this.freecadCommand===t.freecadCommand&&this.obj2gltfCommand===t.obj2gltfCommand&&this.fbx2gltfCommand===t.fbx2gltfCommand&&this.freecadcmdCommand===t.freecadcmdCommand&&this.preferObj2gltfForObj===t.preferObj2gltfForObj&&this.preferFbx2gltfForFbx===t.preferFbx2gltfForFbx&&this.annotationPreviewMode===t.annotationPreviewMode&&this.annotationDisplayMode===t.annotationDisplayMode&&this.previewRendererRollout===t.previewRendererRollout&&this.useThreeRenderer===t.useThreeRenderer&&this.auxiliaryFileFolder===t.auxiliaryFileFolder&&this.renderQuality===t.renderQuality&&this.renderScale===t.renderScale&&this.convertedAssetCache===t.convertedAssetCache}toDOM(){let t=Ml("ai3d-embed-preview ai3d-cm-widget ai3d-embed-preview-lazy");return t.setAttribute("contenteditable","false"),t.style.setProperty("--ai3d-embed-height",`${this.height}px`),this.watchViewport(t),t}destroy(){var t,i;this.destroyed=!0,this.stopViewportWatch(),(t=this.mountedWidget)==null||t.destroy(),this.mountedWidget=null,(i=this.mountedDom)==null||i.remove(),this.mountedDom=null}ignoreEvent(){return!0}watchViewport(t){if(typeof IntersectionObserver=="undefined"){this.mount(t);return}this.viewportObs=new IntersectionObserver(i=>{this.destroyed||this.mountedWidget||i.some(r=>r.isIntersecting||r.intersectionRatio>0)&&(this.stopViewportWatch(),this.mount(t))},{rootMargin:"240px"}),this.viewportObs.observe(t)}stopViewportWatch(){var t;(t=this.viewportObs)==null||t.disconnect(),this.viewportObs=null}async mount(t){let i;try{i=await obe()}catch(a){console.warn("[AI3D] Failed to load Live Preview widget runtime:",a),!this.destroyed&&t.isConnected&&(t.textContent="Ai3d live preview failed to load.");return}let r=new i.ModelEmbedWidget(this.app,this.modelPath,this.width,this.height,this.autoRotate,this.enabledConverterIds,this.freecadCommand,this.obj2gltfCommand,this.fbx2gltfCommand,this.freecadcmdCommand,this.preferObj2gltfForObj,this.preferFbx2gltfForFbx,this.annotationPreviewMode,this.annotationDisplayMode,this.previewRendererRollout,this.useThreeRenderer,this.auxiliaryFileFolder,this.renderQuality,this.renderScale,this.convertedAssetCache,this.getAnnotations);if(this.destroyed||!t.isConnected){r.destroy();return}let s=r.toDOM();if(this.destroyed||!t.isConnected){r.destroy();return}this.mountedWidget=r,this.mountedDom=s,t.replaceWith(s)}}});var Pte={};Be(Pte,{ModelFileSuggestModal:()=>F3});var Cte,F3,Lte=y(()=>{"use strict";Cte=require("obsidian");Wa();xn();F3=class extends Cte.FuzzySuggestModal{constructor(e,t){super(e),this.onChoose=t,this.setPlaceholder(H("modal.selectModel"))}getItems(){return this.app.vault.getFiles().filter(e=>{let t=e.extension.toLowerCase();return _o(t)})}getItemText(e){return e.path}onChooseItem(e){this.onChoose(e)}}});function Dte(n,e){return n==="three"?{backend:n,supportedFormats:cbe,fallbackRole:"Primary single-model preview path",capabilities:[...e],colorPipeline:"sRGB output, no tone mapping, PBR material preservation",fidelityNotes:["Direct GLB/GLTF/STL/PLY/OBJ are expected to preserve geometry scale and material color intent.","Workbench, grid, and SPLAT routes still keep Babylon fallback coverage."]}:{backend:n,supportedFormats:fbe,fallbackRole:"Capability and compatibility backend",capabilities:[...e],colorPipeline:"Babylon material pipeline with conservative fallback behavior",fidelityNotes:["3dgrid, conservative workbench, SPLAT, and converted workbench inputs remain on Babylon.","Babylon remains the rollback path when Three direct rendering is disabled."]}}function Ote(n){return n.backend==="three"?Dte("three",["annotation","animation","measurement","disassembly","focus-selection","wireframe","orientation-gizmo","bounding-box","slice","render-scale","camera-zoom","workbench"]):Dte("babylon",["annotation","animation","measurement","disassembly","focus-selection","wireframe","orientation-gizmo","bounding-box","slice","render-scale","camera-zoom","workbench"])}function Nte(n){return[`${n.backend}`,`formats=${n.supportedFormats.join("/")}`,`capabilities=${n.capabilities.join("/")||"none"}`,`role=${n.fallbackRole}`].join("; ")}var cbe,fbe,wte=y(()=>{"use strict";Ah();cbe=["glb","gltf","stl","ply","obj"],fbe=["glb","gltf","stl","ply","obj","splat","converted-glb"]});var Bte={};Be(Bte,{buildDiagnosticsReport:()=>Sbe});function nS(n){return typeof n=="boolean"?n?"on":"off":typeof n=="number"?Number.isFinite(n)?String(n):"unknown":typeof n=="string"?n.length>0?n:"empty":"unknown"}function dbe(n){var i;let e=(i=n.split(/[\\/]/).pop())!=null?i:n,t=e.lastIndexOf(".");return t<=0||t===e.length-1?"":`.${e.slice(t+1).toLowerCase()}`}function Dh(n,e,t){if(!n)return t;if(e)return n;let i=dbe(n);return i?`<redacted ${i}>`:"<redacted>"}function rS(n,e){return n?`set (${Dh(n,e,"not set")})`:"not set"}function ube(n){let e=n.settings;return e.analysisMode==="local"?"local only":[e.analysisMode,e.serviceBaseUrl.trim()?"service configured":"service missing",`geometry ${nS(e.sendGeometrySummaryToRemote)}`,`preview refs ${nS(e.sendPreviewImagesToRemote)}`,`raw model ${e.sendRawModelToRemote?"blocked if requested":"off"}`].join(", ")}function hbe(n){let e=n.currentModelPath;return e?n.modelAssetProfiles[e]:void 0}function mbe(n){let e=n.lastKnowledgeGeneration;return e?e.status==="pending"?"pending or interrupted; rerun generation to replace the marker":e.status==="failed"?"failed; inspect console details and rerun after fixing the issue":e.warningCount>0?"completed with warnings":"none":"none"}function vbe(n){let e=new Set(n.enabledConverterIds);return pbe.map(t=>{let i=n[t.settingsKey].trim(),r=i.length===0?"command not configured":gbe.test(i)?"command configured, unsafe command rejected":"command configured, path redacted";return`${t.label}: ${e.has(t.id)?"enabled":"disabled"}, ${r}`}).join("; ")}function Ebe(n){let e=n.convertedAssetRecords;if(e.length===0)return"none";let t=new Set(e.map(r=>`${r.sourcePath}:${r.sourceExt}:${r.targetExt}`)).size,i=e.filter(r=>r.warnings.length>0).length;return[`${e.length} record(s) for ${t} source(s)`,"validated before reuse for cache version, converter identity, output presence, and source freshness",i>0?`${i} record(s) carry warning text`:""].filter(Boolean).join("; ")}function Sbe(n){var c,f,d,u,h,m,g,p,_;let{manifest:e,state:t}=n,i=t.settings,r=hbe(t),s=n.includeVaultPaths===!0,a=t.currentModelPath?Bh({ext:(c=t.currentModelPath.split(".").pop())!=null?c:"",annotationMode:r!=null&&r.annotations.length?"readonly":"none",allowEditModeOnThree:!0,allowWorkbenchFeaturesOnThree:i.experimentalThreeWorkbench,rendererRollout:i.previewRendererRollout,useThreeRenderer:i.useThreeRenderer}):null,o=a?Ote(a):null,l=t.lastKnowledgeGeneration;return["# AI Model Workbench Diagnostics","",`Generated: ${(f=n.generatedAt)!=null?f:new Date().toISOString()}`,"","## Runtime","",`- Plugin version: ${e.version}`,`- Minimum Obsidian version: ${e.minAppVersion}`,`- Obsidian API version: ${Fte.apiVersion}`,`- Platform: ${Rr()?"mobile":"desktop"}`,`- Locale: ${i.locale}`,"","## Renderer","",`- Use Three renderer: ${nS(i.useThreeRenderer)}`,`- Converted GLB Three fast path: ${nS(i.useThreeForConvertedDirectView)}`,`- Preview rollout: ${i.previewRendererRollout}`,`- Experimental Three workbench: ${nS(i.experimentalThreeWorkbench)}`,`- Current route: ${a?`${a.backend} (${a.reason})`:"no current model"}`,`- Route capability profile: ${o?Nte(o):"no current model"}`,`- Route color pipeline: ${(d=o==null?void 0:o.colorPipeline)!=null?d:"no current model"}`,`- Render quality: ${i.renderQuality}`,`- Render scale: ${i.renderScale}`,"","## Current Model","",`- Path: ${Dh(t.currentModelPath,s,"none")}`,`- Preview summary: ${t.modelPreview?`${t.modelPreview.meshCount} mesh(es), ${t.modelPreview.triangleCount.toLocaleString()} triangle(s), ${t.modelPreview.materialCount} material(s)`:"not captured"}`,`- Annotation count: ${(u=r==null?void 0:r.annotations.length)!=null?u:0}`,`- Registered part candidates: ${(m=(h=r==null?void 0:r.registeredParts)==null?void 0:h.length)!=null?m:0}`,`- Report note: ${rS(r==null?void 0:r.reportNotePath,s)}`,`- Analysis sidecar: ${rS(r==null?void 0:r.analysisSidecarPath,s)}`,`- Knowledge index: ${rS(r==null?void 0:r.knowledgeIndexPath,s)}`,"","## Knowledge Generation","",`- Mode: ${ube(t)}`,`- Report folder: ${Dh(i.reportFolder,s,"empty")}`,`- Part notes folder: ${Dh(i.partFolder,s,"empty")}`,`- Snapshot folder: ${Dh(i.previewFolder,s,"empty")}`,`- Last generation: ${l?`${l.status} at ${l.generatedAt}`:"none"}`,`- Last generation attention: ${mbe(t)}`,`- Last generated model: ${Dh(l==null?void 0:l.modelPath,s,"none")}`,`- Last report: ${rS(l==null?void 0:l.reportNotePath,s)}`,`- Last index: ${rS(l==null?void 0:l.knowledgeIndexPath,s)}`,`- Last part notes: ${(g=l==null?void 0:l.partNoteCount)!=null?g:0}`,`- Last preview images: ${(p=l==null?void 0:l.previewImageCount)!=null?p:0}`,`- Last warning count: ${(_=l==null?void 0:l.warningCount)!=null?_:0}`,"","## Conversion","",`- Enabled converters: ${i.enabledConverterIds.length?i.enabledConverterIds.join(", "):"none"}`,`- Auxiliary file folder: ${i.auxiliaryFileFolder.trim()?Dh(i.auxiliaryFileFolder,s,"empty"):"default config folder"}`,`- Cached conversions: ${t.convertedAssetRecords.length}`,`- Converter command status: ${vbe(i)}`,`- Conversion cache status: ${Ebe(t)}`,`- Conversion timeout: ${_be}ms outer budget`,"- Converter safety: missing converters report their converter id; unsafe configured commands are rejected before execution; command paths are redacted.",`- Supported direct/model extensions: ${sc().join(", ")}`,"","## Notes","","- Draft service URL and command paths are intentionally omitted from this report.",s?"- Vault-relative model and note paths are included because includeVaultPaths was requested.":"- Vault-relative model, report, index, and folder paths are redacted by default.","- Attach this report with the model format, console error, and reproduction steps when filing a bug.",""].join(`
`)}var Fte,pbe,gbe,_be,Ute=y(()=>{"use strict";Fte=require("obsidian");Wa();wte();_S();Ma();pbe=[{id:"freecad",label:"Python/CadQuery",settingsKey:"freecadCommand"},{id:"obj2gltf",label:"obj2gltf",settingsKey:"obj2gltfCommand"},{id:"fbx2gltf",label:"FBX2glTF",settingsKey:"fbx2gltfCommand"},{id:"assimp",label:"Python/trimesh",settingsKey:"assimpCommand"},{id:"freecadcmd",label:"FreeCADCmd",settingsKey:"freecadcmdCommand"}],gbe=/[;|&<>$`\r\n\t]/,_be=3e5});var Rbe={};Be(Rbe,{default:()=>y0});module.exports=Yte(Rbe);var Fs=require("obsidian");N0();Wa();G0();var Gee=require("obsidian");xn();pS();W0();Wa();var die=new Set(["glb","gltf","stl","ply","obj"]),uie=10*1024*1024;function lB(n,e){var s;let t=ma(n.extension),i=Kg(t),r=((s=e.preferConversionExts)==null?void 0:s.includes(t))&&!!(i!=null&&i.converterId);return(i==null?void 0:i.strategy)==="convert"||r||!die.has(t)?!0:e.restoredFromWorkspace?n.stat.size>=uie:!1}e_();var E0=class extends Gee.FileView{constructor(t,i,r,s){super(t);this.getSettings=i;this.convertedAssetCache=r;this.ps=s;this.delegate=null;this.delegatePromise=null;this.closed=!1;this.manualLoadRequested=!1;this.initialFileLoadSeen=!1}getViewType(){return Qd}getDisplayText(){var t,i;return(i=(t=this.file)==null?void 0:t.name)!=null?i:H("workbench.modelTitle")}getIcon(){return"box"}async onOpen(){this.closed=!1,this.file&&(this.initialFileLoadSeen=!0,await this.loadOrDeferFile(this.file,!0))}async onLoadFile(t){let i=!this.initialFileLoadSeen&&!this.manualLoadRequested&&!this.delegate;this.initialFileLoadSeen=!0,await this.loadOrDeferFile(t,i)}async loadOrDeferFile(t,i){this.closed=!1;let r=this.getSettings();if(!this.delegate&&!this.manualLoadRequested&&lB(t,{restoredFromWorkspace:i,preferConversionExts:vf(r)})){this.renderDeferredLoad(t);return}await this.loadFileNow(t)}async loadFileNow(t){let i=await this.ensureDelegate();!i||this.closed||(i.file=t,await i.onLoadFile(t))}async onClose(){this.closed=!0,this.initialFileLoadSeen=!1,gS(this.contentEl);let t=this.delegate;this.delegate=null,await(t==null?void 0:t.onClose())}async ensureDelegate(){return this.delegate?this.delegate:(this.delegatePromise||(this.delegatePromise=this.loadDelegate()),this.delegatePromise)}async loadDelegate(){this.contentEl.empty(),$d(this.contentEl),this.contentEl.createDiv({cls:"ai3d-inline-empty",text:H("loading.preparingModel")});let{DirectModelView:t}=await Promise.resolve().then(()=>(Vee(),Uee)),i=new t(this.leaf,this.getSettings,this.convertedAssetCache,this.ps);return i.contentEl=this.contentEl,i.file=this.file,this.delegatePromise=null,this.closed?(await i.onClose(),null):(this.delegate=i,i)}renderDeferredLoad(t){this.contentEl.empty(),$d(this.contentEl);let i=this.contentEl.createDiv({cls:"ai3d-inline-empty ai3d-direct-load-gate"});i.createDiv({cls:"ai3d-direct-load-gate-title",text:H("directView.deferredLoadTitle")}),i.createDiv({cls:"ai3d-direct-load-gate-message",text:H("directView.deferredLoadMessage")});let r=i.createDiv({cls:"ai3d-direct-load-gate-meta"});r.createSpan({text:t.name}),r.createSpan({text:WRe(t.stat.size)}),i.createEl("button",{cls:"ai3d-direct-load-gate-button",text:H("directView.deferredLoadButton")}).addEventListener("click",()=>{this.manualLoadRequested=!0,this.loadFileNow(t).finally(()=>{this.manualLoadRequested=!1})})}};function WRe(n){if(!Number.isFinite(n)||n<=0)return"0 B";let e=["B","KB","MB","GB"],t=n,i=0;for(;t>=1024&&i<e.length-1;)t/=1024,i++;let r=t>=100||i===0?0:t>=10?1:2;return`${t.toFixed(r)} ${e[i]}`}pS();var Wee=require("obsidian"),S0=class extends Wee.PluginSettingTab{constructor(t,i){super(t,i);this.plugin=i;this.delegate=null;this.delegatePromise=null}display(){this.containerEl.empty(),this.containerEl.createEl("p",{cls:"setting-item-description",text:"Loading AI model workbench settings..."}),this.ensureDelegate().then(t=>{t.containerEl=this.containerEl,t.display()}).catch(t=>{this.containerEl.empty(),this.containerEl.createEl("p",{cls:"setting-item-description",text:`Failed to load AI Model Workbench settings: ${String(t)}`})})}hide(){var t;(t=this.delegate)==null||t.hide()}ensureDelegate(){var t;return this.delegate?Promise.resolve(this.delegate):((t=this.delegatePromise)!=null||(this.delegatePromise=Promise.resolve().then(()=>(zee(),kee)).then(({AI3DSettingTab:i})=>{let r=new i(this.app,this.plugin);return this.delegate=r,this.delegatePromise=null,r}).catch(i=>{throw this.delegatePromise=null,i})),this.delegatePromise)}};zn();xn();R3();Ma();var B3=er("main"),Tbe=700,Abe=2500;function sS(n,e){return()=>{n().catch(t=>{B3.error(`Command ${e} failed`,{error:String(t)}),new Fs.Notice(`AI3D: ${e} failed \u2014 ${String(t)}`,5e3)})}}function xbe(n){let e=!1,t=null,i=null,r=window,s=()=>{var o;t!==null&&(window.clearTimeout(t),t=null),i!==null&&((o=r.cancelIdleCallback)==null||o.call(r,i),i=null)},a=()=>{e||(s(),n())};return t=window.setTimeout(()=>{t=null,r.requestIdleCallback?i=r.requestIdleCallback(a,{timeout:Abe}):t=window.setTimeout(a,0)},Tbe),()=>{e=!0,s()}}var y0=class extends Fs.Plugin{constructor(){super(...arguments);this.unloaded=!1;this.headingPinObserverStarted=!1;this.headingLinkedProfilesRef=null;this.headingLinkedProfilesResult=!1}getSettings(){return this.ps.store.getState().settings}updateSettings(t){this.ps.updateSettings(t),P1(this.getSettings().logLevel),Fh(this.getSettings().locale)}async onload(){var o;if(this.unloaded=!1,this.ps=Q3(this),await this.ps.load(),this.convertedAssetCache=G3(this.ps.store.getState().convertedAssetRecords,l=>this.ps.setConvertedAssetRecords(l)),P1(this.getSettings().logLevel),!this.ps.localeLoadedFromSaved){let c=((o=navigator.language)!=null?o:"en").startsWith("zh")?"zh-CN":"en";this.updateSettings({locale:c})}Fh(this.getSettings().locale),this.addRibbonIcon("box",H("main.commandImportModel"),()=>this.importModel()),this.addCommand({id:"import-model",name:H("main.commandImportModel"),callback:()=>this.importModel()}),this.addCommand({id:"generate-note",name:H("main.commandGenerateNote"),callback:sS(()=>this.generateNote(),"generate note")}),this.addCommand({id:"open-knowledge-index",name:H("main.commandOpenKnowledgeIndex"),callback:sS(()=>this.openKnowledgeIndex(),"open knowledge index")}),this.addCommand({id:"clear-conversion-cache",name:H("main.commandClearConversionCache"),callback:sS(()=>Promise.resolve(this.clearConversionCache()),"clear conversion cache")}),this.addCommand({id:"check-converters",name:H("main.commandCheckConverters"),callback:sS(()=>this.checkConverterCommands(),"check converters")}),this.addCommand({id:"copy-diagnostics-report",name:H("main.commandCopyDiagnostics"),callback:sS(()=>this.copyDiagnosticsReport(),"copy diagnostics")}),this.addSettingTab(new S0(this.app,this)),this.registerView(Qd,l=>new E0(l,()=>this.getSettings(),this.convertedAssetCache,this.ps)),this.registerExtensions(sc(),Qd);let t=l=>{var c,f;return(f=(c=this.ps.store.getState().modelAssetProfiles[l])==null?void 0:c.annotations)!=null?f:[]},{registerLazyCodeBlockProcessor:i,registerLazyGridCodeBlockProcessor:r}=await Promise.resolve().then(()=>(mte(),hte)),s=i(this.app,()=>this.getSettings(),this.convertedAssetCache,t);this.registerMarkdownCodeBlockProcessor(s.id,s.handler);let a=r(this.app,()=>this.getSettings(),this.convertedAssetCache);this.registerMarkdownCodeBlockProcessor(a.id,a.handler),this.register(this.ps.store.subscribe(()=>{this.unloaded||this.headingPinObserverStarted||!this.hasHeadingLinkedAnnotations()||this.startHeadingPinObserver()})),this.app.workspace.onLayoutReady(()=>{this.unloaded||this.register(xbe(()=>{this.registerLivePreviewExtension(t),this.hasHeadingLinkedAnnotations()&&this.startHeadingPinObserver()}))})}onunload(){this.unloaded=!0,this.ps.dispose()}async startHeadingPinObserver(){if(!(this.unloaded||this.headingPinObserverStarted)){this.headingPinObserverStarted=!0;try{let{setupHeadingPinObserver:t}=await Promise.resolve().then(()=>(gte(),pte));if(this.unloaded)return;t({subscribeStore:i=>this.ps.store.subscribe(i),getModelAssetProfiles:()=>this.ps.store.getState().modelAssetProfiles,registerCleanup:i=>this.register(i),onLayoutChange:i=>{this.registerEvent(this.app.workspace.on("layout-change",i))}})}catch(t){this.headingPinObserverStarted=!1,console.warn("[AI3D] Failed to start heading pin observer:",t)}}}hasHeadingLinkedAnnotations(){let t=this.ps.store.getState().modelAssetProfiles;return this.headingLinkedProfilesRef===t?this.headingLinkedProfilesResult:(this.headingLinkedProfilesRef=t,this.headingLinkedProfilesResult=Xee(t),this.headingLinkedProfilesResult)}async registerLivePreviewExtension(t){if(!this.unloaded)try{let{registerLazyLivePreviewExtension:i}=await Promise.resolve().then(()=>(Ite(),yte));if(this.unloaded)return;let r=i(this.app,()=>this.getSettings(),this.convertedAssetCache,t,s=>this.register(s));for(let s of r)this.registerEditorExtension(s)}catch(i){console.warn("[AI3D] Failed to register Live Preview model embeds:",i)}}importModel(){this.showImportModelModal().catch(t=>{B3.error("Failed to open import modal",{error:String(t)}),new Fs.Notice(`AI3D: failed to open import modal - ${String(t)}`,5e3)})}async showImportModelModal(){let{ModelFileSuggestModal:t}=await Promise.resolve().then(()=>(Lte(),Pte));new t(this.app,i=>{let r=i.extension.toLowerCase();_o(r)&&this.openModelFile(i)}).open()}async openModelFile(t){this.ps.setCurrentModel(t.path,null),await this.app.workspace.getLeaf(!0).openFile(t,{active:!0})}async generateNote(){let{generateKnowledgeNote:t}=await Promise.resolve().then(()=>(_0(),g0));await t(this.app,this.ps)}async openKnowledgeIndex(){let t=this.resolveKnowledgeIndexPath();if(!t){new Fs.Notice(H("workbench.noIndexYet"));return}let i=this.app.vault.getAbstractFileByPath(t);i instanceof Fs.TFile?await this.app.workspace.getLeaf(!0).openFile(i,{active:!0}):new Fs.Notice(Wi("workbench.fileNotFound",{path:t}))}resolveKnowledgeIndexPath(){var a,o,l;let t=this.ps.store.getState(),i=t.currentModelPath,r=i?(a=t.modelAssetProfiles[i])==null?void 0:a.knowledgeIndexPath:void 0;return r||((o=t.lastKnowledgeGeneration)!=null&&o.knowledgeIndexPath?t.lastKnowledgeGeneration.knowledgeIndexPath:(l=Object.values(t.modelAssetProfiles).filter(c=>!!c.knowledgeIndexPath).sort((c,f)=>Date.parse(f.updatedAt)-Date.parse(c.updatedAt))[0])==null?void 0:l.knowledgeIndexPath)}clearConversionCache(){this.convertedAssetCache.clear(),new Fs.Notice("AI 3d conversion cache cleared.")}async checkConverterCommands(){if(Rr()){new Fs.Notice(H("main.converterDiagnosticsMobileUnavailable"),8e3);return}let{inspectAllConverterCommands:t}=await Promise.resolve().then(()=>(Kd(),Q1)),i=await t(this.getSettings()),r=i.filter(a=>a.available).map(a=>a.label),s=i.filter(a=>!a.available).map(a=>a.label);if(s.length===0){new Fs.Notice(`AI 3D converter diagnostics: all commands available (${r.join(", ")}).`,8e3);return}new Fs.Notice(`AI 3D converter diagnostics: available ${r.join(", ")||"none"}; missing ${s.join(", ")}.`,1e4)}async copyDiagnosticsReport(){let{buildDiagnosticsReport:t}=await Promise.resolve().then(()=>(Ute(),Bte)),i=t({manifest:this.manifest,state:this.ps.store.getState()});try{await navigator.clipboard.writeText(i),new Fs.Notice(H("main.diagnosticsCopied"),8e3)}catch(r){let s=this.getSettings().reportFolder.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"").trim()||"Analysis/3D Reports";await this.ensureVaultFolder(s);let a=`AI Model Workbench Diagnostics ${new Date().toISOString().replace(/[:.]/g,"-")}.md`,o=await this.app.vault.create(`${s}/${a}`,i);await this.app.workspace.getLeaf(!0).openFile(o,{active:!0}),new Fs.Notice(H("main.diagnosticsCopyFailed"),1e4)}}async ensureVaultFolder(t){let i="";for(let r of t.split("/").filter(Boolean))i=i?`${i}/${r}`:r,this.app.vault.getAbstractFileByPath(i)||await this.app.vault.createFolder(i).catch(s=>{B3.warn("Failed to create vault folder",{path:i,error:String(s)})})}};