From fd37ba899d8844434f26fae7d7c284062b72723e Mon Sep 17 00:00:00 2001 From: PozzettiAndrea Date: Thu, 4 Jun 2026 20:36:33 +0200 Subject: [PATCH] fullscreen mode for spectate node --- nodes/__init__.py | 3 + nodes/preview_gaussian.py | 27 +- nodes/preview_gaussian_dual.py | 84 + nodes/preview_gaussian_spectate.py | 21 +- web/js/gaussian_preview.js | 174 +- web/js/playcanvas.min.js | 4878 ++++++++++++++++------------ web/viewer_gaussian.html | 411 ++- web/viewer_gaussian_dual.html | 507 +++ 8 files changed, 4005 insertions(+), 2100 deletions(-) create mode 100644 nodes/preview_gaussian_dual.py create mode 100644 web/viewer_gaussian_dual.html diff --git a/nodes/__init__.py b/nodes/__init__.py index 7960072..4a25465 100644 --- a/nodes/__init__.py +++ b/nodes/__init__.py @@ -10,6 +10,7 @@ set at the root, not here. from .preview_gaussian import PreviewGaussians from .preview_gaussian_spectate import PreviewGaussianSpectate from .preview_gaussian_camera import PreviewGaussianCamera +from .preview_gaussian_dual import PreviewGaussianDual from .merge_gaussians import GaussianMerge from .load_ply import LoadPLY from .load_ply_output import LoadPLYOutput @@ -34,6 +35,7 @@ NODE_CLASS_MAPPINGS = { "GaussianExport": GaussianExport, "TransformGaussian": TransformGaussian, "GaussiansFromPointCloud": GaussiansFromPointCloud, + "PreviewGaussianDual": PreviewGaussianDual, } NODE_DISPLAY_NAME_MAPPINGS = { @@ -47,4 +49,5 @@ NODE_DISPLAY_NAME_MAPPINGS = { "GaussianExport": "Gaussian Export", "TransformGaussian": "Transform Gaussian", "GaussiansFromPointCloud": "Gaussians From Point Cloud", + "PreviewGaussianDual": "Preview Gaussian Dual", } diff --git a/nodes/preview_gaussian.py b/nodes/preview_gaussian.py index 1f6a6a5..76f3e93 100644 --- a/nodes/preview_gaussian.py +++ b/nodes/preview_gaussian.py @@ -67,22 +67,16 @@ class PreviewGaussians: "default": 50.0, "min": 5.0, "max": 170.0, "step": 1.0, "tooltip": "Vertical field of view in degrees", }), - "image_width": ("INT", { - "default": 512, "min": 64, "max": 4096, "step": 8, - }), - "image_height": ("INT", { - "default": 512, "min": 64, "max": 4096, "step": 8, - }), - "renderer": (["spark", "playcanvas"], { - "default": "spark", + "renderer": (["playcanvas", "spark"], { + "default": "playcanvas", "tooltip": ( + "playcanvas — PlayCanvas Engine v2.19 GSplat renderer. " + "WebGPU when available, WebGL2 fallback. Good " + "performance on large scenes (5M+ splats). " + "\n" "spark — Three.js + WebGL2. Best SH3 fidelity, " "auto-detects all formats (PLY, compressed.ply, SPZ, " - "KSPLAT, SOG, SPLAT). " - "\n" - "playcanvas — WebGPU path (currently falls back to " - "spark; real adapter pending). Will win on large " - "scenes (5M+ splats) when implemented." + "KSPLAT, SOG, SPLAT)." ), }), "transport_format": (["ply", "spz"], { @@ -107,7 +101,7 @@ class PreviewGaussians: FUNCTION = "preview" CATEGORY = "viewer" - def preview(self, ply_path, fov_degrees, image_width, image_height, renderer, transport_format="ply"): + def preview(self, ply_path, fov_degrees, renderer, transport_format="ply"): if not ply_path: return {"ui": {"error": ["No PLY path provided"]}} if not os.path.exists(ply_path): @@ -117,18 +111,17 @@ class PreviewGaussians: file_size_mb = round(os.path.getsize(ply_path) / (1024 * 1024), 2) num_gaussians = _count_gaussians(ply_path) - intrinsics = get_default_intrinsics(image_width, image_height, fov_degrees) extrinsics = get_default_extrinsics() return {"ui": { "ply_file": [filename], "filename": [filename], - "ply_type": [folder_kind], # "input" | "output" — JS passes to /view?type= + "ply_type": [folder_kind], "ply_subfolder": [subfolder], "file_size_mb": [file_size_mb], "num_gaussians": [num_gaussians], "extrinsics": [extrinsics], - "intrinsics": [intrinsics], + "intrinsics": [None], "fov_degrees": [fov_degrees], "renderer": [renderer], "transport_format": [transport_format], diff --git a/nodes/preview_gaussian_dual.py b/nodes/preview_gaussian_dual.py new file mode 100644 index 0000000..f69634f --- /dev/null +++ b/nodes/preview_gaussian_dual.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: GPL-3.0-or-later + +"""PreviewGaussianDual — side-by-side or slider comparison of two gaussian splats.""" + +import os + +from .common import get_default_extrinsics +from .preview_gaussian import _resolve_for_view, _count_gaussians + + +class PreviewGaussianDual: + """Compare two Gaussian splats side-by-side or with a slider.""" + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "ply_path_1": ("STRING", { + "forceInput": True, + "tooltip": "Path to the first Gaussian Splatting PLY file", + }), + "ply_path_2": ("STRING", { + "forceInput": True, + "tooltip": "Path to the second Gaussian Splatting PLY file", + }), + "layout": (["side_by_side", "slider"], { + "default": "side_by_side", + "tooltip": ( + "side_by_side — two synchronized viewports. " + "slider — overlaid with a draggable divider." + ), + }), + "fov_degrees": ("FLOAT", { + "default": 50.0, "min": 5.0, "max": 170.0, "step": 1.0, + }), + "renderer": (["playcanvas", "spark"], { + "default": "playcanvas", + "tooltip": ( + "playcanvas — PlayCanvas Engine v2.19 GSplat. " + "spark — Three.js + WebGL2, all formats." + ), + }), + "transport_format": (["ply", "spz"], { + "default": "ply", + "tooltip": ( + "ply — lossless, larger. " + "spz — server transcodes to SPZ v2, ~9x smaller." + ), + }), + }, + } + + RETURN_TYPES = () + OUTPUT_NODE = True + FUNCTION = "preview" + CATEGORY = "viewer" + + def preview(self, ply_path_1, ply_path_2, layout, fov_degrees, + renderer, transport_format="ply"): + for i, p in enumerate([ply_path_1, ply_path_2], 1): + if not p: + return {"ui": {"error": [f"No PLY path provided for input {i}"]}} + if not os.path.exists(p): + return {"ui": {"error": [f"File not found (input {i}): {p}"]}} + + fn1, sub1, kind1 = _resolve_for_view(ply_path_1) + fn2, sub2, kind2 = _resolve_for_view(ply_path_2) + + return {"ui": { + "ply_file_1": [fn1], + "ply_type_1": [kind1], + "ply_subfolder_1": [sub1], + "file_size_mb_1": [round(os.path.getsize(ply_path_1) / (1024 * 1024), 2)], + "num_gaussians_1": [_count_gaussians(ply_path_1)], + "ply_file_2": [fn2], + "ply_type_2": [kind2], + "ply_subfolder_2": [sub2], + "file_size_mb_2": [round(os.path.getsize(ply_path_2) / (1024 * 1024), 2)], + "num_gaussians_2": [_count_gaussians(ply_path_2)], + "layout": [layout], + "fov_degrees": [fov_degrees], + "renderer": [renderer], + "transport_format": [transport_format], + }} diff --git a/nodes/preview_gaussian_spectate.py b/nodes/preview_gaussian_spectate.py index 1b48651..3a08f34 100644 --- a/nodes/preview_gaussian_spectate.py +++ b/nodes/preview_gaussian_spectate.py @@ -48,12 +48,6 @@ class PreviewGaussianSpectate: "from PreviewGaussians' 50." ), }), - "image_width": ("INT", { - "default": 768, "min": 64, "max": 4096, "step": 8, - }), - "image_height": ("INT", { - "default": 512, "min": 64, "max": 4096, "step": 8, - }), "move_speed": ("FLOAT", { "default": 2.0, "min": 0.05, "max": 50.0, "step": 0.05, "tooltip": ( @@ -62,12 +56,12 @@ class PreviewGaussianSpectate: "scroll the mouse wheel. Shift = 3x boost." ), }), - "renderer": (["spark", "playcanvas"], { - "default": "spark", + "renderer": (["playcanvas", "spark"], { + "default": "playcanvas", "tooltip": ( - "spark — Three.js + WebGL2, all formats. " - "playcanvas — WebGPU adapter (falls back to spark " - "for now)." + "playcanvas — PlayCanvas Engine v2.19 GSplat. " + "WebGPU when available, WebGL2 fallback. " + "spark — Three.js + WebGL2, all formats." ), }), "transport_format": (["ply", "spz"], { @@ -86,7 +80,7 @@ class PreviewGaussianSpectate: FUNCTION = "preview" CATEGORY = "viewer" - def preview(self, ply_path, fov_degrees, image_width, image_height, + def preview(self, ply_path, fov_degrees, move_speed, renderer, transport_format="ply"): if not ply_path: return {"ui": {"error": ["No PLY path provided"]}} @@ -97,7 +91,6 @@ class PreviewGaussianSpectate: file_size_mb = round(os.path.getsize(ply_path) / (1024 * 1024), 2) num_gaussians = _count_gaussians(ply_path) - intrinsics = get_default_intrinsics(image_width, image_height, fov_degrees) extrinsics = get_default_extrinsics() return {"ui": { @@ -108,7 +101,7 @@ class PreviewGaussianSpectate: "file_size_mb": [file_size_mb], "num_gaussians": [num_gaussians], "extrinsics": [extrinsics], - "intrinsics": [intrinsics], + "intrinsics": [None], "fov_degrees": [fov_degrees], "renderer": [renderer], "transport_format": [transport_format], diff --git a/web/js/gaussian_preview.js b/web/js/gaussian_preview.js index 9ad9844..d278e25 100644 --- a/web/js/gaussian_preview.js +++ b/web/js/gaussian_preview.js @@ -203,7 +203,7 @@ app.registerExtension({ // immediately + wrap each widget's callback to keep the // mirror up to date. const TRACKED = new Set([ - "fov_degrees", "image_width", "image_height", + "fov_degrees", "renderer", "transport_format", ]); this.properties = this.properties || {}; @@ -490,11 +490,15 @@ app.registerExtension({ const plyType = message.ply_type?.[0] || "output"; const plySubfolder = message.ply_subfolder?.[0] || ""; - // Resize node to match image aspect ratio from intrinsics + // Resize node to match image aspect ratio from intrinsics. + // When width/height are 0 (auto), keep the current node + // size and let the viewer fill whatever space is available. if (intrinsics && intrinsics[0] && intrinsics[1]) { const imageWidth = intrinsics[0][2] * 2; // cx * 2 const imageHeight = intrinsics[1][2] * 2; // cy * 2 - this.resizeToAspectRatio(imageWidth, imageHeight); + if (imageWidth > 0 && imageHeight > 0) { + this.resizeToAspectRatio(imageWidth, imageHeight); + } } // Spectate mode: forward the move_speed slider to the @@ -649,5 +653,169 @@ app.registerExtension({ return r; }; } + + // ============================================================== + // Preview Gaussian Dual — side-by-side / slider comparison + // ============================================================== + if (nodeData.name === "PreviewGaussianDual") { + console.log("[GaussianPack] Registering Preview Gaussian Dual node"); + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + const node = this; + + const container = document.createElement("div"); + container.style.cssText = "width:100%;height:100%;display:flex;flex-direction:column;background:#1a1a1a;overflow:hidden;position:relative;"; + + // Loading bar + const loadBar = document.createElement("div"); + loadBar.style.cssText = "position:absolute;top:0;left:0;right:0;height:4px;background:rgba(0,0,0,0.35);z-index:100;transition:opacity 0.3s;pointer-events:none;opacity:0;"; + const loadFill = document.createElement("div"); + loadFill.style.cssText = "height:100%;width:0%;background:linear-gradient(90deg,#3a8,#6c6);transition:width 0.15s;"; + loadBar.appendChild(loadFill); + + const iframe = document.createElement("iframe"); + iframe.style.cssText = "width:100%;flex:1 1 0;min-height:0;border:none;background:#1a1a1a;"; + + const infoPanel = document.createElement("div"); + infoPanel.style.cssText = "background:#1a1a1a;border-top:1px solid #444;padding:6px 12px;font:10px monospace;color:#ccc;line-height:1.3;flex-shrink:0;overflow:hidden;"; + infoPanel.innerHTML = 'Dual view info will appear after execution'; + + container.appendChild(iframe); + container.appendChild(infoPanel); + container.appendChild(loadBar); + + const widget = this.addDOMWidget("preview_gaussian_dual", "GAUSSIAN_DUAL_PREVIEW", container, { serialize: false }); + let currentNodeSize = [768, 500]; + widget.computeSize = () => currentNodeSize; + + this.gaussianDualIframe = iframe; + this.gaussianDualInfoPanel = infoPanel; + this.setSize([768, 500]); + + let iframeLoaded = false; + iframe.addEventListener('load', () => { iframeLoaded = true; }); + + // Camera state persistence + this.properties = this.properties || {}; + window.addEventListener('message', (event) => { + if (event.source !== iframe.contentWindow) return; + if (event.data?.type === "CAMERA_STATE" && event.data.state) { + node.properties["Camera Config"] = { + cameraType: "perspective", + state: JSON.stringify(event.data.state), + }; + } + if (event.data?.type === "MESH_LOADED") { + loadBar.style.opacity = "0"; + const saved = node.properties["Camera Config"]; + if (saved?.state && iframe.contentWindow) { + try { + iframe.contentWindow.postMessage({ + type: "RESTORE_CAMERA_STATE", + state: JSON.parse(saved.state), + }, "*"); + } catch(_) {} + } + } + if (event.data?.type === "MESH_ERROR") { + loadFill.style.background = "#c44"; + loadFill.style.width = "100%"; + } + }); + + const onExecuted = this.onExecuted; + this.onExecuted = function(message) { + onExecuted?.apply(this, arguments); + if (message?.error?.[0]) { + infoPanel.innerHTML = `
Error: ${message.error[0]}
`; + return; + } + if (!message?.ply_file_1?.[0] || !message?.ply_file_2?.[0]) return; + + const layout = message.layout?.[0] || "side_by_side"; + const renderer = message.renderer?.[0] || "playcanvas"; + const transport = message.transport_format?.[0] || "ply"; + const fov = message.fov_degrees?.[0] || 50; + + // Set iframe src with layout param + iframe.src = `/extensions/${EXTENSION_FOLDER}/viewer_gaussian_dual.html?layout=${layout}&v=${Date.now()}`; + + // Resize node for dual view + currentNodeSize = layout === "side_by_side" ? [768, 500] : [512, 580]; + node.setSize(currentNodeSize); + node.setDirtyCanvas(true, true); + + // Build URLs for both PLYs + function buildUrl(filename, type, subfolder) { + const qsType = encodeURIComponent(type); + const qsSub = encodeURIComponent(subfolder); + if (transport === "spz") { + return `/gaussianpack/spz?filename=${encodeURIComponent(filename)}&type=${qsType}&subfolder=${qsSub}`; + } + return `/view?filename=${encodeURIComponent(filename)}&type=${qsType}&subfolder=${qsSub}`; + } + + const url1 = buildUrl(message.ply_file_1[0], message.ply_type_1?.[0] || "output", message.ply_subfolder_1?.[0] || ""); + const url2 = buildUrl(message.ply_file_2[0], message.ply_type_2?.[0] || "output", message.ply_subfolder_2?.[0] || ""); + const fn1 = transport === "spz" ? message.ply_file_1[0].replace(/\.ply$/i, ".spz") : message.ply_file_1[0]; + const fn2 = transport === "spz" ? message.ply_file_2[0].replace(/\.ply$/i, ".spz") : message.ply_file_2[0]; + + // Info panel + const n1 = message.num_gaussians_1?.[0] || 0; + const n2 = message.num_gaussians_2?.[0] || 0; + const s1 = message.file_size_mb_1?.[0] || '?'; + const s2 = message.file_size_mb_2?.[0] || '?'; + infoPanel.innerHTML = ` +
+
G1: ${message.ply_file_1[0]} (${s1} MB, ${n1.toLocaleString()} splats)
+
G2: ${message.ply_file_2[0]} (${s2} MB, ${n2.toLocaleString()} splats)
+
`; + + // Fetch both PLYs and send to iframe + loadFill.style.background = "linear-gradient(90deg,#3a8,#6c6)"; + loadFill.style.width = "0%"; + loadBar.style.opacity = "1"; + + const fetchAndSend = async () => { + if (!iframe.contentWindow) { setTimeout(fetchAndSend, 300); return; } + try { + loadFill.style.width = "10%"; + const [resp1, resp2] = await Promise.all([fetch(url1), fetch(url2)]); + if (!resp1.ok) throw new Error(`G1 fetch failed: ${resp1.status}`); + if (!resp2.ok) throw new Error(`G2 fetch failed: ${resp2.status}`); + loadFill.style.width = "50%"; + const [ab1, ab2] = await Promise.all([resp1.arrayBuffer(), resp2.arrayBuffer()]); + loadFill.style.width = "90%"; + + iframe.contentWindow.postMessage({ + type: "LOAD_DUAL_GAUSSIAN", + data1: ab1, data2: ab2, + filename1: fn1, filename2: fn2, + renderer: renderer, + fov: fov, + timestamp: Date.now(), + }, "*", [ab1, ab2]); + loadFill.style.width = "100%"; + } catch (err) { + infoPanel.innerHTML = `
Error: ${err.message}
`; + loadFill.style.background = "#c44"; + loadFill.style.width = "100%"; + } + }; + + if (iframeLoaded) { + // iframe was already loaded from a previous execution — reload it + iframeLoaded = false; + iframe.addEventListener('load', () => { iframeLoaded = true; fetchAndSend(); }, { once: true }); + } else { + iframe.addEventListener('load', () => { iframeLoaded = true; fetchAndSend(); }, { once: true }); + } + }; + + return r; + }; + } } }); diff --git a/web/js/playcanvas.min.js b/web/js/playcanvas.min.js index 59c4dd9..a5aac1e 100644 --- a/web/js/playcanvas.min.js +++ b/web/js/playcanvas.min.js @@ -1,94 +1,105 @@ /** * @license - * PlayCanvas Engine v2.18.1 revision 5e45104 (RELEASE) + * PlayCanvas Engine v2.19.4 revision d999442 (RELEASE) * Copyright 2011-2026 PlayCanvas Ltd. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ -var e,t;e=this,t=function(e){let t,i,s,r,a,n,o,l,h,c,d,u,f,p,m,_,g,v,S,y,x;var T="u">typeof document?document.currentScript:null;let E="GpuTimings",w="2.18.1",b="5e45104";function C(e,t){for(let i in t){let s=t[i];Array.isArray(s)?e[i]=C([],s):s&&"object"==typeof s?e[i]=C({},s):e[i]=s;}return e}let A={create:()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return ("x"===e?t:3&t|8).toString(16)})},P={delimiter:"/",join(...e){let t=e[0];for(let i=0;i0){a=a.slice(0,a.length-2);continue}e>0&&a.push(P.delimiter),a.push(s[e]);}return r=a.join(""),t||r[0]!==P.delimiter||(r=r.slice(1)),i&&r[r.length-1]!==P.delimiter&&(r+=P.delimiter),r},split(e){let t=e.lastIndexOf(P.delimiter);return -1!==t?[e.substring(0,t),e.substring(t+1)]:["",e]},getBasename:e=>P.split(e)[1],getDirectory:e=>P.split(e)[0],getExtension(e){let t=e.split("?")[0].split(".").pop();return t!==e?`.${t}`:""},isRelativePath:e=>"/"!==e.charAt(0)&&null===e.match(/:\/\//),extractPath(e){let t="",i=e.split("/"),s=0;if(i.length>1)if(P.isRelativePath(e))if("."===i[0])for(s=0;stypeof navigator?navigator.userAgent:"",D="u">typeof window?"browser":"u">typeof global?"node":"worker",R=/android/i.test(I)?"android":/ip(?:[ao]d|hone)/i.test(I)?"ios":/windows/i.test(I)?"windows":/mac os/i.test(I)?"osx":/linux/i.test(I)?"linux":/cros/i.test(I)?"cros":null,L="browser"!==D?null:/Chrome\/|Chromium\/|Edg.*\//.test(I)?"chrome":/Safari\//.test(I)?"safari":/Firefox\//.test(I)?"firefox":"other",M=/xbox/i.test(I),O="browser"===D&&("ontouchstart"in window||"maxTouchPoints"in navigator&&navigator.maxTouchPoints>0),F="browser"===D&&(!!navigator.getGamepads||!!navigator.webkitGetGamepads),N="u">typeof Worker,B=(()=>{let e=false;try{let t=Object.defineProperty({},"passive",{get:function(){return e=!0,!1}});window.addEventListener("testpassive",null,t),window.removeEventListener("testpassive",null,t);}catch(e){}return e})(),k={name:R,environment:D,global:("u">typeof globalThis&&globalThis)??("browser"===D&&window)??("node"===D&&global)??("worker"===D&&self),browser:"browser"===D,worker:"worker"===D,desktop:["windows","osx","linux","cros"].includes(R),mobile:["android","ios"].includes(R),ios:"ios"===R,android:"android"===R,xbox:M,gamepads:F,touch:O,workers:N,passiveEvents:B,browserName:L},U="abcdefghijklmnopqrstuvwxyz",z="ABCDEFGHIJKLMNOPQRSTUVWXYZ";function V(e,t=0){let i=e.length;if(t<0||t>=i)return null;let s=e.charCodeAt(t);if(i>1&&s>=55296&&s<=56319){let i=e.charCodeAt(t+1);if(i>=56320&&i<=57343)return {code:(s-55296)*1024+i-56320+65536,long:true}}return {code:s,long:false}}function G(e,t,i){if(!e)return false;let s=V(e);if(s){let e=s.code;return e>=t&&e<=i}return false}let H={ASCII_LOWERCASE:U,ASCII_UPPERCASE:z,ASCII_LETTERS:U+z,format(e,...t){for(let i=0;ie.map(e=>e>65535?String.fromCharCode(((e-=65536)>>10)+55296,e%1024+56320):String.fromCharCode(e)).join("")};class W{off(){this._removed||this.handler.offByHandle(this);}on(e,t,i=this){return this.handler._addCallback(e,t,i,false)}once(e,t,i=this){return this.handler._addCallback(e,t,i,true)}set removed(e){e&&(this._removed=true);}get removed(){return this._removed}toJSON(e){}constructor(e,t,i,s,r=false){this._removed=false,this.handler=e,this.name=t,this.callback=i,this.scope=s,this._once=r;}}class X{initEventHandler(){this._callbacks=new Map,this._callbackActive=new Map;}_addCallback(e,t,i,s){if(this._callbacks.has(e)||this._callbacks.set(e,[]),this._callbackActive.has(e)){let t=this._callbackActive.get(e);t&&t===this._callbacks.get(e)&&this._callbackActive.set(e,t.slice());}let r=new W(this,e,t,i,s);return this._callbacks.get(e).push(r),r}on(e,t,i=this){return this._addCallback(e,t,i,false)}once(e,t,i=this){return this._addCallback(e,t,i,true)}off(e,t,i){if(e)this._callbackActive.has(e)&&this._callbackActive.get(e)===this._callbacks.get(e)&&this._callbackActive.set(e,this._callbackActive.get(e).slice());else for(let[e,t]of this._callbackActive)this._callbacks.has(e)&&this._callbacks.get(e)===t&&this._callbackActive.set(e,t.slice());if(e)if(t){let s=this._callbacks.get(e);if(!s)return this;for(let e=0;et&&(this._index[e]=i-1);}return true}return false}list(){return this._list}clear(){for(let e in this._list.length=0,this._index)delete this._index[e];}constructor(){this._list=[],this._index={};}}class q{static loadScript(e,t){let i=document.createElement("script");i.setAttribute("src",e),i.onload=()=>{t(null);},i.onerror=()=>{t(`Failed to load script='${e}'`);},document.body.appendChild(i);}static loadWasm(e,t,i){let s=q.wasmSupported()&&t.glueUrl&&t.wasmUrl?t.glueUrl:t.fallbackUrl;s?q.loadScript(s,s=>{if(s)i(s,null);else {let s=window[e];window[e]=void 0,s({locateFile:()=>t.wasmUrl,onAbort:()=>{i("wasm module aborted.");}}).then(e=>{i(null,e);});}}):i("No supported wasm modules found.",null);}static getModule(e){return q.modules.hasOwnProperty(e)||(q.modules[e]={config:null,initializing:false,instance:null,callbacks:[]}),q.modules[e]}static initialize(e,t){if(t.initializing)return;let i=t.config;(i.glueUrl||i.wasmUrl||i.fallbackUrl)&&(t.initializing=true,q.loadWasm(e,i,(e,s)=>{e?i.errorHandler&&i.errorHandler(e):(t.instance=s,t.callbacks.forEach(e=>{e(s);}));}));}}q.modules={},y=S={},q.wasmSupported=()=>(y===S&&(y=(()=>{try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){let e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}return false})()),y);class j{static setConfig(e,t){let i=q.getModule(e);i.config=t,i.callbacks.length>0&&q.initialize(e,i);}static getConfig(e){return q.modules?.[e]?.config}static getInstance(e,t){let i=q.getModule(e);i.instance?t(i.instance):(i.callbacks.push(t),i.config&&q.initialize(e,i));}}class K{get remainingBytes(){return this.dataView.byteLength-this.offset}reset(e=0){this.offset=e;}skip(e){this.offset+=e;}align(e){this.offset=this.offset+e-1&~(e-1);}_inc(e){return this.offset+=e,this.offset-e}readChar(){return String.fromCharCode(this.dataView.getUint8(this.offset++))}readChars(e){let t="";for(let i=0;i=e.byteLength);){let e=String.fromCharCode(this.readU8());if("\n"===e)break;t+=e;}return t}constructor(e){this.offset=0,this.arraybuffer=e,this.dataView=new DataView(e);}}class ${_binarySearch(e){let t,i,s=0,r=this.items.length-1,a=e[this._sortBy];for(;s<=r;)t=Math.floor((s+r)/2),(i=this.items[t][this._sortBy])<=a?s=t+1:i>a&&(r=t-1);return s}_doSort(e,t){let i=this._sortBy;return e[i]-t[i]}insert(e){let t=this._binarySearch(e);this.items.splice(t,0,e),this.length++,this.loopIndex>=t&&this.loopIndex++;}append(e){this.items.push(e),this.length++;}remove(e){let t=this.items.indexOf(e);!(t<0)&&(this.items.splice(t,1),this.length--,this.loopIndex>=t&&this.loopIndex--);}sort(){let e=this.loopIndex>=0?this.items[this.loopIndex]:null;this.items.sort(this._sortHandler),null!==e&&(this.loopIndex=this.items.indexOf(e));}constructor(e){this.items=[],this.length=0,this.loopIndex=-1,this._sortBy=e.sortBy,this._sortHandler=this._doSort.bind(this);}}class Z extends X{add(...e){let t=false,i=this._processArguments(e,true);if(!i.length)return t;for(let e=0;etypeof window&&window.performance&&window.performance.now?performance.now.bind(performance):Date.now,J=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class ee{toString(){let e="";return this.scheme&&(e+=`${this.scheme}:`),this.authority&&(e+=`//${this.authority}`),e+=this.path,this.query&&(e+=`?${this.query}`),this.fragment&&(e+=`#${this.fragment}`),e}getQuery(){let e={};if(this.query)for(let t of decodeURIComponent(this.query).split("&")){let i=t.split("=");e[i[0]]=i[1];}return e}setQuery(e){let t="";for(let i in e)e.hasOwnProperty(i)&&(""!==t&&(t+="&"),t+=`${encodeURIComponent(i)}=${encodeURIComponent(e[i])}`);this.query=t;}constructor(e){let t=e.match(J);this.scheme=t[2],this.authority=t[4],this.path=t[5],this.query=t[7],this.fragment=t[9];}}class et{static set(e,t=true){}static get(e){return et._traceChannels.has(e)}}et._traceChannels=new Set,et.stack=false;let ei={DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,clamp:(e,t,i)=>e>=i?i:e<=t?t:e,intToBytes24:e=>[e>>16&255,e>>8&255,255&e],intToBytes32:e=>[e>>24&255,e>>16&255,e>>8&255,255&e],bytesToInt24:(e,t,i)=>(e.length&&(i=e[2],t=e[1],e=e[0]),e<<16|t<<8|i),bytesToInt32:(e,t,i,s)=>(e.length&&(s=e[3],i=e[2],t=e[1],e=e[0]),(e<<24|t<<16|i<<8|s)>>>0),lerp:(e,t,i)=>e+(t-e)*ei.clamp(i,0,1),lerpAngle:(e,t,i)=>(t-e>180&&(t-=360),t-e<-180&&(t+=360),ei.lerp(e,t,ei.clamp(i,0,1))),powerOfTwo:e=>0!==e&&!(e&e-1),nextPowerOfTwo:e=>(e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e),nearestPowerOfTwo:e=>Math.pow(2,Math.round(Math.log2(e))),random:(e,t)=>Math.random()*(t-e)+e,smoothstep:(e,t,i)=>i<=e?0:i>=t?1:(i=(i-e)/(t-e))*i*(3-2*i),smootherstep:(e,t,i)=>i<=e?0:i>=t?1:(i=(i-e)/(t-e))*i*i*(i*(6*i-15)+10),roundUp:(e,t)=>0===t?e:Math.ceil(e/t)*t,between(e,t,i,s){let r=Math.min(t,i),a=Math.max(t,i);return s?e>=r&&e<=a:e>r&&e7?t=ei.intToBytes32(i):(t=ei.intToBytes24(i))[3]=255,this.set(t[0]/255,t[1]/255,t[2]/255,t[3]/255),this}fromArray(e,t=0){return this.r=e[t]??this.r,this.g=e[t+1]??this.g,this.b=e[t+2]??this.b,this.a=e[t+3]??this.a,this}toString(e,t){let{r:i,g:s,b:r,a}=this;if(t||i>1||s>1||r>1)return `${i.toFixed(3)}, ${s.toFixed(3)}, ${r.toFixed(3)}, ${a.toFixed(3)}`;let n=`#${(0x1000000+(Math.round(255*i)<<16)+(Math.round(255*s)<<8)+Math.round(255*r)).toString(16).slice(1)}`;if(true===e){let e=Math.round(255*a).toString(16);this.a<16/255?n+=`0${e}`:n+=e;}return n}toArray(e=[],t=0,i=true){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,i&&(e[t+3]=this.a),e}constructor(e=0,t=0,i=0,s=1){let r=e.length;3===r||4===r?(this.r=e[0],this.g=e[1],this.b=e[2],this.a=e[3]??1):(this.r=e,this.g=t,this.b=i,this.a=s);}}es.BLACK=Object.freeze(new es(0,0,0,1)),es.BLUE=Object.freeze(new es(0,0,1,1)),es.CYAN=Object.freeze(new es(0,1,1,1)),es.GRAY=Object.freeze(new es(.5,.5,.5,1)),es.GREEN=Object.freeze(new es(0,1,0,1)),es.MAGENTA=Object.freeze(new es(1,0,1,1)),es.RED=Object.freeze(new es(1,0,0,1)),es.WHITE=Object.freeze(new es(1,1,1,1)),es.YELLOW=Object.freeze(new es(1,1,0,1));class er{evaluate(e,t=false){let i;(t||e=this._right)&&this._reset(e);let s=this._curve.type;if(5===s)i=this._p0;else {let t=0===this._recip?0:(e-this._left)*this._recip;i=0===s?ei.lerp(this._p0,this._p1,t):1===s?ei.lerp(this._p0,this._p1,t*t*(3-2*t)):this._evaluateHermite(this._p0,this._p1,this._m0,this._m1,t);}return i}_reset(e){let t=this._curve.keys,i=t.length;if(i)if(e=t[i-1][0])this._left=t[i-1][0],this._right=1/0,this._recip=0,this._p0=this._p1=t[i-1][1],this._m0=this._m1=0;else {let i=0;for(;e>=t[i+1][0];)i++;this._left=t[i][0],this._right=t[i+1][0];let s=1/(this._right-this._left);this._recip=isFinite(s)?s:0,this._p0=t[i][1],this._p1=t[i+1][1],4===this._curve.type&&this._calcTangents(t,i);}else this._left=-1/0,this._right=1/0,this._recip=0,this._p0=this._p1=this._m0=this._m1=0;}_calcTangents(e,t){let i,s,r=e[t],a=e[t+1];if(i=0===t?[e[0][0]+(e[0][0]-e[1][0]),e[0][1]+(e[0][1]-e[1][1])]:e[t-1],s=t===e.length-2?[e[t+1][0]+(e[t+1][0]-e[t][0]),e[t+1][1]+(e[t+1][1]-e[t][1])]:e[t+2],4===this._curve.type){let e=2*(a[0]-r[0])/(a[0]-i[0]),t=2*(a[0]-r[0])/(s[0]-r[0]);this._m0=this._curve.tension*(isFinite(e)?e:0)*(a[1]-i[1]),this._m1=this._curve.tension*(isFinite(t)?t:0)*(s[1]-r[1]);}else {let e=(a[0]-r[0])/(r[0]-i[0]),t=(a[0]-r[0])/(s[0]-a[0]),n=r[1]+(i[1]-r[1])*(isFinite(e)?e:0),o=a[1]+(s[1]-a[1])*(isFinite(t)?t:0),l=this._curve.tension;this._m0=l*(a[1]-n),this._m1=l*(o-r[1]);}}_evaluateHermite(e,t,i,s,r){let a=r*r,n=r+r,o=1-r,l=o*o;return (1+n)*l*e+r*l*i+a*(3-n)*t+a*(r-1)*s}constructor(e,t=0){this._left=-1/0,this._right=1/0,this._recip=0,this._p0=0,this._p1=0,this._m0=0,this._m1=0,this._curve=e,this._reset(t);}}class ea{get length(){return this.keys.length}add(e,t){let i=this.keys,s=i.length,r=0;for(;re);r++);let a=[e,t];return this.keys.splice(r,0,a),a}get(e){return this.keys[e]}sort(){this.keys.sort((e,t)=>e[0]-t[0]);}value(e){return this._eval.evaluate(e,true)}closest(e){let t=this.keys,i=t.length,s=2,r=null;for(let a=0;a=i)s=i,r=t[a];else break}return r}clone(){let e=new this.constructor;return e.keys=this.keys.map(e=>[...e]),e.type=this.type,e.tension=this.tension,e}quantize(e){let t=new Float32Array(e=Math.max(e,2)),i=1/(e-1);t[0]=this._eval.evaluate(0,true);for(let s=1;s1)for(let t=0;t>16&32768,s=t>>12&2047,r=t>>23&255;return r<103?i:r>142?(i|=31744,i|=+(255!==r)&&8388607&t):r<113?(s|=2048,i|=(s>>114-r)+(s>>113-r&1)):(i|=r-112<<10|s>>1,i+=1&s)}static float2RGBA8(e,t){eo[0]=e;let i=el[0];t.r=(i>>24&255)/255,t.g=(i>>16&255)/255,t.b=(i>>8&255)/255,t.a=(255&i)/255;}}class ec{static concentric(e,t){let i=[];i.push(0,0);let s=2*Math.PI/e/t;for(let t=1;t<=e;t++){let r=t/e,a=Math.max(1,Math.floor(2*Math.PI*r/s)),n=2*Math.PI/a;for(let e=0;e0){let i=1/Math.sqrt(t);this.x=e.x*i,this.y=e.y*i,this.z=e.z*i;}return this}floor(e=this){return this.x=Math.floor(e.x),this.y=Math.floor(e.y),this.z=Math.floor(e.z),this}ceil(e=this){return this.x=Math.ceil(e.x),this.y=Math.ceil(e.y),this.z=Math.ceil(e.z),this}round(e=this){return this.x=Math.round(e.x),this.y=Math.round(e.y),this.z=Math.round(e.z),this}min(e){return e.xthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),this}project(e){let t=(this.x*e.x+this.y*e.y+this.z*e.z)/(e.x*e.x+e.y*e.y+e.z*e.z);return this.x=e.x*t,this.y=e.y*t,this.z=e.z*t,this}set(e,t,i){return this.x=e,this.y=t,this.z=i,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}sub2(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}fromArray(e,t=0){return this.x=e[t]??this.x,this.y=e[t+1]??this.y,this.z=e[t+2]??this.z,this}toString(){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,e}constructor(e=0,t=0,i=0){3===e.length?(this.x=e[0],this.y=e[1],this.z=e[2]):(this.x=e,this.y=t,this.z=i);}}ed.ZERO=Object.freeze(new ed(0,0,0)),ed.HALF=Object.freeze(new ed(.5,.5,.5)),ed.ONE=Object.freeze(new ed(1,1,1)),ed.UP=Object.freeze(new ed(0,1,0)),ed.DOWN=Object.freeze(new ed(0,-1,0)),ed.RIGHT=Object.freeze(new ed(1,0,0)),ed.LEFT=Object.freeze(new ed(-1,0,0)),ed.FORWARD=Object.freeze(new ed(0,0,-1)),ed.BACK=Object.freeze(new ed(0,0,1));class eu{clone(){return new this.constructor().copy(this)}copy(e){let t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],this}set(e){let t=this.data;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],this}getX(e=new ed){return e.set(this.data[0],this.data[1],this.data[2])}getY(e=new ed){return e.set(this.data[3],this.data[4],this.data[5])}getZ(e=new ed){return e.set(this.data[6],this.data[7],this.data[8])}equals(e){let t=this.data,i=e.data;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]}isIdentity(){let e=this.data;return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&1===e[4]&&0===e[5]&&0===e[6]&&0===e[7]&&1===e[8]}setIdentity(){let e=this.data;return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,this}toString(){return `[${this.data.join(", ")}]`}transpose(e=this){let t=e.data,i=this.data;if(t===i){let e;e=t[1],i[1]=t[3],i[3]=e,e=t[2],i[2]=t[6],i[6]=e,e=t[5],i[5]=t[7],i[7]=e;}else i[0]=t[0],i[1]=t[3],i[2]=t[6],i[3]=t[1],i[4]=t[4],i[5]=t[7],i[6]=t[2],i[7]=t[5],i[8]=t[8];return this}setFromMat4(e){let t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[4],i[4]=t[5],i[5]=t[6],i[6]=t[8],i[7]=t[9],i[8]=t[10],this}setFromQuat(e){let t=e.x,i=e.y,s=e.z,r=e.w,a=t+t,n=i+i,o=s+s,l=t*a,h=t*n,c=t*o,d=i*n,u=i*o,f=s*o,p=r*a,m=r*n,_=r*o,g=this.data;return g[0]=1-(d+f),g[1]=h+_,g[2]=c-m,g[3]=h-_,g[4]=1-(l+f),g[5]=u+p,g[6]=c+m,g[7]=u-p,g[8]=1-(l+d),this}invertMat4(e){let t=e.data,i=t[0],s=t[1],r=t[2],a=t[4],n=t[5],o=t[6],l=t[8],h=t[9],c=t[10],d=c*n-o*h,u=-c*a+o*l,f=h*a-n*l,p=i*d+s*u+r*f;if(0===p)this.setIdentity();else {let e=1/p,t=this.data;t[0]=d*e,t[1]=(-c*s+r*h)*e,t[2]=(o*s-r*n)*e,t[3]=u*e,t[4]=(c*i-r*l)*e,t[5]=(-o*i+r*a)*e,t[6]=f*e,t[7]=(-h*i+s*l)*e,t[8]=(n*i-s*a)*e;}return this}transformVector(e,t=new ed){let i=this.data,{x:s,y:r,z:a}=e;return t.x=s*i[0]+r*i[3]+a*i[6],t.y=s*i[1]+r*i[4]+a*i[7],t.z=s*i[2]+r*i[5]+a*i[8],t}constructor(){this.data=new Float32Array(9),this.data[0]=this.data[4]=this.data[8]=1;}}eu.IDENTITY=Object.freeze(new eu),eu.ZERO=Object.freeze(new eu().set([0,0,0,0,0,0,0,0,0]));class ef{add(e){return this.x+=e.x,this.y+=e.y,this}add2(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addScaled(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}cross(e){return this.x*e.y-this.y*e.x}distance(e){let t=this.x-e.x,i=this.y-e.y;return Math.sqrt(t*t+i*i)}div(e){return this.x/=e.x,this.y/=e.y,this}div2(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this}divScalar(e){return this.x/=e,this.y/=e,this}dot(e){return this.x*e.x+this.y*e.y}equals(e){return this.x===e.x&&this.y===e.y}equalsApprox(e,t=1e-6){return Math.abs(this.x-e.x)0){let i=1/Math.sqrt(t);this.x=e.x*i,this.y=e.y*i;}return this}rotate(e){let t=Math.atan2(this.x,this.y)+e*ei.DEG_TO_RAD,i=Math.sqrt(this.x*this.x+this.y*this.y);return this.x=Math.sin(t)*i,this.y=Math.cos(t)*i,this}angle(){return Math.atan2(this.x,this.y)*ei.RAD_TO_DEG}angleTo(e){return Math.atan2(this.x*e.y+this.y*e.x,this.x*e.x+this.y*e.y)*ei.RAD_TO_DEG}floor(e=this){return this.x=Math.floor(e.x),this.y=Math.floor(e.y),this}ceil(e=this){return this.x=Math.ceil(e.x),this.y=Math.ceil(e.y),this}round(e=this){return this.x=Math.round(e.x),this.y=Math.round(e.y),this}min(e){return e.xthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),this}set(e,t){return this.x=e,this.y=t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}sub2(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}subScalar(e){return this.x-=e,this.y-=e,this}fromArray(e,t=0){return this.x=e[t]??this.x,this.y=e[t+1]??this.y,this}toString(){return `[${this.x}, ${this.y}]`}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}static angleRad(e,t){return Math.atan2(e.x*t.y-e.y*t.x,e.x*t.x+e.y*t.y)}constructor(e=0,t=0){2===e.length?(this.x=e[0],this.y=e[1]):(this.x=e,this.y=t);}}ef.ZERO=Object.freeze(new ef(0,0)),ef.HALF=Object.freeze(new ef(.5,.5)),ef.ONE=Object.freeze(new ef(1,1)),ef.UP=Object.freeze(new ef(0,1)),ef.DOWN=Object.freeze(new ef(0,-1)),ef.RIGHT=Object.freeze(new ef(1,0)),ef.LEFT=Object.freeze(new ef(-1,0));class ep{add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}add2(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}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addScaled(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,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}div(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}div2(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}divScalar(e){return this.x/=e,this.y/=e,this.z/=e,this.w/=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}equals(e){return this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w}equalsApprox(e,t=1e-6){return Math.abs(this.x-e.x)0){let i=1/Math.sqrt(t);this.x=e.x*i,this.y=e.y*i,this.z=e.z*i,this.w=e.w*i;}return this}floor(e=this){return this.x=Math.floor(e.x),this.y=Math.floor(e.y),this.z=Math.floor(e.z),this.w=Math.floor(e.w),this}ceil(e=this){return this.x=Math.ceil(e.x),this.y=Math.ceil(e.y),this.z=Math.ceil(e.z),this.w=Math.ceil(e.w),this}round(e=this){return this.x=Math.round(e.x),this.y=Math.round(e.y),this.z=Math.round(e.z),this.w=Math.round(e.w),this}min(e){return e.xthis.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}set(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}sub2(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}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}fromArray(e,t=0){return this.x=e[t]??this.x,this.y=e[t+1]??this.y,this.z=e[t+2]??this.z,this.w=e[t+3]??this.w,this}toString(){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,e}constructor(e=0,t=0,i=0,s=0){4===e.length?(this.x=e[0],this.y=e[1],this.z=e[2],this.w=e[3]):(this.x=e,this.y=t,this.z=i,this.w=s);}}ep.ZERO=Object.freeze(new ep(0,0,0,0)),ep.HALF=Object.freeze(new ep(.5,.5,.5,.5)),ep.ONE=Object.freeze(new ep(1,1,1,1));let em=new ef,e_=new ed,eg=new ed,ev=new ed,eS=new ed;class ey{static _getPerspectiveHalfSize(e,t,i,s,r){r?(e.x=s*Math.tan(t*Math.PI/360),e.y=e.x/i):(e.y=s*Math.tan(t*Math.PI/360),e.x=e.y*i);}add2(e,t){let i=e.data,s=t.data,r=this.data;return r[0]=i[0]+s[0],r[1]=i[1]+s[1],r[2]=i[2]+s[2],r[3]=i[3]+s[3],r[4]=i[4]+s[4],r[5]=i[5]+s[5],r[6]=i[6]+s[6],r[7]=i[7]+s[7],r[8]=i[8]+s[8],r[9]=i[9]+s[9],r[10]=i[10]+s[10],r[11]=i[11]+s[11],r[12]=i[12]+s[12],r[13]=i[13]+s[13],r[14]=i[14]+s[14],r[15]=i[15]+s[15],this}add(e){return this.add2(this,e)}clone(){return new this.constructor().copy(this)}copy(e){let t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],i[9]=t[9],i[10]=t[10],i[11]=t[11],i[12]=t[12],i[13]=t[13],i[14]=t[14],i[15]=t[15],this}equals(e){let t=this.data,i=e.data;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]}isIdentity(){let e=this.data;return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}mul2(e,t){let i,s,r,a,n=e.data,o=t.data,l=this.data,h=n[0],c=n[1],d=n[2],u=n[3],f=n[4],p=n[5],m=n[6],_=n[7],g=n[8],v=n[9],S=n[10],y=n[11],x=n[12],T=n[13],E=n[14],w=n[15];return i=o[0],s=o[1],r=o[2],a=o[3],l[0]=h*i+f*s+g*r+x*a,l[1]=c*i+p*s+v*r+T*a,l[2]=d*i+m*s+S*r+E*a,l[3]=u*i+_*s+y*r+w*a,i=o[4],s=o[5],r=o[6],a=o[7],l[4]=h*i+f*s+g*r+x*a,l[5]=c*i+p*s+v*r+T*a,l[6]=d*i+m*s+S*r+E*a,l[7]=u*i+_*s+y*r+w*a,i=o[8],s=o[9],r=o[10],a=o[11],l[8]=h*i+f*s+g*r+x*a,l[9]=c*i+p*s+v*r+T*a,l[10]=d*i+m*s+S*r+E*a,l[11]=u*i+_*s+y*r+w*a,i=o[12],s=o[13],r=o[14],a=o[15],l[12]=h*i+f*s+g*r+x*a,l[13]=c*i+p*s+v*r+T*a,l[14]=d*i+m*s+S*r+E*a,l[15]=u*i+_*s+y*r+w*a,this}mulAffine2(e,t){let i,s,r,a=e.data,n=t.data,o=this.data,l=a[0],h=a[1],c=a[2],d=a[4],u=a[5],f=a[6],p=a[8],m=a[9],_=a[10],g=a[12],v=a[13],S=a[14];return i=n[0],s=n[1],r=n[2],o[0]=l*i+d*s+p*r,o[1]=h*i+u*s+m*r,o[2]=c*i+f*s+_*r,o[3]=0,i=n[4],s=n[5],r=n[6],o[4]=l*i+d*s+p*r,o[5]=h*i+u*s+m*r,o[6]=c*i+f*s+_*r,o[7]=0,i=n[8],s=n[9],r=n[10],o[8]=l*i+d*s+p*r,o[9]=h*i+u*s+m*r,o[10]=c*i+f*s+_*r,o[11]=0,i=n[12],s=n[13],r=n[14],o[12]=l*i+d*s+p*r+g,o[13]=h*i+u*s+m*r+v,o[14]=c*i+f*s+_*r+S,o[15]=1,this}mul(e){return this.mul2(this,e)}transformPoint(e,t=new ed){let i=this.data,{x:s,y:r,z:a}=e;return t.x=s*i[0]+r*i[4]+a*i[8]+i[12],t.y=s*i[1]+r*i[5]+a*i[9]+i[13],t.z=s*i[2]+r*i[6]+a*i[10]+i[14],t}transformVector(e,t=new ed){let i=this.data,{x:s,y:r,z:a}=e;return t.x=s*i[0]+r*i[4]+a*i[8],t.y=s*i[1]+r*i[5]+a*i[9],t.z=s*i[2]+r*i[6]+a*i[10],t}transformVec4(e,t=new ep){let i=this.data,{x:s,y:r,z:a,w:n}=e;return t.x=s*i[0]+r*i[4]+a*i[8]+n*i[12],t.y=s*i[1]+r*i[5]+a*i[9]+n*i[13],t.z=s*i[2]+r*i[6]+a*i[10]+n*i[14],t.w=s*i[3]+r*i[7]+a*i[11]+n*i[15],t}setLookAt(e,t,i){ev.sub2(e,t).normalize(),eg.copy(i).normalize(),e_.cross(eg,ev).normalize(),eg.cross(ev,e_);let s=this.data;return s[0]=e_.x,s[1]=e_.y,s[2]=e_.z,s[3]=0,s[4]=eg.x,s[5]=eg.y,s[6]=eg.z,s[7]=0,s[8]=ev.x,s[9]=ev.y,s[10]=ev.z,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}setFrustum(e,t,i,s,r,a){let n=2*r,o=t-e,l=s-i,h=a-r,c=this.data;return c[0]=n/o,c[1]=0,c[2]=0,c[3]=0,c[4]=0,c[5]=n/l,c[6]=0,c[7]=0,c[8]=(t+e)/o,c[9]=(s+i)/l,c[10]=(-a-r)/h,c[11]=-1,c[12]=0,c[13]=0,c[14]=-n*a/h,c[15]=0,this}setPerspective(e,t,i,s,r){return ey._getPerspectiveHalfSize(em,e,t,i,r),this.setFrustum(-em.x,em.x,-em.y,em.y,i,s)}setOrtho(e,t,i,s,r,a){let n=this.data;return n[0]=2/(t-e),n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/(s-i),n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/(a-r),n[11]=0,n[12]=-(t+e)/(t-e),n[13]=-(s+i)/(s-i),n[14]=-(a+r)/(a-r),n[15]=1,this}setFromAxisAngle(e,t){t*=ei.DEG_TO_RAD;let{x:i,y:s,z:r}=e,a=Math.cos(t),n=Math.sin(t),o=1-a,l=o*i,h=o*s,c=this.data;return c[0]=l*i+a,c[1]=l*s+n*r,c[2]=l*r-n*s,c[3]=0,c[4]=l*s-n*r,c[5]=h*s+a,c[6]=h*r+n*i,c[7]=0,c[8]=l*r+n*s,c[9]=h*r-i*n,c[10]=o*r*r+a,c[11]=0,c[12]=0,c[13]=0,c[14]=0,c[15]=1,this}setTranslate(e,t,i){let s=this.data;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=e,s[13]=t,s[14]=i,s[15]=1,this}setScale(e,t,i){let s=this.data;return s[0]=e,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=t,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=i,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,this}setViewport(e,t,i,s){let r=this.data;return r[0]=.5*i,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=.5*s,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=.5,r[11]=0,r[12]=e+.5*i,r[13]=t+.5*s,r[14]=.5,r[15]=1,this}setReflection(e,t){let i=e.x,s=e.y,r=e.z,a=this.data;return a[0]=1-2*i*i,a[1]=-2*i*s,a[2]=-2*i*r,a[3]=0,a[4]=-2*i*s,a[5]=1-2*s*s,a[6]=-2*s*r,a[7]=0,a[8]=-2*i*r,a[9]=-2*s*r,a[10]=1-2*r*r,a[11]=0,a[12]=-2*i*t,a[13]=-2*s*t,a[14]=-2*r*t,a[15]=1,this}invert(e=this){let t=e.data,i=t[0],s=t[1],r=t[2],a=t[3],n=t[4],o=t[5],l=t[6],h=t[7],c=t[8],d=t[9],u=t[10],f=t[11],p=t[12],m=t[13],_=t[14],g=t[15],v=i*o-s*n,S=i*l-r*n,y=i*h-a*n,x=s*l-r*o,T=s*h-a*o,E=r*h-a*l,w=c*m-d*p,b=c*_-u*p,C=c*g-f*p,A=d*_-u*m,P=d*g-f*m,I=u*g-f*_,D=v*I-S*P+y*A+x*C-T*b+E*w;if(0===D)this.setIdentity();else {let e=1/D,t=this.data;t[0]=(o*I-l*P+h*A)*e,t[1]=(-s*I+r*P-a*A)*e,t[2]=(m*E-_*T+g*x)*e,t[3]=(-d*E+u*T-f*x)*e,t[4]=(-n*I+l*C-h*b)*e,t[5]=(i*I-r*C+a*b)*e,t[6]=(-p*E+_*y-g*S)*e,t[7]=(c*E-u*y+f*S)*e,t[8]=(n*P-o*C+h*w)*e,t[9]=(-i*P+s*C-a*w)*e,t[10]=(p*T-m*y+g*v)*e,t[11]=(-c*T+d*y-f*v)*e,t[12]=(-n*A+o*b-l*w)*e,t[13]=(i*A-s*b+r*w)*e,t[14]=(-p*x+m*S-_*v)*e,t[15]=(c*x-d*S+u*v)*e;}return this}set(e){let t=this.data;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],this}setIdentity(){let e=this.data;return 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,this}setTRS(e,t,i){let s=t.x,r=t.y,a=t.z,n=t.w,o=i.x,l=i.y,h=i.z,c=s+s,d=r+r,u=a+a,f=s*c,p=s*d,m=s*u,_=r*d,g=r*u,v=a*u,S=n*c,y=n*d,x=n*u,T=this.data;return T[0]=(1-(_+v))*o,T[1]=(p+x)*o,T[2]=(m-y)*o,T[3]=0,T[4]=(p-x)*l,T[5]=(1-(f+v))*l,T[6]=(g+S)*l,T[7]=0,T[8]=(m+y)*h,T[9]=(g-S)*h,T[10]=(1-(f+_))*h,T[11]=0,T[12]=e.x,T[13]=e.y,T[14]=e.z,T[15]=1,this}transpose(e=this){let t=e.data,i=this.data;if(t===i){let e;e=t[1],i[1]=t[4],i[4]=e,e=t[2],i[2]=t[8],i[8]=e,e=t[3],i[3]=t[12],i[12]=e,e=t[6],i[6]=t[9],i[9]=e,e=t[7],i[7]=t[13],i[13]=e,e=t[11],i[11]=t[14],i[14]=e;}else i[0]=t[0],i[1]=t[4],i[2]=t[8],i[3]=t[12],i[4]=t[1],i[5]=t[5],i[6]=t[9],i[7]=t[13],i[8]=t[2],i[9]=t[6],i[10]=t[10],i[11]=t[14],i[12]=t[3],i[13]=t[7],i[14]=t[11],i[15]=t[15];return this}getTranslation(e=new ed){return e.set(this.data[12],this.data[13],this.data[14])}getX(e=new ed){return e.set(this.data[0],this.data[1],this.data[2])}getY(e=new ed){return e.set(this.data[4],this.data[5],this.data[6])}getZ(e=new ed){return e.set(this.data[8],this.data[9],this.data[10])}getScale(e=new ed){return this.getX(e_),this.getY(eg),this.getZ(ev),e.set(e_.length(),eg.length(),ev.length()),e}get scaleSign(){return this.getX(e_),this.getY(eg),this.getZ(ev),e_.cross(e_,eg),0>e_.dot(ev)?-1:1}setFromEulerAngles(e,t,i){e*=ei.DEG_TO_RAD,t*=ei.DEG_TO_RAD,i*=ei.DEG_TO_RAD;let s=Math.sin(-e),r=Math.cos(-e),a=Math.sin(-t),n=Math.cos(-t),o=Math.sin(-i),l=Math.cos(-i),h=this.data;return h[0]=n*l,h[1]=-n*o,h[2]=a,h[3]=0,h[4]=r*o+l*s*a,h[5]=r*l-s*a*o,h[6]=-n*s,h[7]=0,h[8]=s*o-r*l*a,h[9]=l*s+r*a*o,h[10]=r*n,h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,this}getEulerAngles(e=new ed){let t,i;this.getScale(eS);let s=eS.x,r=eS.y,a=eS.z;if(0===s||0===r||0===a)return e.set(0,0,0);let n=this.data,o=Math.asin(-n[2]/s),l=.5*Math.PI;return o-l?(t=Math.atan2(n[6]/r,n[10]/a),i=Math.atan2(n[1]/s,n[0]/s)):(i=0,t=-Math.atan2(n[4]/r,n[5]/r)):(i=0,t=Math.atan2(n[4]/r,n[5]/r)),e.set(t,o,i).mulScalar(ei.RAD_TO_DEG)}toString(){return `[${this.data.join(", ")}]`}constructor(){this.data=new Float32Array(16),this.data[0]=this.data[5]=this.data[10]=this.data[15]=1;}}ey.IDENTITY=Object.freeze(new ey),ey.ZERO=Object.freeze(new ey().set([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]));class ex{clone(){return new this.constructor(this.x,this.y,this.z,this.w)}conjugate(e=this){return this.x=-1*e.x,this.y=-1*e.y,this.z=-1*e.z,this.w=e.w,this}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}equals(e){return this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w}equalsApprox(e,t=1e-6){return Math.abs(this.x-e.x)=.99999?(t=2*Math.atan2(r,o),i=Math.PI/2,s=0):(t=Math.atan2(2*(o*r+a*n),1-2*(r*r+a*a)),i=Math.asin(l),s=Math.atan2(2*(o*n+r*a),1-2*(a*a+n*n))),e.set(t,i,s).mulScalar(ei.RAD_TO_DEG)}invert(e=this){return this.conjugate(e).normalize()}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}lerp(e,t,i){let s=(1-i)*(0>e.dot(t)?-1:1);return this.x=e.x*s+t.x*i,this.y=e.y*s+t.y*i,this.z=e.z*s+t.z*i,this.w=e.w*s+t.w*i,this.normalize()}mul(e){let t=this.x,i=this.y,s=this.z,r=this.w,a=e.x,n=e.y,o=e.z,l=e.w;return this.x=r*a+t*l+i*o-s*n,this.y=r*n+i*l+s*a-t*o,this.z=r*o+s*l+t*n-i*a,this.w=r*l-t*a-i*n-s*o,this}mulScalar(e,t=this){return this.x=t.x*e,this.y=t.y*e,this.z=t.z*e,this.w=t.w*e,this}mul2(e,t){let i=e.x,s=e.y,r=e.z,a=e.w,n=t.x,o=t.y,l=t.z,h=t.w;return this.x=a*n+i*h+s*l-r*o,this.y=a*o+s*h+r*n-i*l,this.z=a*l+r*h+i*o-s*n,this.w=a*h-i*n-s*o-r*l,this}normalize(e=this){let t=e.length();return 0===t?(this.x=this.y=this.z=0,this.w=1):(t=1/t,this.x=e.x*t,this.y=e.y*t,this.z=e.z*t,this.w=e.w*t),this}set(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}setFromAxisAngle(e,t){let i=Math.sin(t*=.5*ei.DEG_TO_RAD),s=Math.cos(t);return this.x=i*e.x,this.y=i*e.y,this.z=i*e.z,this.w=s,this}setFromEulerAngles(e,t,i){if(e instanceof ed){let s=e;e=s.x,t=s.y,i=s.z;}let s=.5*ei.DEG_TO_RAD;e*=s,t*=s,i*=s;let r=Math.sin(e),a=Math.cos(e),n=Math.sin(t),o=Math.cos(t),l=Math.sin(i),h=Math.cos(i);return this.x=r*o*h-a*n*l,this.y=a*n*h+r*o*l,this.z=a*o*l-r*n*h,this.w=a*o*h+r*n*l,this}setFromMat4(e){let t,i=e.data,s=i[0],r=i[1],a=i[2],n=i[4],o=i[5],l=i[6],h=i[8],c=i[9],d=i[10];return (s*(o*d-l*c)-r*(n*d-l*h)+a*(n*c-o*h)<0&&(s=-s,r=-r,a=-a),0==(t=s*s+r*r+a*a)||(s*=t=1/Math.sqrt(t),r*=t,a*=t,0==(t=n*n+o*o+l*l)||(n*=t=1/Math.sqrt(t),o*=t,l*=t,0==(t=h*h+c*c+d*d))))?this.set(0,0,0,1):(h*=t=1/Math.sqrt(t),c*=t,(d*=t)<0?s>o?this.set(1+s-o-d,r+n,h+a,l-c):this.set(r+n,1-s+o-d,l+c,h-a):s<-o?this.set(h+a,l+c,1-s-o+d,r-n):this.set(l-c,h-a,r-n,1+s+o+d),this.mulScalar(1/this.length()))}setFromDirections(e,t){let i=1+e.dot(t);return iMath.abs(e.y)?(this.x=-e.z,this.y=0,this.z=e.x):(this.x=0,this.y=-e.z,this.z=e.y),this.w=0):(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()}slerp(e,t,i){let s=e.x,r=e.y,a=e.z,n=e.w,o=t.x,l=t.y,h=t.z,c=t.w,d=n*c+s*o+r*l+a*h;if(d<0&&(c=-c,o=-o,l=-l,h=-h,d=-d),Math.abs(d)>=1)return this.w=n,this.x=s,this.y=r,this.z=a,this;let u=Math.acos(d),f=Math.sqrt(1-d*d);if(.001>Math.abs(f))return this.w=.5*n+.5*c,this.x=.5*s+.5*o,this.y=.5*r+.5*l,this.z=.5*a+.5*h,this;let p=Math.sin((1-i)*u)/f,m=Math.sin(i*u)/f;return this.w=n*p+c*m,this.x=s*p+o*m,this.y=r*p+l*m,this.z=a*p+h*m,this}transformVector(e,t=new ed){let i=e.x,s=e.y,r=e.z,a=this.x,n=this.y,o=this.z,l=this.w,h=l*i+n*r-o*s,c=l*s+o*i-a*r,d=l*r+a*s-n*i,u=-a*i-n*s-o*r;return t.x=h*l+-(u*a)+-(c*o)- -(d*n),t.y=c*l+-(u*n)+-(d*a)- -(h*o),t.z=d*l+-(u*o)+-(h*n)- -(c*a),t}fromArray(e,t=0){return this.x=e[t]??this.x,this.y=e[t+1]??this.y,this.z=e[t+2]??this.z,this.w=e[t+3]??this.w,this}toString(){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,e}constructor(e=0,t=0,i=0,s=1){4===e.length?(this.x=e[0],this.y=e[1],this.z=e[2],this.w=e[3]):(this.x=e,this.y=t,this.z=i,this.w=s);}}ex.IDENTITY=Object.freeze(new ex(0,0,0,1)),ex.ZERO=Object.freeze(new ex(0,0,0,0));let eT=new ed,eE=new ed,ew=new ed,eb=new ed,eC=new ed;class eA{add(e){let t=this.center,i=t.x,s=t.y,r=t.z,a=this.halfExtents,n=a.x,o=a.y,l=a.z,h=i-n,c=i+n,d=s-o,u=s+o,f=r-l,p=r+l,m=e.center,_=m.x,g=m.y,v=m.z,S=e.halfExtents,y=S.x,x=S.y,T=S.z,E=_-y,w=_+y,b=g-x,C=g+x,A=v-T,P=v+T;Ec&&(c=w),bu&&(u=C),Ap&&(p=P),t.x=(h+c)*.5,t.y=(d+u)*.5,t.z=(f+p)*.5,a.x=(c-h)*.5,a.y=(u-d)*.5,a.z=(p-f)*.5;}copy(e){this.center.copy(e.center),this.halfExtents.copy(e.halfExtents);}clone(){return new eA(this.center,this.halfExtents)}intersects(e){let t=this.getMax(),i=this.getMin(),s=e.getMax(),r=e.getMin();return i.x<=s.x&&t.x>=r.x&&i.y<=s.y&&t.y>=r.y&&i.z<=s.z&&t.z>=r.z}_intersectsRay(e,t){let i=eT.copy(this.getMin()).sub(e.origin),s=eE.copy(this.getMax()).sub(e.origin),r=e.direction;0===r.x?(i.x=i.x<0?-Number.MAX_VALUE:Number.MAX_VALUE,s.x=s.x<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.x/=r.x,s.x/=r.x),0===r.y?(i.y=i.y<0?-Number.MAX_VALUE:Number.MAX_VALUE,s.y=s.y<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.y/=r.y,s.y/=r.y),0===r.z?(i.z=i.z<0?-Number.MAX_VALUE:Number.MAX_VALUE,s.z=s.z<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.z/=r.z,s.z/=r.z);let a=ew.set(Math.min(i.x,s.x),Math.min(i.y,s.y),Math.min(i.z,s.z)),n=eb.set(Math.max(i.x,s.x),Math.max(i.y,s.y),Math.max(i.z,s.z)),o=Math.min(Math.min(n.x,n.y),n.z),l=Math.max(Math.max(a.x,a.y),a.z),h=o>=l&&l>=0;return h&&t.copy(e.direction).mulScalar(l).add(e.origin),h}_fastIntersectsRay(e){let t=e.direction;return eT.sub2(e.origin,this.center),eb.set(Math.abs(eT.x),Math.abs(eT.y),Math.abs(eT.z)),ew.mul2(eT,t),(!(eb.x>this.halfExtents.x)||!(ew.x>=0))&&(!(eb.y>this.halfExtents.y)||!(ew.y>=0))&&(!(eb.z>this.halfExtents.z)||!(ew.z>=0))&&(eC.set(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z)),eE.cross(t,eT),eE.set(Math.abs(eE.x),Math.abs(eE.y),Math.abs(eE.z)),!(eE.x>this.halfExtents.y*eC.z+this.halfExtents.z*eC.y)&&!(eE.y>this.halfExtents.x*eC.z+this.halfExtents.z*eC.x)&&!(eE.z>this.halfExtents.x*eC.y+this.halfExtents.y*eC.x))}intersectsRay(e,t){return t?this._intersectsRay(e,t):this._fastIntersectsRay(e)}setMinMax(e,t){this.center.add2(t,e).mulScalar(.5),this.halfExtents.sub2(t,e).mulScalar(.5);}getMin(){return this._min.copy(this.center).sub(this.halfExtents)}getMax(){return this._max.copy(this.center).add(this.halfExtents)}containsPoint(e){let t=this.center,i=this.halfExtents;return !(e.xt.x+i.x)&&!(e.yt.y+i.y)&&!(e.zt.z+i.z)}closestPoint(e,t=new ed){let i=this.center,s=this.halfExtents;return t.set(Math.max(i.x-s.x,Math.min(e.x,i.x+s.x)),Math.max(i.y-s.y,Math.min(e.y,i.y+s.y)),Math.max(i.z-s.z,Math.min(e.z,i.z+s.z)))}setFromTransformedAabb(e,t,i=false){let s=e.center,r=e.halfExtents,a=t.data,n=a[0],o=a[4],l=a[8],h=a[1],c=a[5],d=a[9],u=a[2],f=a[6],p=a[10];if(i){let e=n*n+o*o+l*l;if(e>0){let t=1/Math.sqrt(e);n*=t,o*=t,l*=t;}if((e=h*h+c*c+d*d)>0){let t=1/Math.sqrt(e);h*=t,c*=t,d*=t;}if((e=u*u+f*f+p*p)>0){let t=1/Math.sqrt(e);u*=t,f*=t,p*=t;}}this.center.set(a[12]+n*s.x+o*s.y+l*s.z,a[13]+h*s.x+c*s.y+d*s.z,a[14]+u*s.x+f*s.y+p*s.z),this.halfExtents.set(Math.abs(n)*r.x+Math.abs(o)*r.y+Math.abs(l)*r.z,Math.abs(h)*r.x+Math.abs(c)*r.y+Math.abs(d)*r.z,Math.abs(u)*r.x+Math.abs(f)*r.y+Math.abs(p)*r.z);}static computeMinMax(e,t,i,s=e.length/3){if(s>0){let r=e[0],a=e[1],n=e[2],o=r,l=a,h=n,c=3*s;for(let t=3;to&&(o=i),s>l&&(l=s),c>h&&(h=c);}t.set(r,a,n),i.set(o,l,h);}}compute(e,t){eA.computeMinMax(e,eT,eE,t),this.setMinMax(eT,eE);}intersectsBoundingSphere(e){return this._distanceToBoundingSphereSq(e)<=e.radius*e.radius}_distanceToBoundingSphereSq(e){let t=this.getMin(),i=this.getMax(),s=0,r=["x","y","z"];for(let a=0;a<3;++a){let n=0,o=e.center[r[a]],l=t[r[a]],h=i[r[a]],c=0;oh&&(n+=(c=o-h)*c),s+=n;}return s}_expand(e,t){eT.add2(this.getMin(),e),eE.add2(this.getMax(),t),this.setMinMax(eT,eE);}constructor(e,t){this.center=new ed,this.halfExtents=new ed(.5,.5,.5),this._min=new ed,this._max=new ed,e&&this.center.copy(e),t&&this.halfExtents.copy(t);}}let eP=new ed,eI=new ed;class eD{containsPoint(e){let t=eP.sub2(e,this.center).lengthSq(),i=this.radius;return t0&&s>0)return false;let a=s*s-r;if(a<0)return false;let n=Math.abs(-s-Math.sqrt(a));return t&&t.copy(e.direction).mulScalar(n).add(e.origin),true}intersectsBoundingSphere(e){eP.sub2(e.center,this.center);let t=e.radius+this.radius;return eP.lengthSq()<=t*t}constructor(e=new ed,t=.5){this.center=e,this.radius=t;}}class eR{clone(){return new this.constructor().copy(this)}copy(e){return this.normal.copy(e.normal),this.distance=e.distance,this}intersectsLine(e,t,i){let s=this.distance,r=this.normal.dot(e)+s,a=r/(r-(this.normal.dot(t)+s)),n=a>=0&&a<=1;return n&&i&&i.lerp(e,t,a),n}intersectsRay(e,t){let i=this.normal.dot(e.direction);if(0===i)return false;let s=-(this.normal.dot(e.origin)+this.distance)/i;return s>=0&&t&&t.copy(e.direction).mulScalar(s).add(e.origin),s>=0}normalize(){let e=1/this.normal.length();return this.normal.mulScalar(e),this.distance*=e,this}set(e,t,i,s){return this.normal.set(e,t,i),this.distance=s,this}setFromPointNormal(e,t){return this.normal.copy(t),this.distance=-this.normal.dot(e),this}constructor(e=ed.UP,t=0){this.normal=new ed,this.normal.copy(e),this.distance=t;}}class eL{clone(){return new this.constructor().copy(this)}copy(e){for(let t=0;t<6;t++)this.planes[t].copy(e.planes[t]);return this}setFromMat4(e){let[t,i,s,r,a,n,o,l,h,c,d,u,f,p,m,_]=e.data,g=this.planes;g[0].set(r-t,l-a,u-h,_-f).normalize(),g[1].set(r+t,l+a,u+h,_+f).normalize(),g[2].set(r+i,l+n,u+c,_+p).normalize(),g[3].set(r-i,l-n,u-c,_-p).normalize(),g[4].set(r-s,l-o,u-d,_-m).normalize(),g[5].set(r+s,l+o,u+d,_+m).normalize();}containsPoint(e){for(let t=0;t<6;t++){let{normal:i,distance:s}=this.planes[t];if(i.dot(e)+s<=0)return false}return true}add(e){let t=this.planes,i=e.planes;for(let e=0;e<6;e++)i[e].distance>t[e].distance&&t[e].copy(i[e]);return this}containsSphere(e){let{center:t,radius:i}=e,s=0;for(let e=0;e<6;e++){let{normal:r,distance:a}=this.planes[e],n=r.dot(t)+a;if(n<=-i)return 0;n>i&&s++;}return 6===s?2:1}constructor(){this.planes=[];for(let e=0;e<6;e++)this.planes[e]=new eR;}}class eM{set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.set(e.origin,e.direction)}clone(){return new this.constructor(this.origin,this.direction)}constructor(e,t){this.origin=new ed,this.direction=ed.FORWARD.clone(),e&&this.origin.copy(e),t&&this.direction.copy(t);}}let eO=new eM,eF=new ed,eN=new eD,eB=new ey,ek=new ed,eU=new ed,ez=new ed,eV=new ed,eG=new ed;class eH{set(e,t,i){return this.v0.copy(e),this.v1.copy(t),this.v2.copy(i),this}intersectsRay(e,t){ek.sub2(this.v1,this.v0),eU.sub2(this.v2,this.v0),ez.cross(e.direction,eU);let i=ek.dot(ez);if(i>-1e-6&&i<1e-6)return false;let s=1/i;eV.sub2(e.origin,this.v0);let r=s*eV.dot(ez);if(r<0||r>1)return false;eG.cross(eV,ek);let a=s*e.direction.dot(eG);if(a<0||r+a>1)return false;let n=s*eU.dot(eG);return n>1e-6&&(t instanceof ed&&t.copy(e.direction).mulScalar(n).add(e.origin),true)}toString(){return `[${this.v0.toString()}, ${this.v1.toString()}, ${this.v2.toString()}]`}constructor(e=ed.ZERO,t=ed.ZERO,i=ed.ZERO){this.v0=new ed,this.v1=new ed,this.v2=new ed,this.set(e,t,i);}}let eW=[1,2,4],eX=new Map([[0,{name:"A8",size:1,ldr:true}],[52,{name:"R8",size:1,ldr:true}],[1,{name:"L8",size:1,ldr:true}],[2,{name:"LA8",size:2,ldr:true}],[53,{name:"RG8",size:2,ldr:true}],[3,{name:"RGB565",size:2,ldr:true}],[4,{name:"RGBA5551",size:2,ldr:true}],[5,{name:"RGBA4",size:2,ldr:true}],[6,{name:"RGB8",size:4,ldr:true}],[7,{name:"RGBA8",size:4,ldr:true,srgbFormat:20}],[50,{name:"R16F",size:2}],[51,{name:"RG16F",size:4}],[11,{name:"RGB16F",size:8}],[12,{name:"RGBA16F",size:8}],[13,{name:"RGB32F",size:16}],[14,{name:"RGBA32F",size:16}],[15,{name:"R32F",size:4}],[70,{name:"RG32F",size:8}],[71,{name:"RGB9E5",size:4}],[72,{name:"RG8S",size:2}],[73,{name:"RGBA8S",size:4}],[74,{name:"RGB10A2",size:4}],[75,{name:"RGB10A2U",size:4,isUint:true}],[16,{name:"DEPTH",size:4}],[69,{name:"DEPTH16",size:2}],[17,{name:"DEPTHSTENCIL",size:4}],[18,{name:"111110F",size:4}],[19,{name:"SRGB8",size:4,ldr:true,srgb:true}],[20,{name:"SRGBA8",size:4,ldr:true,srgb:true}],[31,{name:"BGRA8",size:4,ldr:true}],[64,{name:"SBGRA8",size:4,ldr:true,srgb:true}],[8,{name:"DXT1",blockSize:8,ldr:true,srgbFormat:54}],[9,{name:"DXT3",blockSize:16,ldr:true,srgbFormat:55}],[10,{name:"DXT5",blockSize:16,ldr:true,srgbFormat:56}],[21,{name:"ETC1",blockSize:8,ldr:true}],[22,{name:"ETC2_RGB",blockSize:8,ldr:true,srgbFormat:61}],[23,{name:"ETC2_RGBA",blockSize:16,ldr:true,srgbFormat:62}],[24,{name:"PVRTC_2BPP_RGB_1",ldr:true,blockSize:8}],[25,{name:"PVRTC_2BPP_RGBA_1",ldr:true,blockSize:8}],[26,{name:"PVRTC_4BPP_RGB_1",ldr:true,blockSize:8}],[27,{name:"PVRTC_4BPP_RGBA_1",ldr:true,blockSize:8}],[28,{name:"ASTC_4x4",blockSize:16,ldr:true,srgbFormat:63}],[29,{name:"ATC_RGB",blockSize:8,ldr:true}],[30,{name:"ATC_RGBA",blockSize:16,ldr:true}],[65,{name:"BC6H_RGBF",blockSize:16}],[66,{name:"BC6H_RGBUF",blockSize:16}],[67,{name:"BC7_RGBA",blockSize:16,ldr:true,srgbFormat:68}],[54,{name:"DXT1_SRGB",blockSize:8,ldr:true,srgb:true}],[55,{name:"DXT3_SRGBA",blockSize:16,ldr:true,srgb:true}],[56,{name:"DXT5_SRGBA",blockSize:16,ldr:true,srgb:true}],[61,{name:"ETC2_SRGB",blockSize:8,ldr:true,srgb:true}],[62,{name:"ETC2_SRGBA",blockSize:16,ldr:true,srgb:true}],[63,{name:"ASTC_4x4_SRGB",blockSize:16,ldr:true,srgb:true}],[68,{name:"BC7_SRGBA",blockSize:16,ldr:true,srgb:true}],[32,{name:"R8I",size:1,isInt:true}],[34,{name:"R16I",size:2,isInt:true}],[36,{name:"R32I",size:4,isInt:true}],[38,{name:"RG8I",size:2,isInt:true}],[40,{name:"RG16I",size:4,isInt:true}],[42,{name:"RG32I",size:8,isInt:true}],[44,{name:"RGBA8I",size:4,isInt:true}],[46,{name:"RGBA16I",size:8,isInt:true}],[48,{name:"RGBA32I",size:16,isInt:true}],[33,{name:"R8U",size:1,isUint:true}],[35,{name:"R16U",size:2,isUint:true}],[37,{name:"R32U",size:4,isUint:true}],[39,{name:"RG8U",size:2,isUint:true}],[41,{name:"RG16U",size:4,isUint:true}],[43,{name:"RG32U",size:8,isUint:true}],[45,{name:"RGBA8U",size:4,isUint:true}],[47,{name:"RGBA16U",size:8,isUint:true}],[49,{name:"RGBA32U",size:16,isUint:true}]]),eY=e=>eX.get(e)?.blockSize!==void 0,eq=e=>eX.get(e)?.srgb===true,ej=e=>{let t=eX.get(e);return t?.isInt===true||t?.isUint===true},eK={sampler:"sampler2D",returnType:"vec4"},e$={sampler:"usampler2D",returnType:"uvec4"},eZ={sampler:"isampler2D",returnType:"ivec4"},eQ={textureType:"texture_2d",returnType:"vec4f"},eJ={textureType:"texture_2d",returnType:"vec4u"},e0={textureType:"texture_2d",returnType:"vec4i"},e1=e=>{let t=eX.get(e);return t?.isUint?e$:t?.isInt?eZ:eK},e2=e=>{let t=eX.get(e);return t?.isUint?eJ:t?.isInt?e0:eQ},e3=e=>eX.get(e)?.srgbFormat||e,e4=e=>{for(let[t,i]of eX)if(i.srgbFormat===e)return t;return e},e5=e=>{let t=eX.get(e);return !!(t?.ldr&&!t?.srgb)},e6=e=>{switch(e){case 15:case 70:case 13:case 14:return Float32Array;case 36:case 42:case 48:return Int32Array;case 37:case 43:case 49:case 71:case 74:case 75:return Uint32Array;case 34:case 40:case 46:return Int16Array;case 35:case 41:case 47:case 3:case 4:case 5:case 50:case 51:case 11:case 12:return Uint16Array;case 32:case 38:case 44:case 72:case 73:return Int8Array;default:return Uint8Array}},e8="POSITION",e9="NORMAL",e7="TANGENT",te="BLENDWEIGHT",tt="BLENDINDICES",ti="COLOR",ts="TEXCOORD",tr="TEXCOORD0",ta="TEXCOORD1",tn="TEXCOORD2",to="TEXCOORD3",tl="TEXCOORD4",th="TEXCOORD5",tc="TEXCOORD6",td="TEXCOORD7",tu="ATTR0",tf="ATTR1",tp="ATTR2",tm="ATTR3",t_="ATTR4",tg="ATTR5",tv="ATTR6",tS="ATTR7",ty="ATTR8",tx="ATTR9",tT="ATTR10",tE="ATTR11",tw="ATTR12",tb="ATTR13",tC="ATTR14",tA="ATTR15",tP="default",tI="rgbm",tD="rgbe",tR="rgbp",tL="swizzleGGGR",tM="2d-array",tO="cube",tF="cube-array",tN="none",tB="cube",tk="equirect",tU="octahedral",tz="glsl",tV="wgsl",tG=["bool","int","float","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","mat2","mat3","mat4","sampler2D","samplerCube","","sampler2DShadow","samplerCubeShadow","sampler3D","","","","","sampler2DArray","uint","uvec2","uvec3","uvec4","","","","","","","","","","","","","isampler2D","usampler2D","isamplerCube","usamplerCube","isampler3D","usampler3D","isampler2DArray","usampler2DArray"],tH=[["bool"],["i32"],["f32"],["vec2f","vec2"],["vec3f","vec3"],["vec4f","vec4"],["vec2i","vec2"],["vec3i","vec3"],["vec4i","vec4"],["vec2"],["vec3"],["vec4"],["mat2x2f","mat2x2"],["mat3x3f","mat3x3"],["mat4x4f","mat4x4"],["texture_2d"],["texture_cube"],["array"],["texture_depth_2d"],["texture_depth_cube"],["texture_3d"],["array>"],["array>"],["array>"],["array>"],["texture_2d_array"],["u32"],["vec2u","vec2"],["vec3u","vec3"],["vec4u","vec4"],["array"],["array"],["array"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["texture_2d"],["texture_2d"],["texture_cube"],["texture_cube"],["texture_3d"],["texture_3d"],["texture_2d_array"],["texture_2d_array"]],tW=new Map;tH.forEach((e,t)=>{e.forEach(e=>tW.set(e,t));});let tX=new Uint8Array([4,4,6,6,6,6,4,4,4,4,4,4,6,6,6,4,4,6,4,4,4,6,6,6,6,4,5,5,5,5,4,5,4,4,5,4,4,5,4,4,5,4,4,5,4,5,4,5,4,5]),tY="webgl2",tq="webgpu",tj="webgpu:bare",tK="null",t$="ldr_srgb",tZ=["view","mesh","mesh_ub"],tQ="default",tJ="_unused_float_uniform",t0=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Uint16Array],t1=[1,1,2,2,4,4,4,2],t2=[Uint8Array,Uint16Array,Uint32Array],t3=[1,2,4],t4=new Map([["float","f32"],["vec2","vec2f"],["vec3","vec3f"],["vec4","vec4f"],["int","i32"],["ivec2","vec2i"],["ivec3","vec3i"],["ivec4","vec4i"],["uint","u32"],["uvec2","vec2u"],["uvec3","vec3u"],["uvec4","vec4u"]]),t5={};t5[e8]=0,t5[e9]=1,t5[te]=2,t5[tt]=3,t5[ti]=4,t5[tr]=5,t5[ta]=6,t5[tn]=7,t5[to]=8,t5[tl]=9,t5[th]=10,t5[tc]=11,t5[td]=12,t5[e7]=13,t5[tu]=0,t5[tf]=1,t5[tp]=2,t5[tm]=3,t5[t_]=4,t5[tg]=5,t5[tv]=6,t5[tS]=7,t5[ty]=8,t5[tx]=9,t5[tT]=10,t5[tE]=11,t5[tw]=12,t5[tb]=13,t5[tC]=14,t5[tA]=15;let t6=0;class t8{constructor(e,t){this.slot=-1,this.scopeId=null,this.name=e,this.visibility=t;}}class t9 extends t8{}class t7 extends t8{constructor(e,t,i=false){super(e,t),this.format="",this.readOnly=i;}}class ie extends t8{constructor(e,t,i="2d",s=0,r=true,a=null){super(e,t),this.textureDimension=i,this.sampleType=s,this.hasSampler=r,this.samplerName=a??`${e}_sampler`;}}class it extends t8{constructor(e,t=7,i="2d",s=true,r=false){super(e,4),this.format=t,this.textureDimension=i,this.write=s,this.read=r;}}class ii{destroy(){this.impl.destroy();}getTexture(e){let t=this.textureFormatsMap.get(e);return void 0!==t?this.textureFormats[t]:null}getStorageTexture(e){let t=this.storageTextureFormatsMap.get(e);return void 0!==t?this.storageTextureFormats[t]:null}loseContext(){}constructor(e,t){this.uniformBufferFormats=[],this.textureFormats=[],this.storageTextureFormats=[],this.storageBufferFormats=[],this.id=t6++;let i=0;t.forEach(e=>{e.slot=i++,e instanceof ie&&e.hasSampler&&i++,e instanceof t9?this.uniformBufferFormats.push(e):e instanceof ie?this.textureFormats.push(e):e instanceof it?this.storageTextureFormats.push(e):e instanceof t7&&this.storageBufferFormats.push(e);}),this.device=e;let s=e.scope;this.bufferFormatsMap=new Map,this.uniformBufferFormats.forEach((e,t)=>this.bufferFormatsMap.set(e.name,t)),this.textureFormatsMap=new Map,this.textureFormats.forEach((e,t)=>{this.textureFormatsMap.set(e.name,t),e.scopeId=s.resolve(e.name);}),this.storageTextureFormatsMap=new Map,this.storageTextureFormats.forEach((e,t)=>{this.storageTextureFormatsMap.set(e.name,t),e.scopeId=s.resolve(e.name);}),this.storageBufferFormatsMap=new Map,this.storageBufferFormats.forEach((e,t)=>{this.storageBufferFormatsMap.set(e.name,t),e.scopeId=s.resolve(e.name);}),this.impl=e.createBindGroupFormatImpl(this);}}class is{get(e,t){return this._cache.has(e)||(this._cache.set(e,t()),e.on("destroy",()=>{this.remove(e);}),e.on("devicelost",()=>{this._cache.get(e)?.loseContext?.(e);})),this._cache.get(e)}remove(e){this._cache.get(e)?.destroy?.(e),this._cache.delete(e);}constructor(){this._cache=new Map;}}class ir{static calcLevelDimension(e,t){return Math.max(e>>t,1)}static calcMipLevelsCount(e,t,i=1){return 1+Math.floor(Math.log2(Math.max(e,t,i)))}static calcLevelGpuSize(e,t,i,s){let r=eX.get(s),a=eX.get(s)?.size??0;if(a>0)return e*t*i*a;let n=r.blockSize??0,o=Math.floor((e+3)/4),l=Math.floor((t+3)/4),h=Math.floor((i+3)/4);return (24===s||25===s)&&(o=Math.max(Math.floor(o/2),1)),o*l*h*n}static calcGpuSize(e,t,i,s,r,a){let n=0;for(;n+=ir.calcLevelGpuSize(e,t,i,s),r&&(1!==e||1!==t||1!==i);)e=Math.max(e>>1,1),t=Math.max(t>>1,1),i=Math.max(i>>1,1);return n*(a?6:1)}static calcTextureSize(e,t,i=1){let s=Math.ceil(Math.sqrt(e));return i>1&&(s=ei.roundUp(s,i)),t.set(s,Math.ceil(e/s))}}class ia{get(e){let t=this.map.get(e);return void 0===t&&(t=this.id++,this.map.set(e,t)),t}constructor(){this.map=new Map,this.id=0;}}let io=new ia;class il{constructor(e,t=0,i=1,s=0,r=1){this.texture=e,this.baseMipLevel=t,this.mipLevelCount=i,this.baseArrayLayer=s,this.arrayLayerCount=r,this.key=io.get(`${t}:${i}:${s}:${r}`);}}let ih=0;class ic{static createDataTexture2D(e,t,i,s,r,a){return new ic(e,{name:t,width:i,height:s,format:r,mipmaps:false,minFilter:0,magFilter:0,addressU:1,addressV:1,levels:a})}destroy(){let e=this.device;e&&(e.onTextureDestroyed(this),this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this._gpuSize),this._levels=null,this.device=null);}recreateImpl(e=true){let{device:t}=this;this.impl?.destroy(t),this.impl=null,this.impl=t.createTextureImpl(this),this.dirtyAll(),e&&this.upload();}_clearLevels(){this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null];}resize(e,t,i=1){if(this.width!==e||this.height!==t||this.depth!==i){let s=this.device;this.adjustVramSizeTracking(s._vram,-this._gpuSize),this._gpuSize=0,this.impl.destroy(s),this._clearLevels(),this._width=Math.floor(e),this._height=Math.floor(t),this._depth=Math.floor(i),this._updateNumLevels(),this.impl=s.createTextureImpl(this),this.dirtyAll();}}loseContext(){this.impl.loseContext(),this.dirtyAll();}adjustVramSizeTracking(e,t){e.tex+=t;}propertyChanged(e){this.impl.propertyChanged(e),this.renderVersionDirty=this.device.renderVersion;}_updateNumLevels(){let e=this.mipmaps?ir.calcMipLevelsCount(this.width,this.height):1,t=this._numLevelsRequested;this._numLevels=Math.min(t??e,e),this._mipmaps=this._numLevels>1;}get lockedMode(){return this._lockedMode}set minFilter(e){this._minFilter!==e&&(ej(this._format)||(this._minFilter=e,this.propertyChanged(1)));}get minFilter(){return this._minFilter}set magFilter(e){this._magFilter!==e&&(ej(this._format)||(this._magFilter=e,this.propertyChanged(2)));}get magFilter(){return this._magFilter}set addressU(e){this._addressU!==e&&(this._addressU=e,this.propertyChanged(4));}get addressU(){return this._addressU}set addressV(e){this._addressV!==e&&(this._addressV=e,this.propertyChanged(8));}get addressV(){return this._addressV}set addressW(e){this._volume&&e!==this._addressW&&(this._addressW=e,this.propertyChanged(16));}get addressW(){return this._addressW}set compareOnRead(e){this._compareOnRead!==e&&(this._compareOnRead=e,this.propertyChanged(32));}get compareOnRead(){return this._compareOnRead}set compareFunc(e){this._compareFunc!==e&&(this._compareFunc=e,this.propertyChanged(64));}get compareFunc(){return this._compareFunc}set anisotropy(e){this._anisotropy!==e&&(this._anisotropy=e,this.propertyChanged(128));}get anisotropy(){return this._anisotropy}set mipmaps(e){if(this._mipmaps!==e)if(this.device.isWebGPU);else if(ej(this._format));else {let t=this._mipmaps,i=this._numLevels;this._mipmaps=e,this._updateNumLevels(),this.array&&this._numLevels!==i?this.recreateImpl():this._mipmaps!==t&&(this.propertyChanged(1),this._mipmaps?(this._needsMipmapsUpload=true,this.device?.texturesToUpload?.add(this)):this._needsMipmapsUpload=false);}}get mipmaps(){return this._mipmaps}get numLevels(){return this._numLevels}get storage(){return this._storage}get width(){return this._width}get height(){return this._height}get depth(){return this._depth}get format(){return this._format}get cubemap(){return this._cubemap}get gpuSize(){let e=this.pot&&this._mipmaps&&!(this._compressed&&1===this._levels.length);return ir.calcGpuSize(this._width,this._height,this._depth,this._format,e,this._cubemap)}get array(){return this._arrayLength>0}get arrayLength(){return this._arrayLength}get volume(){return this._volume}set type(e){this._type!==e&&(this._type=e,this.device._shadersDirty=true);}get type(){return this._type}set srgb(e){if(e!==eq(this.format))if(e){let e=e3(this.format);this._format!==e&&(this._format=e,this.recreateImpl(),this.device._shadersDirty=true);}else {let e=e4(this.format);this._format!==e&&(this._format=e,this.recreateImpl(),this.device._shadersDirty=true);}}get srgb(){return eq(this.format)}set flipY(e){this._flipY!==e&&(this._flipY=e,this.markForUpload());}get flipY(){return this._flipY}set premultiplyAlpha(e){this._premultiplyAlpha!==e&&(this._premultiplyAlpha=e,this.markForUpload());}get premultiplyAlpha(){return this._premultiplyAlpha}get pot(){return ei.powerOfTwo(this._width)&&ei.powerOfTwo(this._height)}get encoding(){switch(this.type){case tI:return "rgbm";case tD:return "rgbe";case tR:return "rgbp"}return e5(this.format)?"srgb":"linear"}dirtyAll(){this._levelsUpdated=this._cubemap?[[true,true,true,true,true,true]]:[true],this.markForUpload(),this._needsMipmapsUpload=this._mipmaps,this._mipmapsUploaded=false,this.propertyChanged(255);}lock(e={}){e.level??(e.level=0),e.face??(e.face=0),e.mode??(e.mode=2),this._lockedMode=e.mode,this._lockedLevel=e.level;let t=this.cubemap?this._levels[e.face]:this._levels;if(null===t[e.level]){let i=Math.max(1,this._width>>e.level),s=Math.max(1,this._height>>e.level),r=Math.max(1,this._depth>>e.level),a=new ArrayBuffer(ir.calcLevelGpuSize(i,s,r,this._format));t[e.level]=new(e6(this._format))(a);}return t[e.level]}setSource(e,t=0){let i,s;if(this.device._isHTMLElementInterface(e)&&(!this.device.supportsHtmlTextures||this._cubemap||this._volume))return;let r=false;if(this._cubemap){if(e[0]){i=e[0].width||0,s=e[0].height||0;for(let t=0;t<6;t++){let a=e[t];if(!a||a.width!==i||a.height!==s||!this.device._isBrowserInterface(a)){r=true;break}}}else r=true;if(!r)for(let i=0;i<6;i++)this._levels[t][i]!==e[i]&&(this._levelsUpdated[t][i]=true);}else if(this.device._isBrowserInterface(e)||(r=true),!r)if(e!==this._levels[t]&&(this._levelsUpdated[t]=true),e instanceof HTMLVideoElement)i=e.videoWidth,s=e.videoHeight;else if(this.device._isHTMLElementInterface(e)){let t=e.getBoundingClientRect();i=Math.floor(t.width)||1,s=Math.floor(t.height)||1;}else i=e.width,s=e.height;if(r)if(this._width=4,this._height=4,this._cubemap)for(let e=0;e<6;e++)this._levels[t][e]=null,this._levelsUpdated[t][e]=true;else this._levels[t]=null,this._levelsUpdated[t]=true;else 0===t&&(this._width=i,this._height=s),this._levels[t]=e;this._invalid===r&&r||(this._invalid=r,this.upload());}getSource(e=0){return this._levels[e]}unlock(){this._lockedMode,2===this._lockedMode&&this.upload(),this._lockedLevel=-1,this._lockedMode=0;}markForUpload(){this._needsUpload=true,this.device?.texturesToUpload?.add(this);}upload(){this.markForUpload(),this._needsMipmapsUpload=this._mipmaps,this.impl.uploadImmediate?.(this.device,this);}read(e,t,i,s,r={}){return this.impl.read?.(e,t,i,s,r)}write(e,t,i,s,r){return this.impl.write?.(e,t,i,s,r)}getView(e=0,t=1,i=0,s=1){return new il(this,e,t,i,s)}constructor(e,t={}){this._gpuSize=0,this.id=ih++,this._invalid=false,this._lockedLevel=-1,this._lockedMode=0,this.renderVersionDirty=0,this._storage=false,this._numLevels=0,this.device=e,this.name=t.name??"",this._width=Math.floor(t.width??4),this._height=Math.floor(t.height??4),this._format=t.format??7,this._compressed=eY(this._format),this._integerFormat=ej(this._format),this._integerFormat&&(t.minFilter=0,t.magFilter=0),this._volume=t.volume??false,this._depth=Math.floor(t.depth??1),this._arrayLength=Math.floor(t.arrayLength??0),this._storage=t.storage??false,this._cubemap=t.cubemap??false,this._flipY=t.flipY??false,this._premultiplyAlpha=t.premultiplyAlpha??false,this._mipmaps=t.mipmaps??true,this._numLevelsRequested=t.numLevels,void 0!==t.numLevels&&(this._numLevels=t.numLevels),this._updateNumLevels(),this._minFilter=t.minFilter??5,this._magFilter=t.magFilter??1,this._anisotropy=t.anisotropy??1,this._addressU=t.addressU??0,this._addressV=t.addressV??0,this._addressW=t.addressW??0,this._compareOnRead=t.compareOnRead??false,this._compareFunc=t.compareFunc??1,this._type=t.type??tP,this.projection=tN,this._cubemap?this.projection=tB:t.projection&&t.projection!==tB&&(this.projection=t.projection),this._levels=t.levels;let i=!!t.levels;this._levels||this._clearLevels(),this.recreateImpl(i);}}let id={white:[255,255,255,255],gray:[128,128,128,255],black:[0,0,0,255],normal:[128,128,255,255],pink:[255,128,255,255]};class iu{destroy(){this.map.forEach(e=>{e.destroy();});}constructor(){this.map=new Map;}}let ip=new is,im=(e,t)=>{let i=ip.get(e,()=>new iu);if(!i.map.has(t)){let s=new ic(e,{name:`built-in-texture-${t}`,width:1,height:1,format:7}),r=s.lock(),a=id[t];r.set(a),s.unlock(),i.map.set(t,s);}return i.map.get(t)},i_=0;class ig{constructor(){this.offsets=[];}}class iv{destroy(){this.impl.destroy(),this.impl=null,this.format=null,this.defaultUniformBuffer=null;}setUniformBuffer(e,t){let i=this.format.bufferFormatsMap.get(e);this.uniformBuffers[i]!==t&&(this.uniformBuffers[i]=t,this.dirty=true);}setStorageBuffer(e,t){let i=this.format.storageBufferFormatsMap.get(e);this.storageBuffers[i]!==t&&(this.storageBuffers[i]=t,this.dirty=true);}setTexture(e,t){let i=this.format.textureFormatsMap.get(e),s=t instanceof il?t.texture:t;this.textures[i]!==t?(this.textures[i]=t,this.dirty=true):this.renderVersionUpdatede&~(s<e>>t&i,all(e,t,i=1){let s=i<(e&i<t)if(ArrayBuffer.isView(e))e=e.subarray(0,t),i.set(e);else for(let s=0;s>>0}let iO=new ia,iF=[2,4,8,12,16],iN=new is;class iB{get elements(){return this._elements}static getDefaultInstancingFormat(e){return iN.get(e,()=>new iB(e,[{semantic:tE,components:4,type:6},{semantic:tw,components:4,type:6},{semantic:tC,components:4,type:6},{semantic:tA,components:4,type:6}]))}static isElementValid(e,t){let i=t.components*t1[t.type];return !e.isWebGPU||!!iF.includes(i)}update(){this._evaluateHash();}_evaluateHash(){let e=[],t=[],i=this._elements.length;for(let s=0;se+4*Math.ceil(t.components*t1[t.type]/4),0);let s=0,r;for(let e=0,a=t.length;etypeof ImageBitmap&&e instanceof ImageBitmap||"u">typeof HTMLImageElement&&e instanceof HTMLImageElement}_isImageCanvasInterface(e){return "u">typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement}_isImageVideoInterface(e){return "u">typeof HTMLVideoElement&&e instanceof HTMLVideoElement}_isHTMLElementInterface(e){return "u">typeof HTMLElement&&e instanceof HTMLElement&&!("u">typeof HTMLImageElement&&e instanceof HTMLImageElement)&&!("u">typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement)&&!("u">typeof HTMLVideoElement&&e instanceof HTMLVideoElement)}resizeCanvas(e,t){let i=Math.min(this._maxPixelRatio,k.browser?window.devicePixelRatio:1),s=Math.floor(e*i),r=Math.floor(t*i);(s!==this.canvas.width||r!==this.canvas.height)&&this.setResolution(s,r);}setResolution(e,t){this.canvas.width=e,this.canvas.height=t,this.fire(iz.EVENT_RESIZE,e,t);}update(){this.updateClientRect();}updateClientRect(){if(k.worker)this.clientRect.width=this.canvas.width,this.clientRect.height=this.canvas.height;else {let e=this.canvas.getBoundingClientRect();this.clientRect.width=e.width,this.clientRect.height=e.height;}}get width(){return this.canvas.width}get height(){return this.canvas.height}set fullscreen(e){}get fullscreen(){return false}set maxPixelRatio(e){this._maxPixelRatio=e;}get maxPixelRatio(){return this._maxPixelRatio}get deviceType(){return this._deviceType}startRenderPass(e){}endRenderPass(e){}startComputePass(e){}endComputePass(){}frameStart(){this.renderPassIndex=0,this.renderVersion++;}frameEnd(){this.mapsToClear.forEach(e=>e.clear()),this.mapsToClear.clear();}computeDispatch(e,t="Unnamed"){}getRenderableHdrFormat(e=[18,12,14],t=true,i=1){for(let s=0;s1)continue;if(this.textureFloatRenderable&&(!t||this.textureFloatFilterable))return r}}}validateAttributes(e,t,i){}constructor(e,t){var i,s,r,a,n,o;super(),this.backBuffer=null,this.backBufferSize=new ef,this.backBufferAntialias=false,this.isWebGPU=false,this.isWebGL2=false,this.isNull=false,this.isHdr=false,this.maxIndirectDrawCount=1024,this.maxIndirectDispatchCount=256,this.maxColorAttachments=1,this.maxSamples=1,this.supportsMultiDraw=true,this.supportsCompute=false,this.supportsStorageTextureRead=false,this.supportsSubgroups=false,this.supportsSubgroupUniformity=false,this.supportsSubgroupId=false,this.renderTarget=null,this.shaders=[],this.textures=new Set,this.texturesToUpload=new Set,this.targets=new Set,this.renderVersion=0,this.insideRenderPass=false,this.supportsUniformBuffers=false,this.supportsClipDistances=false,this.supportsTextureFormatTier1=false,this.supportsTextureFormatTier2=false,this.supportsPrimitiveIndex=false,this.supportsShaderF16=false,this.supportsHtmlTextures=false,this.textureRG11B10Renderable=false,this.textureFloatFilterable=false,this.blendState=new iy,this.depthState=new iT,this.stencilEnabled=false,this.stencilFront=new iU,this.stencilBack=new iU,this._destroyed=false,this.defaultClearOptions={color:[0,0,0,1],depth:1,stencil:0,flags:3},this.clientRect={width:0,height:0},this._shadersDirty=false,this.capsDefines=new Map,this.mapsToClear=new Set,this.canvas=e,"setAttribute"in e&&e.setAttribute("data-engine",`PlayCanvas ${w}`),this.initOptions={...t},(i=this.initOptions).alpha??(i.alpha=true),(s=this.initOptions).depth??(s.depth=true),(r=this.initOptions).stencil??(r.stencil=true),(a=this.initOptions).antialias??(a.antialias=true),(n=this.initOptions).powerPreference??(n.powerPreference="high-performance"),(o=this.initOptions).displayFormat??(o.displayFormat="ldr"),this._maxPixelRatio=k.browser?Math.min(1,window.devicePixelRatio):1,this.buffers=new Set,this._vram={tex:0,vb:0,ib:0,ub:0,sb:0},this._shaderStats={vsCompiled:0,fsCompiled:0,linked:0,materialShaders:0,compileTime:0},this.initializeContextCaches(),this._drawCallsPerFrame=0,this._shaderSwitchesPerFrame=0,this._primsPerFrame=[];for(let e=0;e<=6;e++)this._primsPerFrame[e]=0;this._renderTargetCreationTime=0,this.scope=new iI("Device"),this.textureBias=this.scope.resolve("textureBias"),this.textureBias.setValue(0);}}iz.EVENT_RESIZE="resizecanvas";let iV=0;class iG{destroy(){let e=this._device;e&&(e.targets.delete(this),e.renderTarget===this&&e.setRenderTarget(null),this.destroyFrameBuffers());}destroyFrameBuffers(){let e=this._device;e&&this.impl.destroy(e);}destroyTextureBuffers(){this._depthBuffer?.destroy(),this._depthBuffer=null,this._colorBuffers?.forEach(e=>{e.destroy();}),this._colorBuffers=null,this._colorBuffer=null;}resize(e,t){if(!(this.mipLevel>0)&&(this._depthBuffer?.resize(e,t),this._colorBuffers?.forEach(i=>{i.resize(e,t);}),this._width!==e||this._height!==t)){this.destroyFrameBuffers();let e=this._device;e.renderTarget===this&&e.setRenderTarget(null),this.evaluateDimensions(),this.validateMrt(),this.impl=e.createRenderTargetImpl(this);}}validateMrt(){}evaluateDimensions(){let e=this._colorBuffer??this._depthBuffer;e&&(this._width=e.width,this._height=e.height,this._mipLevel>0&&(this._width=ir.calcLevelDimension(this._width,this._mipLevel),this._height=ir.calcLevelDimension(this._height,this._mipLevel)));}init(){this.impl.init(this._device,this);}get initialized(){return this.impl.initialized}get device(){return this._device}loseContext(){this.impl.loseContext();}resolve(e=true,t=!!this._depthBuffer){this._device&&this._samples>1&&this.impl.resolve(this._device,this,e,t);}copy(e,t,i){if(!this._device)if(!e._device)return false;else this._device=e._device;return this._device.copyRenderTarget(e,this,t,i)}get samples(){return this._samples}get depth(){return this._depth}get stencil(){return this._stencil}get colorBuffer(){return this._colorBuffer}getColorBuffer(e){return this._colorBuffers?.[e]}get depthBuffer(){return this._depthBuffer}get face(){return this._face}get mipLevel(){return this._mipLevel}get mipmaps(){return this._mipmaps}get width(){return this._width??this._device.width}get height(){return this._height??this._device.height}isColorBufferSrgb(e=0){if(this.device.backBuffer===this)return eq(this.device.backBufferFormat);let t=this.getColorBuffer(e);return !!t&&eq(t.format)}constructor(e={}){this.id=iV++;let t=e.colorBuffer?.device??e.colorBuffers?.[0].device??e.depthBuffer?.device??e.graphicsDevice;this._device=t;let{maxSamples:i}=this._device;if(this._samples=Math.min(e.samples??1,i),t.isWebGPU&&(this._samples=this._samples>1?i:1),this._colorBuffer=e.colorBuffer,e.colorBuffer&&(this._colorBuffers=[e.colorBuffer]),this._depthBuffer=e.depthBuffer,this._face=e.face??0,this._depthBuffer){let e=this._depthBuffer._format;16===e||69===e?(this._depth=true,this._stencil=false):17===e?(this._depth=true,this._stencil=true):(15===e&&this._depthBuffer.device.isWebGPU&&this._samples>1?this._depth=true:this._depth=false,this._stencil=false);}else this._depth=e.depth??true,this._stencil=e.stencil??false;e.colorBuffers&&!this._colorBuffers&&(this._colorBuffers=[...e.colorBuffers],this._colorBuffer=e.colorBuffers[0]),this.autoResolve=e.autoResolve??true,this.name=e.name,this.name||(this.name=this._colorBuffer?.name),this.name||(this.name=this._depthBuffer?.name),this.name||(this.name="Untitled"),this.flipY=e.flipY??false,this._mipLevel=e.mipLevel??0,this._mipLevel>0&&this._depth&&(this._mipLevel=0),this._mipmaps=void 0===e.mipLevel,this.evaluateDimensions(),this.validateMrt(),this.impl=t.createRenderTargetImpl(this);}}class iH{update(e){this.destroy();let t=e.device,i=this.createDescriptor(t,e);this.bindGroup=t.wgpu.createBindGroup(i);}destroy(){this.bindGroup=null;}createDescriptor(e,t){let i=[],s=t.format,r=t.format.uniformBufferFormats;t.uniformBuffers.forEach((e,t)=>{let s=r[t].slot,a=e.persistent?e.impl.buffer:e.allocation.gpuBuffer.buffer;i.push({binding:s,resource:{buffer:a,offset:0,size:e.format.byteSize}});});let a=t.format.textureFormats;t.textures.forEach((t,r)=>{let n=t instanceof il,o=(n?t.texture:t).impl,l=s.textureFormats[r],h=a[r].slot,c=o.getView(e,n?t:void 0);if(i.push({binding:h,resource:c}),l.hasSampler){let t=o.getSampler(e,l.sampleType);i.push({binding:h+1,resource:t});}});let n=t.format.storageTextureFormats;t.storageTextures.forEach((t,s)=>{let r=t instanceof il,a=(r?t.texture:t).impl,o=n[s].slot,l=a.getView(e,r?t:void 0);i.push({binding:o,resource:l});});let o=t.format.storageBufferFormats;return t.storageBuffers.forEach((e,t)=>{let s=e.impl.buffer,r=o[t].slot;i.push({binding:r,resource:{buffer:s}});}),{layout:t.format.impl.bindGroupLayout,entries:i}}}class iW{static shaderStage(e){let t=0;return 1&e&&(t|=GPUShaderStage.VERTEX),2&e&&(t|=GPUShaderStage.FRAGMENT),4&e&&(t|=GPUShaderStage.COMPUTE),t}}let iX=[];iX[0]="",iX[1]="",iX[2]="",iX[52]="r8unorm",iX[53]="rg8unorm",iX[3]="",iX[4]="",iX[5]="",iX[6]="rgba8unorm",iX[7]="rgba8unorm",iX[8]="bc1-rgba-unorm",iX[9]="bc2-rgba-unorm",iX[10]="bc3-rgba-unorm",iX[11]="",iX[12]="rgba16float",iX[50]="r16float",iX[51]="rg16float",iX[13]="",iX[14]="rgba32float",iX[15]="r32float",iX[70]="rg32float",iX[16]="depth32float",iX[69]="depth16unorm",iX[17]="depth24plus-stencil8",iX[18]="rg11b10ufloat",iX[19]="",iX[20]="rgba8unorm-srgb",iX[21]="",iX[22]="etc2-rgb8unorm",iX[23]="etc2-rgba8unorm",iX[24]="",iX[25]="",iX[26]="",iX[27]="",iX[28]="astc-4x4-unorm",iX[29]="",iX[30]="",iX[31]="bgra8unorm",iX[64]="bgra8unorm-srgb",iX[32]="r8sint",iX[33]="r8uint",iX[34]="r16sint",iX[35]="r16uint",iX[36]="r32sint",iX[37]="r32uint",iX[38]="rg8sint",iX[39]="rg8uint",iX[40]="rg16sint",iX[41]="rg16uint",iX[42]="rg32sint",iX[43]="rg32uint",iX[44]="rgba8sint",iX[45]="rgba8uint",iX[46]="rgba16sint",iX[47]="rgba16uint",iX[48]="rgba32sint",iX[49]="rgba32uint",iX[65]="bc6h-rgb-float",iX[66]="bc6h-rgb-ufloat",iX[67]="bc7-rgba-unorm",iX[71]="rgb9e5ufloat",iX[72]="rg8snorm",iX[73]="rgba8snorm",iX[74]="rgb10a2unorm",iX[75]="rgb10a2uint",iX[54]="bc1-rgba-unorm-srgb",iX[55]="bc2-rgba-unorm-srgb",iX[56]="bc3-rgba-unorm-srgb",iX[61]="etc2-rgb8unorm-srgb",iX[62]="etc2-rgba8unorm-srgb",iX[68]="bc7-rgba-unorm-srgb",iX[63]="astc-4x4-unorm-srgb";let iY=[];iY[0]="filtering",iY[1]="non-filtering",iY[2]="comparison",iY[3]="comparison",iY[4]="comparison";let iq=[];iq[0]="float",iq[1]="unfilterable-float",iq[2]="depth",iq[3]="sint",iq[4]="uint";let ij=new ia;class iK{destroy(){this.bindGroupLayout=null;}loseContext(){}createDescriptor(e){let t=[],i="";return e.uniformBufferFormats.forEach(e=>{let s=iW.shaderStage(e.visibility);i+=`#${e.slot}U:${s}`,t.push({binding:e.slot,visibility:s,buffer:{type:"uniform",hasDynamicOffset:true}});}),e.textureFormats.forEach(e=>{let s=iW.shaderStage(e.visibility),r=e.sampleType,a=e.textureDimension,n=iq[r];if(i+=`#${e.slot}T:${s}-${n}-${a}-false`,t.push({binding:e.slot,visibility:s,texture:{sampleType:n,viewDimension:a,multisampled:false}}),e.hasSampler){let a=iY[r];i+=`#${e.slot+1}S:${s}-${a}`,t.push({binding:e.slot+1,visibility:s,sampler:{type:a}});}}),e.storageTextureFormats.forEach(e=>{let{format:s,textureDimension:r}=e,{read:a,write:n}=e;i+=`#${e.slot}ST:${s}-${r}-${a?"r1":"r0"}-${n?"w1":"w0"}`,t.push({binding:e.slot,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:a?n?"read-write":"read-only":"write-only",format:iX[s],viewDimension:r}});}),e.storageBufferFormats.forEach(e=>{let s=e.readOnly,r=iW.shaderStage(e.visibility);i+=`#${e.slot}SB:${r}-${s?"ro":"rw"}`,t.push({binding:e.slot,visibility:r,buffer:{type:s?"read-only-storage":"storage"}});}),{key:i,desc:{entries:t}}}constructor(e){let t=e.device,{key:i,desc:s}=this.createDescriptor(e);this.key=ij.get(i),this.bindGroupLayout=t.wgpu.createBindGroupLayout(s);}}class i${destroy(e){this.buffer&&(e.deferDestroy(this.buffer),this.buffer=null);}get initialized(){return !!this.buffer}loseContext(){}allocate(e,t){this.buffer=e.wgpu.createBuffer({size:t,usage:this.usageFlags});}unlock(e,t){let i=e.wgpu;if(!this.buffer){let i=t.byteLength+3&-4;this.usageFlags|=GPUBufferUsage.COPY_DST,this.allocate(e,i);}let s=t.byteOffset??0,r=new Uint8Array(t.buffer??t,s,t.byteLength),a=new Uint8Array(this.buffer.size);a.set(r),i.queue.writeBuffer(this.buffer,0,a,0,a.length);}read(e,t,i,s,r){return e.readStorageBuffer(this,t,i,s,r)}write(e,t,i,s,r){e.writeStorageBuffer(this,t,i,s,r);}clear(e,t,i){e.clearStorageBuffer(this,t,i);}constructor(e=0){this.buffer=null,this.usageFlags=0,this.usageFlags=e;}}class iZ extends i${unlock(e){let t=e.device;super.unlock(t,e.storage);}constructor(e,t){super(16|128*!!t?.storage),this.format=null,this.format=1===e.format?"uint16":"uint32";}}let iQ={equals(e,t){if(e.length!==t.length)return false;for(let i=0;i{let t=e.interleaved,s=e.instancing?"instance":"vertex",r=[],a=e.elements.length;for(let n=0;n1?`x${o.numComponents}`:""}`}),t&&n!==a-1||(i.push({attributes:r,arrayStride:o.stride,stepMode:s}),r=[]);}};return e&&s(e),t&&s(t),i}constructor(){this.cache=new Map;}}class i2{getPipelineLayout(e){let t=[];return e.forEach(e=>{t.push(e.bindGroupLayout);}),this.device.wgpu.createPipelineLayout({bindGroupLayouts:t})}constructor(e){this.device=e;}}let i3=["point-list","line-list",void 0,"line-strip","triangle-list","triangle-strip",void 0],i4=["add","subtract","reverse-subtract","min","max"],i5=["zero","one","src","one-minus-src","dst","one-minus-dst","src-alpha","src-alpha-saturated","one-minus-src-alpha","dst-alpha","one-minus-dst-alpha","constant","one-minus-constant"],i6=["never","less","equal","less-equal","greater","not-equal","greater-equal","always"],i8=["none","back","front"],i9=["ccw","cw"],i7=["keep","zero","replace","increment-clamp","increment-wrap","decrement-clamp","decrement-wrap","invert"],se=["","uint16","uint32"],st=class{};class si extends i2{get(e,t,i,s,r,a,n,o,l,h,c,d,u,f){let p=e.type;s&&3!==p&&5!==p&&(s=void 0);let m=this.lookupHashes;m[0]=p,m[1]=r.id,m[2]=h,m[3]=l.key,m[4]=o.key,m[5]=t?.renderingHash??0,m[6]=i?.renderingHash??0,m[7]=a.impl.key,m[8]=n[0]?.key??0,m[9]=n[1]?.key??0,m[10]=n[2]?.key??0,m[11]=c?d.key:0,m[12]=c?u.key:0,m[13]=s??0,m[14]=f;let _=iM(m),g=this.cache.get(_);if(g)for(let e=0;e0){let e=0;a.redWrite&&(e|=GPUColorWrite.RED),a.greenWrite&&(e|=GPUColorWrite.GREEN),a.blueWrite&&(e|=GPUColorWrite.BLUE),a.alphaWrite&&(e|=GPUColorWrite.ALPHA);let t=this.getBlend(a);_.forEach(i=>{m.fragment.targets.push({format:i.format,writeMask:e,blend:t});});}return f.createRenderPipeline(m)}constructor(e){super(e),this.lookupHashes=new Uint32Array(15),this.vertexBufferLayout=new i1,this.cache=new Map;}}class ss{constructor(){this.pipeline=null,this.hashes=null;}}class sr extends i2{get(e,t){let i=this.lookupHashes;i[0]=e.impl.computeKey,i[1]=t.impl.key;let s=iM(i),r=this.cache.get(s);if(r)for(let e=0;e{e.object?.destroy();}),this.cache.clear();}clear(){this.cache.clear();}get(e){let t=this.cache.get(e);return t?(t.incRefCount(),t.object):null}set(e,t){this.cache.set(e,new sn(t));}release(e){let t=this.cache.get(e);t&&(t.decRefCount(),0===t.refCount&&(this.cache.delete(e),t.object?.destroy()));}constructor(){this.cache=new Map;}}class sl extends so{loseContext(e){this.clear();}}let sh=new is,sc=e=>sh.get(e,()=>new sl),sd=new ia;class su{destroy(){this.multisampledBuffer?.destroy(),this.multisampledBuffer=null;}}class sf{destroy(e){this.depthTextureInternal&&(this.depthTexture?.destroy(),this.depthTexture=null),this.multisampledDepthBuffer&&(this.multisampledDepthBuffer=null,sc(e).release(this.multisampledDepthBufferKey));}constructor(e){this.depthTexture=null,this.depthTextureInternal=false,this.multisampledDepthBuffer=null,this.format=e,this.hasStencil="depth24plus-stencil8"===e;}}class sp{destroy(e){this.initialized=false,this.assignedColorTexture=null,this.colorAttachments.forEach(e=>{e.destroy();}),this.colorAttachments.length=0,this.depthAttachment?.destroy(e),this.depthAttachment=null;}updateKey(){let e=this.renderTarget,t=`${e.samples}:${this.depthAttachment?this.depthAttachment.format:"nodepth"}`;this.colorAttachments.forEach(e=>{t+=`:${e.format}`;}),this.key=sd.get(t);}assignColorTexture(e,t){this.assignedColorTexture=t;let i=t.createView({format:e.backBufferViewFormat}),s=this.renderPassDescriptor.colorAttachments[0];this.renderTarget.samples>1?s.resolveTarget=i:s.view=i,this.setColorAttachment(0,void 0,e.backBufferViewFormat),this.updateKey();}setColorAttachment(e,t,i){this.colorAttachments[e]||(this.colorAttachments[e]=new su),t&&(this.colorAttachments[e].multisampledBuffer=t),i&&(this.colorAttachments[e].format=i);}init(e,t){let i=e.wgpu;this.initDepthStencil(e,i,t),t._colorBuffers&&t._colorBuffers.forEach((e,t)=>{this.setColorAttachment(t,void 0,e.impl.format);}),this.renderPassDescriptor.colorAttachments=[];let s=this.isBackbuffer?1:t._colorBuffers?.length??0;for(let r=0;r1){let n="depth24plus-stencil8";this.depthAttachment.format=n,this.depthAttachment.hasStencil=true;let l=`${o.id}:${r}:${a}:${s}:${n}`,h=sc(e),c=h.get(l);if(!c){let e={size:[r,a,1],dimension:"2d",sampleCount:s,format:n,usage:GPUTextureUsage.RENDER_ATTACHMENT|(n!==o.impl.format?GPUTextureUsage.TEXTURE_BINDING:0)};c=t.createTexture(e),h.set(l,c);}this.depthAttachment.multisampledDepthBuffer=c,this.depthAttachment.multisampledDepthBufferKey=l,i=c.createView();}else {let e=o.impl.gpuTexture;this.depthAttachment.depthTexture=e,i=e.createView();}else {this.depthAttachment=new sf("depth24plus-stencil8");let e={size:[r,a,1],dimension:"2d",sampleCount:s,format:this.depthAttachment.format,usage:GPUTextureUsage.RENDER_ATTACHMENT};s>1?e.usage|=GPUTextureUsage.TEXTURE_BINDING:e.usage|=GPUTextureUsage.COPY_SRC;let n=t.createTexture(e);this.depthAttachment.depthTexture=n,this.depthAttachment.depthTextureInternal=true,i=n.createView();}this.renderPassDescriptor.depthStencilAttachment={view:i};}}initColor(e,t,i,s){let r={},{samples:a,width:n,height:o,mipLevel:l}=i,h=i.getColorBuffer(s),c=null;if(h&&(c=h.cubemap?h.impl.createView({dimension:"2d",baseArrayLayer:i.face,arrayLayerCount:1,mipLevelCount:1,baseMipLevel:l}):h.impl.createView({mipLevelCount:1,baseMipLevel:l})),a>1){let i={size:[n,o,1],dimension:"2d",sampleCount:a,format:this.isBackbuffer?e.backBufferViewFormat:h.impl.format,usage:GPUTextureUsage.RENDER_ATTACHMENT},l=t.createTexture(i);this.setColorAttachment(s,l,i.format),r.view=l.createView(),r.resolveTarget=c;}else r.view=c;return r}setupForRenderPass(e,t){let i=this.renderPassDescriptor.colorAttachments?.length??0;for(let s=0;s0}calculateOffset(e){let t=this.byteSize<=8?this.byteSize:16;this.count&&(t=16),e=ei.roundUp(e,t),this.offset=e/4;}constructor(e,t,i=0){if(this.shortName=e,this.name=i?`${e}[0]`:e,this.type=t,this.numComponents=sm[t],this.updateType=t,i>0)switch(t){case 2:this.updateType=17;break;case 1:this.updateType=30;break;case 26:this.updateType=31;break;case 0:this.updateType=32;break;case 3:this.updateType=21;break;case 6:this.updateType=33;break;case 27:this.updateType=34;break;case 9:this.updateType=35;break;case 4:this.updateType=22;break;case 7:this.updateType=36;break;case 28:this.updateType=37;break;case 10:this.updateType=38;break;case 5:this.updateType=23;break;case 8:this.updateType=39;break;case 29:this.updateType=40;break;case 11:this.updateType=41;break;case 14:this.updateType=24;}this.count=i;let s=this.numComponents;i&&(s=ei.roundUp(s,4)),this.byteSize=4*s,i&&(this.byteSize*=i);}}class sg{get(e){return this.map.get(e)}constructor(e,t){this.byteSize=0,this.map=new Map,this.scope=e.scope,this.uniforms=t;let i=0;for(let e=0;enew sb(e,i)),u=sC.processUniforms(e,d,t.processingOptions,i),f=`${o} -${l} -${u.code}`,p=r.src.replace("@@@",f),m=`${h} -${c} -${u.code}`;return {vshader:p,fshader:a.src.replace("@@@",m),attributes:n,meshUniformBufferFormat:u.meshUniformBufferFormat,meshBindGroupFormat:u.meshBindGroupFormat}}static extract(e){let t,i=[],s=[],r=[],a=[],n=`@@@ -`;for(;null!==(t=sv.exec(e));){let o=t[1];switch(o){case "attribute":case "varying":case "uniform":case "out":{sS.lastIndex=t.index;let l=sS.exec(e);"attribute"===o?i.push(l[2]):"varying"===o?s.push(l[2]):"out"===o?r.push(l[2]):"uniform"===o&&a.push(l[2]),e=sC.cutOut(e,t.index,sS.lastIndex,n),sv.lastIndex=t.index+n.length,n="";}}}return {src:e,attributes:i,varyings:s,outs:r,uniforms:a}}static processUniforms(e,t,i,s){let r=[],a=[];t.forEach(e=>{e.isSampler?r.push(e):a.push(e);});let n=[];a.forEach(e=>{if(!i.hasUniform(e.name)){let t=tG.indexOf(e.type),i=new s_(e.name,t,e.arraySize);n.push(i);}}),0===n.length&&n.push(new s_(tJ,2));let o=n.length?new sg(e,n):null,l=[];r.forEach(e=>{if(!i.hasTexture(e.name)){let t=0;e.isSignedInt?t=3:e.isUnsignedInt?t=4:("highp"===e.precision&&(t=1),sT.has(e.type)&&(t=2));let i=sE[e.type];l.push(new ie(e.name,3,i,t));}});let h=new ii(e,l),c="";return i.uniformFormats.forEach((e,t)=>{e&&(c+=sC.getUniformShaderDeclaration(e,t,0));}),o&&(c+=sC.getUniformShaderDeclaration(o,2,0)),i.bindGroupFormats.forEach((e,t)=>{e&&(c+=sC.getTexturesShaderDeclaration(e,t));}),{code:c+=sC.getTexturesShaderDeclaration(h,1),meshUniformBufferFormat:o,meshBindGroupFormat:h}}static processVaryings(e,t,i){let s="",r=i?"out":"in";return e.forEach((e,a)=>{let n=sC.splitToWords(e),o=n.slice(0,-1).join(" "),l=n[n.length-1];i?t.set(l,a):a=t.get(l),s+=`layout(location = ${a}) ${r} ${o} ${l}; -`;}),s}static processOuts(e){let t="";return e.forEach((e,i)=>{t+=`layout(location = ${i}) out ${e}; -`;}),t}static getTypeCount(e){let t=parseInt(e.substring(e.length-1),10);return isNaN(t)?1:t}static processAttributes(e,t,i,s){let r="";return e.forEach(e=>{let a=sC.splitToWords(e),n=a[0],o=a[1];if(t.hasOwnProperty(o)){let e,a=t[o],l=t5[a];i.set(l,o);let h=s.getVertexElement(a);if(h){let t=h.dataType;if(6!==t&&7!==t&&!h.normalize&&!h.asInt){let i=sC.getTypeCount(n),s=`_private_${o}`;e=`vec${i} ${o} = vec${i}(${s}); -`,o=s;let r=0===t||2===t||4===t;n=1===i?r?"int":"uint":r?`ivec${i}`:`uvec${i}`;}}r+=`layout(location = ${l}) in ${n} ${o}; -`,e&&(r+=e);}}),r}static splitToWords(e){return (e=e.replace(/\s+/g," ").trim()).split(" ")}static cutOut(e,t,i,s){return e.substring(0,t)+s+e.substring(i)}static getUniformShaderDeclaration(e,t,i){let s=tZ[t],r=`layout(set = ${t}, binding = ${i}, std140) uniform ub_${s} { -`;return e.uniforms.forEach(e=>{let t=tG[e.type];r+=` ${t} ${e.shortName}${e.count?`[${e.count}]`:""}; -`;}),`${r}}; -`}static getTexturesShaderDeclaration(e,t){let i="";return e.textureFormats.forEach(e=>{let s=sw[e.textureDimension],r="texture2DArray"===s,a=4===e.sampleType?"u":3===e.sampleType?"i":"";s=`${a}${s}`;let n="",o="";r&&(n="_texture",o=`#define ${e.name} ${a}sampler2DArray(${e.name}${n}, ${e.name}_sampler) -`),i+=`layout(set = ${t}, binding = ${e.slot}) uniform ${s} ${e.name}${n}; -`,e.hasSampler&&(i+=`layout(set = ${t}, binding = ${e.slot+1}) uniform sampler ${e.name}_sampler; -`),i+=o;}),i}}let sA=/^[ \t]*(attribute|varying|uniform)[\t ]+/gm,sP=/^[ \t]*(attribute|varying|uniform)[ \t]*([^;]+)(;+)/gm,sI=/^[ \t]*var\s*(?:(]*>)\s*([\w\d_]+)\s*:\s*(.*?)\s*;|(<(?!storage,)[^>]*>)?\s*([\w\d_]+)\s*:\s*(texture_.*|storage_texture_.*|storage\w.*|external_texture|sampler(?:_comparison)?)\s*;)\s*$/gm,sD=/(?:@interpolate\([^)]*\)\s*)?([\w]+)\s*:\s*([\w<>]+)/,sR=/(@vertex|@fragment)\s*fn\s+\w+\s*\(\s*(\w+)\s*:[\s\S]*?\{/,sL={texture_1d:{viewDimension:"1d",baseSampleType:0},texture_2d:{viewDimension:"2d",baseSampleType:0},texture_2d_array:{viewDimension:tM,baseSampleType:0},texture_3d:{viewDimension:"3d",baseSampleType:0},texture_cube:{viewDimension:tO,baseSampleType:0},texture_cube_array:{viewDimension:tF,baseSampleType:0},texture_multisampled_2d:{viewDimension:"2d",baseSampleType:0},texture_depth_2d:{viewDimension:"2d",baseSampleType:2},texture_depth_2d_array:{viewDimension:tM,baseSampleType:2},texture_depth_cube:{viewDimension:tO,baseSampleType:2},texture_depth_cube_array:{viewDimension:tF,baseSampleType:2},texture_external:{viewDimension:"2d",baseSampleType:1}},sM={f32:"WrappedF32",i32:"WrappedI32",u32:"WrappedU32",vec2f:"WrappedVec2F",vec2i:"WrappedVec2I",vec2u:"WrappedVec2U"},sO=e=>(e=e.replace(/\s+/g," ").trim()).split(/[\s:]+/),sF=/array<([^,]+),\s*([^>]+)>/;class sN{constructor(e,t){this.ubName=null,this.arraySize=0,this.line=e;let i=sO(e);if(i.length<2){t.failed=true;return}if(this.name=i[0],this.type=i.slice(1).join(" "),this.type.includes("array<")){let e=sF.exec(this.type);this.type=e[1].trim(),this.arraySize=Number(e[2]),isNaN(this.arraySize)&&(t.failed=true);}}}let sB=/^\s*var\s+(\w+)\s*:\s*(texture_\w+)(?:<(\w+)>)?;\s*$/,sk=/^\s*var\s+([\w\d_]+)\s*:\s*(texture_storage_2d|texture_storage_2d_array)<([\w\d_]+),\s*(\w+)>\s*;\s*$/,sU=/^\s*var\s*\s*([\w\d_]+)\s*:\s*(.*)\s*;\s*$/,sz=/^\s*var\s+([\w\d_]+)\s*:\s*texture_external;\s*$/,sV=/^\s*var\s+([\w\d_]+)\s*:\s*(sampler|sampler_comparison)\s*;\s*$/;class sG{equals(e){return this.name===e.name&&this.type===e.type&&this.isTexture===e.isTexture&&this.isSampler===e.isSampler&&this.isStorageTexture===e.isStorageTexture&&this.isStorageBuffer===e.isStorageBuffer&&this.isExternalTexture===e.isExternalTexture&&this.textureFormat===e.textureFormat&&this.textureDimension===e.textureDimension&&this.sampleType===e.sampleType&&this.textureType===e.textureType&&this.format===e.format&&this.access===e.access&&this.accessMode===e.accessMode&&this.samplerType===e.samplerType&&true}constructor(e,t){this.originalLine=e,this.line=e,this.isTexture=false,this.isSampler=false,this.isStorageTexture=false,this.isStorageBuffer=false,this.isExternalTexture=false,this.type="",this.matchedElements=[];let i=this.line.match(sB);if(i){this.name=i[1],this.type=i[2],this.textureFormat=i[3],this.isTexture=true,this.matchedElements.push(...i);let e=((e,t)=>{let i=sL[e],s=i.baseSampleType;if(0===i.baseSampleType&&"texture_multisampled_2d"!==e)switch(t){case "u32":s=4;break;case "i32":s=3;break;case "f32":s=0;break;case "uff":s=1;}return {viewDimension:i.viewDimension,sampleType:s}})(this.type,this.textureFormat);this.textureDimension=e.viewDimension,this.sampleType=e.sampleType;}let s=this.line.match(sk);s&&(this.isStorageTexture=true,this.name=s[1],this.textureType=s[2],this.format=s[3],this.access=s[4],this.matchedElements.push(...s));let r=this.line.match(sU);r&&(this.isStorageBuffer=true,this.accessMode=r[1]||"none",this.name=r[2],this.type=r[3],this.matchedElements.push(...r));let a=this.line.match(sz);a&&(this.name=a[1],this.isExternalTexture=true,this.matchedElements.push(...r));let n=this.line.match(sV);n&&(this.name=n[1],this.samplerType=n[2],this.isSampler=true,this.matchedElements.push(...n)),0===this.matchedElements.length&&(t.failed=true);}}class sH{static run(e,t,i){let s=new Map,r=sH.extract(t.vshader),a=sH.extract(t.fshader),n=new Map,o=sH.processAttributes(r.attributes,t.attributes,n,t.processingOptions,i),l=sH.processVaryings(r.varyings,s,true,e),h=sH.processVaryings(a.varyings,s,false,e),c=Array.from(new Set(r.uniforms.concat(a.uniforms))).map(e=>new sN(e,i)),d=sH.processUniforms(e,c,t.processingOptions,i);r.src=sH.renameUniformAccess(r.src,c),a.src=sH.renameUniformAccess(a.src,c);let u=sH.mergeResources(r.resources,a.resources,i),f=sH.processResources(e,u,t.processingOptions,i),p=sH.generateFragmentOutputStruct(a.src,e.maxColorAttachments);r.src=sH.copyInputs(r.src,i),a.src=sH.copyInputs(a.src,i);let m=`${o} -${l} -${d.code} -${f.code} -`,_=r.src.replace("@@@",m),g=`${h} -${p} -${d.code} -${f.code} -`;return {vshader:_,fshader:a.src.replace("@@@",g),attributes:n,meshUniformBufferFormat:d.meshUniformBufferFormat,meshBindGroupFormat:f.meshBindGroupFormat}}static extract(e){let t,i=[],s=[],r=[],a=[],n=`@@@ -`;for(;null!==(t=sA.exec(e));){let a=t[1];sP.lastIndex=t.index;let o=sP.exec(e);"attribute"===a?i.push(o[2]):"varying"===a?s.push(o[2]):"uniform"===a&&r.push(o[2]),e=sH.cutOut(e,t.index,sP.lastIndex,n),sA.lastIndex=t.index+n.length,n="";}for(;null!==(t=sI.exec(e));)a.push(t[0]),e=sH.cutOut(e,t.index,sI.lastIndex,n),sI.lastIndex=t.index+n.length,n="";return {src:e,attributes:i,varyings:s,uniforms:r,resources:a}}static processUniforms(e,t,i,s){let r=[];t.forEach(e=>{if(i.hasUniform(e.name))e.ubName="ub_view";else {e.ubName="ub_mesh_ub";let t=tW.get(e.type),i=new s_(e.name,t,e.arraySize);r.push(i);}}),0===r.length&&r.push(new s_(tJ,2));let a=new sg(e,r),n="";return i.uniformFormats.forEach((e,t)=>{e&&(n+=sH.getUniformShaderDeclaration(e,t,0));}),a&&(n+=sH.getUniformShaderDeclaration(a,2,0)),{code:n,meshUniformBufferFormat:a}}static renameUniformAccess(e,t){return t.forEach(t=>{let i=`uniform.${t.name}`,s=`${t.ubName}.${t.name}`,r=RegExp(`\\b${i}\\b`,"g");e=e.replace(r,s);}),e}static mergeResources(e,t,i){let s=e.map(e=>new sG(e,i));return t.map(e=>new sG(e,i)).forEach(e=>{let t=s.find(t=>t.name===e.name);t?t.equals(e)||(i.failed=true):s.push(e);}),s}static processResources(e,t,i,s){let r=[];for(let e=0;e{e&&(n+=sH.getTextureShaderDeclaration(e,t));}),{code:n+=sH.getTextureShaderDeclaration(a,1),meshBindGroupFormat:a}}static getUniformShaderDeclaration(e,t,i){let s=tZ[t],r=`struct_ub_${s}`,a=`struct ${r} { -`;return e.uniforms.forEach(e=>{let t=tH[e.type][0];e.count>0?(sM.hasOwnProperty(t)&&(t=sM[t]),a+=` ${e.shortName}: array<${t}, ${e.count}>, -`):a+=` ${e.shortName}: ${t}, -`;}),a+=`}; -@group(${t}) @binding(${i}) var ub_${s} : ${r}; +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.pc = {})); +})(this, (function (exports) { 'use strict'; + var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null; +var pc=(()=>{var Ix=Object.defineProperty;var UH=Object.getOwnPropertyDescriptor;var kH=Object.getOwnPropertyNames;var zH=Object.prototype.hasOwnProperty;var GH=(c,t,e)=>t in c?Ix(c,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):c[t]=e;var EC=(c=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(c,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):c)(function(c){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+c+'" is not supported')});var VH=(c,t)=>{for(var e in t)Ix(c,e,{get:t[e],enumerable:!0})},HH=(c,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of kH(t))!zH.call(c,i)&&i!==e&&Ix(c,i,{get:()=>t[i],enumerable:!(s=UH(t,i))||s.enumerable});return c};var WH=c=>HH(Ix({},"__esModule",{value:!0}),c);var n=(c,t,e)=>GH(c,typeof t!="symbol"?t+"":t,e);var r7={};VH(r7,{ABSOLUTE_URL:()=>Ja,ACTION_GAMEPAD:()=>Gg,ACTION_KEYBOARD:()=>zg,ACTION_MOUSE:()=>kg,ADDRESS_CLAMP_TO_EDGE:()=>ie,ADDRESS_MIRRORED_REPEAT:()=>xo,ADDRESS_REPEAT:()=>Je,AMBIENTSRC_AMBIENTSH:()=>mp,AMBIENTSRC_CONSTANT:()=>gp,AMBIENTSRC_ENVALATLAS:()=>_p,ANIM_BLEND_1D:()=>hB,ANIM_BLEND_2D_CARTESIAN:()=>KI,ANIM_BLEND_2D_DIRECTIONAL:()=>YI,ANIM_BLEND_DIRECT:()=>jI,ANIM_CONTROL_STATES:()=>sh,ANIM_EQUAL_TO:()=>WI,ANIM_GREATER_THAN:()=>zI,ANIM_GREATER_THAN_EQUAL_TO:()=>VI,ANIM_INTERRUPTION_NEXT:()=>BI,ANIM_INTERRUPTION_NEXT_PREV:()=>kI,ANIM_INTERRUPTION_NONE:()=>Am,ANIM_INTERRUPTION_PREV:()=>NI,ANIM_INTERRUPTION_PREV_NEXT:()=>UI,ANIM_LAYER_ADDITIVE:()=>$I,ANIM_LAYER_OVERWRITE:()=>OS,ANIM_LESS_THAN:()=>GI,ANIM_LESS_THAN_EQUAL_TO:()=>HI,ANIM_NOT_EQUAL_TO:()=>XI,ANIM_PARAMETER_BOOLEAN:()=>g0,ANIM_PARAMETER_FLOAT:()=>_0,ANIM_PARAMETER_INTEGER:()=>m0,ANIM_PARAMETER_TRIGGER:()=>cu,ANIM_STATE_ANY:()=>fu,ANIM_STATE_END:()=>qI,ANIM_STATE_START:()=>hu,ASPECT_AUTO:()=>Ac,ASPECT_MANUAL:()=>vp,ASSET_ANIMATION:()=>r8,ASSET_AUDIO:()=>a8,ASSET_CONTAINER:()=>S8,ASSET_CSS:()=>m8,ASSET_CUBEMAP:()=>d8,ASSET_HTML:()=>_8,ASSET_IMAGE:()=>o8,ASSET_JSON:()=>n8,ASSET_MATERIAL:()=>c8,ASSET_MODEL:()=>l8,ASSET_SCRIPT:()=>g8,ASSET_SHADER:()=>p8,ASSET_TEXT:()=>h8,ASSET_TEXTURE:()=>f8,ASSET_TEXTUREATLAS:()=>u8,AXIS_KEY:()=>pae,AXIS_MOUSE_X:()=>bW,AXIS_MOUSE_Y:()=>DW,AXIS_PAD_L_X:()=>LW,AXIS_PAD_L_Y:()=>MW,AXIS_PAD_R_X:()=>OW,AXIS_PAD_R_Y:()=>FW,AnimBinder:()=>ua,AnimClip:()=>th,AnimClipHandler:()=>T_,AnimComponent:()=>du,AnimComponentLayer:()=>Im,AnimComponentSystem:()=>Rm,AnimController:()=>wm,AnimCurve:()=>Th,AnimData:()=>an,AnimEvaluator:()=>ih,AnimEvents:()=>rh,AnimSnapshot:()=>lu,AnimStateGraph:()=>en,AnimStateGraphHandler:()=>y_,AnimTarget:()=>ml,AnimTrack:()=>Qs,Animation:()=>iu,AnimationComponent:()=>uu,AnimationComponentSystem:()=>Pm,AnimationHandler:()=>v_,AnimationKey:()=>fl,AnimationNode:()=>ul,AppBase:()=>Pi,AppOptions:()=>Tm,Application:()=>mA,Asset:()=>ae,AssetListLoader:()=>_A,AssetReference:()=>pa,AssetRegistry:()=>ha,AudioHandler:()=>E_,AudioListenerComponent:()=>pu,AudioListenerComponentSystem:()=>bm,BAKE_COLOR:()=>sY,BAKE_COLORDIR:()=>zf,BINDGROUP_MESH:()=>Ua,BINDGROUP_MESH_UB:()=>$r,BINDGROUP_VIEW:()=>Io,BLENDEQUATION_ADD:()=>ii,BLENDEQUATION_MAX:()=>SD,BLENDEQUATION_MIN:()=>gD,BLENDEQUATION_REVERSE_SUBTRACT:()=>_D,BLENDEQUATION_SUBTRACT:()=>XZ,BLENDMODE_CONSTANT:()=>kC,BLENDMODE_CONSTANT_ALPHA:()=>jq,BLENDMODE_CONSTANT_COLOR:()=>Yq,BLENDMODE_DST_ALPHA:()=>HZ,BLENDMODE_DST_COLOR:()=>UC,BLENDMODE_ONE:()=>_s,BLENDMODE_ONE_MINUS_CONSTANT:()=>zC,BLENDMODE_ONE_MINUS_CONSTANT_ALPHA:()=>qq,BLENDMODE_ONE_MINUS_CONSTANT_COLOR:()=>Kq,BLENDMODE_ONE_MINUS_DST_ALPHA:()=>WZ,BLENDMODE_ONE_MINUS_DST_COLOR:()=>mD,BLENDMODE_ONE_MINUS_SRC_ALPHA:()=>Zl,BLENDMODE_ONE_MINUS_SRC_COLOR:()=>GZ,BLENDMODE_SRC_ALPHA:()=>$l,BLENDMODE_SRC_ALPHA_SATURATE:()=>VZ,BLENDMODE_SRC_COLOR:()=>pD,BLENDMODE_ZERO:()=>Fx,BLEND_ADDITIVE:()=>ea,BLEND_ADDITIVEALPHA:()=>op,BLEND_MAX:()=>hp,BLEND_MIN:()=>cp,BLEND_MULTIPLICATIVE:()=>ap,BLEND_MULTIPLICATIVE2X:()=>np,BLEND_NONE:()=>wt,BLEND_NORMAL:()=>ls,BLEND_PREMULTIPLIED:()=>Ms,BLEND_SCREEN:()=>lp,BLEND_SUBTRACTIVE:()=>rp,BLUR_BOX:()=>RX,BLUR_GAUSSIAN:()=>Kg,BODYFLAG_KINEMATIC_OBJECT:()=>b0,BODYFLAG_NORESPONSE_OBJECT:()=>gu,BODYFLAG_STATIC_OBJECT:()=>gB,BODYGROUP_DEFAULT:()=>uke,BODYGROUP_DYNAMIC:()=>vB,BODYGROUP_ENGINE_1:()=>dke,BODYGROUP_ENGINE_2:()=>pke,BODYGROUP_ENGINE_3:()=>mke,BODYGROUP_KINEMATIC:()=>TB,BODYGROUP_NONE:()=>fke,BODYGROUP_STATIC:()=>iR,BODYGROUP_TRIGGER:()=>yB,BODYGROUP_USER_1:()=>_ke,BODYGROUP_USER_2:()=>gke,BODYGROUP_USER_3:()=>Ske,BODYGROUP_USER_4:()=>xke,BODYGROUP_USER_5:()=>vke,BODYGROUP_USER_6:()=>Tke,BODYGROUP_USER_7:()=>yke,BODYGROUP_USER_8:()=>Eke,BODYMASK_ALL:()=>rR,BODYMASK_NONE:()=>Ake,BODYMASK_NOT_STATIC:()=>D0,BODYMASK_NOT_STATIC_KINEMATIC:()=>Pke,BODYMASK_STATIC:()=>Cke,BODYSTATE_ACTIVE_TAG:()=>Mm,BODYSTATE_DISABLE_DEACTIVATION:()=>HS,BODYSTATE_DISABLE_SIMULATION:()=>WS,BODYSTATE_ISLAND_SLEEPING:()=>SB,BODYSTATE_WANTS_DEACTIVATION:()=>xB,BODYTYPE_DYNAMIC:()=>Ui,BODYTYPE_KINEMATIC:()=>tn,BODYTYPE_STATIC:()=>Sl,BUFFERUSAGE_COPY_DST:()=>$e,BUFFERUSAGE_COPY_SRC:()=>mi,BUFFERUSAGE_INDEX:()=>U4,BUFFERUSAGE_INDIRECT:()=>pn,BUFFERUSAGE_READ:()=>Nx,BUFFERUSAGE_STORAGE:()=>GC,BUFFERUSAGE_UNIFORM:()=>z4,BUFFERUSAGE_VERTEX:()=>k4,BUFFERUSAGE_WRITE:()=>YZ,BUFFER_DYNAMIC:()=>hd,BUFFER_GPUDYNAMIC:()=>Bx,BUFFER_STATIC:()=>Xs,BUFFER_STREAM:()=>VC,BUTTON_TRANSITION_MODE_SPRITE_CHANGE:()=>uB,BUTTON_TRANSITION_MODE_TINT:()=>eR,Batch:()=>Xf,BatchGroup:()=>pt,BatchManager:()=>Rp,BinaryHandler:()=>A_,BindGroupFormat:()=>Ue,BindStorageBufferFormat:()=>K,BindStorageTextureFormat:()=>Xn,BindTextureFormat:()=>Ki,BindUniformBufferFormat:()=>Qe,BlendState:()=>Oe,BoundingBox:()=>ge,BoundingSphere:()=>Br,BoxGeometry:()=>ci,Bundle:()=>$c,BundleHandler:()=>_m,BundleRegistry:()=>pm,ButtonComponent:()=>es,ButtonComponentSystem:()=>Lm,CHUNKAPI_1_51:()=>$q,CHUNKAPI_1_55:()=>Zq,CHUNKAPI_1_56:()=>Qq,CHUNKAPI_1_57:()=>Jq,CHUNKAPI_1_58:()=>e$,CHUNKAPI_1_60:()=>t$,CHUNKAPI_1_62:()=>s$,CHUNKAPI_1_65:()=>i$,CHUNKAPI_1_70:()=>r$,CHUNKAPI_2_1:()=>a$,CHUNKAPI_2_3:()=>o$,CHUNKAPI_2_5:()=>n$,CHUNKAPI_2_6:()=>l$,CHUNKAPI_2_7:()=>c$,CHUNKAPI_2_8:()=>h$,CLEARFLAG_COLOR:()=>mn,CLEARFLAG_DEPTH:()=>_n,CLEARFLAG_STENCIL:()=>Yh,CUBEFACE_NEGX:()=>jZ,CUBEFACE_NEGY:()=>$Z,CUBEFACE_NEGZ:()=>QZ,CUBEFACE_POSX:()=>KZ,CUBEFACE_POSY:()=>qZ,CUBEFACE_POSZ:()=>ZZ,CUBEPROJ_BOX:()=>gT,CUBEPROJ_NONE:()=>pp,CULLFACE_BACK:()=>gn,CULLFACE_FRONT:()=>HC,CULLFACE_FRONTANDBACK:()=>G4,CULLFACE_NONE:()=>Ze,CURVE_LINEAR:()=>M4,CURVE_SMOOTHSTEP:()=>RC,CURVE_SPLINE:()=>cD,CURVE_STEP:()=>O4,Camera:()=>Bs,CameraComponent:()=>ar,CameraComponentSystem:()=>o_,CameraFrame:()=>WA,CameraFrameOptions:()=>Wu,CanvasFont:()=>gA,CapsuleGeometry:()=>Yc,ChunkUtils:()=>li,CollisionComponent:()=>eo,CollisionComponentSystem:()=>Fm,Color:()=>F,Component:()=>le,ComponentSystem:()=>Fe,ComponentSystemRegistry:()=>mm,Compute:()=>Ye,ComputeRadixSort:()=>tm,ConeGeometry:()=>qa,ContactPoint:()=>KS,ContactResult:()=>jS,ContainerHandler:()=>P_,ContainerResource:()=>GE,Controller:()=>sT,CssHandler:()=>w_,CubemapHandler:()=>I_,Curve:()=>Ps,CurveSet:()=>ki,CylinderGeometry:()=>Ci,DETAILMODE_ADD:()=>FX,DETAILMODE_MAX:()=>kX,DETAILMODE_MIN:()=>UX,DETAILMODE_MUL:()=>ST,DETAILMODE_OVERLAY:()=>BX,DETAILMODE_SCREEN:()=>NX,DEVICETYPE_NULL:()=>Tf,DEVICETYPE_WEBGL2:()=>vf,DEVICETYPE_WEBGPU:()=>Ig,DEVICETYPE_WEBGPU_BARE:()=>Xx,DISPLAYFORMAT_HDR:()=>mP,DISPLAYFORMAT_LDR:()=>pP,DISPLAYFORMAT_LDR_SRGB:()=>Md,DISTANCE_EXPONENTIAL:()=>dX,DISTANCE_INVERSE:()=>uX,DISTANCE_LINEAR:()=>ep,DITHER_BAYER8:()=>dL,DITHER_BLUENOISE:()=>pL,DITHER_IGNNOISE:()=>mL,DITHER_NONE:()=>Bi,DefaultAnimBinder:()=>ah,DepthState:()=>Pt,DomeGeometry:()=>jp,DrawCommands:()=>Cf,DualGestureSource:()=>YA,ELEMENTTYPE_GROUP:()=>mu,ELEMENTTYPE_IMAGE:()=>Dm,ELEMENTTYPE_TEXT:()=>kS,EMITTERSHAPE_BOX:()=>Ni,EMITTERSHAPE_SPHERE:()=>hw,EVENT_CULL_END:()=>Pw,EVENT_GAMEPADCONNECTED:()=>N$,EVENT_GAMEPADDISCONNECTED:()=>B$,EVENT_KEYDOWN:()=>P$,EVENT_KEYUP:()=>w$,EVENT_MOUSEDOWN:()=>I$,EVENT_MOUSEMOVE:()=>R$,EVENT_MOUSEUP:()=>b$,EVENT_MOUSEWHEEL:()=>D$,EVENT_POSTCULL:()=>sS,EVENT_POSTRENDER:()=>Ew,EVENT_POSTRENDER_LAYER:()=>Cw,EVENT_PRECULL:()=>tS,EVENT_PRERENDER:()=>yw,EVENT_PRERENDER_LAYER:()=>Aw,EVENT_SELECT:()=>U$,EVENT_SELECTEND:()=>z$,EVENT_SELECTSTART:()=>k$,EVENT_TOUCHCANCEL:()=>F$,EVENT_TOUCHEND:()=>M$,EVENT_TOUCHMOVE:()=>O$,EVENT_TOUCHSTART:()=>L$,ElementComponent:()=>zs,ElementComponentSystem:()=>zm,ElementDragHelper:()=>io,ElementInput:()=>J_,ElementInputEvent:()=>Gu,ElementMouseEvent:()=>Ll,ElementSelectEvent:()=>ga,ElementTouchEvent:()=>Ml,Entity:()=>Ne,EnvLighting:()=>bc,EventHandle:()=>td,EventHandler:()=>J,FILLMODE_FILL_WINDOW:()=>bI,FILLMODE_KEEP_ASPECT:()=>Ky,FILLMODE_NONE:()=>s8,FILTER_LINEAR:()=>De,FILTER_LINEAR_MIPMAP_LINEAR:()=>gs,FILTER_LINEAR_MIPMAP_NEAREST:()=>kr,FILTER_NEAREST:()=>ve,FILTER_NEAREST_MIPMAP_LINEAR:()=>Ur,FILTER_NEAREST_MIPMAP_NEAREST:()=>zi,FITMODE_CONTAIN:()=>tR,FITMODE_COVER:()=>sR,FITMODE_STRETCH:()=>_u,FITTING_BOTH:()=>J8,FITTING_NONE:()=>xR,FITTING_SHRINK:()=>DB,FITTING_STRETCH:()=>Q8,FOG_EXP:()=>mX,FOG_EXP2:()=>_X,FOG_LINEAR:()=>rw,FOG_NONE:()=>Mi,FONT_BITMAP:()=>dR,FONT_MSDF:()=>vu,FRESNEL_NONE:()=>hL,FRESNEL_SCHLICK:()=>Sc,FRONTFACE_CCW:()=>Sn,FRONTFACE_CW:()=>xD,FUNC_ALWAYS:()=>zr,FUNC_EQUAL:()=>ud,FUNC_GREATER:()=>H4,FUNC_GREATEREQUAL:()=>X4,FUNC_LESS:()=>fd,FUNC_LESSEQUAL:()=>WC,FUNC_NEVER:()=>V4,FUNC_NOTEQUAL:()=>W4,FloatPacking:()=>Hs,FlyController:()=>QA,FocusController:()=>eC,FogParams:()=>Zp,FolderHandler:()=>R_,Font:()=>Ou,FontHandler:()=>b_,ForwardRenderer:()=>Bc,FramePass:()=>Nt,FramePassBloom:()=>rg,FramePassCameraFrame:()=>hg,FramePassColorGrab:()=>wc,FramePassDof:()=>ng,FramePassRadixSort:()=>By,Frustum:()=>So,GAMMA_NONE:()=>Zi,GAMMA_SRGB:()=>No,GIZMOAXIS_FACE:()=>RH,GIZMOAXIS_X:()=>yH,GIZMOAXIS_XY:()=>wH,GIZMOAXIS_XYZ:()=>IH,GIZMOAXIS_XZ:()=>PH,GIZMOAXIS_Y:()=>EH,GIZMOAXIS_YZ:()=>CH,GIZMOAXIS_Z:()=>AH,GIZMOSPACE_LOCAL:()=>vH,GIZMOSPACE_WORLD:()=>TH,GSPLATDATA_COMPACT:()=>iS,GSPLATDATA_LARGE:()=>aY,GSPLAT_DEBUG_AABBS:()=>AT,GSPLAT_DEBUG_HEATMAP:()=>Ep,GSPLAT_DEBUG_LOD:()=>Pc,GSPLAT_DEBUG_NODE_AABBS:()=>CT,GSPLAT_DEBUG_NONE:()=>Wf,GSPLAT_DEBUG_SH_UPDATE:()=>yp,GSPLAT_FORWARD:()=>Fs,GSPLAT_RENDERER_AUTO:()=>ET,GSPLAT_RENDERER_COMPUTE:()=>Hf,GSPLAT_RENDERER_RASTER_CPU_SORT:()=>tl,GSPLAT_RENDERER_RASTER_GPU_SORT:()=>Cc,GSPLAT_SHADOW:()=>el,GSPLAT_STREAM_INSTANCE:()=>Vf,GSPLAT_STREAM_RESOURCE:()=>Rw,GSplatComponent:()=>Du,GSplatComponentSystem:()=>vh,GSplatContainer:()=>Hy,GSplatData:()=>Qa,GSplatFormat:()=>Pr,GSplatHandler:()=>D_,GSplatInstance:()=>hm,GSplatProcessor:()=>Yy,GSplatResource:()=>$o,GSplatResourceBase:()=>rt,GSplatSogData:()=>ca,GSplatSogResource:()=>jc,GamePads:()=>Qd,GamepadSource:()=>Tx,Geometry:()=>Jt,Gizmo:()=>ho,GltfExporter:()=>kA,GraphNode:()=>Pe,GraphicsDevice:()=>tt,HierarchyHandler:()=>L_,HtmlHandler:()=>M_,Http:()=>Vt,I18n:()=>fa,INDEXFORMAT_UINT16:()=>Is,INDEXFORMAT_UINT32:()=>Ii,INDEXFORMAT_UINT8:()=>dd,INTERPOLATION_CUBIC:()=>FI,INTERPOLATION_LINEAR:()=>OI,INTERPOLATION_STEP:()=>cB,ImageElement:()=>Nm,IndexBuffer:()=>os,IndexedList:()=>sd,InputConsumer:()=>vx,InputController:()=>fn,InputDelta:()=>Sx,InputFrame:()=>xx,InputSource:()=>cr,JointComponent:()=>hh,JointComponentSystem:()=>Gm,JsonHandler:()=>O_,JsonStandardMaterialParser:()=>F_,KEY_0:()=>Bae,KEY_1:()=>Uae,KEY_2:()=>kae,KEY_3:()=>zae,KEY_4:()=>Gae,KEY_5:()=>Vae,KEY_6:()=>Hae,KEY_7:()=>Wae,KEY_8:()=>Xae,KEY_9:()=>Yae,KEY_A:()=>qae,KEY_ADD:()=>Ooe,KEY_ALT:()=>Tae,KEY_B:()=>$ae,KEY_BACKSPACE:()=>mae,KEY_BACK_SLASH:()=>tne,KEY_C:()=>Zae,KEY_CAPS_LOCK:()=>Eae,KEY_CLOSE_BRACKET:()=>sne,KEY_COMMA:()=>Zoe,KEY_CONTEXT_MENU:()=>yoe,KEY_CONTROL:()=>vae,KEY_D:()=>Qae,KEY_DECIMAL:()=>Boe,KEY_DELETE:()=>Nae,KEY_DIVIDE:()=>Uoe,KEY_DOWN:()=>Mae,KEY_E:()=>Jae,KEY_END:()=>Iae,KEY_ENTER:()=>Sae,KEY_EQUAL:()=>jae,KEY_ESCAPE:()=>Aae,KEY_F:()=>eoe,KEY_F1:()=>koe,KEY_F10:()=>joe,KEY_F11:()=>qoe,KEY_F12:()=>$oe,KEY_F2:()=>zoe,KEY_F3:()=>Goe,KEY_F4:()=>Voe,KEY_F5:()=>Hoe,KEY_F6:()=>Woe,KEY_F7:()=>Xoe,KEY_F8:()=>Yoe,KEY_F9:()=>Koe,KEY_G:()=>toe,KEY_H:()=>soe,KEY_HOME:()=>Rae,KEY_I:()=>ioe,KEY_INSERT:()=>Fae,KEY_J:()=>roe,KEY_K:()=>aoe,KEY_L:()=>ooe,KEY_LEFT:()=>bae,KEY_M:()=>noe,KEY_META:()=>ine,KEY_MULTIPLY:()=>Moe,KEY_N:()=>loe,KEY_NUMPAD_0:()=>Eoe,KEY_NUMPAD_1:()=>Aoe,KEY_NUMPAD_2:()=>Coe,KEY_NUMPAD_3:()=>Poe,KEY_NUMPAD_4:()=>woe,KEY_NUMPAD_5:()=>Ioe,KEY_NUMPAD_6:()=>Roe,KEY_NUMPAD_7:()=>boe,KEY_NUMPAD_8:()=>Doe,KEY_NUMPAD_9:()=>Loe,KEY_O:()=>coe,KEY_OPEN_BRACKET:()=>ene,KEY_P:()=>hoe,KEY_PAGE_DOWN:()=>wae,KEY_PAGE_UP:()=>Pae,KEY_PAUSE:()=>yae,KEY_PERIOD:()=>Qoe,KEY_PRINT_SCREEN:()=>Oae,KEY_Q:()=>foe,KEY_R:()=>uoe,KEY_RETURN:()=>gae,KEY_RIGHT:()=>Lae,KEY_S:()=>doe,KEY_SEMICOLON:()=>Kae,KEY_SEPARATOR:()=>Foe,KEY_SHIFT:()=>xae,KEY_SLASH:()=>Joe,KEY_SPACE:()=>Cae,KEY_SUBTRACT:()=>Noe,KEY_T:()=>poe,KEY_TAB:()=>_ae,KEY_U:()=>moe,KEY_UP:()=>Dae,KEY_V:()=>_oe,KEY_W:()=>goe,KEY_WINDOWS:()=>Toe,KEY_X:()=>Soe,KEY_Y:()=>xoe,KEY_Z:()=>voe,Kernel:()=>rd,Key:()=>T$,Keyboard:()=>mc,KeyboardEvent:()=>Zd,KeyboardMouseSource:()=>qA,LAYERID_DEPTH:()=>Zt,LAYERID_IMMEDIATE:()=>Zn,LAYERID_SKYBOX:()=>$n,LAYERID_UI:()=>Va,LAYERID_WORLD:()=>Os,LAYER_GIZMO:()=>gX,LAYER_HUD:()=>ow,LAYER_WORLD:()=>Xg,LIGHTFALLOFF_INVERSESQUARED:()=>dT,LIGHTFALLOFF_LINEAR:()=>uT,LIGHTSHAPE_DISK:()=>hT,LIGHTSHAPE_PUNCTUAL:()=>$i,LIGHTSHAPE_RECT:()=>cT,LIGHTSHAPE_SPHERE:()=>fT,LIGHTTYPE_COUNT:()=>xX,LIGHTTYPE_DIRECTIONAL:()=>Ce,LIGHTTYPE_OMNI:()=>We,LIGHTTYPE_POINT:()=>SX,LIGHTTYPE_SPOT:()=>je,LIGHT_COLOR_DIVIDER:()=>If,Layer:()=>Dt,LayerComposition:()=>ol,LayoutCalculator:()=>Hm,LayoutChildComponent:()=>Tu,LayoutChildComponentSystem:()=>Vm,LayoutGroupComponent:()=>yu,LayoutGroupComponentSystem:()=>Wm,Light:()=>kc,LightComponent:()=>Ru,LightComponentSystem:()=>n_,LightingParams:()=>zc,Lightmapper:()=>Em,LitMaterial:()=>ky,LitOptions:()=>E$,LitShaderOptions:()=>Xa,LocalizedAsset:()=>Bm,MASK_AFFECT_DYNAMIC:()=>cs,MASK_AFFECT_LIGHTMAPPED:()=>xi,MASK_BAKE:()=>vi,MOTION_FREE:()=>nh,MOTION_LIMITED:()=>lh,MOTION_LOCKED:()=>ch,MOUSEBUTTON_LEFT:()=>rne,MOUSEBUTTON_MIDDLE:()=>ane,MOUSEBUTTON_NONE:()=>NW,MOUSEBUTTON_RIGHT:()=>one,Mat3:()=>Ws,Mat4:()=>W,Material:()=>Us,MaterialHandler:()=>N_,Mesh:()=>_e,MeshInstance:()=>we,MiniStats:()=>LA,Model:()=>Ei,ModelComponent:()=>Tl,ModelComponentSystem:()=>Xm,ModelHandler:()=>B_,Morph:()=>Ko,MorphInstance:()=>Ar,MorphTarget:()=>Gc,Mouse:()=>qi,MouseEvent:()=>za,MultiTouchSource:()=>KA,Node:()=>y$,NullGraphicsDevice:()=>$d,ORIENTATION_HORIZONTAL:()=>Ge,ORIENTATION_VERTICAL:()=>dt,OrbitController:()=>JA,OrientedBox:()=>Ox,OutlineRenderer:()=>OA,PAD_1:()=>rL,PAD_2:()=>nne,PAD_3:()=>lne,PAD_4:()=>cne,PAD_DOWN:()=>$W,PAD_FACE_1:()=>BW,PAD_FACE_2:()=>UW,PAD_FACE_3:()=>kW,PAD_FACE_4:()=>zW,PAD_LEFT:()=>ZW,PAD_L_SHOULDER_1:()=>GW,PAD_L_SHOULDER_2:()=>HW,PAD_L_STICK_BUTTON:()=>KW,PAD_L_STICK_X:()=>$P,PAD_L_STICK_Y:()=>ZP,PAD_RIGHT:()=>QW,PAD_R_SHOULDER_1:()=>VW,PAD_R_SHOULDER_2:()=>WW,PAD_R_STICK_BUTTON:()=>jW,PAD_R_STICK_X:()=>QP,PAD_R_STICK_Y:()=>JP,PAD_SELECT:()=>XW,PAD_START:()=>YW,PAD_UP:()=>qW,PAD_VENDOR:()=>JW,PARTICLEMODE_CPU:()=>MX,PARTICLEMODE_GPU:()=>jg,PARTICLEORIENTATION_EMITTER:()=>OX,PARTICLEORIENTATION_SCREEN:()=>vc,PARTICLEORIENTATION_WORLD:()=>fw,PARTICLESORT_DISTANCE:()=>bX,PARTICLESORT_NEWER_FIRST:()=>DX,PARTICLESORT_NONE:()=>up,PARTICLESORT_OLDER_FIRST:()=>LX,PIXELFORMAT_111110F:()=>Gi,PIXELFORMAT_A8:()=>pd,PIXELFORMAT_ASTC_4x4:()=>_d,PIXELFORMAT_ASTC_4x4_SRGB:()=>Wh,PIXELFORMAT_ATC_RGB:()=>gd,PIXELFORMAT_ATC_RGBA:()=>Sd,PIXELFORMAT_BC6F:()=>Td,PIXELFORMAT_BC6UF:()=>yd,PIXELFORMAT_BC7:()=>Ed,PIXELFORMAT_BC7_SRGBA:()=>Xh,PIXELFORMAT_BGRA8:()=>tc,PIXELFORMAT_DEPTH:()=>Ys,PIXELFORMAT_DEPTH16:()=>Xr,PIXELFORMAT_DEPTHSTENCIL:()=>fr,PIXELFORMAT_DXT1:()=>To,PIXELFORMAT_DXT1_SRGB:()=>kh,PIXELFORMAT_DXT3:()=>Ql,PIXELFORMAT_DXT3_SRGBA:()=>zh,PIXELFORMAT_DXT5:()=>Gr,PIXELFORMAT_DXT5_SRGBA:()=>Gh,PIXELFORMAT_ETC1:()=>Eo,PIXELFORMAT_ETC2_RGB:()=>Jl,PIXELFORMAT_ETC2_RGBA:()=>ec,PIXELFORMAT_ETC2_SRGB:()=>Vh,PIXELFORMAT_ETC2_SRGBA:()=>Hh,PIXELFORMAT_L8:()=>md,PIXELFORMAT_L8_A8:()=>Uq,PIXELFORMAT_LA8:()=>vo,PIXELFORMAT_PVRTC_2BPP_RGBA_1:()=>Hr,PIXELFORMAT_PVRTC_2BPP_RGB_1:()=>Vr,PIXELFORMAT_PVRTC_4BPP_RGBA_1:()=>Co,PIXELFORMAT_PVRTC_4BPP_RGB_1:()=>Ao,PIXELFORMAT_R16F:()=>yn,PIXELFORMAT_R16I:()=>qh,PIXELFORMAT_R16U:()=>$h,PIXELFORMAT_R32F:()=>Mt,PIXELFORMAT_R32I:()=>Zh,PIXELFORMAT_R32U:()=>zt,PIXELFORMAT_R4_G4_B4_A4:()=>Gq,PIXELFORMAT_R5_G5_B5_A1:()=>zq,PIXELFORMAT_R5_G6_B5:()=>kq,PIXELFORMAT_R8:()=>Wr,PIXELFORMAT_R8I:()=>jh,PIXELFORMAT_R8U:()=>sc,PIXELFORMAT_R8_G8_B8:()=>Vq,PIXELFORMAT_R8_G8_B8_A8:()=>Hq,PIXELFORMAT_RG16F:()=>of,PIXELFORMAT_RG16I:()=>Jh,PIXELFORMAT_RG16U:()=>ef,PIXELFORMAT_RG32F:()=>nf,PIXELFORMAT_RG32I:()=>tf,PIXELFORMAT_RG32U:()=>Tn,PIXELFORMAT_RG8:()=>Po,PIXELFORMAT_RG8I:()=>Qh,PIXELFORMAT_RG8S:()=>cf,PIXELFORMAT_RG8U:()=>xd,PIXELFORMAT_RGB10A2:()=>ff,PIXELFORMAT_RGB10A2U:()=>uf,PIXELFORMAT_RGB16F:()=>vn,PIXELFORMAT_RGB32F:()=>Kh,PIXELFORMAT_RGB565:()=>ya,PIXELFORMAT_RGB8:()=>Ss,PIXELFORMAT_RGB9E5:()=>lf,PIXELFORMAT_RGBA16F:()=>Me,PIXELFORMAT_RGBA16I:()=>rf,PIXELFORMAT_RGBA16U:()=>Rs,PIXELFORMAT_RGBA32F:()=>ke,PIXELFORMAT_RGBA32I:()=>af,PIXELFORMAT_RGBA32U:()=>At,PIXELFORMAT_RGBA4:()=>Ea,PIXELFORMAT_RGBA5551:()=>xn,PIXELFORMAT_RGBA8:()=>ce,PIXELFORMAT_RGBA8I:()=>sf,PIXELFORMAT_RGBA8S:()=>hf,PIXELFORMAT_RGBA8U:()=>vd,PIXELFORMAT_SBGRA8:()=>ic,PIXELFORMAT_SRGB:()=>Wq,PIXELFORMAT_SRGB8:()=>yo,PIXELFORMAT_SRGBA:()=>Xq,PIXELFORMAT_SRGBA8:()=>st,PRIMITIVE_LINELOOP:()=>Eg,PRIMITIVE_LINES:()=>Pn,PRIMITIVE_LINESTRIP:()=>mf,PRIMITIVE_POINTS:()=>Aa,PRIMITIVE_TRIANGLES:()=>Yt,PRIMITIVE_TRIFAN:()=>dr,PRIMITIVE_TRISTRIP:()=>Ks,PROJECTION_ORTHOGRAPHIC:()=>ni,PROJECTION_PERSPECTIVE:()=>ts,ParticleEmitter:()=>Xp,ParticleSystemComponent:()=>Km,ParticleSystemComponentSystem:()=>jm,Picker:()=>SA,Plane:()=>go,PlaneGeometry:()=>$a,Pose:()=>ei,PostEffect:()=>TS,PostEffectQueue:()=>a_,ProgramLibrary:()=>im,QuadRender:()=>hs,Quat:()=>$,RADIX_SORT_AUTO:()=>PT,RADIX_SORT_ONESWEEP:()=>wT,RADIX_SORT_PORTABLE:()=>bw,REFLECTIONSRC_CUBEMAP:()=>Mf,REFLECTIONSRC_ENVATLAS:()=>Df,REFLECTIONSRC_ENVATLASHQ:()=>Lf,REFLECTIONSRC_NONE:()=>gr,REFLECTIONSRC_SPHEREMAP:()=>TT,RENDERSTYLE_POINTS:()=>dp,RENDERSTYLE_SOLID:()=>Oo,RENDERSTYLE_WIREFRAME:()=>Fo,RESOLUTION_AUTO:()=>jy,RESOLUTION_FIXED:()=>DI,RIGIDBODY_ACTIVE_TAG:()=>K$,RIGIDBODY_CF_KINEMATIC_OBJECT:()=>X$,RIGIDBODY_CF_NORESPONSE_OBJECT:()=>Y$,RIGIDBODY_CF_STATIC_OBJECT:()=>W$,RIGIDBODY_DISABLE_DEACTIVATION:()=>$$,RIGIDBODY_DISABLE_SIMULATION:()=>Z$,RIGIDBODY_ISLAND_SLEEPING:()=>j$,RIGIDBODY_TYPE_DYNAMIC:()=>V$,RIGIDBODY_TYPE_KINEMATIC:()=>H$,RIGIDBODY_TYPE_STATIC:()=>G$,RIGIDBODY_WANTS_DEACTIVATION:()=>q$,Ray:()=>ws,RaycastResult:()=>Qm,ReadStream:()=>Kl,RenderComponent:()=>Au,RenderComponentSystem:()=>qm,RenderHandler:()=>g_,RenderPass:()=>yt,RenderPassCompose:()=>ag,RenderPassDepthAwareBlur:()=>Hu,RenderPassDownsample:()=>hn,RenderPassForward:()=>Ya,RenderPassPicker:()=>$_,RenderPassPrepass:()=>lg,RenderPassShaderQuad:()=>Ut,RenderPassSsao:()=>cg,RenderPassTAA:()=>og,RenderPassUpsample:()=>ig,RenderTarget:()=>me,ResourceHandler:()=>Re,ResourceLoader:()=>Zc,RigidBodyComponent:()=>Js,RigidBodyComponentSystem:()=>Al,RotateGizmo:()=>uC,SAMPLETYPE_DEPTH:()=>gi,SAMPLETYPE_FLOAT:()=>rs,SAMPLETYPE_INT:()=>Hi,SAMPLETYPE_UINT:()=>Wi,SAMPLETYPE_UNFILTERABLE_FLOAT:()=>Vi,SCALEMODE_BLEND:()=>CR,SCALEMODE_NONE:()=>fh,SCROLLBAR_VISIBILITY_SHOW_ALWAYS:()=>pK,SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED:()=>mK,SCROLL_MODE_BOUNCE:()=>Tk,SCROLL_MODE_CLAMP:()=>uK,SCROLL_MODE_INFINITE:()=>dK,SEMANTIC_ATTR0:()=>Ag,SEMANTIC_ATTR1:()=>_f,SEMANTIC_ATTR10:()=>ED,SEMANTIC_ATTR11:()=>Id,SEMANTIC_ATTR12:()=>Rd,SEMANTIC_ATTR13:()=>AD,SEMANTIC_ATTR14:()=>bd,SEMANTIC_ATTR15:()=>Da,SEMANTIC_ATTR2:()=>Cd,SEMANTIC_ATTR3:()=>Pd,SEMANTIC_ATTR4:()=>wd,SEMANTIC_ATTR5:()=>vD,SEMANTIC_ATTR6:()=>TD,SEMANTIC_ATTR7:()=>yD,SEMANTIC_ATTR8:()=>rc,SEMANTIC_ATTR9:()=>ac,SEMANTIC_BLENDINDICES:()=>$t,SEMANTIC_BLENDWEIGHT:()=>bs,SEMANTIC_COLOR:()=>Ct,SEMANTIC_NORMAL:()=>Ot,SEMANTIC_POSITION:()=>ee,SEMANTIC_TANGENT:()=>vs,SEMANTIC_TEXCOORD:()=>Ux,SEMANTIC_TEXCOORD0:()=>_t,SEMANTIC_TEXCOORD1:()=>ri,SEMANTIC_TEXCOORD2:()=>Ca,SEMANTIC_TEXCOORD3:()=>Pa,SEMANTIC_TEXCOORD4:()=>wa,SEMANTIC_TEXCOORD5:()=>Ia,SEMANTIC_TEXCOORD6:()=>Ra,SEMANTIC_TEXCOORD7:()=>ba,SHADERDEF_BATCH:()=>Uf,SHADERDEF_DIRLM:()=>Ff,SHADERDEF_INSTANCING:()=>ko,SHADERDEF_LM:()=>yc,SHADERDEF_LMAMBIENT:()=>Bf,SHADERDEF_MORPH_NORMAL:()=>Go,SHADERDEF_MORPH_POSITION:()=>zo,SHADERDEF_MORPH_TEXTURE_BASED_INT:()=>Vo,SHADERDEF_NOSHADOW:()=>Tc,SHADERDEF_SCREENSPACE:()=>Ec,SHADERDEF_SKIN:()=>Uo,SHADERDEF_TANGENTS:()=>Nf,SHADERDEF_UV0:()=>Of,SHADERDEF_UV1:()=>$g,SHADERDEF_VCOLOR:()=>Zg,SHADERLANGUAGE_GLSL:()=>fe,SHADERLANGUAGE_WGSL:()=>se,SHADERPASS_ALBEDO:()=>YX,SHADERPASS_AO:()=>QX,SHADERPASS_EMISSION:()=>JX,SHADERPASS_FORWARD:()=>XX,SHADERPASS_GLOSS:()=>$X,SHADERPASS_LIGHTING:()=>eY,SHADERPASS_METALNESS:()=>ZX,SHADERPASS_OPACITY:()=>jX,SHADERPASS_SPECULARITY:()=>qX,SHADERPASS_UV0:()=>tY,SHADERPASS_WORLDNORMAL:()=>KX,SHADERSTAGE_COMPUTE:()=>X,SHADERSTAGE_FRAGMENT:()=>Yi,SHADERSTAGE_VERTEX:()=>Xi,SHADERTAG_MATERIAL:()=>Cg,SHADER_DEPTH_PICK:()=>Sp,SHADER_FORWARD:()=>Sr,SHADER_PICK:()=>ta,SHADER_PREPASS:()=>xr,SHADER_SHADOW:()=>kf,SHADOWCAMERA_NAME:()=>Gf,SHADOWUPDATE_NONE:()=>$s,SHADOWUPDATE_REALTIME:()=>Qg,SHADOWUPDATE_THISFRAME:()=>Qi,SHADOW_CASCADE_0:()=>CX,SHADOW_CASCADE_1:()=>PX,SHADOW_CASCADE_2:()=>wX,SHADOW_CASCADE_3:()=>IX,SHADOW_CASCADE_ALL:()=>cw,SHADOW_PCF1:()=>AX,SHADOW_PCF1_16F:()=>mT,SHADOW_PCF1_32F:()=>pT,SHADOW_PCF3:()=>vX,SHADOW_PCF3_16F:()=>_T,SHADOW_PCF3_32F:()=>Oi,SHADOW_PCF5:()=>EX,SHADOW_PCF5_16F:()=>uL,SHADOW_PCF5_32F:()=>fL,SHADOW_PCSS_32F:()=>xc,SHADOW_VSM16:()=>TX,SHADOW_VSM32:()=>yX,SHADOW_VSM_16F:()=>Yg,SHADOW_VSM_32F:()=>fp,SKYTYPE_BOX:()=>vw,SKYTYPE_DOME:()=>Tw,SKYTYPE_INFINITE:()=>Jn,SORTMODE_BACK2FRONT:()=>Jg,SORTMODE_CUSTOM:()=>xw,SORTMODE_FRONT2BACK:()=>Sw,SORTMODE_MANUAL:()=>gw,SORTMODE_MATERIALMESH:()=>yT,SORTMODE_NONE:()=>Ho,SPECOCC_AO:()=>Bo,SPECOCC_GLOSSDEPENDENT:()=>vT,SPECOCC_NONE:()=>xT,SPRITETYPE_ANIMATED:()=>eE,SPRITETYPE_SIMPLE:()=>J0,SPRITE_RENDERMODE_SIMPLE:()=>Ti,SPRITE_RENDERMODE_SLICED:()=>It,SPRITE_RENDERMODE_TILED:()=>Rt,SSAOTYPE_COMBINE:()=>GA,SSAOTYPE_LIGHTING:()=>zA,SSAOTYPE_NONE:()=>cn,STENCILOP_DECREMENT:()=>$C,STENCILOP_DECREMENTWRAP:()=>e5,STENCILOP_INCREMENT:()=>qC,STENCILOP_INCREMENTWRAP:()=>J4,STENCILOP_INVERT:()=>t5,STENCILOP_KEEP:()=>wn,STENCILOP_REPLACE:()=>jC,STENCILOP_ZERO:()=>Q4,ScaleGizmo:()=>gC,Scene:()=>Bt,SceneHandler:()=>U_,SceneRegistry:()=>xm,SceneRegistryItem:()=>au,SceneSettingsHandler:()=>xA,ScopeId:()=>Bd,ScopeSpace:()=>Ud,ScreenComponent:()=>Pu,ScreenComponentSystem:()=>Jm,Script:()=>ks,ScriptAttributes:()=>ao,ScriptComponent:()=>or,ScriptComponentSystem:()=>h_,ScriptHandler:()=>k_,ScriptRegistry:()=>Sm,ScriptType:()=>Mr,ScrollViewComponent:()=>dh,ScrollViewComponentSystem:()=>e_,ScrollbarComponent:()=>ph,ScrollbarComponentSystem:()=>t_,Shader:()=>Be,ShaderChunks:()=>ne,ShaderHandler:()=>z_,ShaderMaterial:()=>ct,ShaderPass:()=>Ns,ShaderUtils:()=>Se,SingleContactResult:()=>YS,SingleGestureSource:()=>XA,Skeleton:()=>Hc,Skin:()=>Vc,SkinBatchInstance:()=>Yf,SkinInstance:()=>er,Sky:()=>qp,SortedLoopArray:()=>po,Sound:()=>sp,SoundComponent:()=>ma,SoundComponentSystem:()=>s_,SoundInstance:()=>_r,SoundInstance3d:()=>ip,SoundManager:()=>tp,SoundSlot:()=>ir,SphereGeometry:()=>wr,Sprite:()=>Qp,SpriteAnimationClip:()=>rr,SpriteComponent:()=>Lr,SpriteComponentSystem:()=>i_,SpriteHandler:()=>G_,StandardMaterial:()=>it,StandardMaterialOptions:()=>tr,StencilParameters:()=>Ls,StorageBuffer:()=>Ee,TEXHINT_ASSET:()=>r5,TEXHINT_LIGHTMAP:()=>a5,TEXHINT_NONE:()=>s5,TEXHINT_SHADOWMAP:()=>i5,TEXPROPERTY_ADDRESS_U:()=>bg,TEXPROPERTY_ADDRESS_V:()=>Dg,TEXPROPERTY_ADDRESS_W:()=>Lg,TEXPROPERTY_ALL:()=>_P,TEXPROPERTY_ANISOTROPY:()=>Fg,TEXPROPERTY_COMPARE_FUNC:()=>Og,TEXPROPERTY_COMPARE_ON_READ:()=>Mg,TEXPROPERTY_MAG_FILTER:()=>Rg,TEXPROPERTY_MIN_FILTER:()=>Od,TEXTUREDIMENSION_1D:()=>zx,TEXTUREDIMENSION_2D:()=>Ds,TEXTUREDIMENSION_2D_ARRAY:()=>Yr,TEXTUREDIMENSION_3D:()=>bn,TEXTUREDIMENSION_CUBE:()=>Kr,TEXTUREDIMENSION_CUBE_ARRAY:()=>Dd,TEXTURELOCK_NONE:()=>Pg,TEXTURELOCK_READ:()=>ZC,TEXTURELOCK_WRITE:()=>kx,TEXTUREPROJECTION_CUBE:()=>Ld,TEXTUREPROJECTION_EQUIRECT:()=>Gx,TEXTUREPROJECTION_NONE:()=>QC,TEXTUREPROJECTION_OCTAHEDRAL:()=>JC,TEXTURETYPE_DEFAULT:()=>Gt,TEXTURETYPE_RGBE:()=>oc,TEXTURETYPE_RGBM:()=>_i,TEXTURETYPE_RGBP:()=>In,TEXTURETYPE_SWIZZLEGGGR:()=>Rn,TONEMAP_ACES:()=>VX,TONEMAP_ACES2:()=>HX,TONEMAP_FILMIC:()=>zX,TONEMAP_HEJL:()=>GX,TONEMAP_LINEAR:()=>Qn,TONEMAP_NEUTRAL:()=>WX,TONEMAP_NONE:()=>Rf,TRACEID_ASSETS:()=>u4,TRACEID_BINDGROUPFORMAT_ALLOC:()=>a4,TRACEID_BINDGROUP_ALLOC:()=>r4,TRACEID_BUFFERS:()=>f4,TRACEID_COMPUTEPIPELINE_ALLOC:()=>n4,TRACEID_ELEMENT:()=>c4,TRACEID_GPU_TIMINGS:()=>AC,TRACEID_OCTREE_RESOURCES:()=>p4,TRACEID_PIPELINELAYOUT_ALLOC:()=>l4,TRACEID_RENDERPIPELINE_ALLOC:()=>o4,TRACEID_RENDER_ACTION:()=>qH,TRACEID_RENDER_FRAME:()=>XH,TRACEID_RENDER_FRAME_TIME:()=>YH,TRACEID_RENDER_PASS:()=>KH,TRACEID_RENDER_PASS_DETAIL:()=>jH,TRACEID_RENDER_QUEUE:()=>d4,TRACEID_RENDER_TARGET_ALLOC:()=>$H,TRACEID_SHADER_ALLOC:()=>QH,TRACEID_SHADER_COMPILE:()=>JH,TRACEID_TEXTURES:()=>h4,TRACEID_TEXTURE_ALLOC:()=>ZH,TRACEID_VRAM_IB:()=>s4,TRACEID_VRAM_SB:()=>i4,TRACEID_VRAM_TEXTURE:()=>e4,TRACEID_VRAM_VB:()=>t4,TYPE_FLOAT16:()=>nc,TYPE_FLOAT32:()=>ye,TYPE_INT16:()=>qs,TYPE_INT32:()=>He,TYPE_INT8:()=>js,TYPE_UINT16:()=>Ri,TYPE_UINT32:()=>kt,TYPE_UINT8:()=>ai,Tags:()=>va,Template:()=>Nu,TemplateHandler:()=>V_,TextElement:()=>Um,TextHandler:()=>H_,Texture:()=>Z,TextureAtlas:()=>Jp,TextureAtlasHandler:()=>W_,TextureHandler:()=>X_,TextureUtils:()=>gt,TextureView:()=>Zr,TorusGeometry:()=>Za,Touch:()=>Jd,TouchDevice:()=>_c,TouchEvent:()=>qn,Tracing:()=>ed,TransformFeedback:()=>Qv,TransformGizmo:()=>is,TranslateGizmo:()=>lC,Tri:()=>cd,UNIFORMTYPE_BOOL:()=>wo,UNIFORMTYPE_BOOLARRAY:()=>Un,UNIFORMTYPE_BVEC2:()=>Dn,UNIFORMTYPE_BVEC2ARRAY:()=>zn,UNIFORMTYPE_BVEC3:()=>Ln,UNIFORMTYPE_BVEC3ARRAY:()=>Vn,UNIFORMTYPE_BVEC4:()=>Mn,UNIFORMTYPE_BVEC4ARRAY:()=>xf,UNIFORMTYPE_FLOAT:()=>Te,UNIFORMTYPE_FLOATARRAY:()=>On,UNIFORMTYPE_INT:()=>bi,UNIFORMTYPE_INTARRAY:()=>Fa,UNIFORMTYPE_ITEXTURE2D:()=>oP,UNIFORMTYPE_ITEXTURE2D_ARRAY:()=>uP,UNIFORMTYPE_ITEXTURE3D:()=>hP,UNIFORMTYPE_ITEXTURECUBE:()=>lP,UNIFORMTYPE_IVEC2:()=>jr,UNIFORMTYPE_IVEC2ARRAY:()=>Na,UNIFORMTYPE_IVEC3:()=>Di,UNIFORMTYPE_IVEC3ARRAY:()=>Ba,UNIFORMTYPE_IVEC4:()=>qr,UNIFORMTYPE_IVEC4ARRAY:()=>cc,UNIFORMTYPE_MAT2:()=>lc,UNIFORMTYPE_MAT3:()=>La,UNIFORMTYPE_MAT4:()=>as,UNIFORMTYPE_MAT4ARRAY:()=>wg,UNIFORMTYPE_TEXTURE2D:()=>eP,UNIFORMTYPE_TEXTURE2D_ARRAY:()=>aP,UNIFORMTYPE_TEXTURE2D_SHADOW:()=>sP,UNIFORMTYPE_TEXTURE3D:()=>rP,UNIFORMTYPE_TEXTURECUBE:()=>tP,UNIFORMTYPE_TEXTURECUBE_SHADOW:()=>iP,UNIFORMTYPE_UINT:()=>pe,UNIFORMTYPE_UINTARRAY:()=>Bn,UNIFORMTYPE_UTEXTURE2D:()=>nP,UNIFORMTYPE_UTEXTURE2D_ARRAY:()=>dP,UNIFORMTYPE_UTEXTURE3D:()=>fP,UNIFORMTYPE_UTEXTURECUBE:()=>cP,UNIFORMTYPE_UVEC2:()=>Ma,UNIFORMTYPE_UVEC2ARRAY:()=>kn,UNIFORMTYPE_UVEC3:()=>Oa,UNIFORMTYPE_UVEC3ARRAY:()=>Gn,UNIFORMTYPE_UVEC4:()=>Li,UNIFORMTYPE_UVEC4ARRAY:()=>Sf,UNIFORMTYPE_VEC2:()=>pr,UNIFORMTYPE_VEC2ARRAY:()=>Fn,UNIFORMTYPE_VEC3:()=>Kt,UNIFORMTYPE_VEC3ARRAY:()=>Nn,UNIFORMTYPE_VEC4:()=>oi,UNIFORMTYPE_VEC4ARRAY:()=>gf,UNIFORM_BUFFER_DEFAULT_SLOT_NAME:()=>Hn,UNUSED_UNIFORM_NAME:()=>yf,URI:()=>jl,UniformBufferFormat:()=>Xe,UniformFormat:()=>Y,UsdzExporter:()=>UA,VIEW_CENTER:()=>xp,VIEW_LEFT:()=>iY,VIEW_RIGHT:()=>rY,Vec2:()=>B,Vec3:()=>x,Vec4:()=>Q,VertexBuffer:()=>ft,VertexFormat:()=>Ft,VertexIterator:()=>Jr,ViewCube:()=>xC,WORKBUFFER_UPDATE_ALWAYS:()=>Iw,WORKBUFFER_UPDATE_AUTO:()=>Tp,WORKBUFFER_UPDATE_ONCE:()=>ww,WasmModule:()=>Yl,WebglGraphicsDevice:()=>pc,WebgpuGraphicsDevice:()=>Kd,WorldClusters:()=>sl,XRDEPTHSENSINGFORMAT_F32:()=>cx,XRDEPTHSENSINGFORMAT_L8A8:()=>nx,XRDEPTHSENSINGFORMAT_R16U:()=>lx,XRDEPTHSENSINGUSAGE_CPU:()=>Cb,XRDEPTHSENSINGUSAGE_GPU:()=>ox,XREYE_LEFT:()=>yq,XREYE_NONE:()=>Tq,XREYE_RIGHT:()=>Eq,XRHAND_LEFT:()=>Ab,XRHAND_NONE:()=>Aq,XRHAND_RIGHT:()=>Cq,XRPAD_A:()=>lX,XRPAD_B:()=>cX,XRPAD_SQUEEZE:()=>oX,XRPAD_STICK_BUTTON:()=>nX,XRPAD_STICK_X:()=>sX,XRPAD_STICK_Y:()=>iX,XRPAD_TOUCHPAD_BUTTON:()=>rX,XRPAD_TOUCHPAD_X:()=>eX,XRPAD_TOUCHPAD_Y:()=>tX,XRPAD_TRIGGER:()=>aX,XRSPACE_BOUNDEDFLOOR:()=>_q,XRSPACE_LOCAL:()=>pq,XRSPACE_LOCALFLOOR:()=>mq,XRSPACE_UNBOUNDED:()=>gq,XRSPACE_VIEWER:()=>hA,XRTARGETRAY_GAZE:()=>Sq,XRTARGETRAY_POINTER:()=>vq,XRTARGETRAY_SCREEN:()=>xq,XRTRACKABLE_MESH:()=>Iq,XRTRACKABLE_PLANE:()=>wq,XRTRACKABLE_POINT:()=>Pq,XRTYPE_AR:()=>bl,XRTYPE_INLINE:()=>yb,XRTYPE_VR:()=>Eb,XrAnchor:()=>nn,XrAnchors:()=>oo,XrDomOverlay:()=>Y_,XrFinger:()=>K_,XrHand:()=>Ph,XrHitTest:()=>_a,XrHitTestSource:()=>Ah,XrImageTracking:()=>Bu,XrInput:()=>lr,XrInputSource:()=>Es,XrJoint:()=>Uu,XrLightEstimation:()=>wh,XrManager:()=>no,XrMeshDetection:()=>ln,XrPlane:()=>Ih,XrPlaneDetection:()=>on,XrTrackedImage:()=>Ch,XrView:()=>zu,XrViews:()=>Rh,ZoneComponent:()=>ro,ZoneComponentSystem:()=>r_,ambientSrcNames:()=>mw,app:()=>n0,basisInitialize:()=>vb,bindGroupNames:()=>Ng,blendNames:()=>Wg,calculateNormals:()=>Kp,calculateTangents:()=>Zs,createBox:()=>p$,createCapsule:()=>_$,createCone:()=>g$,createCylinder:()=>S$,createGraphicsDevice:()=>iL,createMesh:()=>x$,createPlane:()=>d$,createScript:()=>ub,createShader:()=>SL,createShaderFromCode:()=>xL,createSphere:()=>u$,createTorus:()=>m$,createURI:()=>lD,cubemaProjectionNames:()=>uw,ditherNames:()=>eS,dracoDecode:()=>UE,dracoInitialize:()=>SG,drawFullscreenQuad:()=>v$,drawQuadWithShader:()=>Qt,extend:()=>Wl,fresnelNames:()=>aw,gammaNames:()=>qg,getGlslShaderType:()=>An,getPixelFormatArrayType:()=>pf,getReservedScriptNames:()=>PG,getTouchTargetCoords:()=>Pf,getWgslShaderType:()=>Ad,guid:()=>bx,http:()=>Le,indexFormatByteSize:()=>XC,isCompressedPixelFormat:()=>En,isIntegerPixelFormat:()=>ur,isSrgbPixelFormat:()=>df,lightFalloffNames:()=>lw,lightShapeNames:()=>nw,lightTypeNames:()=>lT,math:()=>R,now:()=>Tt,path:()=>xe,pixelFormatGammaToLinear:()=>YC,pixelFormatInfo:()=>xs,pixelFormatLinearToGamma:()=>Cn,platform:()=>ue,primitiveGlslToWgslTypeMap:()=>Bg,reflectionSrcNames:()=>pw,registerScript:()=>ax,reprojectTexture:()=>oa,requiresManualGamma:()=>KC,revision:()=>Rx,script:()=>fm,semanticToLocation:()=>ze,shaderChunks:()=>A$,shadowTypeInfo:()=>Fi,specularOcclusionNames:()=>dw,spriteRenderModeNames:()=>_w,string:()=>Nr,tonemapNames:()=>bf,typedArrayIndexFormats:()=>Ef,typedArrayIndexFormatsByteSize:()=>gP,typedArrayToType:()=>l5,typedArrayTypes:()=>Ro,typedArrayTypesByteSize:()=>Wn,uniformTypeToName:()=>Vx,uniformTypeToNameMapWGSL:()=>Wx,uniformTypeToNameWGSL:()=>Hx,uniformTypeToStorage:()=>o5,version:()=>Ju,vertexTypesNames:()=>n5});var XH="RenderFrame",YH="RenderFrameTime",KH="RenderPass",jH="RenderPassDetail",qH="RenderAction",$H="RenderTargetAlloc",ZH="TextureAlloc",QH="ShaderAlloc",JH="ShaderCompile",e4="VRAM.Texture",t4="VRAM.Vb",s4="VRAM.Ib",i4="VRAM.Sb",r4="BindGroupAlloc",a4="BindGroupFormatAlloc",o4="RenderPipelineAlloc",n4="ComputePipelineAlloc",l4="PipelineLayoutAlloc",c4="Element",h4="Textures",f4="Buffers",u4="Assets",d4="RenderQueue",p4="OctreeResources",AC="GpuTimings";var Ju="2.19.4",Rx="d999442";function Wl(c,t){for(let e in t){let s=t[e];Array.isArray(s)?c[e]=Wl([],s):s&&typeof s=="object"?c[e]=Wl({},s):c[e]=s}return c}var bx={create(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,c=>{let t=Math.random()*16|0;return(c==="x"?t:t&3|8).toString(16)})}};var xe={delimiter:"/",join(...c){let t=c[0];for(let e=0;e0){r=r.slice(0,r.length-2);continue}a>0&&r.push(xe.delimiter),r.push(s[a])}return i=r.join(""),!t&&i[0]===xe.delimiter&&(i=i.slice(1)),e&&i[i.length-1]!==xe.delimiter&&(i+=xe.delimiter),i},split(c){let t=c.lastIndexOf(xe.delimiter);return t!==-1?[c.substring(0,t),c.substring(t+1)]:["",c]},getBasename(c){return xe.split(c)[1]},getDirectory(c){return xe.split(c)[0]},getExtension(c){let t=c.split("?")[0].split(".").pop();return t!==c?`.${t}`:""},isRelativePath(c){return c.charAt(0)!=="/"&&c.match(/:\/\//)===null},extractPath(c){let t="",e=c.split("/"),s=0;if(e.length>1)if(xe.isRelativePath(c))if(e[0]===".")for(s=0;s{let c=!1;try{let t=Object.defineProperty({},"passive",{get:function(){return c=!0,!1}});window.addEventListener("testpassive",null,t),window.removeEventListener("testpassive",null,t)}catch{}return c},Fr=typeof navigator<"u"?navigator.userAgent:"",dn=typeof window<"u"?"browser":typeof global<"u"?"node":"worker",vg=/android/i.test(Fr)?"android":/ip(?:[ao]d|hone)/i.test(Fr)?"ios":/windows/i.test(Fr)?"windows":/mac os/i.test(Fr)?"osx":/linux/i.test(Fr)?"linux":/cros/i.test(Fr)?"cros":null,_4=dn!=="browser"?null:/Chrome\/|Chromium\/|Edg.*\//.test(Fr)?"chrome":/Safari\//.test(Fr)?"safari":/Firefox\//.test(Fr)?"firefox":"other",g4=/xbox/i.test(Fr),S4=/Macintosh/i.test(Fr)&&typeof navigator<"u"&&navigator.maxTouchPoints>0&&!/iPhone|iPad|iPod/i.test(Fr),x4=dn==="browser"&&("ontouchstart"in window||"maxTouchPoints"in navigator&&navigator.maxTouchPoints>0),v4=dn==="browser"&&(!!navigator.getGamepads||!!navigator.webkitGetGamepads),T4=typeof Worker<"u",y4=m4(),ue={name:vg,environment:dn,global:(typeof globalThis<"u"&&globalThis)??(dn==="browser"&&window)??(dn==="node"&&global)??(dn==="worker"&&self),browser:dn==="browser",worker:dn==="worker",desktop:["windows","osx","linux","cros"].includes(vg),mobile:["android","ios"].includes(vg),ios:vg==="ios",android:vg==="android",visionos:S4,xbox:g4,gamepads:v4,touch:x4,workers:T4,passiveEvents:y4,browserName:_4};var aD="abcdefghijklmnopqrstuvwxyz",oD="ABCDEFGHIJKLMNOPQRSTUVWXYZ",E4=aD+oD,CC=55296,nD=56319,sD=56320,A4=57343,C4=8205,iD=127462,rD=127487,P4=127995,w4=127999,I4=8400,R4=8447,PC=65024,wC=65039;function IC(c,t=0){let e=c.length;if(t<0||t>=e)return null;let s=c.charCodeAt(t);if(e>1&&s>=CC&&s<=nD){let i=c.charCodeAt(t+1);if(i>=sD&&i<=A4)return{code:(s-CC)*1024+i-sD+65536,long:!0}}return{code:s,long:!1}}function Xl(c,t,e){if(!c)return!1;let s=IC(c);if(s){let i=s.code;return i>=t&&i<=e}return!1}function b4(c,t){if(t===c.length-1)return 1;if(Xl(c[t],CC,nD)){let e=c.substring(t,t+2),s=c.substring(t+2,t+4);return Xl(s,P4,w4)||Xl(e,iD,rD)&&Xl(s,iD,rD)?4:Xl(s,PC,wC)?3:2}return Xl(c[t+1],PC,wC)?2:1}var Nr={ASCII_LOWERCASE:aD,ASCII_UPPERCASE:oD,ASCII_LETTERS:E4,format(c,...t){for(let e=0;et>65535?(t-=65536,String.fromCharCode((t>>10)+55296,t%1024+56320)):String.fromCharCode(t)).join("")}};var Tg=class Tg{static set(t,e=!0){}static get(t){return Tg._traceChannels.has(t)}};n(Tg,"_traceChannels",new Set),n(Tg,"stack",!1);var ed=Tg;var td=class{constructor(t,e,s,i,r=!1){n(this,"handler");n(this,"name");n(this,"callback");n(this,"scope");n(this,"_once");n(this,"_removed",!1);this.handler=t,this.name=e,this.callback=s,this.scope=i,this._once=r}off(){this._removed||this.handler.offByHandle(this)}on(t,e,s=this){return this.handler._addCallback(t,e,s,!1)}once(t,e,s=this){return this.handler._addCallback(t,e,s,!0)}set removed(t){t&&(this._removed=!0)}get removed(){return this._removed}toJSON(t){}};var J=class{constructor(){n(this,"_callbacks",new Map);n(this,"_callbackActive",new Map)}initEventHandler(){this._callbacks=new Map,this._callbackActive=new Map}_addCallback(t,e,s,i){if(this._callbacks.has(t)||this._callbacks.set(t,[]),this._callbackActive.has(t)){let a=this._callbackActive.get(t);a&&a===this._callbacks.get(t)&&this._callbackActive.set(t,a.slice())}let r=new td(this,t,e,s,i);return this._callbacks.get(t).push(r),r}on(t,e,s=this){return this._addCallback(t,e,s,!1)}once(t,e,s=this){return this._addCallback(t,e,s,!0)}off(t,e,s){if(t)this._callbackActive.has(t)&&this._callbackActive.get(t)===this._callbacks.get(t)&&this._callbackActive.set(t,this._callbackActive.get(t).slice());else for(let[i,r]of this._callbackActive)this._callbacks.has(i)&&this._callbacks.get(i)===r&&this._callbackActive.set(i,r.slice());if(t)if(e){let i=this._callbacks.get(t);if(!i)return this;for(let r=0;re&&(this._index[t]=s-1)}return!0}return!1}list(){return this._list}clear(){this._list.length=0;for(let t in this._index)delete this._index[t]}};var D4=c=>{let t={},e=t;return()=>(e===t&&(e=c()),e)},uo=class uo{static loadScript(t,e){let s=document.createElement("script");s.setAttribute("src",t),s.onload=()=>{e(null)},s.onerror=()=>{e(`Failed to load script='${t}'`)},document.body.appendChild(s)}static loadWasm(t,e,s){let i=uo.wasmSupported()&&e.glueUrl&&e.wasmUrl?e.glueUrl:e.fallbackUrl;i?uo.loadScript(i,r=>{if(r)s(r,null);else{let a=window[t];window[t]=void 0,a({locateFile:()=>e.wasmUrl,onAbort:()=>{s("wasm module aborted.")}}).then(o=>{s(null,o)})}}):s("No supported wasm modules found.",null)}static getModule(t){return uo.modules.hasOwnProperty(t)||(uo.modules[t]={config:null,initializing:!1,instance:null,callbacks:[]}),uo.modules[t]}static initialize(t,e){if(e.initializing)return;let s=e.config;(s.glueUrl||s.wasmUrl||s.fallbackUrl)&&(e.initializing=!0,uo.loadWasm(t,s,(i,r)=>{i?s.errorHandler&&s.errorHandler(i):(e.instance=r,e.callbacks.forEach(a=>{a(r)}))}))}};n(uo,"modules",{}),n(uo,"wasmSupported",D4(()=>{try{if(typeof WebAssembly=="object"&&typeof WebAssembly.instantiate=="function"){let t=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(t instanceof WebAssembly.Module)return new WebAssembly.Instance(t)instanceof WebAssembly.Instance}}catch{}return!1}));var Bh=uo,Yl=class{static setConfig(t,e){let s=Bh.getModule(t);s.config=e,s.callbacks.length>0&&Bh.initialize(t,s)}static getConfig(t){return Bh.modules?.[t]?.config}static getInstance(t,e){let s=Bh.getModule(t);s.instance?e(s.instance):(s.callbacks.push(e),s.config&&Bh.initialize(t,s))}};var Kl=class{constructor(t){n(this,"arraybuffer");n(this,"dataView");n(this,"offset",0);this.arraybuffer=t,this.dataView=new DataView(t)}get remainingBytes(){return this.dataView.byteLength-this.offset}reset(t=0){this.offset=t}skip(t){this.offset+=t}align(t){this.offset=this.offset+t-1&~(t-1)}_inc(t){return this.offset+=t,this.offset-t}readChar(){return String.fromCharCode(this.dataView.getUint8(this.offset++))}readChars(t){let e="";for(let s=0;s=t.byteLength);){let s=String.fromCharCode(this.readU8());if(s===` +`)break;e+=s}return e}};var po=class{constructor(t){n(this,"items",[]);n(this,"length",0);n(this,"loopIndex",-1);n(this,"_sortBy");n(this,"_sortHandler");this._sortBy=t.sortBy,this._sortHandler=this._doSort.bind(this)}_binarySearch(t){let e=0,s=this.items.length-1,i=t[this._sortBy],r,a;for(;e<=s;)r=Math.floor((e+s)/2),a=this.items[r][this._sortBy],a<=i?e=r+1:a>i&&(s=r-1);return e}_doSort(t,e){let s=this._sortBy;return t[s]-e[s]}insert(t){let e=this._binarySearch(t);this.items.splice(e,0,t),this.length++,this.loopIndex>=e&&this.loopIndex++}append(t){this.items.push(t),this.length++}remove(t){let e=this.items.indexOf(t);e<0||(this.items.splice(e,1),this.length--,this.loopIndex>=e&&this.loopIndex--)}sort(){let t=this.loopIndex>=0?this.items[this.loopIndex]:null;this.items.sort(this._sortHandler),t!==null&&(this.loopIndex=this.items.indexOf(t))}};var va=class extends J{constructor(e){super();n(this,"_index",{});n(this,"_list",[]);n(this,"_parent");this._parent=e}add(...e){let s=!1,i=this._processArguments(e,!0);if(!i.length)return s;for(let r=0;r=e?e:c<=t?t:c},intToBytes24(c){let t=c>>16&255,e=c>>8&255,s=c&255;return[t,e,s]},intToBytes32(c){let t=c>>24&255,e=c>>16&255,s=c>>8&255,i=c&255;return[t,e,s,i]},bytesToInt24(c,t,e){return c.length&&(e=c[2],t=c[1],c=c[0]),c<<16|t<<8|e},bytesToInt32(c,t,e,s){return c.length&&(s=c[3],e=c[2],t=c[1],c=c[0]),(c<<24|t<<16|e<<8|s)>>>0},lerp(c,t,e){return c+(t-c)*R.clamp(e,0,1)},lerpAngle(c,t,e){return t-c>180&&(t-=360),t-c<-180&&(t+=360),R.lerp(c,t,R.clamp(e,0,1))},powerOfTwo(c){return c!==0&&!(c&c-1)},nextPowerOfTwo(c){return c--,c|=c>>1,c|=c>>2,c|=c>>4,c|=c>>8,c|=c>>16,c++,c},nearestPowerOfTwo(c){return Math.pow(2,Math.round(Math.log2(c)))},random(c,t){let e=t-c;return Math.random()*e+c},smoothstep(c,t,e){return e<=c?0:e>=t?1:(e=(e-c)/(t-c),e*e*(3-2*e))},smootherstep(c,t,e){return e<=c?0:e>=t?1:(e=(e-c)/(t-c),e*e*e*(e*(e*6-15)+10))},roundUp(c,t){return t===0?c:Math.ceil(c/t)*t},between(c,t,e,s){let i=Math.min(t,e),r=Math.max(t,e);return s?c>=i&&c<=r:c>i&&c7?s=R.intToBytes32(e):(s=R.intToBytes24(e),s[3]=255),this.set(s[0]/255,s[1]/255,s[2]/255,s[3]/255),this}fromArray(t,e=0){return this.r=t[e]??this.r,this.g=t[e+1]??this.g,this.b=t[e+2]??this.b,this.a=t[e+3]??this.a,this}toString(t,e){let{r:s,g:i,b:r,a}=this;if(e||s>1||i>1||r>1)return`${s.toFixed(3)}, ${i.toFixed(3)}, ${r.toFixed(3)}, ${a.toFixed(3)}`;let o=`#${((1<<24)+(Math.round(s*255)<<16)+(Math.round(i*255)<<8)+Math.round(r*255)).toString(16).slice(1)}`;if(t===!0){let l=Math.round(a*255).toString(16);this.a<16/255?o+=`0${l}`:o+=l}return o}toArray(t=[],e=0,s=!0){return t[e]=this.r,t[e+1]=this.g,t[e+2]=this.b,s&&(t[e+3]=this.a),t}};n(ps,"BLACK",Object.freeze(new ps(0,0,0,1))),n(ps,"BLUE",Object.freeze(new ps(0,0,1,1))),n(ps,"CYAN",Object.freeze(new ps(0,1,1,1))),n(ps,"GRAY",Object.freeze(new ps(.5,.5,.5,1))),n(ps,"GREEN",Object.freeze(new ps(0,1,0,1))),n(ps,"MAGENTA",Object.freeze(new ps(1,0,1,1))),n(ps,"RED",Object.freeze(new ps(1,0,0,1))),n(ps,"WHITE",Object.freeze(new ps(1,1,1,1))),n(ps,"YELLOW",Object.freeze(new ps(1,1,0,1)));var F=ps;var id=class{constructor(t,e=0){n(this,"_curve");n(this,"_left",-1/0);n(this,"_right",1/0);n(this,"_recip",0);n(this,"_p0",0);n(this,"_p1",0);n(this,"_m0",0);n(this,"_m1",0);this._curve=t,this._reset(e)}evaluate(t,e=!1){(e||t=this._right)&&this._reset(t);let s,i=this._curve.type;if(i===5)s=this._p0;else{let r=this._recip===0?0:(t-this._left)*this._recip;i===0?s=R.lerp(this._p0,this._p1,r):i===1?s=R.lerp(this._p0,this._p1,r*r*(3-2*r)):s=this._evaluateHermite(this._p0,this._p1,this._m0,this._m1,r)}return s}_reset(t){let e=this._curve.keys,s=e.length;if(!s)this._left=-1/0,this._right=1/0,this._recip=0,this._p0=this._p1=this._m0=this._m1=0;else if(t=e[s-1][0])this._left=e[s-1][0],this._right=1/0,this._recip=0,this._p0=this._p1=e[s-1][1],this._m0=this._m1=0;else{let i=0;for(;t>=e[i+1][0];)i++;this._left=e[i][0],this._right=e[i+1][0];let r=1/(this._right-this._left);this._recip=isFinite(r)?r:0,this._p0=e[i][1],this._p1=e[i+1][1],this._curve.type===4&&this._calcTangents(e,i)}}_calcTangents(t,e){let s,i=t[e],r=t[e+1],a;if(e===0?s=[t[0][0]+(t[0][0]-t[1][0]),t[0][1]+(t[0][1]-t[1][1])]:s=t[e-1],e===t.length-2?a=[t[e+1][0]+(t[e+1][0]-t[e][0]),t[e+1][1]+(t[e+1][1]-t[e][1])]:a=t[e+2],this._curve.type===4){let o=2*(r[0]-i[0])/(r[0]-s[0]),l=2*(r[0]-i[0])/(a[0]-i[0]);this._m0=this._curve.tension*(isFinite(o)?o:0)*(r[1]-s[1]),this._m1=this._curve.tension*(isFinite(l)?l:0)*(a[1]-i[1])}else{let o=(r[0]-i[0])/(i[0]-s[0]),l=(r[0]-i[0])/(a[0]-r[0]),h=i[1]+(s[1]-i[1])*(isFinite(o)?o:0),f=r[1]+(a[1]-r[1])*(isFinite(l)?l:0),u=this._curve.tension;this._m0=u*(r[1]-h),this._m1=u*(f-i[1])}}_evaluateHermite(t,e,s,i,r){let a=r*r,o=r+r,l=1-r,h=l*l;return t*((1+o)*h)+s*(r*h)+e*(a*(3-o))+i*(a*(r-1))}};var Ps=class{constructor(t){n(this,"keys",[]);n(this,"type",1);n(this,"tension",.5);n(this,"_eval",new id(this));if(t)for(let e=0;et);r++);let a=[t,e];return this.keys.splice(r,0,a),a}get(t){return this.keys[t]}sort(){this.keys.sort((t,e)=>t[0]-e[0])}value(t){return this._eval.evaluate(t,!0)}closest(t){let e=this.keys,s=e.length,i=2,r=null;for(let a=0;a=o)i=o,r=e[a];else break}return r}clone(){let t=new this.constructor;return t.keys=this.keys.map(e=>[...e]),t.type=this.type,t.tension=this.tension,t}quantize(t){t=Math.max(t,2);let e=new Float32Array(t),s=1/(t-1);e[0]=this._eval.evaluate(0,!0);for(let i=1;i1)for(let e=0;e>16&32768,i=e>>12&2047,r=e>>23&255;return r<103?s:r>142?(s|=31744,s|=(r===255?0:1)&&e&8388607,s):r<113?(i|=2048,s|=(i>>114-r)+(i>>113-r&1),s):(s|=r-112<<10|i>>1,s+=i&1,s)}static float2RGBA8(t,e){bC[0]=t;let s=hD[0];e.r=(s>>24&255)/255,e.g=(s>>16&255)/255,e.b=(s>>8&255)/255,e.a=(s&255)/255}};var rd=class{static concentric(t,e){let s=[];s.push(0,0);let i=2*Math.PI/t/e;for(let r=1;r<=t;r++){let a=r/t,o=2*Math.PI*a,l=Math.max(1,Math.floor(o/i)),h=2*Math.PI/l;for(let f=0;f0){let s=1/Math.sqrt(e);this.x=t.x*s,this.y=t.y*s,this.z=t.z*s}return this}floor(t=this){return this.x=Math.floor(t.x),this.y=Math.floor(t.y),this.z=Math.floor(t.z),this}ceil(t=this){return this.x=Math.ceil(t.x),this.y=Math.ceil(t.y),this.z=Math.ceil(t.z),this}round(t=this){return this.x=Math.round(t.x),this.y=Math.round(t.y),this.z=Math.round(t.z),this}min(t){return t.xthis.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this}project(t){let e=this.x*t.x+this.y*t.y+this.z*t.z,s=t.x*t.x+t.y*t.y+t.z*t.z,i=e/s;return this.x=t.x*i,this.y=t.y*i,this.z=t.z*i,this}set(t,e,s){return this.x=t,this.y=e,this.z=s,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}sub2(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}fromArray(t,e=0){return this.x=t[e]??this.x,this.y=t[e+1]??this.y,this.z=t[e+2]??this.z,this}toString(){return`[${this.x}, ${this.y}, ${this.z}]`}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}};n(ms,"ZERO",Object.freeze(new ms(0,0,0))),n(ms,"HALF",Object.freeze(new ms(.5,.5,.5))),n(ms,"ONE",Object.freeze(new ms(1,1,1))),n(ms,"UP",Object.freeze(new ms(0,1,0))),n(ms,"DOWN",Object.freeze(new ms(0,-1,0))),n(ms,"RIGHT",Object.freeze(new ms(1,0,0))),n(ms,"LEFT",Object.freeze(new ms(-1,0,0))),n(ms,"FORWARD",Object.freeze(new ms(0,0,-1))),n(ms,"BACK",Object.freeze(new ms(0,0,1)));var x=ms;var ad=class ad{constructor(){n(this,"data",new Float32Array(9));this.data[0]=this.data[4]=this.data[8]=1}clone(){let t=this.constructor;return new t().copy(this)}copy(t){let e=t.data,s=this.data;return s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],this}set(t){let e=this.data;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],this}getX(t=new x){return t.set(this.data[0],this.data[1],this.data[2])}getY(t=new x){return t.set(this.data[3],this.data[4],this.data[5])}getZ(t=new x){return t.set(this.data[6],this.data[7],this.data[8])}equals(t){let e=this.data,s=t.data;return e[0]===s[0]&&e[1]===s[1]&&e[2]===s[2]&&e[3]===s[3]&&e[4]===s[4]&&e[5]===s[5]&&e[6]===s[6]&&e[7]===s[7]&&e[8]===s[8]}isIdentity(){let t=this.data;return t[0]===1&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===1&&t[5]===0&&t[6]===0&&t[7]===0&&t[8]===1}setIdentity(){let t=this.data;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,this}toString(){return`[${this.data.join(", ")}]`}transpose(t=this){let e=t.data,s=this.data;if(e===s){let i;i=e[1],s[1]=e[3],s[3]=i,i=e[2],s[2]=e[6],s[6]=i,i=e[5],s[5]=e[7],s[7]=i}else s[0]=e[0],s[1]=e[3],s[2]=e[6],s[3]=e[1],s[4]=e[4],s[5]=e[7],s[6]=e[2],s[7]=e[5],s[8]=e[8];return this}setFromMat4(t){let e=t.data,s=this.data;return s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[4],s[4]=e[5],s[5]=e[6],s[6]=e[8],s[7]=e[9],s[8]=e[10],this}setFromQuat(t){let e=t.x,s=t.y,i=t.z,r=t.w,a=e+e,o=s+s,l=i+i,h=e*a,f=e*o,u=e*l,d=s*o,p=s*l,m=i*l,_=r*a,S=r*o,g=r*l,T=this.data;return T[0]=1-(d+m),T[1]=f+g,T[2]=u-S,T[3]=f-g,T[4]=1-(h+m),T[5]=p+_,T[6]=u+S,T[7]=p-_,T[8]=1-(h+d),this}invertMat4(t){let e=t.data,s=e[0],i=e[1],r=e[2],a=e[4],o=e[5],l=e[6],h=e[8],f=e[9],u=e[10],d=u*o-l*f,p=-u*i+r*f,m=l*i-r*o,_=-u*a+l*h,S=u*s-r*h,g=-l*s+r*a,T=f*a-o*h,C=-f*s+i*h,v=o*s-i*a,E=s*d+i*_+r*T;if(E===0)this.setIdentity();else{let y=1/E,P=this.data;P[0]=d*y,P[1]=p*y,P[2]=m*y,P[3]=_*y,P[4]=S*y,P[5]=g*y,P[6]=T*y,P[7]=C*y,P[8]=v*y}return this}transformVector(t,e=new x){let s=this.data,{x:i,y:r,z:a}=t;return e.x=i*s[0]+r*s[3]+a*s[6],e.y=i*s[1]+r*s[4]+a*s[7],e.z=i*s[2]+r*s[5]+a*s[8],e}};n(ad,"IDENTITY",Object.freeze(new ad)),n(ad,"ZERO",Object.freeze(new ad().set([0,0,0,0,0,0,0,0,0])));var Ws=ad;var pi=class pi{constructor(t=0,e=0){n(this,"x");n(this,"y");t.length===2?(this.x=t[0],this.y=t[1]):(this.x=t,this.y=e)}add(t){return this.x+=t.x,this.y+=t.y,this}add2(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addScaled(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}clone(){let t=this.constructor;return new t(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}cross(t){return this.x*t.y-this.y*t.x}distance(t){let e=this.x-t.x,s=this.y-t.y;return Math.sqrt(e*e+s*s)}div(t){return this.x/=t.x,this.y/=t.y,this}div2(t,e){return this.x=t.x/e.x,this.y=t.y/e.y,this}divScalar(t){return this.x/=t,this.y/=t,this}dot(t){return this.x*t.x+this.y*t.y}equals(t){return this.x===t.x&&this.y===t.y}equalsApprox(t,e=1e-6){return Math.abs(this.x-t.x)0){let s=1/Math.sqrt(e);this.x=t.x*s,this.y=t.y*s}return this}rotate(t){let e=Math.atan2(this.x,this.y)+t*R.DEG_TO_RAD,s=Math.sqrt(this.x*this.x+this.y*this.y);return this.x=Math.sin(e)*s,this.y=Math.cos(e)*s,this}angle(){return Math.atan2(this.x,this.y)*R.RAD_TO_DEG}angleTo(t){return Math.atan2(this.x*t.y+this.y*t.x,this.x*t.x+this.y*t.y)*R.RAD_TO_DEG}floor(t=this){return this.x=Math.floor(t.x),this.y=Math.floor(t.y),this}ceil(t=this){return this.x=Math.ceil(t.x),this.y=Math.ceil(t.y),this}round(t=this){return this.x=Math.round(t.x),this.y=Math.round(t.y),this}min(t){return t.xthis.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),this}set(t,e){return this.x=t,this.y=e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}sub2(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}subScalar(t){return this.x-=t,this.y-=t,this}fromArray(t,e=0){return this.x=t[e]??this.x,this.y=t[e+1]??this.y,this}toString(){return`[${this.x}, ${this.y}]`}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}static angleRad(t,e){return Math.atan2(t.x*e.y-t.y*e.x,t.x*e.x+t.y*e.y)}};n(pi,"ZERO",Object.freeze(new pi(0,0))),n(pi,"HALF",Object.freeze(new pi(.5,.5))),n(pi,"ONE",Object.freeze(new pi(1,1))),n(pi,"UP",Object.freeze(new pi(0,1))),n(pi,"DOWN",Object.freeze(new pi(0,-1))),n(pi,"RIGHT",Object.freeze(new pi(1,0))),n(pi,"LEFT",Object.freeze(new pi(-1,0)));var B=pi;var ql=class ql{constructor(t=0,e=0,s=0,i=0){n(this,"x");n(this,"y");n(this,"z");n(this,"w");t.length===4?(this.x=t[0],this.y=t[1],this.z=t[2],this.w=t[3]):(this.x=t,this.y=e,this.z=s,this.w=i)}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}add2(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addScaled(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}clone(){let t=this.constructor;return new t(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}div(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}div2(t,e){return this.x=t.x/e.x,this.y=t.y/e.y,this.z=t.z/e.z,this.w=t.w/e.w,this}divScalar(t){return this.x/=t,this.y/=t,this.z/=t,this.w/=t,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}equals(t){return this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w}equalsApprox(t,e=1e-6){return Math.abs(this.x-t.x)0){let s=1/Math.sqrt(e);this.x=t.x*s,this.y=t.y*s,this.z=t.z*s,this.w=t.w*s}return this}floor(t=this){return this.x=Math.floor(t.x),this.y=Math.floor(t.y),this.z=Math.floor(t.z),this.w=Math.floor(t.w),this}ceil(t=this){return this.x=Math.ceil(t.x),this.y=Math.ceil(t.y),this.z=Math.ceil(t.z),this.w=Math.ceil(t.w),this}round(t=this){return this.x=Math.round(t.x),this.y=Math.round(t.y),this.z=Math.round(t.z),this.w=Math.round(t.w),this}min(t){return t.xthis.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this}set(t,e,s,i){return this.x=t,this.y=e,this.z=s,this.w=i,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}sub2(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}fromArray(t,e=0){return this.x=t[e]??this.x,this.y=t[e+1]??this.y,this.z=t[e+2]??this.z,this.w=t[e+3]??this.w,this}toString(){return`[${this.x}, ${this.y}, ${this.z}, ${this.w}]`}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}};n(ql,"ZERO",Object.freeze(new ql(0,0,0,0))),n(ql,"HALF",Object.freeze(new ql(.5,.5,.5,.5))),n(ql,"ONE",Object.freeze(new ql(1,1,1,1)));var Q=ql;var yg=new B,Ta=new x,mo=new x,_o=new x,Dx=new x,Uh=class Uh{constructor(){n(this,"data",new Float32Array(16));this.data[0]=this.data[5]=this.data[10]=this.data[15]=1}static _getPerspectiveHalfSize(t,e,s,i,r){r?(t.x=i*Math.tan(e*Math.PI/360),t.y=t.x/s):(t.y=i*Math.tan(e*Math.PI/360),t.x=t.y*s)}add2(t,e){let s=t.data,i=e.data,r=this.data;return r[0]=s[0]+i[0],r[1]=s[1]+i[1],r[2]=s[2]+i[2],r[3]=s[3]+i[3],r[4]=s[4]+i[4],r[5]=s[5]+i[5],r[6]=s[6]+i[6],r[7]=s[7]+i[7],r[8]=s[8]+i[8],r[9]=s[9]+i[9],r[10]=s[10]+i[10],r[11]=s[11]+i[11],r[12]=s[12]+i[12],r[13]=s[13]+i[13],r[14]=s[14]+i[14],r[15]=s[15]+i[15],this}add(t){return this.add2(this,t)}clone(){let t=this.constructor;return new t().copy(this)}copy(t){let e=t.data,s=this.data;return s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=e[12],s[13]=e[13],s[14]=e[14],s[15]=e[15],this}equals(t){let e=this.data,s=t.data;return e[0]===s[0]&&e[1]===s[1]&&e[2]===s[2]&&e[3]===s[3]&&e[4]===s[4]&&e[5]===s[5]&&e[6]===s[6]&&e[7]===s[7]&&e[8]===s[8]&&e[9]===s[9]&&e[10]===s[10]&&e[11]===s[11]&&e[12]===s[12]&&e[13]===s[13]&&e[14]===s[14]&&e[15]===s[15]}isIdentity(){let t=this.data;return t[0]===1&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===1&&t[6]===0&&t[7]===0&&t[8]===0&&t[9]===0&&t[10]===1&&t[11]===0&&t[12]===0&&t[13]===0&&t[14]===0&&t[15]===1}mul2(t,e){let s=t.data,i=e.data,r=this.data,a=s[0],o=s[1],l=s[2],h=s[3],f=s[4],u=s[5],d=s[6],p=s[7],m=s[8],_=s[9],S=s[10],g=s[11],T=s[12],C=s[13],v=s[14],E=s[15],y,P,A,w;return y=i[0],P=i[1],A=i[2],w=i[3],r[0]=a*y+f*P+m*A+T*w,r[1]=o*y+u*P+_*A+C*w,r[2]=l*y+d*P+S*A+v*w,r[3]=h*y+p*P+g*A+E*w,y=i[4],P=i[5],A=i[6],w=i[7],r[4]=a*y+f*P+m*A+T*w,r[5]=o*y+u*P+_*A+C*w,r[6]=l*y+d*P+S*A+v*w,r[7]=h*y+p*P+g*A+E*w,y=i[8],P=i[9],A=i[10],w=i[11],r[8]=a*y+f*P+m*A+T*w,r[9]=o*y+u*P+_*A+C*w,r[10]=l*y+d*P+S*A+v*w,r[11]=h*y+p*P+g*A+E*w,y=i[12],P=i[13],A=i[14],w=i[15],r[12]=a*y+f*P+m*A+T*w,r[13]=o*y+u*P+_*A+C*w,r[14]=l*y+d*P+S*A+v*w,r[15]=h*y+p*P+g*A+E*w,this}mulAffine2(t,e){let s=t.data,i=e.data,r=this.data,a=s[0],o=s[1],l=s[2],h=s[4],f=s[5],u=s[6],d=s[8],p=s[9],m=s[10],_=s[12],S=s[13],g=s[14],T,C,v;return T=i[0],C=i[1],v=i[2],r[0]=a*T+h*C+d*v,r[1]=o*T+f*C+p*v,r[2]=l*T+u*C+m*v,r[3]=0,T=i[4],C=i[5],v=i[6],r[4]=a*T+h*C+d*v,r[5]=o*T+f*C+p*v,r[6]=l*T+u*C+m*v,r[7]=0,T=i[8],C=i[9],v=i[10],r[8]=a*T+h*C+d*v,r[9]=o*T+f*C+p*v,r[10]=l*T+u*C+m*v,r[11]=0,T=i[12],C=i[13],v=i[14],r[12]=a*T+h*C+d*v+_,r[13]=o*T+f*C+p*v+S,r[14]=l*T+u*C+m*v+g,r[15]=1,this}mul(t){return this.mul2(this,t)}transformPoint(t,e=new x){let s=this.data,{x:i,y:r,z:a}=t;return e.x=i*s[0]+r*s[4]+a*s[8]+s[12],e.y=i*s[1]+r*s[5]+a*s[9]+s[13],e.z=i*s[2]+r*s[6]+a*s[10]+s[14],e}transformVector(t,e=new x){let s=this.data,{x:i,y:r,z:a}=t;return e.x=i*s[0]+r*s[4]+a*s[8],e.y=i*s[1]+r*s[5]+a*s[9],e.z=i*s[2]+r*s[6]+a*s[10],e}transformVec4(t,e=new Q){let s=this.data,{x:i,y:r,z:a,w:o}=t;return e.x=i*s[0]+r*s[4]+a*s[8]+o*s[12],e.y=i*s[1]+r*s[5]+a*s[9]+o*s[13],e.z=i*s[2]+r*s[6]+a*s[10]+o*s[14],e.w=i*s[3]+r*s[7]+a*s[11]+o*s[15],e}setLookAt(t,e,s){_o.sub2(t,e).normalize(),mo.copy(s).normalize(),Ta.cross(mo,_o).normalize(),mo.cross(_o,Ta);let i=this.data;return i[0]=Ta.x,i[1]=Ta.y,i[2]=Ta.z,i[3]=0,i[4]=mo.x,i[5]=mo.y,i[6]=mo.z,i[7]=0,i[8]=_o.x,i[9]=_o.y,i[10]=_o.z,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}setFrustum(t,e,s,i,r,a){let o=2*r,l=e-t,h=i-s,f=a-r,u=this.data;return u[0]=o/l,u[1]=0,u[2]=0,u[3]=0,u[4]=0,u[5]=o/h,u[6]=0,u[7]=0,u[8]=(e+t)/l,u[9]=(i+s)/h,u[10]=(-a-r)/f,u[11]=-1,u[12]=0,u[13]=0,u[14]=-o*a/f,u[15]=0,this}setPerspective(t,e,s,i,r){return Uh._getPerspectiveHalfSize(yg,t,e,s,r),this.setFrustum(-yg.x,yg.x,-yg.y,yg.y,s,i)}setOrtho(t,e,s,i,r,a){let o=this.data;return o[0]=2/(e-t),o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2/(i-s),o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=-2/(a-r),o[11]=0,o[12]=-(e+t)/(e-t),o[13]=-(i+s)/(i-s),o[14]=-(a+r)/(a-r),o[15]=1,this}setFromAxisAngle(t,e){e*=R.DEG_TO_RAD;let{x:s,y:i,z:r}=t,a=Math.cos(e),o=Math.sin(e),l=1-a,h=l*s,f=l*i,u=this.data;return u[0]=h*s+a,u[1]=h*i+o*r,u[2]=h*r-o*i,u[3]=0,u[4]=h*i-o*r,u[5]=f*i+a,u[6]=f*r+o*s,u[7]=0,u[8]=h*r+o*i,u[9]=f*r-s*o,u[10]=l*r*r+a,u[11]=0,u[12]=0,u[13]=0,u[14]=0,u[15]=1,this}setTranslate(t,e,s){let i=this.data;return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=1,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=t,i[13]=e,i[14]=s,i[15]=1,this}setScale(t,e,s){let i=this.data;return i[0]=t,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=e,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=s,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,this}setViewport(t,e,s,i){let r=this.data;return r[0]=s*.5,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=i*.5,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=.5,r[11]=0,r[12]=t+s*.5,r[13]=e+i*.5,r[14]=.5,r[15]=1,this}setReflection(t,e){let s=t.x,i=t.y,r=t.z,a=this.data;return a[0]=1-2*s*s,a[1]=-2*s*i,a[2]=-2*s*r,a[3]=0,a[4]=-2*s*i,a[5]=1-2*i*i,a[6]=-2*i*r,a[7]=0,a[8]=-2*s*r,a[9]=-2*i*r,a[10]=1-2*r*r,a[11]=0,a[12]=-2*s*e,a[13]=-2*i*e,a[14]=-2*r*e,a[15]=1,this}invert(t=this){let e=t.data,s=e[0],i=e[1],r=e[2],a=e[3],o=e[4],l=e[5],h=e[6],f=e[7],u=e[8],d=e[9],p=e[10],m=e[11],_=e[12],S=e[13],g=e[14],T=e[15],C=s*l-i*o,v=s*h-r*o,E=s*f-a*o,y=i*h-r*l,P=i*f-a*l,A=r*f-a*h,w=u*S-d*_,I=u*g-p*_,D=u*T-m*_,O=d*g-p*S,G=d*T-m*S,M=p*T-m*g,H=C*M-v*G+E*O+y*D-P*I+A*w;if(H===0)this.setIdentity();else{let U=1/H,L=this.data;L[0]=(l*M-h*G+f*O)*U,L[1]=(-i*M+r*G-a*O)*U,L[2]=(S*A-g*P+T*y)*U,L[3]=(-d*A+p*P-m*y)*U,L[4]=(-o*M+h*D-f*I)*U,L[5]=(s*M-r*D+a*I)*U,L[6]=(-_*A+g*E-T*v)*U,L[7]=(u*A-p*E+m*v)*U,L[8]=(o*G-l*D+f*w)*U,L[9]=(-s*G+i*D-a*w)*U,L[10]=(_*P-S*E+T*C)*U,L[11]=(-u*P+d*E-m*C)*U,L[12]=(-o*O+l*I-h*w)*U,L[13]=(s*O-i*I+r*w)*U,L[14]=(-_*y+S*v-g*C)*U,L[15]=(u*y-d*v+p*C)*U}return this}set(t){let e=this.data;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this}setIdentity(){let t=this.data;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}setTRS(t,e,s){let i=e.x,r=e.y,a=e.z,o=e.w,l=s.x,h=s.y,f=s.z,u=i+i,d=r+r,p=a+a,m=i*u,_=i*d,S=i*p,g=r*d,T=r*p,C=a*p,v=o*u,E=o*d,y=o*p,P=this.data;return P[0]=(1-(g+C))*l,P[1]=(_+y)*l,P[2]=(S-E)*l,P[3]=0,P[4]=(_-y)*h,P[5]=(1-(m+C))*h,P[6]=(T+v)*h,P[7]=0,P[8]=(S+E)*f,P[9]=(T-v)*f,P[10]=(1-(m+g))*f,P[11]=0,P[12]=t.x,P[13]=t.y,P[14]=t.z,P[15]=1,this}transpose(t=this){let e=t.data,s=this.data;if(e===s){let i;i=e[1],s[1]=e[4],s[4]=i,i=e[2],s[2]=e[8],s[8]=i,i=e[3],s[3]=e[12],s[12]=i,i=e[6],s[6]=e[9],s[9]=i,i=e[7],s[7]=e[13],s[13]=i,i=e[11],s[11]=e[14],s[14]=i}else s[0]=e[0],s[1]=e[4],s[2]=e[8],s[3]=e[12],s[4]=e[1],s[5]=e[5],s[6]=e[9],s[7]=e[13],s[8]=e[2],s[9]=e[6],s[10]=e[10],s[11]=e[14],s[12]=e[3],s[13]=e[7],s[14]=e[11],s[15]=e[15];return this}getTranslation(t=new x){return t.set(this.data[12],this.data[13],this.data[14])}getX(t=new x){return t.set(this.data[0],this.data[1],this.data[2])}getY(t=new x){return t.set(this.data[4],this.data[5],this.data[6])}getZ(t=new x){return t.set(this.data[8],this.data[9],this.data[10])}getScale(t=new x){return this.getX(Ta),this.getY(mo),this.getZ(_o),t.set(Ta.length(),mo.length(),_o.length()),t}get scaleSign(){return this.getX(Ta),this.getY(mo),this.getZ(_o),Ta.cross(Ta,mo),Ta.dot(_o)<0?-1:1}setFromEulerAngles(t,e,s){t*=R.DEG_TO_RAD,e*=R.DEG_TO_RAD,s*=R.DEG_TO_RAD;let i=Math.sin(-t),r=Math.cos(-t),a=Math.sin(-e),o=Math.cos(-e),l=Math.sin(-s),h=Math.cos(-s),f=this.data;return f[0]=o*h,f[1]=-o*l,f[2]=a,f[3]=0,f[4]=r*l+h*i*a,f[5]=r*h-i*a*l,f[6]=-o*i,f[7]=0,f[8]=i*l-r*h*a,f[9]=h*i+r*a*l,f[10]=r*o,f[11]=0,f[12]=0,f[13]=0,f[14]=0,f[15]=1,this}getEulerAngles(t=new x){this.getScale(Dx);let e=Dx.x,s=Dx.y,i=Dx.z;if(e===0||s===0||i===0)return t.set(0,0,0);let r=this.data,a=Math.asin(-r[2]/e),o=Math.PI*.5,l,h;return a-o?(l=Math.atan2(r[6]/s,r[10]/i),h=Math.atan2(r[1]/e,r[0]/e)):(h=0,l=-Math.atan2(r[4]/s,r[5]/s)):(h=0,l=Math.atan2(r[4]/s,r[5]/s)),t.set(l,a,h).mulScalar(R.RAD_TO_DEG)}toString(){return`[${this.data.join(", ")}]`}};n(Uh,"IDENTITY",Object.freeze(new Uh)),n(Uh,"ZERO",Object.freeze(new Uh().set([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])));var W=Uh;var od=class od{constructor(t=0,e=0,s=0,i=1){n(this,"x");n(this,"y");n(this,"z");n(this,"w");t.length===4?(this.x=t[0],this.y=t[1],this.z=t[2],this.w=t[3]):(this.x=t,this.y=e,this.z=s,this.w=i)}clone(){let t=this.constructor;return new t(this.x,this.y,this.z,this.w)}conjugate(t=this){return this.x=t.x*-1,this.y=t.y*-1,this.z=t.z*-1,this.w=t.w,this}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}equals(t){return this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w}equalsApprox(t,e=1e-6){return Math.abs(this.x-t.x)=.99999?(e=2*Math.atan2(r,l),s=Math.PI/2,i=0):(e=Math.atan2(2*(l*r+a*o),1-2*(r*r+a*a)),s=Math.asin(h),i=Math.atan2(2*(l*o+r*a),1-2*(a*a+o*o))),t.set(e,s,i).mulScalar(R.RAD_TO_DEG)}invert(t=this){return this.conjugate(t).normalize()}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}lerp(t,e,s){let i=(1-s)*(t.dot(e)<0?-1:1);return this.x=t.x*i+e.x*s,this.y=t.y*i+e.y*s,this.z=t.z*i+e.z*s,this.w=t.w*i+e.w*s,this.normalize()}mul(t){let e=this.x,s=this.y,i=this.z,r=this.w,a=t.x,o=t.y,l=t.z,h=t.w;return this.x=r*a+e*h+s*l-i*o,this.y=r*o+s*h+i*a-e*l,this.z=r*l+i*h+e*o-s*a,this.w=r*h-e*a-s*o-i*l,this}mulScalar(t,e=this){return this.x=e.x*t,this.y=e.y*t,this.z=e.z*t,this.w=e.w*t,this}mul2(t,e){let s=t.x,i=t.y,r=t.z,a=t.w,o=e.x,l=e.y,h=e.z,f=e.w;return this.x=a*o+s*f+i*h-r*l,this.y=a*l+i*f+r*o-s*h,this.z=a*h+r*f+s*l-i*o,this.w=a*f-s*o-i*l-r*h,this}normalize(t=this){let e=t.length();return e===0?(this.x=this.y=this.z=0,this.w=1):(e=1/e,this.x=t.x*e,this.y=t.y*e,this.z=t.z*e,this.w=t.w*e),this}set(t,e,s,i){return this.x=t,this.y=e,this.z=s,this.w=i,this}setFromAxisAngle(t,e){e*=.5*R.DEG_TO_RAD;let s=Math.sin(e),i=Math.cos(e);return this.x=s*t.x,this.y=s*t.y,this.z=s*t.z,this.w=i,this}setFromEulerAngles(t,e,s){if(t instanceof x){let u=t;t=u.x,e=u.y,s=u.z}let i=.5*R.DEG_TO_RAD;t*=i,e*=i,s*=i;let r=Math.sin(t),a=Math.cos(t),o=Math.sin(e),l=Math.cos(e),h=Math.sin(s),f=Math.cos(s);return this.x=r*l*f-a*o*h,this.y=a*o*f+r*l*h,this.z=a*l*h-r*o*f,this.w=a*l*f+r*o*h,this}setFromMat4(t){let e=t.data,s=e[0],i=e[1],r=e[2],a=e[4],o=e[5],l=e[6],h=e[8],f=e[9],u=e[10];s*(o*u-l*f)-i*(a*u-l*h)+r*(a*f-o*h)<0&&(s=-s,i=-i,r=-r);let p;return p=s*s+i*i+r*r,p===0?this.set(0,0,0,1):(p=1/Math.sqrt(p),s*=p,i*=p,r*=p,p=a*a+o*o+l*l,p===0?this.set(0,0,0,1):(p=1/Math.sqrt(p),a*=p,o*=p,l*=p,p=h*h+f*f+u*u,p===0?this.set(0,0,0,1):(p=1/Math.sqrt(p),h*=p,f*=p,u*=p,u<0?s>o?this.set(1+s-o-u,i+a,h+r,l-f):this.set(i+a,1-s+o-u,l+f,h-r):s<-o?this.set(h+r,l+f,1-s-o+u,i-a):this.set(l-f,h-r,i-a,1+s+o+u),this.mulScalar(1/this.length()))))}setFromDirections(t,e){let s=1+t.dot(e);return sMath.abs(t.y)?(this.x=-t.z,this.y=0,this.z=t.x,this.w=0):(this.x=0,this.y=-t.z,this.z=t.y,this.w=0):(this.x=t.y*e.z-t.z*e.y,this.y=t.z*e.x-t.x*e.z,this.z=t.x*e.y-t.y*e.x,this.w=s),this.normalize()}slerp(t,e,s){let i=t.x,r=t.y,a=t.z,o=t.w,l=e.x,h=e.y,f=e.z,u=e.w,d=o*u+i*l+r*h+a*f;if(d<0&&(u=-u,l=-l,h=-h,f=-f,d=-d),Math.abs(d)>=1)return this.w=o,this.x=i,this.y=r,this.z=a,this;let p=Math.acos(d),m=Math.sqrt(1-d*d);if(Math.abs(m)<.001)return this.w=o*.5+u*.5,this.x=i*.5+l*.5,this.y=r*.5+h*.5,this.z=a*.5+f*.5,this;let _=Math.sin((1-s)*p)/m,S=Math.sin(s*p)/m;return this.w=o*_+u*S,this.x=i*_+l*S,this.y=r*_+h*S,this.z=a*_+f*S,this}transformVector(t,e=new x){let s=t.x,i=t.y,r=t.z,a=this.x,o=this.y,l=this.z,h=this.w,f=h*s+o*r-l*i,u=h*i+l*s-a*r,d=h*r+a*i-o*s,p=-a*s-o*i-l*r;return e.x=f*h+p*-a+u*-l-d*-o,e.y=u*h+p*-o+d*-a-f*-l,e.z=d*h+p*-l+f*-o-u*-a,e}fromArray(t,e=0){return this.x=t[e]??this.x,this.y=t[e+1]??this.y,this.z=t[e+2]??this.z,this.w=t[e+3]??this.w,this}toString(){return`[${this.x}, ${this.y}, ${this.z}, ${this.w}]`}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}};n(od,"IDENTITY",Object.freeze(new od(0,0,0,1))),n(od,"ZERO",Object.freeze(new od(0,0,0,0)));var $=od;var nd=new x,ld=new x,fD=new x,uD=new x,F4=new x,ge=class c{constructor(t,e){n(this,"center",new x);n(this,"halfExtents",new x(.5,.5,.5));n(this,"_min",new x);n(this,"_max",new x);t&&this.center.copy(t),e&&this.halfExtents.copy(e)}add(t){let e=this.center,s=e.x,i=e.y,r=e.z,a=this.halfExtents,o=a.x,l=a.y,h=a.z,f=s-o,u=s+o,d=i-l,p=i+l,m=r-h,_=r+h,S=t.center,g=S.x,T=S.y,C=S.z,v=t.halfExtents,E=v.x,y=v.y,P=v.z,A=g-E,w=g+E,I=T-y,D=T+y,O=C-P,G=C+P;Au&&(u=w),Ip&&(p=D),O_&&(_=G),e.x=(f+u)*.5,e.y=(d+p)*.5,e.z=(m+_)*.5,a.x=(u-f)*.5,a.y=(p-d)*.5,a.z=(_-m)*.5}copy(t){this.center.copy(t.center),this.halfExtents.copy(t.halfExtents)}clone(){return new c(this.center,this.halfExtents)}intersects(t){let e=this.getMax(),s=this.getMin(),i=t.getMax(),r=t.getMin();return s.x<=i.x&&e.x>=r.x&&s.y<=i.y&&e.y>=r.y&&s.z<=i.z&&e.z>=r.z}_intersectsRay(t,e){let s=nd.copy(this.getMin()).sub(t.origin),i=ld.copy(this.getMax()).sub(t.origin),r=t.direction;r.x===0?(s.x=s.x<0?-Number.MAX_VALUE:Number.MAX_VALUE,i.x=i.x<0?-Number.MAX_VALUE:Number.MAX_VALUE):(s.x/=r.x,i.x/=r.x),r.y===0?(s.y=s.y<0?-Number.MAX_VALUE:Number.MAX_VALUE,i.y=i.y<0?-Number.MAX_VALUE:Number.MAX_VALUE):(s.y/=r.y,i.y/=r.y),r.z===0?(s.z=s.z<0?-Number.MAX_VALUE:Number.MAX_VALUE,i.z=i.z<0?-Number.MAX_VALUE:Number.MAX_VALUE):(s.z/=r.z,i.z/=r.z);let a=fD.set(Math.min(s.x,i.x),Math.min(s.y,i.y),Math.min(s.z,i.z)),o=uD.set(Math.max(s.x,i.x),Math.max(s.y,i.y),Math.max(s.z,i.z)),l=Math.min(Math.min(o.x,o.y),o.z),h=Math.max(Math.max(a.x,a.y),a.z),f=l>=h&&h>=0;return f&&e.copy(t.direction).mulScalar(h).add(t.origin),f}_fastIntersectsRay(t){let e=nd,s=ld,i=fD,r=uD,a=F4,o=t.direction;return e.sub2(t.origin,this.center),r.set(Math.abs(e.x),Math.abs(e.y),Math.abs(e.z)),i.mul2(e,o),!(r.x>this.halfExtents.x&&i.x>=0||r.y>this.halfExtents.y&&i.y>=0||r.z>this.halfExtents.z&&i.z>=0||(a.set(Math.abs(o.x),Math.abs(o.y),Math.abs(o.z)),s.cross(o,e),s.set(Math.abs(s.x),Math.abs(s.y),Math.abs(s.z)),s.x>this.halfExtents.y*a.z+this.halfExtents.z*a.y)||s.y>this.halfExtents.x*a.z+this.halfExtents.z*a.x||s.z>this.halfExtents.x*a.y+this.halfExtents.y*a.x)}intersectsRay(t,e){return e?this._intersectsRay(t,e):this._fastIntersectsRay(t)}setMinMax(t,e){this.center.add2(e,t).mulScalar(.5),this.halfExtents.sub2(e,t).mulScalar(.5)}getMin(){return this._min.copy(this.center).sub(this.halfExtents)}getMax(){return this._max.copy(this.center).add(this.halfExtents)}containsPoint(t){let e=this.center,s=this.halfExtents;return!(t.xe.x+s.x||t.ye.y+s.y||t.ze.z+s.z)}closestPoint(t,e=new x){let s=this.center,i=this.halfExtents;return e.set(Math.max(s.x-i.x,Math.min(t.x,s.x+i.x)),Math.max(s.y-i.y,Math.min(t.y,s.y+i.y)),Math.max(s.z-i.z,Math.min(t.z,s.z+i.z)))}setFromTransformedAabb(t,e,s=!1){let i=t.center,r=t.halfExtents,a=e.data,o=a[0],l=a[4],h=a[8],f=a[1],u=a[5],d=a[9],p=a[2],m=a[6],_=a[10];if(s){let S=o*o+l*l+h*h;if(S>0){let g=1/Math.sqrt(S);o*=g,l*=g,h*=g}if(S=f*f+u*u+d*d,S>0){let g=1/Math.sqrt(S);f*=g,u*=g,d*=g}if(S=p*p+m*m+_*_,S>0){let g=1/Math.sqrt(S);p*=g,m*=g,_*=g}}this.center.set(a[12]+o*i.x+l*i.y+h*i.z,a[13]+f*i.x+u*i.y+d*i.z,a[14]+p*i.x+m*i.y+_*i.z),this.halfExtents.set(Math.abs(o)*r.x+Math.abs(l)*r.y+Math.abs(h)*r.z,Math.abs(f)*r.x+Math.abs(u)*r.y+Math.abs(d)*r.z,Math.abs(p)*r.x+Math.abs(m)*r.y+Math.abs(_)*r.z)}static computeMinMax(t,e,s,i=t.length/3){if(i>0){let r=t[0],a=t[1],o=t[2],l=r,h=a,f=o,u=i*3;for(let d=3;dl&&(l=p),m>h&&(h=m),_>f&&(f=_)}e.set(r,a,o),s.set(l,h,f)}}compute(t,e){c.computeMinMax(t,nd,ld,e),this.setMinMax(nd,ld)}intersectsBoundingSphere(t){return this._distanceToBoundingSphereSq(t)<=t.radius*t.radius}_distanceToBoundingSphereSq(t){let e=this.getMin(),s=this.getMax(),i=0,r=["x","y","z"];for(let a=0;a<3;++a){let o=0,l=t.center[r[a]],h=e[r[a]],f=s[r[a]],u=0;lf&&(u=l-f,o+=u*u),i+=o}return i}_expand(t,e){nd.add2(this.getMin(),t),ld.add2(this.getMax(),e),this.setMinMax(nd,ld)}};var Lx=new x,N4=new x,Br=class{constructor(t=new x,e=.5){n(this,"center");n(this,"radius");this.center=t,this.radius=e}containsPoint(t){let e=Lx.sub2(t,this.center).lengthSq(),s=this.radius;return e0&&i>0)return!1;let a=i*i-r;if(a<0)return!1;let o=Math.abs(-i-Math.sqrt(a));return e&&e.copy(t.direction).mulScalar(o).add(t.origin),!0}intersectsBoundingSphere(t){Lx.sub2(t.center,this.center);let e=t.radius+this.radius;return Lx.lengthSq()<=e*e}};var go=class{constructor(t=x.UP,e=0){n(this,"normal",new x);n(this,"distance");this.normal.copy(t),this.distance=e}clone(){let t=this.constructor;return new t().copy(this)}copy(t){return this.normal.copy(t.normal),this.distance=t.distance,this}intersectsLine(t,e,s){let i=this.distance,r=this.normal.dot(t)+i,a=this.normal.dot(e)+i,o=r/(r-a),l=o>=0&&o<=1;return l&&s&&s.lerp(t,e,o),l}intersectsRay(t,e){let s=this.normal.dot(t.direction);if(s===0)return!1;let i=-(this.normal.dot(t.origin)+this.distance)/s;return i>=0&&e&&e.copy(t.direction).mulScalar(i).add(t.origin),i>=0}normalize(){let t=1/this.normal.length();return this.normal.mulScalar(t),this.distance*=t,this}set(t,e,s,i){return this.normal.set(t,e,s),this.distance=i,this}setFromPointNormal(t,e){return this.normal.copy(e),this.distance=-this.normal.dot(t),this}};var So=class{constructor(){n(this,"planes",[]);for(let t=0;t<6;t++)this.planes[t]=new go}clone(){let t=this.constructor;return new t().copy(this)}copy(t){for(let e=0;e<6;e++)this.planes[e].copy(t.planes[e]);return this}setFromMat4(t){let e=t.data,s=e[0],i=e[1],r=e[2],a=e[3],o=e[4],l=e[5],h=e[6],f=e[7],u=e[8],d=e[9],p=e[10],m=e[11],_=e[12],S=e[13],g=e[14],T=e[15],C=this.planes;C[0].set(a-s,f-o,m-u,T-_).normalize(),C[1].set(a+s,f+o,m+u,T+_).normalize(),C[2].set(a+i,f+l,m+d,T+S).normalize(),C[3].set(a-i,f-l,m-d,T-S).normalize(),C[4].set(a-r,f-h,m-p,T-g).normalize(),C[5].set(a+r,f+h,m+p,T+g).normalize()}containsPoint(t){for(let e=0;e<6;e++){let{normal:s,distance:i}=this.planes[e];if(s.dot(t)+i<=0)return!1}return!0}add(t){let e=this.planes,s=t.planes;for(let i=0;i<6;i++)s[i].distance>e[i].distance&&e[i].copy(s[i]);return this}containsSphere(t){let{center:e,radius:s}=t,i=0;for(let r=0;r<6;r++){let{normal:a,distance:o}=this.planes[r],l=a.dot(e)+o;if(l<=-s)return 0;l>s&&i++}return i===6?2:1}};var ws=class{constructor(t,e){n(this,"origin",new x);n(this,"direction",x.FORWARD.clone());t&&this.origin.copy(t),e&&this.direction.copy(e)}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.set(t.origin,t.direction)}clone(){return new this.constructor(this.origin,this.direction)}};var Mx=new ws,dD=new x,DC=new Br,B4=new W,Ox=class{constructor(t=new W,e){n(this,"halfExtents",new x(.5,.5,.5));n(this,"_modelTransform");n(this,"_worldTransform");n(this,"_aabb");e&&this.halfExtents.copy(e),this._modelTransform=t.clone().invert(),this._worldTransform=t.clone(),this._aabb=new ge(new x,this.halfExtents)}set worldTransform(t){this._worldTransform.copy(t),this._modelTransform.copy(t).invert()}get worldTransform(){return this._worldTransform}intersectsRay(t,e){if(this._modelTransform.transformPoint(t.origin,Mx.origin),this._modelTransform.transformVector(t.direction,Mx.direction),e){let s=this._aabb._intersectsRay(Mx,e);return B4.copy(this._modelTransform).invert().transformPoint(e,e),s}return this._aabb._fastIntersectsRay(Mx)}containsPoint(t){return this._modelTransform.transformPoint(t,dD),this._aabb.containsPoint(dD)}intersectsBoundingSphere(t){return this._modelTransform.transformPoint(t.center,DC.center),DC.radius=t.radius,!!this._aabb.intersectsBoundingSphere(DC)}};var LC=new x,MC=new x,OC=new x,FC=new x,NC=new x,BC=1e-6,cd=class{constructor(t=x.ZERO,e=x.ZERO,s=x.ZERO){n(this,"v0",new x);n(this,"v1",new x);n(this,"v2",new x);this.set(t,e,s)}set(t,e,s){return this.v0.copy(t),this.v1.copy(e),this.v2.copy(s),this}intersectsRay(t,e){LC.sub2(this.v1,this.v0),MC.sub2(this.v2,this.v0),OC.cross(t.direction,MC);let s=LC.dot(OC);if(s>-BC&&s1)return!1;NC.cross(FC,LC);let a=i*t.direction.dot(NC);if(a<0||r+a>1)return!1;let o=i*MC.dot(NC);return o>BC?(e instanceof x&&e.copy(t.direction).mulScalar(o).add(t.origin),!0):!1}toString(){return`[${this.v0.toString()}, ${this.v1.toString()}, ${this.v2.toString()}]`}};var Je=0,ie=1,xo=2,Fx=0,_s=1,pD=2,GZ=3,UC=4,mD=5,$l=6,VZ=7,Zl=8,HZ=9,WZ=10,kC=11,zC=12,ii=0,XZ=1,_D=2,gD=3,SD=4,Nx=1,YZ=2,mi=4,$e=8,U4=16,k4=32,z4=64,GC=128,pn=256,Xs=0,hd=1,VC=2,Bx=3,mn=1,_n=2,Yh=4,KZ=0,jZ=1,qZ=2,$Z=3,ZZ=4,QZ=5,Ze=0,gn=1,HC=2,G4=3,Sn=0,xD=1,ve=0,De=1,zi=2,Ur=3,kr=4,gs=5,V4=0,fd=1,ud=2,WC=3,H4=4,W4=5,X4=6,zr=7,dd=0,Is=1,Ii=2,XC=[1,2,4],pd=0,md=1,vo=2,ya=3,xn=4,Ea=5,Ss=6,ce=7,To=8,Ql=9,Gr=10,vn=11,Me=12,Kh=13,ke=14,Mt=15,Ys=16,fr=17,Gi=18,yo=19,st=20,Eo=21,Jl=22,ec=23,Vr=24,Hr=25,Ao=26,Co=27,_d=28,gd=29,Sd=30,tc=31,jh=32,sc=33,qh=34,$h=35,Zh=36,zt=37,Qh=38,xd=39,Jh=40,ef=41,tf=42,Tn=43,sf=44,vd=45,rf=46,Rs=47,af=48,At=49,yn=50,of=51,Wr=52,Po=53,kh=54,zh=55,Gh=56,Vh=61,Hh=62,Wh=63,ic=64,Td=65,yd=66,Ed=67,Xh=68,Xr=69,nf=70,lf=71,cf=72,hf=73,ff=74,uf=75,xs=new Map([[pd,{name:"A8",size:1,ldr:!0}],[Wr,{name:"R8",size:1,ldr:!0}],[md,{name:"L8",size:1,ldr:!0}],[vo,{name:"LA8",size:2,ldr:!0}],[Po,{name:"RG8",size:2,ldr:!0}],[ya,{name:"RGB565",size:2,ldr:!0}],[xn,{name:"RGBA5551",size:2,ldr:!0}],[Ea,{name:"RGBA4",size:2,ldr:!0}],[Ss,{name:"RGB8",size:4,ldr:!0}],[ce,{name:"RGBA8",size:4,ldr:!0,srgbFormat:st}],[yn,{name:"R16F",size:2}],[of,{name:"RG16F",size:4}],[vn,{name:"RGB16F",size:8}],[Me,{name:"RGBA16F",size:8}],[Kh,{name:"RGB32F",size:16}],[ke,{name:"RGBA32F",size:16}],[Mt,{name:"R32F",size:4}],[nf,{name:"RG32F",size:8}],[lf,{name:"RGB9E5",size:4}],[cf,{name:"RG8S",size:2}],[hf,{name:"RGBA8S",size:4}],[ff,{name:"RGB10A2",size:4}],[uf,{name:"RGB10A2U",size:4,isUint:!0}],[Ys,{name:"DEPTH",size:4}],[Xr,{name:"DEPTH16",size:2}],[fr,{name:"DEPTHSTENCIL",size:4}],[Gi,{name:"111110F",size:4}],[yo,{name:"SRGB8",size:4,ldr:!0,srgb:!0}],[st,{name:"SRGBA8",size:4,ldr:!0,srgb:!0}],[tc,{name:"BGRA8",size:4,ldr:!0}],[ic,{name:"SBGRA8",size:4,ldr:!0,srgb:!0}],[To,{name:"DXT1",blockSize:8,ldr:!0,srgbFormat:kh}],[Ql,{name:"DXT3",blockSize:16,ldr:!0,srgbFormat:zh}],[Gr,{name:"DXT5",blockSize:16,ldr:!0,srgbFormat:Gh}],[Eo,{name:"ETC1",blockSize:8,ldr:!0}],[Jl,{name:"ETC2_RGB",blockSize:8,ldr:!0,srgbFormat:Vh}],[ec,{name:"ETC2_RGBA",blockSize:16,ldr:!0,srgbFormat:Hh}],[Vr,{name:"PVRTC_2BPP_RGB_1",ldr:!0,blockSize:8}],[Hr,{name:"PVRTC_2BPP_RGBA_1",ldr:!0,blockSize:8}],[Ao,{name:"PVRTC_4BPP_RGB_1",ldr:!0,blockSize:8}],[Co,{name:"PVRTC_4BPP_RGBA_1",ldr:!0,blockSize:8}],[_d,{name:"ASTC_4x4",blockSize:16,ldr:!0,srgbFormat:Wh}],[gd,{name:"ATC_RGB",blockSize:8,ldr:!0}],[Sd,{name:"ATC_RGBA",blockSize:16,ldr:!0}],[Td,{name:"BC6H_RGBF",blockSize:16}],[yd,{name:"BC6H_RGBUF",blockSize:16}],[Ed,{name:"BC7_RGBA",blockSize:16,ldr:!0,srgbFormat:Xh}],[kh,{name:"DXT1_SRGB",blockSize:8,ldr:!0,srgb:!0}],[zh,{name:"DXT3_SRGBA",blockSize:16,ldr:!0,srgb:!0}],[Gh,{name:"DXT5_SRGBA",blockSize:16,ldr:!0,srgb:!0}],[Vh,{name:"ETC2_SRGB",blockSize:8,ldr:!0,srgb:!0}],[Hh,{name:"ETC2_SRGBA",blockSize:16,ldr:!0,srgb:!0}],[Wh,{name:"ASTC_4x4_SRGB",blockSize:16,ldr:!0,srgb:!0}],[Xh,{name:"BC7_SRGBA",blockSize:16,ldr:!0,srgb:!0}],[jh,{name:"R8I",size:1,isInt:!0}],[qh,{name:"R16I",size:2,isInt:!0}],[Zh,{name:"R32I",size:4,isInt:!0}],[Qh,{name:"RG8I",size:2,isInt:!0}],[Jh,{name:"RG16I",size:4,isInt:!0}],[tf,{name:"RG32I",size:8,isInt:!0}],[sf,{name:"RGBA8I",size:4,isInt:!0}],[rf,{name:"RGBA16I",size:8,isInt:!0}],[af,{name:"RGBA32I",size:16,isInt:!0}],[sc,{name:"R8U",size:1,isUint:!0}],[$h,{name:"R16U",size:2,isUint:!0}],[zt,{name:"R32U",size:4,isUint:!0}],[xd,{name:"RG8U",size:2,isUint:!0}],[ef,{name:"RG16U",size:4,isUint:!0}],[Tn,{name:"RG32U",size:8,isUint:!0}],[vd,{name:"RGBA8U",size:4,isUint:!0}],[Rs,{name:"RGBA16U",size:8,isUint:!0}],[At,{name:"RGBA32U",size:16,isUint:!0}]]),En=c=>xs.get(c)?.blockSize!==void 0,df=c=>xs.get(c)?.srgb===!0,ur=c=>{let t=xs.get(c);return t?.isInt===!0||t?.isUint===!0},Y4={sampler:"sampler2D",returnType:"vec4"},K4={sampler:"usampler2D",returnType:"uvec4"},j4={sampler:"isampler2D",returnType:"ivec4"},q4={textureType:"texture_2d",returnType:"vec4f"},$4={textureType:"texture_2d",returnType:"vec4u"},Z4={textureType:"texture_2d",returnType:"vec4i"},An=c=>{let t=xs.get(c);return t?.isUint?K4:t?.isInt?j4:Y4},Ad=c=>{let t=xs.get(c);return t?.isUint?$4:t?.isInt?Z4:q4},Cn=c=>xs.get(c)?.srgbFormat||c,YC=c=>{for(let[t,e]of xs)if(e.srgbFormat===c)return t;return c},KC=c=>{let t=xs.get(c);return!!(t?.ldr&&!t?.srgb)},pf=c=>{switch(c){case Mt:case nf:case Kh:case ke:return Float32Array;case Zh:case tf:case af:return Int32Array;case zt:case Tn:case At:case lf:case ff:case uf:return Uint32Array;case qh:case Jh:case rf:return Int16Array;case $h:case ef:case Rs:case ya:case xn:case Ea:case yn:case of:case vn:case Me:return Uint16Array;case jh:case Qh:case sf:case cf:case hf:return Int8Array;default:return Uint8Array}},Aa=0,Pn=1,Eg=2,mf=3,Yt=4,Ks=5,dr=6,ee="POSITION",Ot="NORMAL",vs="TANGENT",bs="BLENDWEIGHT",$t="BLENDINDICES",Ct="COLOR",Ux="TEXCOORD",_t="TEXCOORD0",ri="TEXCOORD1",Ca="TEXCOORD2",Pa="TEXCOORD3",wa="TEXCOORD4",Ia="TEXCOORD5",Ra="TEXCOORD6",ba="TEXCOORD7",Ag="ATTR0",_f="ATTR1",Cd="ATTR2",Pd="ATTR3",wd="ATTR4",vD="ATTR5",TD="ATTR6",yD="ATTR7",rc="ATTR8",ac="ATTR9",ED="ATTR10",Id="ATTR11",Rd="ATTR12",AD="ATTR13",bd="ATTR14",Da="ATTR15",Cg=1,wn=0,Q4=1,jC=2,qC=3,J4=4,$C=5,e5=6,t5=7,Pg=0,ZC=1,kx=2,Gt="default",_i="rgbm",oc="rgbe",In="rgbp",Rn="swizzleGGGR",s5=0,i5=1,r5=2,a5=3,zx="1d",Ds="2d",Yr="2d-array",Kr="cube",Dd="cube-array",bn="3d",rs=0,Vi=1,gi=2,Hi=3,Wi=4,QC="none",Ld="cube",Gx="equirect",JC="octahedral",fe="glsl",se="wgsl",js=0,ai=1,qs=2,Ri=3,He=4,kt=5,ye=6,nc=7,wo=0,bi=1,Te=2,pr=3,Kt=4,oi=5,jr=6,Di=7,qr=8,Dn=9,Ln=10,Mn=11,lc=12,La=13,as=14,eP=15,tP=16,On=17,sP=18,iP=19,rP=20,Fn=21,Nn=22,gf=23,wg=24,aP=25,pe=26,Ma=27,Oa=28,Li=29,Fa=30,Bn=31,Un=32,Na=33,kn=34,zn=35,Ba=36,Gn=37,Vn=38,cc=39,Sf=40,xf=41,oP=42,nP=43,lP=44,cP=45,hP=46,fP=47,uP=48,dP=49,Vx=["bool","int","float","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","mat2","mat3","mat4","sampler2D","samplerCube","","sampler2DShadow","samplerCubeShadow","sampler3D","","","","","sampler2DArray","uint","uvec2","uvec3","uvec4","","","","","","","","","","","","","isampler2D","usampler2D","isamplerCube","usamplerCube","isampler3D","usampler3D","isampler2DArray","usampler2DArray"],Hx=[["bool"],["i32"],["f32"],["vec2f","vec2"],["vec3f","vec3"],["vec4f","vec4"],["vec2i","vec2"],["vec3i","vec3"],["vec4i","vec4"],["vec2"],["vec3"],["vec4"],["mat2x2f","mat2x2"],["mat3x3f","mat3x3"],["mat4x4f","mat4x4"],["texture_2d"],["texture_cube"],["array"],["texture_depth_2d"],["texture_depth_cube"],["texture_3d"],["array>"],["array>"],["array>"],["array>"],["texture_2d_array"],["u32"],["vec2u","vec2"],["vec3u","vec3"],["vec4u","vec4"],["array"],["array"],["array"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["texture_2d"],["texture_2d"],["texture_cube"],["texture_cube"],["texture_3d"],["texture_3d"],["texture_2d_array"],["texture_2d_array"]],Wx=new Map;Hx.forEach((c,t)=>{c.forEach(e=>Wx.set(e,t))});var o5=new Uint8Array([He,He,ye,ye,ye,ye,He,He,He,He,He,He,ye,ye,ye,He,He,ye,He,He,He,ye,ye,ye,ye,He,kt,kt,kt,kt,He,kt,He,He,kt,He,He,kt,He,He,kt,He,He,kt,He,kt,He,kt,He,kt]),vf="webgl2",Ig="webgpu",Xx="webgpu:bare",Tf="null",Xi=1,Yi=2,X=4,pP="ldr",Md="ldr_srgb",mP="hdr",Od=1,Rg=2,bg=4,Dg=8,Lg=16,Mg=32,Og=64,Fg=128,_P=255,Io=0,Ua=1,$r=2,Ng=["view","mesh","mesh_ub"],Hn="default",yf="_unused_float_uniform",Ro=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Uint16Array],Wn=[1,1,2,2,4,4,4,2],n5=["INT8","UINT8","INT16","UINT16","INT32","UINT32","FLOAT32","FLOAT16"],l5={Int8Array:js,Uint8Array:ai,Int16Array:qs,Uint16Array:Ri,Int32Array:He,Uint32Array:kt,Float32Array:ye},Ef=[Uint8Array,Uint16Array,Uint32Array],gP=[1,2,4],Bg=new Map([["float","f32"],["vec2","vec2f"],["vec3","vec3f"],["vec4","vec4f"],["int","i32"],["ivec2","vec2i"],["ivec3","vec3i"],["ivec4","vec4i"],["uint","u32"],["uvec2","vec2u"],["uvec3","vec3u"],["uvec4","vec4u"]]),ze={};ze[ee]=0;ze[Ot]=1;ze[bs]=2;ze[$t]=3;ze[Ct]=4;ze[_t]=5;ze[ri]=6;ze[Ca]=7;ze[Pa]=8;ze[wa]=9;ze[Ia]=10;ze[Ra]=11;ze[ba]=12;ze[vs]=13;ze[Ag]=0;ze[_f]=1;ze[Cd]=2;ze[Pd]=3;ze[wd]=4;ze[vD]=5;ze[TD]=6;ze[yD]=7;ze[rc]=8;ze[ac]=9;ze[ED]=10;ze[Id]=11;ze[Rd]=12;ze[AD]=13;ze[bd]=14;ze[Da]=15;var Yx=c=>{typeof window>"u"||window.isSecureContext};var c5=0,Fd=class{constructor(t,e){n(this,"slot",-1);n(this,"scopeId",null);this.name=t,this.visibility=e}},Qe=class extends Fd{},K=class extends Fd{constructor(e,s,i=!1){super(e,s);n(this,"format","");this.readOnly=i}},Ki=class extends Fd{constructor(t,e,s=Ds,i=rs,r=!0,a=null){super(t,e),this.textureDimension=s,this.sampleType=i,this.hasSampler=r,this.samplerName=a??`${t}_sampler`}},Xn=class extends Fd{constructor(t,e=ce,s=Ds,i=!0,r=!1){super(t,X),this.format=e,this.textureDimension=s,this.write=i,this.read=r}},Ue=class{constructor(t,e){n(this,"uniformBufferFormats",[]);n(this,"textureFormats",[]);n(this,"storageTextureFormats",[]);n(this,"storageBufferFormats",[]);this.id=c5++;let s=0;e.forEach(r=>{r.slot=s++,r instanceof Ki&&r.hasSampler&&s++,r instanceof Qe?this.uniformBufferFormats.push(r):r instanceof Ki?this.textureFormats.push(r):r instanceof Xn?this.storageTextureFormats.push(r):r instanceof K&&this.storageBufferFormats.push(r)}),this.device=t;let i=t.scope;this.bufferFormatsMap=new Map,this.uniformBufferFormats.forEach((r,a)=>this.bufferFormatsMap.set(r.name,a)),this.textureFormatsMap=new Map,this.textureFormats.forEach((r,a)=>{this.textureFormatsMap.set(r.name,a),r.scopeId=i.resolve(r.name)}),this.storageTextureFormatsMap=new Map,this.storageTextureFormats.forEach((r,a)=>{this.storageTextureFormatsMap.set(r.name,a),r.scopeId=i.resolve(r.name)}),this.storageBufferFormatsMap=new Map,this.storageBufferFormats.forEach((r,a)=>{this.storageBufferFormatsMap.set(r.name,a),r.scopeId=i.resolve(r.name)}),this.impl=t.createBindGroupFormatImpl(this)}destroy(){this.impl.destroy()}getTexture(t){let e=this.textureFormatsMap.get(t);return e!==void 0?this.textureFormats[e]:null}getStorageTexture(t){let e=this.storageTextureFormatsMap.get(t);return e!==void 0?this.storageTextureFormats[e]:null}loseContext(){}};var et=class{constructor(){n(this,"_cache",new Map)}get(t,e){return this._cache.has(t)||(this._cache.set(t,e()),t.on("destroy",()=>{this.remove(t)}),t.on("devicelost",()=>{this._cache.get(t)?.loseContext?.(t)})),this._cache.get(t)}remove(t){this._cache.get(t)?.destroy?.(t),this._cache.delete(t)}};var gt=class c{static calcLevelDimension(t,e){return Math.max(t>>e,1)}static calcMipLevelsCount(t,e,s=1){return 1+Math.floor(Math.log2(Math.max(t,e,s)))}static calcLevelGpuSize(t,e,s,i){let r=xs.get(i),a=xs.get(i)?.size??0;if(a>0)return t*e*s*a;let o=r.blockSize??0,l=Math.floor((t+3)/4),h=Math.floor((e+3)/4),f=Math.floor((s+3)/4);return(i===Vr||i===Hr)&&(l=Math.max(Math.floor(l/2),1)),l*h*f*o}static calcGpuSize(t,e,s,i,r,a){let o=0;for(;o+=c.calcLevelGpuSize(t,e,s,i),!(!r||t===1&&e===1&&s===1);)t=Math.max(t>>1,1),e=Math.max(e>>1,1),s=Math.max(s>>1,1);return o*(a?6:1)}static calcTextureSize(t,e,s=1){let i=Math.ceil(Math.sqrt(t));return s>1&&(i=R.roundUp(i,s)),e.set(i,Math.ceil(t/i))}};var Si=class{constructor(){n(this,"map",new Map);n(this,"id",0)}get(t){let e=this.map.get(t);return e===void 0&&(e=this.id++,this.map.set(t,e)),e}};var h5=new Si,Zr=class{constructor(t,e=0,s=1,i=0,r=1){n(this,"texture");n(this,"baseMipLevel");n(this,"mipLevelCount");n(this,"baseArrayLayer");n(this,"arrayLayerCount");n(this,"key");this.texture=t,this.baseMipLevel=e,this.mipLevelCount=s,this.baseArrayLayer=i,this.arrayLayerCount=r,this.key=h5.get(`${e}:${s}:${i}:${r}`)}};var f5=0,Z=class c{constructor(t,e={}){n(this,"name");n(this,"_gpuSize",0);n(this,"releaseSourceAfterUpload",!1);n(this,"id",f5++);n(this,"_invalid",!1);n(this,"_lockedLevel",-1);n(this,"_lockedMode",Pg);n(this,"renderVersionDirty",0);n(this,"_storage",!1);n(this,"_numLevels",0);n(this,"_numLevelsRequested");this.device=t,this.name=e.name??"",this._width=Math.floor(e.width??4),this._height=Math.floor(e.height??4),this._format=e.format??ce,this._compressed=En(this._format),this._integerFormat=ur(this._format),this._integerFormat&&(e.minFilter=0,e.magFilter=0),this._volume=e.volume??!1,this._depth=Math.floor(e.depth??1),this._arrayLength=Math.floor(e.arrayLength??0),this._storage=e.storage??!1,this._cubemap=e.cubemap??!1,this._flipY=e.flipY??!1,this._premultiplyAlpha=e.premultiplyAlpha??!1,this._mipmaps=e.mipmaps??!0,this._numLevelsRequested=e.numLevels,e.numLevels!==void 0&&(this._numLevels=e.numLevels),this._updateNumLevels(),this._minFilter=e.minFilter??5,this._magFilter=e.magFilter??1,this._anisotropy=e.anisotropy??1,this._addressU=e.addressU??0,this._addressV=e.addressV??0,this._addressW=e.addressW??0,this._compareOnRead=e.compareOnRead??!1,this._compareFunc=e.compareFunc??1,this._type=e.type??Gt,this.projection=QC,this._cubemap?this.projection=Ld:e.projection&&e.projection!==Ld&&(this.projection=e.projection),this._levels=e.levels;let s=!!e.levels;this._levels||this._clearLevels(),this.recreateImpl(s)}static createDataTexture2D(t,e,s,i,r,a){return new c(t,{name:e,width:s,height:i,format:r,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1,levels:a})}destroy(){let t=this.device;t&&(t.onTextureDestroyed(this),this.impl.destroy(t),this.adjustVramSizeTracking(t._vram,-this._gpuSize),this.releaseSourceAfterUpload&&this.releaseImageSources(),this._levels=null,this.device=null)}releaseImageSources(){if(this.releaseSourceAfterUpload=!1,!(typeof ImageBitmap>"u"||!this._levels))for(let t=0;tt,this._numLevels=Math.min(e??t,t),this._mipmaps=this._numLevels>1}get lockedMode(){return this._lockedMode}set minFilter(t){this._minFilter!==t&&(ur(this._format)||(this._minFilter=t,this.propertyChanged(Od)))}get minFilter(){return this._minFilter}set magFilter(t){this._magFilter!==t&&(ur(this._format)||(this._magFilter=t,this.propertyChanged(Rg)))}get magFilter(){return this._magFilter}set addressU(t){this._addressU!==t&&(this._addressU=t,this.propertyChanged(bg))}get addressU(){return this._addressU}set addressV(t){this._addressV!==t&&(this._addressV=t,this.propertyChanged(Dg))}get addressV(){return this._addressV}set addressW(t){this._volume&&t!==this._addressW&&(this._addressW=t,this.propertyChanged(Lg))}get addressW(){return this._addressW}set compareOnRead(t){this._compareOnRead!==t&&(this._compareOnRead=t,this.propertyChanged(Mg))}get compareOnRead(){return this._compareOnRead}set compareFunc(t){this._compareFunc!==t&&(this._compareFunc=t,this.propertyChanged(Og))}get compareFunc(){return this._compareFunc}set anisotropy(t){this._anisotropy!==t&&(this._anisotropy=t,this.propertyChanged(Fg))}get anisotropy(){return this._anisotropy}set mipmaps(t){if(this._mipmaps!==t&&!this.device.isWebGPU){if(!ur(this._format)){let e=this._mipmaps,s=this._numLevels;this._mipmaps=t,this._updateNumLevels(),this.array&&this._numLevels!==s?this.recreateImpl():this._mipmaps!==e&&(this.propertyChanged(Od),this._mipmaps?(this._needsMipmapsUpload=!0,this.device?.texturesToUpload?.add(this)):this._needsMipmapsUpload=!1)}}}get mipmaps(){return this._mipmaps}get numLevels(){return this._numLevels}get storage(){return this._storage}get width(){return this._width}get height(){return this._height}get depth(){return this._depth}get format(){return this._format}get cubemap(){return this._cubemap}get gpuSize(){let t=this.pot&&this._mipmaps&&!(this._compressed&&this._levels.length===1);return gt.calcGpuSize(this._width,this._height,this._depth,this._format,t,this._cubemap)}get array(){return this._arrayLength>0}get arrayLength(){return this._arrayLength}get volume(){return this._volume}set type(t){this._type!==t&&(this._type=t,this.device._shadersDirty=!0)}get type(){return this._type}set srgb(t){let e=df(this.format);if(t!==e)if(t){let s=Cn(this.format);this._format!==s&&(this._format=s,this.recreateImpl(),this.device._shadersDirty=!0)}else{let s=YC(this.format);this._format!==s&&(this._format=s,this.recreateImpl(),this.device._shadersDirty=!0)}}get srgb(){return df(this.format)}set flipY(t){this._flipY!==t&&(this._flipY=t,this.markForUpload())}get flipY(){return this._flipY}set premultiplyAlpha(t){this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this.markForUpload())}get premultiplyAlpha(){return this._premultiplyAlpha}get pot(){return R.powerOfTwo(this._width)&&R.powerOfTwo(this._height)}get encoding(){switch(this.type){case _i:return"rgbm";case oc:return"rgbe";case In:return"rgbp"}return KC(this.format)?"srgb":"linear"}dirtyAll(){this._levelsUpdated=this._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0],this.markForUpload(),this._needsMipmapsUpload=this._mipmaps,this._mipmapsUploaded=!1,this.propertyChanged(_P)}lock(t={}){t.level??(t.level=0),t.face??(t.face=0),t.mode??(t.mode=kx),this._lockedMode=t.mode,this._lockedLevel=t.level;let e=this.cubemap?this._levels[t.face]:this._levels;if(!e[t.level]){let s=Math.max(1,this._width>>t.level),i=Math.max(1,this._height>>t.level),r=Math.max(1,this._depth>>t.level),a=new ArrayBuffer(gt.calcLevelGpuSize(s,i,r,this._format));e[t.level]=new(pf(this._format))(a)}return e[t.level]}setSource(t,e=0){if(this.device._isHTMLElementInterface(t)&&(!this.device.supportsHtmlTextures||this._cubemap||this._volume))return;let s=!1,i,r;if(this._cubemap){if(t[0]){i=t[0].width||0,r=t[0].height||0;for(let a=0;a<6;a++){let o=t[a];if(!o||o.width!==i||o.height!==r||!this.device._isBrowserInterface(o)){s=!0;break}}}else s=!0;if(!s)for(let a=0;a<6;a++)this._levels[e][a]!==t[a]&&(this._levelsUpdated[e][a]=!0)}else if(this.device._isBrowserInterface(t)||(s=!0),!s)if(t!==this._levels[e]&&(this._levelsUpdated[e]=!0),t instanceof HTMLVideoElement)i=t.videoWidth,r=t.videoHeight;else if(this.device._isHTMLElementInterface(t)){let a=t.getBoundingClientRect();i=Math.floor(a.width)||1,r=Math.floor(a.height)||1}else i=t.width,r=t.height;if(s)if(this._width=4,this._height=4,this._cubemap)for(let a=0;a<6;a++)this._levels[e][a]=null,this._levelsUpdated[e][a]=!0;else this._levels[e]=null,this._levelsUpdated[e]=!0;else e===0&&(this._width=i,this._height=r),this._levels[e]=t;(this._invalid!==s||!s)&&(this._invalid=s,this.upload())}getSource(t=0){return this._levels[t]}unlock(){this._lockedMode,Pg,this._lockedMode===kx&&this.upload(),this._lockedLevel=-1,this._lockedMode=Pg}markForUpload(){this._needsUpload=!0,this.device?.texturesToUpload?.add(this)}upload(){this.markForUpload(),this._needsMipmapsUpload=this._mipmaps,this.impl.uploadImmediate?.(this.device,this)}read(t,e,s,i,r={}){return this.impl.read?.(t,e,s,i,r)}write(t,e,s,i,r){return this.impl.write?.(t,e,s,i,r)}getView(t=0,e=1,s=0,i=1){return new Zr(this,t,e,s,i)}};var u5={white:[255,255,255,255],gray:[128,128,128,255],black:[0,0,0,255],normal:[128,128,255,255],pink:[255,128,255,255]},SP=class{constructor(){n(this,"map",new Map)}destroy(){this.map.forEach(t=>{t.destroy()})}},d5=new et,bo=(c,t)=>{let e=d5.get(c,()=>new SP);if(!e.map.has(t)){let s=new Z(c,{name:`built-in-texture-${t}`,width:1,height:1,format:ce}),i=s.lock(),r=u5[t];i.set(r),s.unlock(),e.map.set(t,s)}return e.map.get(t)};var p5=0,hc=class{constructor(){n(this,"bindGroup");n(this,"offsets",[])}},ji=class{constructor(t,e,s){n(this,"renderVersionUpdated",-1);n(this,"uniformBuffers");n(this,"uniformBufferOffsets",[]);this.id=p5++,this.device=t,this.format=e,this.dirty=!0,this.impl=t.createBindGroupImpl(this),this.textures=[],this.storageTextures=[],this.storageBuffers=[],this.uniformBuffers=[],this.defaultUniformBuffer=s,s&&this.setUniformBuffer(Hn,s)}destroy(){this.impl.destroy(),this.impl=null,this.format=null,this.defaultUniformBuffer=null}setUniformBuffer(t,e){let s=this.format.bufferFormatsMap.get(t);this.uniformBuffers[s]!==e&&(this.uniformBuffers[s]=e,this.dirty=!0)}setStorageBuffer(t,e){let s=this.format.storageBufferFormatsMap.get(t);this.storageBuffers[s]!==e&&(this.storageBuffers[s]=e,this.dirty=!0)}setTexture(t,e){let s=this.format.textureFormatsMap.get(t),i=e instanceof Zr?e.texture:e;this.textures[s]!==e?(this.textures[s]=e,this.dirty=!0):this.renderVersionUpdated>t&e},all(c,t,e=1){let s=e<e)if(ArrayBuffer.isView(t))t=t.subarray(0,e),s.set(t);else for(let i=0;i>>0}var v5=new Si,T5=[2,4,8,12,16],y5=new et,Ft=class c{constructor(t,e,s){this.device=t,this._elements=[],this.hasUv0=!1,this.hasUv1=!1,this.hasColor=!1,this.hasTangents=!1,this.verticesByteSize=0,this.vertexCount=s,this.interleaved=s===void 0,this.instancing=!1,this.size=e.reduce((a,o)=>a+Math.ceil(o.components*Wn[o.type]/4)*4,0);let i=0,r;for(let a=0,o=e.length;anew c(t,[{semantic:Id,components:4,type:ye},{semantic:Rd,components:4,type:ye},{semantic:bd,components:4,type:ye},{semantic:Da,components:4,type:ye}]))}static isElementValid(t,e){let s=e.components*Wn[e.type];return!(t.isWebGPU&&!T5.includes(s))}update(){this._evaluateHash()}_evaluateHash(){let t=[],e=[],s=this._elements.length;for(let r=0;re.clear()),this.mapsToClear.clear()}computeDispatch(e,s="Unnamed"){}getRenderableHdrFormat(e=[Gi,Me,ke],s=!0,i=1){for(let r=0;r1)continue;if(this.textureFloatRenderable&&(!s||this.textureFloatFilterable))return a;break}}}validateAttributes(e,s,i){}};n($x,"EVENT_RESIZE","resizecanvas");var tt=$x;var C5=0,me=class{constructor(t={}){n(this,"name");n(this,"_device");n(this,"_colorBuffer");n(this,"_colorBuffers");n(this,"_depthBuffer");n(this,"_depth");n(this,"_stencil");n(this,"_samples");n(this,"autoResolve");n(this,"_face");n(this,"_mipLevel");n(this,"_mipmaps");n(this,"_width");n(this,"_height");n(this,"flipY");this.id=C5++;let e=t.colorBuffer?.device??t.colorBuffers?.[0].device??t.depthBuffer?.device??t.graphicsDevice;this._device=e;let{maxSamples:s}=this._device;if(this._samples=Math.min(t.samples??1,s),e.isWebGPU&&(this._samples=this._samples>1?s:1),this._colorBuffer=t.colorBuffer,t.colorBuffer&&(this._colorBuffers=[t.colorBuffer]),this._depthBuffer=t.depthBuffer,this._face=t.face??0,this._depthBuffer){let i=this._depthBuffer._format;i===Ys||i===Xr?(this._depth=!0,this._stencil=!1):i===fr?(this._depth=!0,this._stencil=!0):i===Mt&&this._depthBuffer.device.isWebGPU&&this._samples>1?(this._depth=!0,this._stencil=!1):(this._depth=!1,this._stencil=!1)}else this._depth=t.depth??!0,this._stencil=t.stencil??!1;t.colorBuffers&&(this._colorBuffers||(this._colorBuffers=[...t.colorBuffers],this._colorBuffer=t.colorBuffers[0])),this.autoResolve=t.autoResolve??!0,this.name=t.name,this.name||(this.name=this._colorBuffer?.name),this.name||(this.name=this._depthBuffer?.name),this.name||(this.name="Untitled"),this.flipY=t.flipY??!1,this._mipLevel=t.mipLevel??0,this._mipLevel>0&&this._depth&&(this._mipLevel=0),this._mipmaps=t.mipLevel===void 0,this.evaluateDimensions(),this.validateMrt(),this.impl=e.createRenderTargetImpl(this)}destroy(){let t=this._device;t&&(t.targets.delete(this),t.renderTarget===this&&t.setRenderTarget(null),this.destroyFrameBuffers())}destroyFrameBuffers(){let t=this._device;t&&this.impl.destroy(t)}destroyTextureBuffers(){this._depthBuffer?.destroy(),this._depthBuffer=null,this._colorBuffers?.forEach(t=>{t.destroy()}),this._colorBuffers=null,this._colorBuffer=null}resize(t,e){if(!(this.mipLevel>0)&&(this._depthBuffer?.resize(t,e),this._colorBuffers?.forEach(s=>{s.resize(t,e)}),this._width!==t||this._height!==e)){this.destroyFrameBuffers();let s=this._device;s.renderTarget===this&&s.setRenderTarget(null),this.evaluateDimensions(),this.validateMrt(),this.impl=s.createRenderTargetImpl(this)}}validateMrt(){}evaluateDimensions(){let t=this._colorBuffer??this._depthBuffer;t&&(this._width=t.width,this._height=t.height,this._mipLevel>0&&(this._width=gt.calcLevelDimension(this._width,this._mipLevel),this._height=gt.calcLevelDimension(this._height,this._mipLevel)))}init(){this.impl.init(this._device,this)}get initialized(){return this.impl.initialized}get device(){return this._device}loseContext(){this.impl.loseContext()}resolve(t=!0,e=!!this._depthBuffer){this._device&&this._samples>1&&this.impl.resolve(this._device,this,t,e)}copy(t,e,s){if(!this._device)if(t._device)this._device=t._device;else return!1;return this._device.copyRenderTarget(t,this,e,s)}get samples(){return this._samples}get depth(){return this._depth}get stencil(){return this._stencil}get colorBuffer(){return this._colorBuffer}getColorBuffer(t){return this._colorBuffers?.[t]}get depthBuffer(){return this._depthBuffer}get face(){return this._face}get mipLevel(){return this._mipLevel}get mipmaps(){return this._mipmaps}get width(){return this._width??this._device.width}get height(){return this._height??this._device.height}isColorBufferSrgb(t=0){if(this.device.backBuffer===this)return df(this.device.backBufferFormat);let e=this.getColorBuffer(t);return e?df(e.format):!1}};var Zx=class{constructor(){n(this,"bindGroup")}update(t){this.destroy();let e=t.device,s=this.createDescriptor(e,t);this.bindGroup=e.wgpu.createBindGroup(s)}destroy(){this.bindGroup=null}createDescriptor(t,e){let s=[],i=e.format,r=e.format.uniformBufferFormats;e.uniformBuffers.forEach((f,u)=>{let d=r[u].slot,p=f.persistent?f.impl.buffer:f.allocation.gpuBuffer.buffer;s.push({binding:d,resource:{buffer:p,offset:0,size:f.format.byteSize}})});let a=e.format.textureFormats;e.textures.forEach((f,u)=>{let d=f instanceof Zr,m=(d?f.texture:f).impl,_=i.textureFormats[u],S=a[u].slot,g=m.getView(t,d?f:void 0);if(s.push({binding:S,resource:g}),_.hasSampler){let T=m.getSampler(t,_.sampleType);s.push({binding:S+1,resource:T})}});let o=e.format.storageTextureFormats;e.storageTextures.forEach((f,u)=>{let d=f instanceof Zr,m=(d?f.texture:f).impl,_=o[u].slot,S=m.getView(t,d?f:void 0);s.push({binding:_,resource:S})});let l=e.format.storageBufferFormats;return e.storageBuffers.forEach((f,u)=>{let d=f.impl.buffer,p=l[u].slot;s.push({binding:p,resource:{buffer:d}})}),{layout:e.format.impl.bindGroupLayout,entries:s}}};var kd=class{static shaderStage(t){let e=0;return t&Xi&&(e|=GPUShaderStage.VERTEX),t&Yi&&(e|=GPUShaderStage.FRAGMENT),t&X&&(e|=GPUShaderStage.COMPUTE),e}};var he=[];he[pd]="";he[md]="";he[vo]="";he[Wr]="r8unorm";he[Po]="rg8unorm";he[ya]="";he[xn]="";he[Ea]="";he[Ss]="rgba8unorm";he[ce]="rgba8unorm";he[To]="bc1-rgba-unorm";he[Ql]="bc2-rgba-unorm";he[Gr]="bc3-rgba-unorm";he[vn]="";he[Me]="rgba16float";he[yn]="r16float";he[of]="rg16float";he[Kh]="";he[ke]="rgba32float";he[Mt]="r32float";he[nf]="rg32float";he[Ys]="depth32float";he[Xr]="depth16unorm";he[fr]="depth24plus-stencil8";he[Gi]="rg11b10ufloat";he[yo]="";he[st]="rgba8unorm-srgb";he[Eo]="";he[Jl]="etc2-rgb8unorm";he[ec]="etc2-rgba8unorm";he[Vr]="";he[Hr]="";he[Ao]="";he[Co]="";he[_d]="astc-4x4-unorm";he[gd]="";he[Sd]="";he[tc]="bgra8unorm";he[ic]="bgra8unorm-srgb";he[jh]="r8sint";he[sc]="r8uint";he[qh]="r16sint";he[$h]="r16uint";he[Zh]="r32sint";he[zt]="r32uint";he[Qh]="rg8sint";he[xd]="rg8uint";he[Jh]="rg16sint";he[ef]="rg16uint";he[tf]="rg32sint";he[Tn]="rg32uint";he[sf]="rgba8sint";he[vd]="rgba8uint";he[rf]="rgba16sint";he[Rs]="rgba16uint";he[af]="rgba32sint";he[At]="rgba32uint";he[Td]="bc6h-rgb-float";he[yd]="bc6h-rgb-ufloat";he[Ed]="bc7-rgba-unorm";he[lf]="rgb9e5ufloat";he[cf]="rg8snorm";he[hf]="rgba8snorm";he[ff]="rgb10a2unorm";he[uf]="rgb10a2uint";he[kh]="bc1-rgba-unorm-srgb";he[zh]="bc2-rgba-unorm-srgb";he[Gh]="bc3-rgba-unorm-srgb";he[Vh]="etc2-rgb8unorm-srgb";he[Hh]="etc2-rgba8unorm-srgb";he[Xh]="bc7-rgba-unorm-srgb";he[Wh]="astc-4x4-unorm-srgb";var zd=[];zd[rs]="filtering";zd[Vi]="non-filtering";zd[gi]="comparison";zd[Hi]="comparison";zd[Wi]="comparison";var Gd=[];Gd[rs]="float";Gd[Vi]="unfilterable-float";Gd[gi]="depth";Gd[Hi]="sint";Gd[Wi]="uint";var P5=new Si,Qx=class{constructor(t){let e=t.device,{key:s,desc:i}=this.createDescriptor(t);this.key=P5.get(s),this.bindGroupLayout=e.wgpu.createBindGroupLayout(i)}destroy(){this.bindGroupLayout=null}loseContext(){}createDescriptor(t){let e=[],s="";return t.uniformBufferFormats.forEach(r=>{let a=kd.shaderStage(r.visibility);s+=`#${r.slot}U:${a}`,e.push({binding:r.slot,visibility:a,buffer:{type:"uniform",hasDynamicOffset:!0}})}),t.textureFormats.forEach(r=>{let a=kd.shaderStage(r.visibility),o=r.sampleType,l=r.textureDimension,h=!1,f=Gd[o];if(s+=`#${r.slot}T:${a}-${f}-${l}-${h}`,e.push({binding:r.slot,visibility:a,texture:{sampleType:f,viewDimension:l,multisampled:h}}),r.hasSampler){let u=zd[o];s+=`#${r.slot+1}S:${a}-${u}`,e.push({binding:r.slot+1,visibility:a,sampler:{type:u}})}}),t.storageTextureFormats.forEach(r=>{let{format:a,textureDimension:o}=r,{read:l,write:h}=r;s+=`#${r.slot}ST:${a}-${o}-${l?"r1":"r0"}-${h?"w1":"w0"}`,e.push({binding:r.slot,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:l?h?"read-write":"read-only":"write-only",format:he[a],viewDimension:o}})}),t.storageBufferFormats.forEach(r=>{let a=r.readOnly,o=kd.shaderStage(r.visibility);s+=`#${r.slot}SB:${o}-${a?"ro":"rw"}`,e.push({binding:r.slot,visibility:o,buffer:{type:a?"read-only-storage":"storage"}})}),{key:s,desc:{entries:e}}}};var Lo=class{constructor(t=0){n(this,"buffer",null);n(this,"usageFlags",0);this.usageFlags=t}destroy(t){this.buffer&&(t.deferDestroy(this.buffer),this.buffer=null)}get initialized(){return!!this.buffer}loseContext(){this.buffer=null}allocate(t,e){this.buffer=t.wgpu.createBuffer({size:e,usage:this.usageFlags})}unlock(t,e){let s=t.wgpu;if(!this.buffer){let o=e.byteLength+3&-4;this.usageFlags|=GPUBufferUsage.COPY_DST,this.allocate(t,o)}let i=e.byteOffset??0,r=new Uint8Array(e.buffer??e,i,e.byteLength),a=new Uint8Array(this.buffer.size);a.set(r),s.queue.writeBuffer(this.buffer,0,a,0,a.length)}read(t,e,s,i,r){return t.readStorageBuffer(this,e,s,i,r)}write(t,e,s,i,r){t.writeStorageBuffer(this,e,s,i,r)}clear(t,e,s){t.clearStorageBuffer(this,e,s)}};var Jx=class extends Lo{constructor(e,s){super(16|(s?.storage?128:0));n(this,"format",null);this.format=e.format===1?"uint16":"uint32"}unlock(e){let s=e.device;super.unlock(s,e.storage)}};var ev={equals(c,t){if(c.length!==t.length)return!1;for(let e=0;e{let a=r.interleaved,o=r.instancing?"instance":"vertex",l=[],h=r.elements.length;for(let f=0;f1?`x${u.numComponents}`:""}`}),(!a||f===h-1)&&(s.push({attributes:l,arrayStride:u.stride,stepMode:o}),l=[])}};return t&&i(t),e&&i(e),s}};var w5=0,Vd=class{constructor(t){this.device=t}getPipelineLayout(t){let e=[];t.forEach(r=>{e.push(r.bindGroupLayout)});let s={bindGroupLayouts:e};return w5++,this.device.wgpu.createPipelineLayout(s)}};var I5=0,R5=["point-list","line-list",void 0,"line-strip","triangle-list","triangle-strip",void 0],kD=["add","subtract","reverse-subtract","min","max"],sv=["zero","one","src","one-minus-src","dst","one-minus-dst","src-alpha","src-alpha-saturated","one-minus-src-alpha","dst-alpha","one-minus-dst-alpha","constant","one-minus-constant"],vP=["never","less","equal","less-equal","greater","not-equal","greater-equal","always"],b5=["none","back","front"],D5=["ccw","cw"],Hd=["keep","zero","replace","increment-clamp","increment-wrap","decrement-clamp","decrement-wrap","invert"],L5=["","uint16","uint32"],TP=class{constructor(){n(this,"pipeline");n(this,"hashes")}},iv=class extends Vd{constructor(e){super(e);n(this,"lookupHashes",new Uint32Array(15));this.vertexBufferLayout=new tv,this.cache=new Map}get(e,s,i,r,a,o,l,h,f,u,d,p,m,_){let S=e.type;r&&S!==mf&&S!==Ks&&(r=void 0);let g=this.lookupHashes;g[0]=S,g[1]=a.id,g[2]=u,g[3]=f.key,g[4]=h.key,g[5]=s?.renderingHash??0,g[6]=i?.renderingHash??0,g[7]=o.impl.key,g[8]=l[0]?.key??0,g[9]=l[1]?.key??0,g[10]=l[2]?.key??0,g[11]=d?p.key:0,g[12]=d?m.key:0,g[13]=r??0,g[14]=_;let T=dc(g),C=this.cache.get(T);if(C)for(let A=0;A0){let v=0;o.redWrite&&(v|=GPUColorWrite.RED),o.greenWrite&&(v|=GPUColorWrite.GREEN),o.blueWrite&&(v|=GPUColorWrite.BLUE),o.alphaWrite&&(v|=GPUColorWrite.ALPHA);let E=this.getBlend(o);T.forEach(y=>{g.fragment.targets.push({format:y.format,writeMask:v,blend:E})})}return I5++,_.createRenderPipeline(g)}};var M5=0,yP=class{constructor(){n(this,"pipeline",null);n(this,"hashes",null)}},rv=class extends Vd{constructor(){super(...arguments);n(this,"lookupHashes",new Uint32Array(2));n(this,"cache",new Map)}get(e,s){let i=this.lookupHashes;i[0]=e.impl.computeKey,i[1]=s.impl.key;let r=dc(i),a=this.cache.get(r);if(a)for(let h=0;h{t.object?.destroy()}),this.cache.clear()}clear(){this.cache.clear()}get(t){let e=this.cache.get(t);return e?(e.incRefCount(),e.object):null}set(t,e){this.cache.set(t,new EP(e))}release(t){let e=this.cache.get(t);e&&(e.decRefCount(),e.refCount===0&&(this.cache.delete(t),e.object?.destroy()))}};var AP=class extends av{loseContext(t){this.clear()}},O5=new et,Af=c=>O5.get(c,()=>new AP);var F5=new Si,CP=class{constructor(){n(this,"format");n(this,"multisampledBuffer")}destroy(t){t.deferDestroy(this.multisampledBuffer),this.multisampledBuffer=null}},ov=class{constructor(t){n(this,"format");n(this,"hasStencil");n(this,"depthTexture",null);n(this,"depthTextureInternal",!1);n(this,"multisampledDepthBuffer",null);n(this,"multisampledDepthBufferKey");this.format=t,this.hasStencil=t==="depth24plus-stencil8"}destroy(t){this.depthTextureInternal&&(t.deferDestroy(this.depthTexture),this.depthTexture=null),this.multisampledDepthBuffer&&(this.multisampledDepthBuffer=null,Af(t).release(this.multisampledDepthBufferKey))}},nv=class{constructor(t){n(this,"initialized",!1);n(this,"key");n(this,"colorAttachments",[]);n(this,"depthAttachment",null);n(this,"assignedColorTexture",null);n(this,"renderPassDescriptor",{});n(this,"isBackbuffer",!1);this.renderTarget=t}destroy(t){this.initialized=!1,this.assignedColorTexture=null,this.colorAttachments.forEach(e=>{e.destroy(t)}),this.colorAttachments.length=0,this.depthAttachment?.destroy(t),this.depthAttachment=null}updateKey(){let e=`${this.renderTarget.samples}:${this.depthAttachment?this.depthAttachment.format:"nodepth"}`;this.colorAttachments.forEach(s=>{e+=`:${s.format}`}),this.key=F5.get(e)}assignColorTexture(t,e){this.assignedColorTexture=t;let s=this.renderTarget.device,i=s?.xrColorTextureViewDescriptor,r=i&&t===s.xrColorTexture,a=t.createView(r?i:{format:e}),o=this.renderPassDescriptor.colorAttachments[0];this.renderTarget.samples>1?o.resolveTarget=a:o.view=a,this.setColorAttachment(0,void 0,e),this.updateKey()}setColorAttachment(t,e,s){this.colorAttachments[t]||(this.colorAttachments[t]=new CP),e&&(this.colorAttachments[t].multisampledBuffer=e),s&&(this.colorAttachments[t].format=s)}init(t,e){let s=t.wgpu;this.initDepthStencil(t,s,e),e._colorBuffers&&e._colorBuffers.forEach((r,a)=>{this.setColorAttachment(a,void 0,r.impl.format)}),this.renderPassDescriptor.colorAttachments=[];let i=this.isBackbuffer?1:e._colorBuffers?.length??0;for(let r=0;r1){let f="depth24plus-stencil8";this.depthAttachment.format=f,this.depthAttachment.hasStencil=f==="depth24plus-stencil8";let u=`${l.id}:${r}:${a}:${i}:${f}`,d=Af(t),p=d.get(u);if(!p){let m={size:[r,a,1],dimension:"2d",sampleCount:i,format:f,usage:GPUTextureUsage.RENDER_ATTACHMENT|(f!==l.impl.format?GPUTextureUsage.TEXTURE_BINDING:0)};p=e.createTexture(m),d.set(u,p)}this.depthAttachment.multisampledDepthBuffer=p,this.depthAttachment.multisampledDepthBufferKey=u,h=p.createView()}else{let f=l.impl.gpuTexture;this.depthAttachment.depthTexture=f,h=f.createView()}else{this.depthAttachment=new ov("depth24plus-stencil8");let f={size:[r,a,1],dimension:"2d",sampleCount:i,format:this.depthAttachment.format,usage:GPUTextureUsage.RENDER_ATTACHMENT};i>1?f.usage|=GPUTextureUsage.TEXTURE_BINDING:f.usage|=GPUTextureUsage.COPY_SRC;let u=e.createTexture(f);this.depthAttachment.depthTexture=u,this.depthAttachment.depthTextureInternal=!0,h=u.createView()}this.renderPassDescriptor.depthStencilAttachment={view:h}}}initColor(t,e,s,i){let r={},{samples:a,width:o,height:l,mipLevel:h}=s,f=s.getColorBuffer(i),u=null;if(f&&(f.cubemap?u=f.impl.createView({dimension:"2d",baseArrayLayer:s.face,arrayLayerCount:1,mipLevelCount:1,baseMipLevel:h}):u=f.impl.createView({mipLevelCount:1,baseMipLevel:h})),a>1){let d=this.isBackbuffer?this.colorAttachments[i]?.format??t.backBufferViewFormat:f.impl.format,p={size:[o,l,1],dimension:"2d",sampleCount:a,format:d,usage:GPUTextureUsage.RENDER_ATTACHMENT},m=e.createTexture(p);this.setColorAttachment(i,m,p.format),r.view=m.createView(),r.resolveTarget=u}else r.view=u;return r}setupForRenderPass(t,e){let s=this.renderPassDescriptor.colorAttachments?.length??0;for(let r=0;r0)switch(e){case Te:this.updateType=On;break;case bi:this.updateType=Fa;break;case pe:this.updateType=Bn;break;case wo:this.updateType=Un;break;case pr:this.updateType=Fn;break;case jr:this.updateType=Na;break;case Ma:this.updateType=kn;break;case Dn:this.updateType=zn;break;case Kt:this.updateType=Nn;break;case Di:this.updateType=Ba;break;case Oa:this.updateType=Gn;break;case Ln:this.updateType=Vn;break;case oi:this.updateType=gf;break;case qr:this.updateType=cc;break;case Li:this.updateType=Sf;break;case Mn:this.updateType=xf;break;case as:this.updateType=wg;break;default:break}this.count=s;let i=this.numComponents;s&&(i=R.roundUp(i,4)),this.byteSize=i*4,s&&(this.byteSize*=s)}get isArrayType(){return this.count>0}calculateOffset(t){let e=this.byteSize<=8?this.byteSize:16;this.count&&(e=16),t=R.roundUp(t,e),this.offset=t/4}},Xe=class{constructor(t,e){n(this,"byteSize",0);n(this,"map",new Map);this.scope=t.scope,this.uniforms=e;let s=0;for(let i=0;inew IP(v,s)),_=c.processUniforms(t,m,e.processingOptions,s),S=`${l} +${h} +${_.code}`,g=r.src.replace(wP,S),T=`${f} +${u} +${_.code}`,C=a.src.replace(wP,T);return{vshader:g,fshader:C,attributes:o,meshUniformBufferFormat:_.meshUniformBufferFormat,meshBindGroupFormat:_.meshBindGroupFormat}}static extract(t){let e=[],s=[],i=[],r=[],a=`${wP} +`,o;for(;(o=zD.exec(t))!==null;){let l=o[1];switch(l){case"attribute":case"varying":case"uniform":case"out":{PP.lastIndex=o.index;let h=PP.exec(t);l==="attribute"?e.push(h[2]):l==="varying"?s.push(h[2]):l==="out"?i.push(h[2]):l==="uniform"&&r.push(h[2]),t=c.cutOut(t,o.index,PP.lastIndex,a),zD.lastIndex=o.index+a.length,a="";break}}}return{src:t,attributes:e,varyings:s,outs:i,uniforms:r}}static processUniforms(t,e,s,i){let r=[],a=[];e.forEach(d=>{d.isSampler?r.push(d):a.push(d)});let o=[];a.forEach(d=>{if(!s.hasUniform(d.name)){let p=Vx.indexOf(d.type),m=new Y(d.name,p,d.arraySize);o.push(m)}}),o.length===0&&o.push(new Y(yf,Te));let l=o.length?new Xe(t,o):null,h=[];r.forEach(d=>{if(!s.hasTexture(d.name)){let p=rs;d.isSignedInt?p=Hi:d.isUnsignedInt?p=Wi:(d.precision==="highp"&&(p=Vi),U5.has(d.type)&&(p=gi));let m=k5[d.type];h.push(new Ki(d.name,Xi|Yi,m,p))}});let f=new Ue(t,h),u="";return s.uniformFormats.forEach((d,p)=>{d&&(u+=c.getUniformShaderDeclaration(d,p,0))}),l&&(u+=c.getUniformShaderDeclaration(l,$r,0)),s.bindGroupFormats.forEach((d,p)=>{d&&(u+=c.getTexturesShaderDeclaration(d,p))}),u+=c.getTexturesShaderDeclaration(f,Ua),{code:u,meshUniformBufferFormat:l,meshBindGroupFormat:f}}static processVaryings(t,e,s){let i="",r=s?"out":"in";return t.forEach((a,o)=>{let l=c.splitToWords(a),h=l.slice(0,-1).join(" "),f=l[l.length-1];s?e.set(f,o):o=e.get(f),i+=`layout(location = ${o}) ${r} ${h} ${f}; +`}),i}static processOuts(t){let e="";return t.forEach((s,i)=>{e+=`layout(location = ${i}) out ${s}; +`}),e}static getTypeCount(t){let e=t.substring(t.length-1),s=parseInt(e,10);return isNaN(s)?1:s}static processAttributes(t,e,s,i){let r="",a={};return t.forEach(o=>{let l=c.splitToWords(o),h=l[0],f=l[1];if(e.hasOwnProperty(f)){let u=e[f],d=ze[u];a[d]=u,s.set(d,f);let p,m=i.getVertexElement(u);if(m){let _=m.dataType;if(_!==ye&&_!==nc&&!m.normalize&&!m.asInt){let S=c.getTypeCount(h),g=`_private_${f}`;p=`vec${S} ${f} = vec${S}(${g}); +`,f=g;let T=_===js||_===qs||_===He;S===1?h=T?"int":"uint":h=T?`ivec${S}`:`uvec${S}`}}r+=`layout(location = ${d}) in ${h} ${f}; +`,p&&(r+=p)}}),r}static splitToWords(t){return t=t.replace(/\s+/g," ").trim(),t.split(" ")}static cutOut(t,e,s,i){return t.substring(0,e)+i+t.substring(s)}static getUniformShaderDeclaration(t,e,s){let i=Ng[e],r=`layout(set = ${e}, binding = ${s}, std140) uniform ub_${i} { +`;return t.uniforms.forEach(a=>{let o=Vx[a.type];r+=` ${o} ${a.shortName}${a.count?`[${a.count}]`:""}; +`}),`${r}}; +`}static getTexturesShaderDeclaration(t,e){let s="";return t.textureFormats.forEach(i=>{let r=z5[i.textureDimension],a=r==="texture2DArray",o=i.sampleType===Wi?"u":i.sampleType===Hi?"i":"";r=`${o}${r}`;let l="",h="";a&&(l="_texture",h=`#define ${i.name} ${o}sampler2DArray(${i.name}${l}, ${i.name}_sampler) +`),s+=`layout(set = ${e}, binding = ${i.slot}) uniform ${r} ${i.name}${l}; +`,i.hasSampler&&(s+=`layout(set = ${e}, binding = ${i.slot+1}) uniform sampler ${i.name}_sampler; +`),s+=h}),s}};var GD=/^[ \t]*(attribute|varying|uniform)[\t ]+/gm,RP=/^[ \t]*(attribute|varying|uniform)[ \t]*([^;]+)(;+)/gm,bP=/^[ \t]*var\s*(?:(]*>)\s*([\w\d_]+)\s*:\s*(.*?)\s*;|(<(?!storage,)[^>]*>)?\s*([\w\d_]+)\s*:\s*(texture_.*|storage_texture_.*|storage\w.*|external_texture|sampler(?:_comparison)?)\s*;)\s*$/gm,G5=/(?:@interpolate\([^)]*\)\s*)?([\w]+)\s*:\s*([\w<>]+)/,DP="@@@",LP=/(@vertex|@fragment)\s*fn\s+\w+\s*\(\s*(\w+)\s*:[\s\S]*?\{/,VD=[{wgslName:"position",wgslType:"vec4f",wgslBuiltin:"position",pcName:"pcPosition",isFallback:!0},{wgslName:"frontFacing",wgslType:"bool",wgslBuiltin:"front_facing",pcName:"pcFrontFacing"},{wgslName:"sampleIndex",wgslType:"u32",wgslBuiltin:"sample_index",pcName:"pcSampleIndex"},{wgslName:"primitiveIndex",wgslType:"u32",wgslBuiltin:"primitive_index",pcName:"pcPrimitiveIndex",requiresFeature:"supportsPrimitiveIndex"}],HD=[{wgslName:"vertexIndex",wgslType:"u32",wgslBuiltin:"vertex_index",pcName:"pcVertexIndex",isFallback:!0},{wgslName:"instanceIndex",wgslType:"u32",wgslBuiltin:"instance_index",pcName:"pcInstanceIndex"}],WD=(c,t,e,s)=>c.filter(i=>i.requiresFeature&&!s[i.requiresFeature]?!1:new RegExp(`\\b(?:${i.pcName}|${e}\\.${i.wgslName})\\b`).test(t)),XD=(c,t,e,s)=>{if(c.length===0&&!s){let i=t.find(r=>r.isFallback&&(!r.requiresFeature||e[r.requiresFeature]));if(i)return[i]}return c},YD=c=>c.map(t=>` @builtin(${t.wgslBuiltin}) ${t.wgslName} : ${t.wgslType}, +`).join(""),KD=c=>c.map(t=>` var ${t.pcName}: ${t.wgslType}; +`).join(""),jD=c=>c.map(t=>` ${t.pcName} = input.${t.wgslName}; +`).join(""),V5={texture_1d:{viewDimension:zx,baseSampleType:rs},texture_2d:{viewDimension:Ds,baseSampleType:rs},texture_2d_array:{viewDimension:Yr,baseSampleType:rs},texture_3d:{viewDimension:bn,baseSampleType:rs},texture_cube:{viewDimension:Kr,baseSampleType:rs},texture_cube_array:{viewDimension:Dd,baseSampleType:rs},texture_multisampled_2d:{viewDimension:Ds,baseSampleType:rs},texture_depth_2d:{viewDimension:Ds,baseSampleType:gi},texture_depth_2d_array:{viewDimension:Yr,baseSampleType:gi},texture_depth_cube:{viewDimension:Kr,baseSampleType:gi},texture_depth_cube_array:{viewDimension:Dd,baseSampleType:gi},texture_external:{viewDimension:Ds,baseSampleType:Vi}},H5=(c,t)=>{let e=V5[c],s=e.baseSampleType;if(e.baseSampleType===rs&&c!=="texture_multisampled_2d")switch(t){case"u32":s=Wi;break;case"i32":s=Hi;break;case"f32":s=rs;break;case"uff":s=Vi;break}return{viewDimension:e.viewDimension,sampleType:s}},W5=(c,t)=>{if(t===gi)switch(c){case Ds:return"texture_depth_2d";case Yr:return"texture_depth_2d_array";case Kr:return"texture_depth_cube";case Dd:return"texture_depth_cube_array";default:}let e;switch(c){case zx:e="texture_1d";break;case Ds:e="texture_2d";break;case Yr:e="texture_2d_array";break;case bn:e="texture_3d";break;case Kr:e="texture_cube";break;case Dd:e="texture_cube_array";break;default:}let s;switch(t){case rs:case Vi:s="f32";break;case Wi:s="u32";break;case Hi:s="i32";break;default:}return`${e}<${s}>`},qD={f32:"WrappedF32",i32:"WrappedI32",u32:"WrappedU32",vec2f:"WrappedVec2F",vec2i:"WrappedVec2I",vec2u:"WrappedVec2U"},$D=c=>(c=c.replace(/\s+/g," ").trim(),c.split(/[\s:]+/)),X5=/array<([^,]+),\s*([^>]+)>/,MP=class{constructor(t,e){n(this,"ubName",null);n(this,"arraySize",0);this.line=t;let s=$D(t);if(s.length<2){e.failed=!0;return}if(this.name=s[0],this.type=s.slice(1).join(" "),this.type.includes("array<")){let i=X5.exec(this.type);this.type=i[1].trim(),this.arraySize=Number(i[2]),isNaN(this.arraySize)&&(e.failed=!0)}}},Y5=/^\s*var\s+(\w+)\s*:\s*(texture_\w+)(?:<(\w+)>)?;\s*$/,K5=/^\s*var\s+([\w\d_]+)\s*:\s*(texture_storage_2d|texture_storage_2d_array)<([\w\d_]+),\s*(\w+)>\s*;\s*$/,j5=/^\s*var\s*\s*([\w\d_]+)\s*:\s*(.*)\s*;\s*$/,q5=/^\s*var\s+([\w\d_]+)\s*:\s*texture_external;\s*$/,$5=/^\s*var\s+([\w\d_]+)\s*:\s*(sampler|sampler_comparison)\s*;\s*$/,cv=class{constructor(t,e){this.originalLine=t,this.line=t,this.isTexture=!1,this.isSampler=!1,this.isStorageTexture=!1,this.isStorageBuffer=!1,this.isExternalTexture=!1,this.type="",this.matchedElements=[];let s=this.line.match(Y5);if(s){this.name=s[1],this.type=s[2],this.textureFormat=s[3],this.isTexture=!0,this.matchedElements.push(...s);let l=H5(this.type,this.textureFormat);this.textureDimension=l.viewDimension,this.sampleType=l.sampleType}let i=this.line.match(K5);i&&(this.isStorageTexture=!0,this.name=i[1],this.textureType=i[2],this.format=i[3],this.access=i[4],this.matchedElements.push(...i));let r=this.line.match(j5);r&&(this.isStorageBuffer=!0,this.accessMode=r[1]||"none",this.name=r[2],this.type=r[3],this.matchedElements.push(...r));let a=this.line.match(q5);a&&(this.name=a[1],this.isExternalTexture=!0,this.matchedElements.push(...r));let o=this.line.match($5);o&&(this.name=o[1],this.samplerType=o[2],this.isSampler=!0,this.matchedElements.push(...o)),this.matchedElements.length===0&&(e.failed=!0)}equals(t){return!(this.name!==t.name||this.type!==t.type||this.isTexture!==t.isTexture||this.isSampler!==t.isSampler||this.isStorageTexture!==t.isStorageTexture||this.isStorageBuffer!==t.isStorageBuffer||this.isExternalTexture!==t.isExternalTexture||this.textureFormat!==t.textureFormat||this.textureDimension!==t.textureDimension||this.sampleType!==t.sampleType||this.textureType!==t.textureType||this.format!==t.format||this.access!==t.access||this.accessMode!==t.accessMode||this.samplerType!==t.samplerType)}},hv=class c{static run(t,e,s){let i=new Map,r=c.extract(e.vshader),a=c.extract(e.fshader),o=r.src.match(LP)?.[2]??"",l=a.src.match(LP)?.[2]??"",h=new Map,f=c.processAttributes(r.attributes,e.attributes,h,e.processingOptions,s,t,r.src,o),u=c.processVaryings(r.varyings,i,!0,t),d=c.processVaryings(a.varyings,i,!1,t,a.src,l),p=r.uniforms.concat(a.uniforms),_=Array.from(new Set(p)).map(A=>new MP(A,s)),S=c.processUniforms(t,_,e.processingOptions,s);r.src=c.renameUniformAccess(r.src,_),a.src=c.renameUniformAccess(a.src,_);let g=c.mergeResources(r.resources,a.resources,s),T=c.processResources(t,g,e.processingOptions,s),C=c.generateFragmentOutputStruct(a.src,t.maxColorAttachments);r.src=c.copyInputs(r.src,s),a.src=c.copyInputs(a.src,s);let v=`${f} +${u} +${S.code} +${T.code} +`,E=r.src.replace(DP,v),y=`${d} +${C} +${S.code} +${T.code} +`,P=a.src.replace(DP,y);return{vshader:E,fshader:P,attributes:h,meshUniformBufferFormat:S.meshUniformBufferFormat,meshBindGroupFormat:T.meshBindGroupFormat}}static extract(t){let e=[],s=[],i=[],r=[],a=`${DP} +`,o;for(;(o=GD.exec(t))!==null;){let l=o[1];RP.lastIndex=o.index;let h=RP.exec(t);l==="attribute"?e.push(h[2]):l==="varying"?s.push(h[2]):l==="uniform"&&i.push(h[2]),t=c.cutOut(t,o.index,RP.lastIndex,a),GD.lastIndex=o.index+a.length,a=""}for(;(o=bP.exec(t))!==null;)r.push(o[0]),t=c.cutOut(t,o.index,bP.lastIndex,a),bP.lastIndex=o.index+a.length,a="";return{src:t,attributes:e,varyings:s,uniforms:i,resources:r}}static processUniforms(t,e,s,i){let r=[];e.forEach(l=>{if(s.hasUniform(l.name))l.ubName="ub_view";else{l.ubName="ub_mesh_ub";let h=Wx.get(l.type),f=new Y(l.name,h,l.arraySize);r.push(f)}}),r.length===0&&r.push(new Y(yf,Te));let a=new Xe(t,r),o="";return s.uniformFormats.forEach((l,h)=>{l&&(o+=c.getUniformShaderDeclaration(l,h,0))}),a&&(o+=c.getUniformShaderDeclaration(a,$r,0)),{code:o,meshUniformBufferFormat:a}}static renameUniformAccess(t,e){return e.forEach(s=>{let i=`uniform.${s.name}`,r=`${s.ubName}.${s.name}`,a=new RegExp(`\\b${i}\\b`,"g");t=t.replace(a,r)}),t}static mergeResources(t,e,s){let i=t.map(a=>new cv(a,s));return e.map(a=>new cv(a,s)).forEach(a=>{let o=i.find(l=>l.name===a.name);o?o.equals(a)||(s.failed=!0):i.push(a)}),i}static processResources(t,e,s,i){let r=[];for(let l=0;l{l&&(o+=c.getTextureShaderDeclaration(l,h))}),o+=c.getTextureShaderDeclaration(a,Ua),{code:o,meshBindGroupFormat:a}}static getUniformShaderDeclaration(t,e,s){let i=Ng[e],r=`struct_ub_${i}`,a=`struct ${r} { +`;return t.uniforms.forEach(o=>{let l=Hx[o.type][0];o.count>0?(qD.hasOwnProperty(l)&&(l=qD[l]),a+=` ${o.shortName}: array<${l}, ${o.count}>, +`):a+=` ${o.shortName}: ${l}, +`}),a+=`}; +`,a+=`@group(${e}) @binding(${s}) var ub_${i} : ${r}; -`}static getTextureShaderDeclaration(e,t){let i="";return e.textureFormats.forEach(e=>{let s=((e,t)=>{let i,s;if(2===t)switch(e){case "2d":return "texture_depth_2d";case tM:return "texture_depth_2d_array";case tO:return "texture_depth_cube";case tF:return "texture_depth_cube_array"}switch(e){case "1d":i="texture_1d";break;case "2d":i="texture_2d";break;case tM:i="texture_2d_array";break;case "3d":i="texture_3d";break;case tO:i="texture_cube";break;case tF:i="texture_cube_array";}switch(t){case 0:case 1:s="f32";break;case 4:s="u32";break;case 3:s="i32";}return `${i}<${s}>`})(e.textureDimension,e.sampleType);if(i+=`@group(${t}) @binding(${e.slot}) var ${e.name}: ${s}; -`,e.hasSampler){let s=2===e.sampleType?"sampler_comparison":"sampler";i+=`@group(${t}) @binding(${e.slot+1}) var ${e.samplerName}: ${s}; -`;}}),e.storageBufferFormats.forEach(e=>{let s=e.readOnly?"read":"read_write";i+=`@group(${t}) @binding(${e.slot}) var ${e.name} : ${e.format}; -`;}),i}static processVaryings(e,t,i,s){let r="",a="",n="";e.forEach((e,s)=>{let o=e.match(sD);if(o){let l=o[1],h=o[2];i?t.set(l,s):s=t.get(l),r+=` @location(${s}) ${e}, -`,i||(a+=` var ${l}: ${h}; -`,n+=` ${l} = input.${l}; -`);}}),i?r+=" @builtin(position) position : vec4f,\n":(r+=" @builtin(position) position : vec4f,\n @builtin(front_facing) frontFacing : bool,\n @builtin(sample_index) sampleIndex : u32,\n",s.supportsPrimitiveIndex&&(r+=" @builtin(primitive_index) primitiveIndex : u32,\n"));let o=s.supportsPrimitiveIndex?` - var pcPrimitiveIndex: u32; - `:"",l=s.supportsPrimitiveIndex?` - pcPrimitiveIndex = input.primitiveIndex; - `:"",h=i?"":` - var pcPosition: vec4f; - var pcFrontFacing: bool; - var pcSampleIndex: u32; - ${o} - ${a} - - // function to copy inputs (varyings) to private global variables - fn _pcCopyInputs(input: FragmentInput) { - ${n} - pcPosition = input.position; - pcFrontFacing = input.frontFacing; - pcSampleIndex = input.sampleIndex; - ${l} - } - `;return ` - struct ${i?"VertexOutput":"FragmentInput"} { - ${r} - }; - ${h} - `}static generateFragmentOutputStruct(e,t){let i="struct FragmentOutput {\n",s=e=>`color${e>0?e:""}`;for(let r=0;r":"vec2f","vec3":"vec3f","vec4":"vec4f"})[e]||e]||null}static processAttributes(e,t={},i,s,r){let a="",n="",o="";return e.forEach(e=>{let r=sO(e),l=r[0],h=r[1],c=h;if(t.hasOwnProperty(l)){let r=t[l],d=t5[r];i.set(d,l);let u=s.getVertexElement(r);if(u){let e=u.dataType;6===e||7===e||u.normalize||u.asInt||(h=sH.floatAttributeToInt(h,0===e||2===e||4===e));}a+=` @location(${d}) ${l}: ${h}, -`,n+=` var ${e}; -`,o+=` ${l} = ${c}(input.${l}); -`;}}),` - struct VertexInput { - ${a} - @builtin(vertex_index) vertexIndex : u32, // built-in vertex index - @builtin(instance_index) instanceIndex : u32 // built-in instance index - }; +`,a}static getTextureShaderDeclaration(t,e){let s="";return t.textureFormats.forEach(i=>{let r=W5(i.textureDimension,i.sampleType);if(s+=`@group(${e}) @binding(${i.slot}) var ${i.name}: ${r}; +`,i.hasSampler){let a=i.sampleType===gi?"sampler_comparison":"sampler";s+=`@group(${e}) @binding(${i.slot+1}) var ${i.samplerName}: ${a}; +`}}),t.storageBufferFormats.forEach(i=>{let r=i.readOnly?"read":"read_write";s+=`@group(${e}) @binding(${i.slot}) var ${i.name} : ${i.format}; +`}),s}static processVaryings(t,e,s,i,r="",a=""){let o="",l="",h="";if(t.forEach((u,d)=>{let p=u.match(G5);if(p){let m=p[1],_=p[2];s?e.set(m,d):d=e.get(m),o+=` @location(${d}) ${u}, +`,s||(l+=` var ${m}: ${_}; +`,h+=` ${m} = input.${m}; +`)}}),s)return o+=` @builtin(position) position : vec4f, +`,` + struct VertexOutput { + ${o} + }; + `;let f=XD(WD(VD,r,a,i),VD,i,o.length>0);return o+=YD(f),` + struct FragmentInput { + ${o} + }; - ${n} - var pcVertexIndex: u32; - var pcInstanceIndex: u32; + ${KD(f)} + ${l} - fn _pcCopyInputs(input: VertexInput) { - ${o} - pcVertexIndex = input.vertexIndex; - pcInstanceIndex = input.instanceIndex; - } - `}static copyInputs(e,t){let i=e.match(sR);if(!i||!i[2])return e;let s=i[2],r=i.index+i[0].length-1;return e.slice(0,r+1)+` - _pcCopyInputs(${s});`+e.slice(r+1)}static cutOut(e,t,i,s){return e.substring(0,t)+s+e.substring(i)}}let sW=new ia;class sX{destroy(e){this._vertexCode=null,this._fragmentCode=null;}createShaderModule(e,t){return this.shader.device.wgpu.createShaderModule({code:e})}getVertexShaderModule(){return this.createShaderModule(this._vertexCode,"Vertex")}getFragmentShaderModule(){return this.createShaderModule(this._fragmentCode,"Fragment")}getComputeShaderModule(){return this.createShaderModule(this._computeCode,"Compute")}processGLSL(){let e=this.shader,t=sC.run(e.device,e.definition,e);this._vertexCode=this.transpile(t.vshader,"vertex",e.definition.vshader),this._fragmentCode=this.transpile(t.fshader,"fragment",e.definition.fshader),this._vertexCode&&this._fragmentCode?e.ready=true:e.failed=true,e.meshUniformBufferFormat=t.meshUniformBufferFormat,e.meshBindGroupFormat=t.meshBindGroupFormat,e.attributes=t.attributes;}processWGSL(){let e=this.shader,t=sH.run(e.device,e.definition,e);this._vertexCode=t.vshader,this._fragmentCode=t.fshader,e.meshUniformBufferFormat=t.meshUniformBufferFormat,e.meshBindGroupFormat=t.meshBindGroupFormat,e.attributes=t.attributes;}transpile(e,t,i){let s=this.shader.device;if(!s.glslang||!s.twgsl)return null;try{let i=s.glslang.compileGLSL(e,t);return s.twgsl.convertSpirV2WGSL(i)}catch(e){}}get vertexCode(){return this._vertexCode}get fragmentCode(){return this._fragmentCode}get computeKey(){if(void 0===this._computeKey){let e=`${this._computeCode}|${this.computeEntryPoint}`;this._computeKey=sW.get(e);}return this._computeKey}loseContext(){}restoreContext(e,t){}constructor(e){this._vertexCode=null,this._fragmentCode=null,this._computeCode=null,this.vertexEntryPoint="main",this.fragmentEntryPoint="main",this.computeEntryPoint="main",this.shader=e;let t=e.definition;t.shaderLanguage===tV?(t.cshader?(this._computeCode=t.cshader??null,this.computeUniformBufferFormats=t.computeUniformBufferFormats,this.computeBindGroupFormat=t.computeBindGroupFormat,t.computeEntryPoint&&(this.computeEntryPoint=t.computeEntryPoint)):(this.vertexEntryPoint="vertexMain",this.fragmentEntryPoint="fragmentMain",t.processingOptions?this.processWGSL():(this._vertexCode=t.vshader??null,this._fragmentCode=t.fshader??null,e.meshUniformBufferFormat=t.meshUniformBufferFormat,e.meshBindGroupFormat=t.meshBindGroupFormat)),e.ready=true):t.processingOptions&&this.processGLSL();}}let sY=[];sY[0]="repeat",sY[1]="clamp-to-edge",sY[2]="mirror-repeat";let sq=[];sq[0]={level:"nearest",mip:"nearest"},sq[1]={level:"linear",mip:"nearest"},sq[2]={level:"nearest",mip:"nearest"},sq[3]={level:"nearest",mip:"linear"},sq[4]={level:"linear",mip:"nearest"},sq[5]={level:"linear",mip:"linear"};class sj{create(e){let t,i=this.texture,s=e.wgpu,r=i.numLevels;eY(i.format)&&(i.width%4!=0||i.height%4!=0)&&(i._width=ei.roundUp(i.width,4),i._height=ei.roundUp(i.height,4)),this.desc={size:{width:i.width,height:i.height,depthOrArrayLayers:i.cubemap?6:i.array?i.arrayLength:1},format:this.format,mipLevelCount:r,sampleCount:1,dimension:i.volume?"3d":"2d",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC|(eY(i.format)?0:GPUTextureUsage.RENDER_ATTACHMENT)|(i.storage?GPUTextureUsage.STORAGE_BINDING:0)},this.gpuTexture=s.createTexture(this.desc),17===this.texture.format&&(t={format:"depth24plus",aspect:"depth-only"}),this.view=this.createView(t),this.viewCache.clear();}destroy(e){e.deferDestroy(this.gpuTexture),this.gpuTexture=null,this.view=null,this.viewCache.clear(),this.samplers.length=0;}propertyChanged(e){this.samplers.length=0;}getView(e,t){if(this.uploadImmediate(e,this.texture),t){let e=this.viewCache.get(t.key);return e||(e=this.createView({baseMipLevel:t.baseMipLevel,mipLevelCount:t.mipLevelCount,baseArrayLayer:t.baseArrayLayer,arrayLayerCount:t.arrayLayerCount}),this.viewCache.set(t.key,e)),e}return this.view}createView(e){let t=e??{},i=this.desc,s=this.texture,r={format:t.format??i.format,dimension:t.dimension??(s.cubemap?"cube":s.volume?"3d":s.array?"2d-array":"2d"),aspect:t.aspect??"all",baseMipLevel:t.baseMipLevel??0,mipLevelCount:t.mipLevelCount??i.mipLevelCount,baseArrayLayer:t.baseArrayLayer??0,arrayLayerCount:t.arrayLayerCount??i.depthOrArrayLayers};return this.gpuTexture.createView(r)}getSampler(e,t){let i=this.samplers[t];if(!i){let s=this.texture,r={addressModeU:sY[s.addressU],addressModeV:sY[s.addressV],addressModeW:sY[s.addressW]};!t&&s.compareOnRead&&(t=2),2===t||3===t||4===t?(r.compare="less",r.magFilter="linear",r.minFilter="linear"):1===t||!e.textureFloatFilterable&&(14===s.format||12===s.format)||17===this.texture.format||ej(this.texture.format)?(r.magFilter="nearest",r.minFilter="nearest",r.mipmapFilter="nearest"):(r.magFilter=sq[s.magFilter].level,r.minFilter=sq[s.minFilter].level,r.mipmapFilter=sq[s.minFilter].mip);let a="linear"===r.minFilter&&"linear"===r.magFilter&&"linear"===r.mipmapFilter;r.maxAnisotropy=a?ei.clamp(Math.round(s._anisotropy),1,e.maxTextureAnisotropy):1,i=e.wgpu.createSampler(r),this.samplers[t]=i;}return i}loseContext(){}uploadImmediate(e,t){(t._needsUpload||t._needsMipmapsUpload)&&(this.uploadData(e),t._needsUpload=false,t._needsMipmapsUpload=false);}uploadData(e){let t=this.texture;if(this.desc&&(this.desc.size.width!==t.width||this.desc.size.height!==t.height)&&(this.gpuTexture.destroy(),this.create(e),t.renderVersionDirty=e.renderVersion),t._levels){let i=false,s=false,r=t.numLevels;for(let a=0;atypeof ImageBitmap&&e instanceof ImageBitmap||"u">typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"u">typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"u">typeof OffscreenCanvas&&e instanceof OffscreenCanvas}uploadExternalImage(e,t,i,s){let r={texture:this.gpuTexture,mipLevel:i,origin:[0,0,s],aspect:"all",premultipliedAlpha:this.texture._premultiplyAlpha},a={width:this.desc.size.width,height:this.desc.size.height,depthOrArrayLayers:1};e.submit(),t instanceof HTMLCanvasElement&&t.getContext("2d"),e.wgpu.queue.copyExternalImageToTexture({source:t,origin:[0,0],flipY:false},r,a);}uploadTypedArrayData(e,t,i,s){let r,a,n=this.texture,o=e.wgpu,l={texture:this.gpuTexture,origin:[0,0,s],mipLevel:i},h=ir.calcLevelDimension(n.width,i),c=ir.calcLevelDimension(n.height,i);ir.calcLevelGpuSize(h,c,1,n.format);let d=eX.get(n.format);if(d.size)r={offset:0,bytesPerRow:d.size*h,rowsPerImage:c},a={width:h,height:c};else if(d.blockSize){let e=e=>Math.floor((e+3)/4);r={offset:0,bytesPerRow:d.blockSize*e(h),rowsPerImage:e(c)},a={width:Math.max(4,h),height:Math.max(4,c)};}e.submit(),o.queue.writeTexture(l,t,r,a);}read(e,t,i,s,r){let a=r.mipLevel??0,n=r.face??0,o=r.data??null,l=r.immediate??false,h=this.texture,c=i*eX.get(h.format).size,d=ei.roundUp(c,256),u=d*s,f=h.device,p=f.createBufferImpl(9);p.allocate(f,u);let m={texture:this.gpuTexture,mipLevel:a,origin:[e,t,n]},_={buffer:p.buffer,offset:0,bytesPerRow:d};return f.getCommandEncoder().copyTextureToBuffer(m,_,{width:i,height:s,depthOrArrayLayers:1}),f.readBuffer(p,u,null,l).then(e=>{let t=e6(h.format),i=o?.buffer??new ArrayBuffer(s*c),r=new Uint8Array(i,o?.byteOffset??0,s*c);for(let t=0;t|>=)\s*([\w"']+)/i,s9=/[+\-]/g,s7=/include[ \t]+"([\w-]+)(?:\s*,\s*([\w-]+))?"/g,re=/\{i\}/g,rt=/(pcFragColor[1-8])\b/g,ri=/^\d+(?:\.\d+)?$/;class rs{static run(e,t=new Map,i={}){rs.sourceName=i.sourceName,e=(e=this.stripComments(e)).split(/\r?\n/).map(e=>e.trimEnd()).join("\n");let s=new Map,r=new Map;if(null===(e=this._preprocess(e,s,r,t,i.stripDefines)))return null;let a=new Map;return s.forEach((e,t)=>{Number.isInteger(parseFloat(e))&&!e.includes(".")&&a.set(t,e);}),e=this.stripComments(e),e=this.stripUnusedColorAttachments(e,i),e=this.RemoveEmptyLines(e),e=this.processArraySize(e,a),e=this.injectDefines(e,r)}static stripUnusedColorAttachments(e,t){if(t.stripUnusedColorAttachments){let t=new Map,i=e.match(rt);if(i?.forEach(e=>{let i=parseInt(e.charAt(e.length-1),10);t.set(i,(t.get(i)??0)+1);}),Array.from(t.values()).some(e=>1===e)){let i=e.split("\n"),s=[];for(let e=0;e0&&1===t.get(e))continue}s.push(i[e]);}e=s.join("\n");}}return e}static stripComments(e){return e.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm,"$1")}static processArraySize(e,t){return null!==e&&t.forEach((t,i)=>{e=e.replace(RegExp(`\\[${i}\\]`,"g"),`[${t}]`);}),e}static injectDefines(e,t){if(null!==e&&t.size>0){let i=e.split("\n");t.forEach((e,t)=>{let s=RegExp(t,"g");for(let t=0;t""===e.trim()?"":e).join("\n")).replace(/(\n\n){3,}/g,"\n\n")),e}static _preprocess(e,t=new Map,i,s,r){let a,n=[],o=false;for(;null!==(a=sZ.exec(e))&&!o;){let l=a[1];switch(l){case "define":{sQ.lastIndex=a.index;let s=sQ.exec(e);o||(o=null===s);let l=s[1];s3.lastIndex=s.index;let h=s3.exec(l)[0],c=l.substring(h.length).trim();""===c&&(c="true");let d=rs._keep(n),u=r;if(d){let r=h.startsWith("{")&&h.endsWith("}");r&&(u=true),r?i.set(h,c):t.set(h,c),u&&(e=e.substring(0,s.index-1)+e.substring(sQ.lastIndex),sZ.lastIndex=s.index-1);}u||(sZ.lastIndex=s.index+s[0].length);break}case "undef":{s0.lastIndex=a.index;let i=s0.exec(e),s=i[1].trim();rs._keep(n)&&(t.delete(s),r&&(e=e.substring(0,i.index-1)+e.substring(s0.lastIndex),sZ.lastIndex=i.index-1)),r||(sZ.lastIndex=i.index+i[0].length);break}case "extension":{sJ.lastIndex=a.index;let i=sJ.exec(e);if(o||(o=null===i),i){let e=i[1];rs._keep(n)&&t.set(e,"true");}sZ.lastIndex=i.index+i[0].length;break}case "ifdef":case "ifndef":case "if":{s1.lastIndex=a.index;let i=s1.exec(e),s=i[2],r=rs.evaluate(s,t);o||(o=r.error);let h=r.result;"ifndef"===l&&(h=!h),n.push({anyKeep:h,keep:h,start:a.index,end:s1.lastIndex}),sZ.lastIndex=i.index+i[0].length;break}case "endif":case "else":case "elif":{s2.lastIndex=a.index;let i=s2.exec(e),s=n.pop();if(!s){o=true;continue}let r=s.keep?e.substring(s.end,a.index):"";e=e.substring(0,s.start)+r+e.substring(s2.lastIndex),sZ.lastIndex=s.start+r.length;let l=i[1];if("else"===l||"elif"===l){let e=false;if(!s.anyKeep)if("else"===l)e=!s.keep;else {let s=rs.evaluate(i[2],t);e=s.result,o||(o=s.error);}n.push({anyKeep:s.anyKeep||e,keep:e,start:sZ.lastIndex,end:sZ.lastIndex});}break}case "include":{s7.lastIndex=a.index;let i=s7.exec(e);if(o||(o=null===i),!i){o=true;continue}let r=i[1].trim(),l=i[2]?.trim();if(rs._keep(n)){let a=s?.get(r);if(void 0!==a){if(a=this.stripComments(a),l){let e=parseFloat(t.get(l));if(Number.isInteger(e)){let t="";for(let i=0;i0&&(o=true),o)?null:e}static _keep(e){for(let t=0;t":n=e>s;break;case ">=":n=e>=s;break;default:i=true;}return {result:n,error:i}}return {result:t.has(e),error:i}}static processParentheses(e,t){let i=false,s=e.trim();for(;s.startsWith("(")&&s.endsWith(")");){let e=0,t=true;for(let i=0;ia&&(a=r,n=t),e=true);}else ")"===s[t]&&(l>0?l--:r>0&&(r===a&&-1!==n&&(o=t),r--));if(!e||-1===n||-1===o)break;let h=s.substring(n+1,o),{result:c,error:d}=rs.evaluate(h,t);i=i||d,s=s.substring(0,n)+(c?"true":"false")+s.substring(o+1);}return {expression:s,error:i}}static evaluate(e,t){let i=null===s9.exec(e),s=e,r=false;if(-1!==e.replace(s5,"").indexOf("(")){let i=rs.processParentheses(e,t);s=i.expression,r=i.error;}if(r)return {result:false,error:true};for(let e of s.split("||")){let s=e.split("&&"),r=true;for(let e of s){let{result:i,error:s}=rs.evaluateAtomicExpression(e.trim(),t);if(!i||s){r=false;break}}if(r)return {result:true,error:!i}}return {result:false,error:!i}}}var rr=` + // function to copy inputs (varyings) to private global variables + fn _pcCopyInputs(input: FragmentInput) { + ${h} + ${jD(f)} + } + `}static generateFragmentOutputStruct(t,e){let s=`struct FragmentOutput { +`,i=a=>`color${a>0?a:""}`;for(let a=0;a":"vec2f","vec3":"vec3f","vec4":"vec4f"}[t]||t;return{f32:e?"i32":"u32",vec2f:e?"vec2i":"vec2u",vec3f:e?"vec3i":"vec3u",vec4f:e?"vec4i":"vec4u"}[i]||null}static processAttributes(t,e={},s,i,r,a,o="",l=""){let h="",f="",u="",d={};t.forEach(m=>{let _=$D(m),S=_[0],g=_[1],T=g;if(e.hasOwnProperty(S)){let C=e[S],v=ze[C];d[v]=C,s.set(v,S);let E=i.getVertexElement(C);if(E){let y=E.dataType;if(y!==ye&&y!==nc&&!E.normalize&&!E.asInt){let P=y===js||y===qs||y===He;g=c.floatAttributeToInt(g,P)}}h+=` @location(${v}) ${S}: ${g}, +`,f+=` var ${m}; +`,u+=` ${S} = ${T}(input.${S}); +`}});let p=XD(WD(HD,o,l,a),HD,a,h.length>0);return` + struct VertexInput { + ${h} + ${YD(p)} + }; + + ${f} + ${KD(p)} + + fn _pcCopyInputs(input: VertexInput) { + ${u} + ${jD(p)} + } + `}static copyInputs(t,e){let s=t.match(LP);if(!s||!s[2])return t;let i=s[2],r=s.index+s[0].length-1,a=t.slice(0,r+1),o=t.slice(r+1),l=` + _pcCopyInputs(${i});`;return a+l+o}static cutOut(t,e,s,i){return t.substring(0,e)+i+t.substring(s)}};var Z5=new Si,fv=class{constructor(t){n(this,"_vertexCode",null);n(this,"_fragmentCode",null);n(this,"_computeCode",null);n(this,"_computeKey");n(this,"vertexEntryPoint","main");n(this,"fragmentEntryPoint","main");n(this,"computeEntryPoint","main");this.shader=t;let e=t.definition;e.shaderLanguage===se?(e.cshader?(this._computeCode=e.cshader??null,this.computeUniformBufferFormats=e.computeUniformBufferFormats,this.computeBindGroupFormat=e.computeBindGroupFormat,e.computeEntryPoint&&(this.computeEntryPoint=e.computeEntryPoint)):(this.vertexEntryPoint="vertexMain",this.fragmentEntryPoint="fragmentMain",e.processingOptions?this.processWGSL():(this._vertexCode=e.vshader??null,this._fragmentCode=e.fshader??null,t.meshUniformBufferFormat=e.meshUniformBufferFormat,t.meshBindGroupFormat=e.meshBindGroupFormat)),t.ready=!0):e.processingOptions&&this.processGLSL()}destroy(t){this._vertexCode=null,this._fragmentCode=null}createShaderModule(t,e){return this.shader.device.wgpu.createShaderModule({code:t})}getVertexShaderModule(){return this.createShaderModule(this._vertexCode,"Vertex")}getFragmentShaderModule(){return this.createShaderModule(this._fragmentCode,"Fragment")}getComputeShaderModule(){return this.createShaderModule(this._computeCode,"Compute")}processGLSL(){let t=this.shader,e=lv.run(t.device,t.definition,t);this._vertexCode=this.transpile(e.vshader,"vertex",t.definition.vshader),this._fragmentCode=this.transpile(e.fshader,"fragment",t.definition.fshader),this._vertexCode&&this._fragmentCode?t.ready=!0:t.failed=!0,t.meshUniformBufferFormat=e.meshUniformBufferFormat,t.meshBindGroupFormat=e.meshBindGroupFormat,t.attributes=e.attributes}processWGSL(){let t=this.shader,e=hv.run(t.device,t.definition,t);this._vertexCode=e.vshader,this._fragmentCode=e.fshader,t.meshUniformBufferFormat=e.meshUniformBufferFormat,t.meshBindGroupFormat=e.meshBindGroupFormat,t.attributes=e.attributes}transpile(t,e,s){let i=this.shader.device;if(!i.glslang||!i.twgsl)return null;try{let r=i.glslang.compileGLSL(t,e);return i.twgsl.convertSpirV2WGSL(r)}catch{}}get vertexCode(){return this._vertexCode}get fragmentCode(){return this._fragmentCode}get computeKey(){if(this._computeKey===void 0){let t=`${this._computeCode}|${this.computeEntryPoint}`;this._computeKey=Z5.get(t)}return this._computeKey}loseContext(){}restoreContext(t,e){}};var Wd=[];Wd[0]="repeat";Wd[1]="clamp-to-edge";Wd[2]="mirror-repeat";var jn=[];jn[0]={level:"nearest",mip:"nearest"};jn[1]={level:"linear",mip:"nearest"};jn[2]={level:"nearest",mip:"nearest"};jn[3]={level:"nearest",mip:"linear"};jn[4]={level:"linear",mip:"nearest"};jn[5]={level:"linear",mip:"linear"};var Q5=c=>{},uv=class{constructor(t){n(this,"gpuTexture");n(this,"view");n(this,"samplers",[]);n(this,"desc");n(this,"format");n(this,"viewCache",new Map);this.texture=t,this.format=he[t.format],this.create(t.device)}create(t){let e=this.texture,s=t.wgpu,i=e.numLevels;En(e.format)&&(e.width%4!==0||e.height%4!==0)&&(e._width=R.roundUp(e.width,4),e._height=R.roundUp(e.height,4)),this.desc={size:{width:e.width,height:e.height,depthOrArrayLayers:e.cubemap?6:e.array?e.arrayLength:1},format:this.format,mipLevelCount:i,sampleCount:1,dimension:e.volume?"3d":"2d",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC|(En(e.format)?0:GPUTextureUsage.RENDER_ATTACHMENT)|(e.storage?GPUTextureUsage.STORAGE_BINDING:0)},this.gpuTexture=s.createTexture(this.desc);let r;this.texture.format===fr&&(r={format:"depth24plus",aspect:"depth-only"}),this.view=this.createView(r),this.viewCache.clear()}destroy(t){t.deferDestroy(this.gpuTexture),this.gpuTexture=null,this.view=null,this.viewCache.clear(),this.samplers.length=0}propertyChanged(t){this.samplers.length=0}getView(t,e){if(this.uploadImmediate(t,this.texture),e){let s=this.viewCache.get(e.key);return s||(s=this.createView({baseMipLevel:e.baseMipLevel,mipLevelCount:e.mipLevelCount,baseArrayLayer:e.baseArrayLayer,arrayLayerCount:e.arrayLayerCount}),this.viewCache.set(e.key,s)),s}return this.view}createView(t){let e=t??{},s=this.desc,i=this.texture,r=()=>i.cubemap?"cube":i.volume?"3d":i.array?"2d-array":"2d",a={format:e.format??s.format,dimension:e.dimension??r(),aspect:e.aspect??"all",baseMipLevel:e.baseMipLevel??0,mipLevelCount:e.mipLevelCount??s.mipLevelCount,baseArrayLayer:e.baseArrayLayer??0,arrayLayerCount:e.arrayLayerCount??s.depthOrArrayLayers};return this.gpuTexture.createView(a)}getSampler(t,e){let s=this.samplers[e];if(!s){let i=this.texture,r,a={addressModeU:Wd[i.addressU],addressModeV:Wd[i.addressV],addressModeW:Wd[i.addressW]};!e&&i.compareOnRead&&(e=gi),e===gi||e===Hi||e===Wi?(a.compare="less",a.magFilter="linear",a.minFilter="linear",r="Compare"):e===Vi?(a.magFilter="nearest",a.minFilter="nearest",a.mipmapFilter="nearest",r="Unfilterable"):!t.textureFloatFilterable&&(i.format===ke||i.format===Me)||this.texture.format===fr||ur(this.texture.format)?(a.magFilter="nearest",a.minFilter="nearest",a.mipmapFilter="nearest",r="Nearest"):(a.magFilter=jn[i.magFilter].level,a.minFilter=jn[i.minFilter].level,a.mipmapFilter=jn[i.minFilter].mip);let o=a.minFilter==="linear"&&a.magFilter==="linear"&&a.mipmapFilter==="linear";a.maxAnisotropy=o?R.clamp(Math.round(i._anisotropy),1,t.maxTextureAnisotropy):1,s=t.wgpu.createSampler(a),this.samplers[e]=s}return s}loseContext(){}uploadImmediate(t,e){(e._needsUpload||e._needsMipmapsUpload)&&(this.uploadData(t),e._needsUpload=!1,e._needsMipmapsUpload=!1)}uploadData(t){let e=this.texture;if(this.desc&&(this.desc.size.width!==e.width||this.desc.size.height!==e.height)&&(t.deferDestroy(this.gpuTexture),this.create(t),e.renderVersionDirty=t.renderVersion),e._levels){let s=!1,i=!1,r=e.numLevels;for(let a=0;aMath.floor((_+3)/4);d={offset:0,bytesPerRow:u.blockSize*m(l),rowsPerImage:m(h)},p={width:Math.max(4,l),height:Math.max(4,h)}}t.submit(),a.queue.writeTexture(o,e,d,p)}read(t,e,s,i,r){let a=r.mipLevel??0,o=r.face??0,l=r.data??null,h=r.immediate??!1,f=this.texture,u=xs.get(f.format),d=s*u.size,p=R.roundUp(d,256),m=p*i,_=f.device,S=_.createBufferImpl(9);S.allocate(_,m);let g={texture:this.gpuTexture,mipLevel:a,origin:[t,e,o]},T={buffer:S.buffer,offset:0,bytesPerRow:p},C={width:s,height:i,depthOrArrayLayers:1};return _.getCommandEncoder().copyTextureToBuffer(g,T,C),_.readBuffer(S,m,null,h).then(E=>{let y=pf(f.format),P=l?.buffer??new ArrayBuffer(i*d),A=new Uint8Array(P,l?.byteOffset??0,i*d);for(let w=0;w|>=)\s*([\w"']+)/i,iW=/[+\-]/g,UP=/include[ \t]+"([\w-]+)(?:\s*,\s*([\w-]+))?"/g,rW=/\{i\}/g,JD=/(pcFragColor[1-8])\b/g,aW=/^\d+(?:\.\d+)?$/,mr=class mr{static run(t,e=new Map,s={}){mr.sourceName=s.sourceName,t=this.stripComments(t),t=t.split(/\r?\n/).map(o=>o.trimEnd()).join(` +`);let i=new Map,r=new Map;if(t=this._preprocess(t,i,r,e,s.stripDefines),t===null)return null;let a=new Map;return i.forEach((o,l)=>{Number.isInteger(parseFloat(o))&&!o.includes(".")&&a.set(l,o)}),t=this.stripComments(t),t=this.stripUnusedColorAttachments(t,s),t=this.RemoveEmptyLines(t),t=this.processArraySize(t,a),t=this.injectDefines(t,r),t}static stripUnusedColorAttachments(t,e){if(e.stripUnusedColorAttachments){let s=new Map;if(t.match(JD)?.forEach(a=>{let o=parseInt(a.charAt(a.length-1),10);s.set(o,(s.get(o)??0)+1)}),Array.from(s.values()).some(a=>a===1)){let a=t.split(` +`),o=[];for(let l=0;l0&&s.get(f)===1)continue}o.push(a[l])}t=o.join(` +`)}}return t}static stripComments(t){return t.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm,"$1")}static processArraySize(t,e){return t!==null&&e.forEach((s,i)=>{t=t.replace(new RegExp(`\\[${i}\\]`,"g"),`[${s}]`)}),t}static injectDefines(t,e){if(t!==null&&e.size>0){let s=t.split(` +`);e.forEach((i,r)=>{let a=new RegExp(r,"g");for(let o=0;oe.trim()===""?"":e).join(` +`),t=t.replace(/(\n\n){3,}/g,` + +`)),t}static _preprocess(t,e=new Map,s,i,r){let a=t,o=[],l=!1,h;for(;(h=ka.exec(t))!==null&&!l;){let f=h[1];switch(f){case"define":{OP.lastIndex=h.index;let u=OP.exec(t);l||(l=u===null);let d=u[1];QD.lastIndex=u.index;let m=QD.exec(d)[0],_=d.substring(m.length).trim();_===""&&(_="true");let S=mr._keep(o),g=r;if(S){let T=m.startsWith("{")&&m.endsWith("}");T&&(g=!0),T?s.set(m,_):e.set(m,_),g&&(t=t.substring(0,u.index-1)+t.substring(OP.lastIndex),ka.lastIndex=u.index-1)}g||(ka.lastIndex=u.index+u[0].length);break}case"undef":{FP.lastIndex=h.index;let u=FP.exec(t),d=u[1].trim();mr._keep(o)&&(e.delete(d),r&&(t=t.substring(0,u.index-1)+t.substring(FP.lastIndex),ka.lastIndex=u.index-1)),r||(ka.lastIndex=u.index+u[0].length);break}case"extension":{ZD.lastIndex=h.index;let u=ZD.exec(t);if(l||(l=u===null),u){let d=u[1];mr._keep(o)&&e.set(d,"true")}ka.lastIndex=u.index+u[0].length;break}case"ifdef":case"ifndef":case"if":{NP.lastIndex=h.index;let u=NP.exec(t),d=u[2],p=mr.evaluate(d,e);l||(l=p.error);let m=p.result;f==="ifndef"&&(m=!m),o.push({anyKeep:m,keep:m,start:h.index,end:NP.lastIndex}),ka.lastIndex=u.index+u[0].length;break}case"endif":case"else":case"elif":{BP.lastIndex=h.index;let u=BP.exec(t),d=o.pop();if(!d){l=!0;continue}let p=d.keep?t.substring(d.end,h.index):"";t=t.substring(0,d.start)+p+t.substring(BP.lastIndex),ka.lastIndex=d.start+p.length;let m=u[1];if(m==="else"||m==="elif"){let _=!1;if(!d.anyKeep)if(m==="else")_=!d.keep;else{let S=mr.evaluate(u[2],e);_=S.result,l||(l=S.error)}o.push({anyKeep:d.anyKeep||_,keep:_,start:ka.lastIndex,end:ka.lastIndex})}break}case"include":{UP.lastIndex=h.index;let u=UP.exec(t);if(l||(l=u===null),!u){l=!0;continue}let d=u[1].trim(),p=u[2]?.trim();if(mr._keep(o)){let _=i?.get(d);if(_!==void 0){if(_=this.stripComments(_),p){let S=e.get(p),g=parseFloat(S);if(Number.isInteger(g)){let T="";for(let C=0;C0&&(l=!0),l?null:t}static _keep(t){for(let e=0;e":u=l>h;break;case">=":u=l>=h;break;default:s=!0}return{result:u,error:s}}return{result:e.has(t),error:s}}static processParentheses(t,e){let s=!1,i=t.trim();for(;i.startsWith("(")&&i.endsWith(")");){let r=0,a=!0;for(let o=0;oo&&(o=a,l=m),r=!0)}else i[m]===")"&&(f>0?f--:a>0&&(a===o&&l!==-1&&(h=m),a--));if(!r||l===-1||h===-1)break;let u=i.substring(l+1,h),{result:d,error:p}=mr.evaluate(u,e);s=s||p,i=i.substring(0,l)+(d?"true":"false")+i.substring(h+1)}return{expression:i,error:s}}static evaluate(t,e){let s=iW.exec(t)===null,i=t,r=!1;if(t.replace(eW,"").indexOf("(")!==-1){let l=mr.processParentheses(t,e);i=l.expression,r=l.error}if(r)return{result:!1,error:!0};let o=i.split("||");for(let l of o){let h=l.split("&&"),f=!0;for(let u of h){let{result:d,error:p}=mr.evaluateAtomicExpression(u.trim(),e);if(!d||p){f=!1;break}}if(f)return{result:!0,error:!s}}return{result:!1,error:!s}}};n(mr,"sourceName");var Xd=mr;var mv=` #ifndef outType_0 #define outType_0 vec4 #endif @@ -141,7 +152,7 @@ layout(location = 7) out highp outType_7 pcFragColor7; #define TEXTURE_ACCEPT(name) sampler2D name #define TEXTURE_ACCEPT_HIGHP(name) highp sampler2D name #define GL2 -`,ra=` +`;var _v=` #extension GL_ANGLE_multi_draw : enable #define attribute in #define varying out @@ -153,7 +164,7 @@ layout(location = 7) out highp outType_7 pcFragColor7; #define TEXTURE_PASS(name) name #define TEXTURE_ACCEPT(name) sampler2D name #define TEXTURE_ACCEPT_HIGHP(name) highp sampler2D name -`,rn=` +`;var gv=` #extension GL_EXT_samplerless_texture_functions : require #ifndef outType_0 #define outType_0 vec4 @@ -209,7 +220,7 @@ layout(location = 7) out highp outType_7 pcFragColor7; #define TEXTURE_ACCEPT_HIGHP TEXTURE_ACCEPT #define GL2 #define WEBGPU -`,ro=` +`;var Sv=` #extension GL_EXT_samplerless_texture_functions : require #define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv) #define itexture2D(res, uv) texture(isampler2D(res, res ## _sampler), uv) @@ -222,10 +233,10 @@ layout(location = 7) out highp outType_7 pcFragColor7; #define VERTEXSHADER #define gl_VertexID gl_VertexIndex #define gl_InstanceID gl_InstanceIndex -`,rl=` -`,rh=` +`;var xv=` +`;var vv=` #define VERTEXSHADER -`,rc=` +`;var kP=` vec2 getGrabScreenPos(vec4 clipPos) { vec2 uv = (clipPos.xy / clipPos.w) * 0.5 + 0.5; #ifdef WEBGPU @@ -239,7 +250,7 @@ vec2 getImageEffectUV(vec2 uv) { #endif return uv; } -`,rd=` +`;var zP=` #define WEBGPU fn getGrabScreenPos(clipPos: vec4) -> vec2 { var uv: vec2 = (clipPos.xy / clipPos.w) * 0.5 + vec2(0.5); @@ -257,7 +268,7 @@ struct WrappedU32 { @size(16) element: u32 } struct WrappedVec2F { @size(16) element: vec2f } struct WrappedVec2I { @size(16) element: vec2i } struct WrappedVec2U { @size(16) element: vec2u } -`,ru=` +`;var Ug=` #ifdef CAPS_SHADER_F16 alias half = f16; alias half2 = vec2; @@ -275,190 +286,219 @@ struct WrappedVec2U { @size(16) element: vec2u } alias half3x3 = mat3x3f; alias half4x4 = mat4x4f; #endif -`;let rf={vertex_position:e8,vertex_normal:e9,vertex_tangent:e7,vertex_texCoord0:tr,vertex_texCoord1:ta,vertex_texCoord2:tn,vertex_texCoord3:to,vertex_texCoord4:tl,vertex_texCoord5:th,vertex_texCoord6:tc,vertex_texCoord7:td,vertex_color:ti,vertex_boneIndices:tt,vertex_boneWeights:te};class rp{static createDefinition(e,t){let i,s,r=e=>{let t=e.fragmentOutputTypes??"vec4";return Array.isArray(t)||(t=[t]),t},a=(t,i,s,a)=>{let n=e.isWebGPU?t:i,o="";if(!s){let t=r(a);for(let i=0;i{let s=rp.getWGSLEnables(e,t?"vertex":"fragment");if(!t){let t=r(i);for(let i=0;i{i+=`#define ${t} ${e} -`;}),i+="\n",t?.forEach((e,t)=>{i+=`#define ${t} ${e} -`;}),i+="\n"}static getShaderNameCode(e){return `#define SHADER_NAME ${e} -`}static versionCode(e){return e.isWebGPU?"#version 450\n":"#version 300 es\n"}static precisionCode(e,t){t&&"highp"!==t&&"mediump"!==t&&"lowp"!==t&&(t=null),t&&("highp"===t&&"highp"!==e.maxPrecision&&(t="mediump"),"mediump"===t&&"lowp"===e.maxPrecision&&(t="lowp"));let i=t||e.precision;return ` - precision ${i} float; - precision ${i} int; - precision ${i} usampler2D; - precision ${i} isampler2D; - precision ${i} sampler2DShadow; - precision ${i} samplerCubeShadow; - precision ${i} sampler2DArray; - `}static collectAttributes(e){let t={},i=0,s=e.indexOf("attribute");for(;s>=0&&(!(s>0)||"/"!==e[s-1]);){let r=false;if(s>0){let t=e.lastIndexOf("\n",s);t=-1!==t?t+1:0,e.substring(t,s).includes("#")&&(r=true);}if(!r){let r=e.indexOf(";",s),a=e.lastIndexOf(" ",r),n=e.substring(a+1,r);if(t[n]);else {let e=rf[n];void 0!==e?t[n]=e:(t[n]=`ATTR${i}`,i++);}}s=e.indexOf("attribute",s+1);}return t}}let rm=0;class r_{init(){this.ready=false,this.failed=false;}get label(){return `Shader Id ${this.id} (${this.definition.shaderLanguage===tV?"WGSL":"GLSL"}) ${this.name}`}destroy(){this.device.onDestroyShader(this),this.impl.destroy(this);}loseContext(){this.init(),this.impl.loseContext();}restoreContext(){this.impl.restoreContext(this.device,this);}constructor(e,t){if(this.attributes=new Map,this.id=rm++,this.device=e,this.definition=t,this.name=t.name||"Untitled",this.init(),t.cshader){let i=rp.getWGSLEnables(e,"compute")+rp.getDefinesCode(e,t.cdefines)+t.cshader,s=t.cincludes??new Map;s.has("halfTypesCS")||s.set("halfTypesCS",ru),t.cshader=rs.run(i,s,{sourceName:`compute shader for ${this.label}`,stripDefines:true});}else {let i=t.shaderLanguage===tV;t.vshader=rs.run(t.vshader,t.vincludes,{sourceName:`vertex shader for ${this.label}`,stripDefines:i}),t.shaderLanguage===tz&&(t.attributes??(t.attributes=rp.collectAttributes(t.vshader)));let s=e.isWebGL2&&("osx"===k.name||"ios"===k.name);if(t.fshader=rs.run(t.fshader,t.fincludes,{stripUnusedColorAttachments:s,stripDefines:i,sourceName:`fragment shader for ${this.label}`}),!t.vshader||!t.fshader){this.failed=true;return}}this.impl=e.createShaderImpl(this);}}class rg{}class rv{}class rS{destroy(){this.gpuBuffers.forEach(e=>{e.destroy(this.device);}),this.gpuBuffers=null,this.stagingBuffers.forEach(e=>{e.destroy(this.device);}),this.stagingBuffers=null,this.usedBuffers=null,this.activeBuffer=null;}alloc(e,t){if(this.activeBuffer){let e=ei.roundUp(this.activeBuffer.size,this.bufferAlignment);this.bufferSize-e{let s=e.storageFloat32;s[i]=t[0],s[i+1]=t[1];},ry[4]=(e,t,i)=>{let s=e.storageFloat32;s[i]=t[0],s[i+1]=t[1],s[i+2]=t[2];},ry[5]=(e,t,i)=>{let s=e.storageFloat32;s[i]=t[0],s[i+1]=t[1],s[i+2]=t[2],s[i+3]=t[3];},ry[1]=function(e,t,i){e.storageInt32[i]=t;},ry[6]=function(e,t,i){let s=e.storageInt32;s[i]=t[0],s[i+1]=t[1];},ry[7]=function(e,t,i){let s=e.storageInt32;s[i]=t[0],s[i+1]=t[1],s[i+2]=t[2];},ry[8]=function(e,t,i){let s=e.storageInt32;s[i]=t[0],s[i+1]=t[1],s[i+2]=t[2],s[i+3]=t[3];},ry[12]=(e,t,i)=>{let s=e.storageFloat32;s[i]=t[0],s[i+1]=t[1],s[i+4]=t[2],s[i+5]=t[3],s[i+8]=t[4],s[i+9]=t[5];},ry[13]=(e,t,i)=>{let s=e.storageFloat32;s[i]=t[0],s[i+1]=t[1],s[i+2]=t[2],s[i+4]=t[3],s[i+5]=t[4],s[i+6]=t[5],s[i+8]=t[6],s[i+9]=t[7],s[i+10]=t[8];},ry[17]=function(e,t,i,s){let r=e.storageFloat32;for(let e=0;e{let r=e.storageFloat32;for(let e=0;e{let r=e.storageFloat32;for(let e=0;e{e.storageUint32[i]=t;},ry[27]=(e,t,i,s)=>{let r=e.storageUint32;r[i]=t[0],r[i+1]=t[1];},ry[28]=(e,t,i,s)=>{let r=e.storageUint32;r[i]=t[0],r[i+1]=t[1],r[i+2]=t[2];},ry[29]=(e,t,i,s)=>{let r=e.storageUint32;r[i]=t[0],r[i+1]=t[1],r[i+2]=t[2],r[i+3]=t[3];},ry[30]=function(e,t,i,s){let r=e.storageInt32;for(let e=0;e{let r=e.storageInt32;for(let e=0;e{let r=e.storageUint32;for(let e=0;e{let r=e.storageInt32;for(let e=0;e{let r=e.storageUint32;for(let e=0;e{let p=d.fragmentOutputTypes??"vec4";return Array.isArray(p)||(p=[p]),p},i=(d,p,m,_)=>{let S=t.isWebGPU?d:p,g="";if(!m){let T=s(_);for(let C=0;C{let m=c.getWGSLEnables(t,d?"vertex":"fragment");if(!d){let _=s(p);for(let S=0;S{s+=`#define ${r} ${i} +`}),s+=` +`,e?.forEach((i,r)=>{s+=`#define ${r} ${i} +`}),s+=` +`,s}static getShaderNameCode(t){return`#define SHADER_NAME ${t} +`}static versionCode(t){return t.isWebGPU?`#version 450 +`:`#version 300 es +`}static precisionCode(t,e){e&&e!=="highp"&&e!=="mediump"&&e!=="lowp"&&(e=null),e&&(e==="highp"&&t.maxPrecision!=="highp"&&(e="mediump"),e==="mediump"&&t.maxPrecision==="lowp"&&(e="lowp"));let s=e||t.precision;return` + precision ${s} float; + precision ${s} int; + precision ${s} usampler2D; + precision ${s} isampler2D; + precision ${s} sampler2DShadow; + precision ${s} samplerCubeShadow; + precision ${s} sampler2DArray; + `}static collectAttributes(t){let e={},s=0,i=t.indexOf("attribute");for(;i>=0&&!(i>0&&t[i-1]==="/");){let r=!1;if(i>0){let a=t.lastIndexOf(` +`,i);a=a!==-1?a+1:0,t.substring(a,i).includes("#")&&(r=!0)}if(!r){let a=t.indexOf(";",i),o=t.lastIndexOf(" ",a),l=t.substring(o+1,a);if(!e[l]){let h=oW[l];h!==void 0?e[l]=h:(e[l]=`ATTR${s}`,s++)}}i=t.indexOf("attribute",i+1)}return e}};var nW=0,Be=class{constructor(t,e){n(this,"meshUniformBufferFormat");n(this,"meshBindGroupFormat");n(this,"attributes",new Map);if(this.id=nW++,this.device=t,this.definition=e,this.name=e.name||"Untitled",this.init(),e.cshader){let s=ns.getWGSLEnables(t,"compute"),i=ns.getDefinesCode(t,e.cdefines),r=s+i+e.cshader,a=e.cincludes??new Map;a.has("halfTypesCS")||a.set("halfTypesCS",Ug),e.cshader=Xd.run(r,a,{sourceName:`compute shader for ${this.label}`,stripDefines:!0})}else{let s=e.shaderLanguage===se;e.vshader=Xd.run(e.vshader,e.vincludes,{sourceName:`vertex shader for ${this.label}`,stripDefines:s}),e.shaderLanguage===fe&&(e.attributes??(e.attributes=ns.collectAttributes(e.vshader)));let i=t.isWebGL2&&(ue.name==="osx"||ue.name==="ios");if(e.fshader=Xd.run(e.fshader,e.fincludes,{stripUnusedColorAttachments:i,stripDefines:s,sourceName:`fragment shader for ${this.label}`}),!e.vshader||!e.fshader){this.failed=!0;return}}this.impl=t.createShaderImpl(this)}init(){this.ready=!1,this.failed=!1}get label(){return`Shader Id ${this.id} (${this.definition.shaderLanguage===se?"WGSL":"GLSL"}) ${this.name}`}destroy(){this.device.onDestroyShader(this),this.impl.destroy(this)}loseContext(){this.init(),this.impl.loseContext()}restoreContext(){this.impl.restoreContext(this.device,this)}};var GP=class{constructor(){n(this,"gpuBuffer");n(this,"stagingBuffer");n(this,"offset");n(this,"size")}},Tv=class{constructor(){n(this,"storage");n(this,"gpuBuffer");n(this,"offset")}},yv=class{constructor(t,e,s){n(this,"bufferSize");n(this,"gpuBuffers",[]);n(this,"stagingBuffers",[]);n(this,"usedBuffers",[]);n(this,"activeBuffer",null);this.device=t,this.bufferSize=e,this.bufferAlignment=s}destroy(){this.gpuBuffers.forEach(t=>{t.destroy(this.device)}),this.gpuBuffers=null,this.stagingBuffers.forEach(t=>{t.destroy(this.device)}),this.stagingBuffers=null,this.usedBuffers=null,this.activeBuffer=null}alloc(t,e){if(this.activeBuffer){let r=R.roundUp(this.activeBuffer.size,this.bufferAlignment);this.bufferSize-r{let s=c.storageFloat32;s[e]=t[0],s[e+1]=t[1]};ut[Kt]=(c,t,e)=>{let s=c.storageFloat32;s[e]=t[0],s[e+1]=t[1],s[e+2]=t[2]};ut[oi]=(c,t,e)=>{let s=c.storageFloat32;s[e]=t[0],s[e+1]=t[1],s[e+2]=t[2],s[e+3]=t[3]};ut[bi]=function(c,t,e){let s=c.storageInt32;s[e]=t};ut[jr]=function(c,t,e){let s=c.storageInt32;s[e]=t[0],s[e+1]=t[1]};ut[Di]=function(c,t,e){let s=c.storageInt32;s[e]=t[0],s[e+1]=t[1],s[e+2]=t[2]};ut[qr]=function(c,t,e){let s=c.storageInt32;s[e]=t[0],s[e+1]=t[1],s[e+2]=t[2],s[e+3]=t[3]};ut[lc]=(c,t,e)=>{let s=c.storageFloat32;s[e]=t[0],s[e+1]=t[1],s[e+4]=t[2],s[e+5]=t[3],s[e+8]=t[4],s[e+9]=t[5]};ut[La]=(c,t,e)=>{let s=c.storageFloat32;s[e]=t[0],s[e+1]=t[1],s[e+2]=t[2],s[e+4]=t[3],s[e+5]=t[4],s[e+6]=t[5],s[e+8]=t[6],s[e+9]=t[7],s[e+10]=t[8]};ut[On]=function(c,t,e,s){let i=c.storageFloat32;for(let r=0;r{let i=c.storageFloat32;for(let r=0;r{let i=c.storageFloat32;for(let r=0;r{let i=c.storageUint32;i[e]=t};ut[Ma]=(c,t,e,s)=>{let i=c.storageUint32;i[e]=t[0],i[e+1]=t[1]};ut[Oa]=(c,t,e,s)=>{let i=c.storageUint32;i[e]=t[0],i[e+1]=t[1],i[e+2]=t[2]};ut[Li]=(c,t,e,s)=>{let i=c.storageUint32;i[e]=t[0],i[e+1]=t[1],i[e+2]=t[2],i[e+3]=t[3]};ut[Fa]=function(c,t,e,s){let i=c.storageInt32;for(let r=0;r{let i=c.storageInt32;for(let r=0;r{let i=c.storageUint32;for(let r=0;r{let i=c.storageInt32;for(let r=0;r{let i=c.storageUint32;for(let r=0;r ubMesh : ub_mesh; + @group(2) @binding(0) var ubMesh : ub_mesh; - var pos : array = array( - vec2(-1.0, 1.0), vec2(1.0, 1.0), - vec2(-1.0, -1.0), vec2(1.0, -1.0) - ); + var pos : array = array( + vec2(-1.0, 1.0), vec2(1.0, 1.0), + vec2(-1.0, -1.0), vec2(1.0, -1.0) + ); - struct VertexOutput { - @builtin(position) position : vec4f - } + struct VertexOutput { + @builtin(position) position : vec4f + } - @vertex - fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput { - var output : VertexOutput; - output.position = vec4(pos[vertexIndex], ubMesh.depth, 1.0); - return output; - } + @vertex + fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput { + var output : VertexOutput; + output.position = vec4(pos[vertexIndex], ubMesh.depth, 1.0); + return output; + } - @fragment - fn fragmentMain() -> @location(0) vec4f { - return ubMesh.color; - } - `;this.shader=new r_(e,{name:"WebGPUClearRendererShader",shaderLanguage:tV,vshader:t,fshader:t}),this.uniformBuffer=new rx(e,new sg(e,[new s_("color",5),new s_("depth",2)]),false),this.dynamicBindGroup=new ig,this.colorData=new Float32Array(4);}}class rw{destroy(){this.shader.destroy(),this.shader=null,this.pipelineCache.clear();}generate(e){let t=e.desc;if(t.mipLevelCount<=1||e.texture.volume)return;let i=this.device,s=i.wgpu,r=t.format,a=this.pipelineCache.get(r);if(!a){let e=this.shader.impl;a=s.createRenderPipeline({layout:"auto",vertex:{module:e.getVertexShaderModule(),entryPoint:e.vertexEntryPoint},fragment:{module:e.getFragmentShaderModule(),entryPoint:e.fragmentEntryPoint,targets:[{format:r}]},primitive:{topology:"triangle-strip"}}),this.pipelineCache.set(r,a);}let n=e.texture,o=n.cubemap?6:n.array?n.arrayLength:1,l=[];for(let t=0;t @location(0) vec4f { + return ubMesh.color; + } + `;this.shader=new Be(t,{name:"WebGPUClearRendererShader",shaderLanguage:se,vshader:e,fshader:e}),this.uniformBuffer=new Qr(t,new Xe(t,[new Y("color",oi),new Y("depth",Te)]),!1),this.dynamicBindGroup=new hc,this.colorData=new Float32Array(4)}destroy(){this.shader.destroy(),this.shader=null,this.uniformBuffer.destroy(),this.uniformBuffer=null}clear(t,e,s,i){s=s||i;let r=s.flags??i.flags;if(r!==0){let{uniformBuffer:a,dynamicBindGroup:o}=this;a.startUpdate(o),t.setBindGroup($r,o.bindGroup,o.offsets),t.setBindGroup(Ua,t.emptyBindGroup);let l;if(r&1&&(e.colorBuffer||e.impl.assignedColorTexture)){let f=s.color??i.color;this.colorData.set(f),l=Oe.NOBLEND}else l=Oe.NOWRITE;a.set("color",this.colorData);let h;if(r&2&&e.depth){let f=s.depth??i.depth;a.set("depth",f),h=Pt.WRITEDEPTH}else a.set("depth",1),h=Pt.NODEPTH;r&4&&e.stencil,a.endUpdate(),t.setDrawStates(l,h),t.setShader(this.shader),t.draw(lW)}}};var Av=class{constructor(t){n(this,"device");n(this,"pipelineCache",new Map);this.device=t;let e=` - var pos : array = array( - vec2(-1.0, 1.0), vec2(1.0, 1.0), - vec2(-1.0, -1.0), vec2(1.0, -1.0) - ); + var pos : array = array( + vec2(-1.0, 1.0), vec2(1.0, 1.0), + vec2(-1.0, -1.0), vec2(1.0, -1.0) + ); - struct VertexOutput { - @builtin(position) position : vec4f, - @location(0) texCoord : vec2f - }; + struct VertexOutput { + @builtin(position) position : vec4f, + @location(0) texCoord : vec2f + }; - @vertex - fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput { - var output : VertexOutput; - output.texCoord = pos[vertexIndex] * vec2f(0.5, -0.5) + vec2f(0.5); - output.position = vec4f(pos[vertexIndex], 0, 1); - return output; - } + @vertex + fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput { + var output : VertexOutput; + output.texCoord = pos[vertexIndex] * vec2f(0.5, -0.5) + vec2f(0.5); + output.position = vec4f(pos[vertexIndex], 0, 1); + return output; + } - @group(0) @binding(0) var imgSampler : sampler; - @group(0) @binding(1) var img : texture_2d; + @group(0) @binding(0) var imgSampler : sampler; + @group(0) @binding(1) var img : texture_2d; - @fragment - fn fragmentMain(@location(0) texCoord : vec2f) -> @location(0) vec4f { - return textureSample(img, imgSampler, texCoord); - } - `;this.shader=new r_(e,{name:"WebGPUMipmapRendererShader",shaderLanguage:tV,vshader:t,fshader:t}),this.minSampler=e.wgpu.createSampler({minFilter:"linear"});}}class rb{getBindGroup(e){let t=e.format.byteSize,i=this.bindGroupCache.get(t);return i||((i=new iv(this.device,this.bindGroupFormat,e)).update(),this.bindGroupCache.set(t,i)),i}constructor(e){this.bindGroupCache=new Map,this.device=e,this.bindGroupFormat=new ii(this.device,[new t9(tQ,3)]);}}class rC extends rb{destroy(e){e._vram.ub-=this.buffer.size,this.buffer.destroy(),this.buffer=null;}onAvailable(){this.mappedRange=this.buffer.getMappedRange();}alloc(e,t){return new Int32Array(this.mappedRange,e,t/4)}constructor(e,t,i){super(e),this.buffer=null,this.mappedRange=null,this.buffer=e.wgpu.createBuffer({size:t,usage:i?GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,mappedAtCreation:i}),i&&this.onAvailable(),e._vram.ub+=t;}}class rA extends rS{createBuffer(e,t,i){return new rC(e,t,i)}submit(){super.submit();let e=this.usedBuffers.length;if(e){let t=this.device,i=this.gpuBuffers,s=t.wgpu.createCommandEncoder();for(let t=e-1;t>=0;t--){let{stagingBuffer:e,gpuBuffer:r,offset:a,size:n}=this.usedBuffers[t],o=e.buffer;o.unmap(),s.copyBufferToBuffer(o,a,r.buffer,a,n),i.push(r);}let r=s.finish();t.addCommandBuffer(r,true);for(let t=0;t{this.stagingBuffers&&(e.onAvailable(),this.stagingBuffers.push(e));});}this.pendingStagingBuffers.length=0;}}constructor(...e){super(...e),this.pendingStagingBuffers=[];}}class rP{loseContext(){this.pastFrameAllocations.clear();}set enabled(e){this._enableRequest=e;}get enabled(){return this._enableRequest}get passTimings(){return this._passTimings}processEnableRequest(){this._enableRequest!==this._enabled&&(this._enabled=this._enableRequest,this._enabled||(this._frameTime=0));}request(e){this.pastFrameAllocations.set(e,this.frameAllocations),this.frameAllocations=[];}_parsePassName(e){let t=this._nameCache.get(e);return void 0===t&&(t=e.startsWith("RenderPass")?e.substring(10):e,this._nameCache.set(e,t)),t}report(e,t){if(t){let i=this.pastFrameAllocations.get(e);if(!i)return;t.length>0&&(this._frameTime=t.reduce((e,t)=>e+t,0)),this._passTimings.clear();for(let e=0;e=this.maxCount)return -1;let t=this.frameAllocations.length;return this.frameAllocations.push(e),t}get slotCount(){return this.frameAllocations.length}constructor(){this.frameAllocations=[],this.pastFrameAllocations=new Map,this._enabled=false,this._enableRequest=false,this._frameTime=0,this._passTimings=new Map,this._nameCache=new Map,this.maxCount=9999;}}class rI{destroy(){this.querySet?.destroy(),this.querySet=null,this.queryBuffer?.destroy(),this.queryBuffer=null,this.activeStagingBuffer=null,this.stagingBuffers.forEach(e=>{e.destroy();}),this.stagingBuffers=null;}getStagingBuffer(){let e=this.stagingBuffers.pop();return e||(e=this.device.wgpu.createBuffer({size:this.queryBuffer.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})),e}resolve(e){let t=this.device.getCommandEncoder();t.resolveQuerySet(this.querySet,0,e,this.queryBuffer,0);let i=this.getStagingBuffer();this.activeStagingBuffer=i,t.copyBufferToBuffer(this.queryBuffer,0,i,0,this.bytesPerSlot*e);}request(e,t){let i=this.activeStagingBuffer;return this.activeStagingBuffer=null,i.mapAsync(GPUMapMode.READ).then(()=>{let s=new BigInt64Array(i.getMappedRange()),r=[];for(let t=0;t{this.report(e.renderVersion,e.timings);}),super.request(e);}}constructor(e){super(),this.device=e,this.maxCount=1024,this.timestampQueriesSet=e.supportsTimestampQuery?new rI(e,true,2*this.maxCount):null;}}class rR{destroy(){this.shader.destroy(),this.shader=null,this.pipelineCache=null;}getPipeline(e){let t=this.pipelineCache.get(e);return t||(t=this.createPipeline(e),this.pipelineCache.set(e,t)),t}createPipeline(e){let t=this.shader.impl;return this.device.wgpu.createRenderPipeline({layout:"auto",vertex:{module:t.getVertexShaderModule(),entryPoint:t.vertexEntryPoint},fragment:{module:t.getFragmentShaderModule(),entryPoint:t.fragmentEntryPoint,targets:[{format:e}]},primitive:{topology:"triangle-strip"}})}resolveDepth(e,t,i){let s=this.device,r=s.wgpu,a=this.getPipeline(i.format),n=t.depthOrArrayLayers;for(let s=0;s @location(0) vec4f { + return textureSample(img, imgSampler, texCoord); + } + `;this.shader=new Be(t,{name:"WebGPUMipmapRendererShader",shaderLanguage:se,vshader:e,fshader:e}),this.minSampler=t.wgpu.createSampler({minFilter:"linear"})}destroy(){this.shader.destroy(),this.shader=null,this.pipelineCache.clear()}generate(t){let e=t.desc;if(e.mipLevelCount<=1||t.texture.volume)return;let s=this.device,i=s.wgpu,r=e.format,a=this.pipelineCache.get(r);if(!a){let u=this.shader.impl;a=i.createRenderPipeline({layout:"auto",vertex:{module:u.getVertexShaderModule(),entryPoint:u.vertexEntryPoint},fragment:{module:u.getFragmentShaderModule(),entryPoint:u.fragmentEntryPoint,targets:[{format:r}]},primitive:{topology:"triangle-strip"}}),this.pipelineCache.set(r,a)}let o=t.texture,l=o.cubemap?6:o.array?o.arrayLength:1,h=[];for(let u=0;u=0;o--){let l=this.usedBuffers[o],{stagingBuffer:h,gpuBuffer:f,offset:u,size:d}=l,p=h.buffer;p.unmap(),r.copyBufferToBuffer(p,u,f.buffer,u,d),i.push(f)}let a=r.finish();s.addCommandBuffer(a,!0);for(let o=0;o{this.stagingBuffers&&(i.onAvailable(),this.stagingBuffers.push(i))})}this.pendingStagingBuffers.length=0}}};var Yd=class{constructor(){n(this,"frameAllocations",[]);n(this,"pastFrameAllocations",new Map);n(this,"_enabled",!1);n(this,"_enableRequest",!1);n(this,"_frameTime",0);n(this,"_passTimings",new Map);n(this,"_nameCache",new Map);n(this,"maxCount",9999)}loseContext(){this.pastFrameAllocations.clear()}set enabled(t){this._enableRequest=t}get enabled(){return this._enableRequest}get passTimings(){return this._passTimings}processEnableRequest(){this._enableRequest!==this._enabled&&(this._enabled=this._enableRequest,this._enabled||(this._frameTime=0))}request(t){this.pastFrameAllocations.set(t,this.frameAllocations),this.frameAllocations=[]}_parsePassName(t){let e=this._nameCache.get(t);return e===void 0&&(t.startsWith("RenderPass")?e=t.substring(10):e=t,this._nameCache.set(t,e)),e}report(t,e){if(e){let s=this.pastFrameAllocations.get(t);if(!s)return;e.length>0&&(this._frameTime=e.reduce((i,r)=>i+r,0)),this._passTimings.clear();for(let i=0;i=this.maxCount)return-1;let e=this.frameAllocations.length;return this.frameAllocations.push(t),e}get slotCount(){return this.frameAllocations.length}};var Iv=class{constructor(t,e,s){n(this,"querySet");n(this,"stagingBuffers",[]);n(this,"activeStagingBuffer",null);n(this,"bytesPerSlot");this.device=t,this.capacity=s,this.bytesPerSlot=e?8:4;let i=t.wgpu;this.querySet=i.createQuerySet({type:e?"timestamp":"occlusion",count:s}),this.queryBuffer=i.createBuffer({size:this.bytesPerSlot*s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST})}destroy(){this.device.deferDestroy(this.querySet),this.querySet=null,this.device.deferDestroy(this.queryBuffer),this.queryBuffer=null,this.activeStagingBuffer=null,this.stagingBuffers.forEach(t=>{t.destroy()}),this.stagingBuffers=null}getStagingBuffer(){let t=this.stagingBuffers.pop();return t||(t=this.device.wgpu.createBuffer({size:this.queryBuffer.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})),t}resolve(t){let s=this.device.getCommandEncoder();s.resolveQuerySet(this.querySet,0,t,this.queryBuffer,0);let i=this.getStagingBuffer();this.activeStagingBuffer=i,s.copyBufferToBuffer(this.queryBuffer,0,i,0,this.bytesPerSlot*t)}request(t,e){let s=this.activeStagingBuffer;return this.activeStagingBuffer=null,s.mapAsync(GPUMapMode.READ).then(()=>{let i=new BigInt64Array(s.getMappedRange()),r=[];for(let a=0;a{this.report(s.renderVersion,s.timings)}),super.request(e)}}};var bv=class{constructor(t){n(this,"device");n(this,"pipelineCache",new Map);this.device=t;let e=` - var pos : array = array( - vec2(-1.0, 1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, -1.0) - ); + var pos : array = array( + vec2(-1.0, 1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, -1.0) + ); - struct VertexOutput { - @builtin(position) position : vec4f, - }; + struct VertexOutput { + @builtin(position) position : vec4f, + }; - @vertex - fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput { - var output : VertexOutput; - output.position = vec4f(pos[vertexIndex], 0, 1); - return output; - } + @vertex + fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput { + var output : VertexOutput; + output.position = vec4f(pos[vertexIndex], 0, 1); + return output; + } - @group(0) @binding(0) var img : texture_depth_multisampled_2d; + @group(0) @binding(0) var img : texture_depth_multisampled_2d; - @fragment - fn fragmentMain(@builtin(position) fragColor: vec4f) -> @location(0) vec4f { - // load th depth value from sample index 0 - var depth = textureLoad(img, vec2i(fragColor.xy), 0u); - return vec4f(depth, 0.0, 0.0, 0.0); - } - `;this.shader=new r_(e,{name:"WebGPUResolverDepthShader",shaderLanguage:tV,vshader:t,fshader:t});}}class rL{destroy(){this.uniformBuffers.forEach(e=>e.destroy()),this.uniformBuffers.length=0,this.bindGroup.destroy(),this.bindGroup=null;}updateBindGroup(){let{bindGroup:e}=this;e.updateUniformBuffers(),e.update();}dispatch(e,t,i){let s=this.compute.device;s.setBindGroup(0,this.bindGroup);let r=s.passEncoder;r.setPipeline(this.pipeline);let{indirectSlotIndex:a,indirectBuffer:n,indirectFrameStamp:o}=this.compute;if(a>=0){let e;e=n?n.impl.buffer:s.indirectDispatchBuffer.impl.buffer,r.dispatchWorkgroupsIndirect(e,12*a);}else r.dispatchWorkgroups(e,t,i);}constructor(e){this.uniformBuffers=[],this.bindGroup=null,this.compute=e;let{device:t,shader:i}=e,{computeBindGroupFormat:s,computeUniformBufferFormats:r}=i.impl;if(this.bindGroup=new iv(t,s),r){for(let e in r)if(r.hasOwnProperty(e)){let i=new rx(t,r[e],true);this.uniformBuffers.push(i),this.bindGroup.setUniformBuffer(e,i);}}this.pipeline=t.computePipeline.get(i,s);}}let rM=0;class rO{destroy(){let e=this.device;e.buffers.delete(this),this.adjustVramSizeTracking(e._vram,-this.byteSize),this.impl.destroy(e);}adjustVramSizeTracking(e,t){e.sb+=t;}read(e=0,t=this.byteSize,i=null,s=false){return this.impl.read(this.device,e,t,i,s)}write(e=0,t,i=0,s){this.impl.write(this.device,e,t,i,s);}clear(e=0,t=this.byteSize){this.impl.clear(this.device,e,t);}copy(e,t=0,i=0,s=e.byteSize-t){this.device.getCommandEncoder().copyBufferToBuffer(e.impl.buffer,t,this.impl.buffer,i,s);}constructor(e,t,i=0,s=true){this.id=rM++,this.device=e,this.byteSize=t,this.bufferUsage=i,this.impl=e.createBufferImpl(s?128|i:i),this.impl.allocate(e,t),this.device.buffers.add(this),this.adjustVramSizeTracking(e._vram,this.byteSize);}}class rF{allocate(e){this.gpuIndirect&&this.gpuIndirect.length===5*e||(this.storage?.destroy(),this.gpuIndirect=new Uint32Array(5*e),this.gpuIndirectSigned=new Int32Array(this.gpuIndirect.buffer),this.storage=new rO(this.device,this.gpuIndirect.byteLength,264));}add(e,t,i,s,r=0,a=0){let n=5*e;this.gpuIndirect[n+0]=t,this.gpuIndirect[n+1]=i,this.gpuIndirect[n+2]=s,this.gpuIndirectSigned[n+3]=r,this.gpuIndirect[n+4]=a;}update(e){return this.storage&&e>0&&this.storage.write(0,this.gpuIndirect,0,5*e),0}destroy(){this.storage?.destroy(),this.storage=null;}constructor(e){this.gpuIndirect=null,this.gpuIndirectSigned=null,this.storage=null,this.device=e;}}class rN{_onDeviceLost(){}destroy(){this._destroyed=true,this.availableStagingBuffers.forEach(e=>e.destroy()),this.pendingStagingBuffers.forEach(e=>e.destroy());}update(e){let t=this.pendingStagingBuffers;for(let e=0;e{this._destroyed?i.destroy():this.availableStagingBuffers.push(i);});}t.length=0;let i=this.availableStagingBuffers;for(let t=i.length-1;t>=0;t--)i[t].size output: array>; -var sdata: array; + @fragment + fn fragmentMain(@builtin(position) fragColor: vec4f) -> @location(0) vec4f { + // load th depth value from sample index 0 + var depth = textureLoad(img, vec2i(fragColor.xy), 0u); + return vec4f(depth, 0.0, 0.0, 0.0); + } + `;this.shader=new Be(t,{name:"WebGPUResolverDepthShader",shaderLanguage:se,vshader:e,fshader:e})}destroy(){this.shader.destroy(),this.shader=null,this.pipelineCache=null}getPipeline(t){let e=this.pipelineCache.get(t);return e||(e=this.createPipeline(t),this.pipelineCache.set(t,e)),e}createPipeline(t){let e=this.shader.impl;return this.device.wgpu.createRenderPipeline({layout:"auto",vertex:{module:e.getVertexShaderModule(),entryPoint:e.vertexEntryPoint},fragment:{module:e.getFragmentShaderModule(),entryPoint:e.fragmentEntryPoint,targets:[{format:t}]},primitive:{topology:"triangle-strip"}})}resolveDepth(t,e,s){let i=this.device,r=i.wgpu,a=this.getPipeline(s.format),o=e.depthOrArrayLayers;for(let l=0;lt.destroy()),this.uniformBuffers.length=0,this.bindGroup.destroy(),this.bindGroup=null}updateBindGroup(){let{bindGroup:t}=this;t.updateUniformBuffers(),t.update()}dispatch(t,e,s){let i=this.compute.device;i.setBindGroup(0,this.bindGroup);let r=i.passEncoder;r.setPipeline(this.pipeline);let{indirectSlotIndex:a,indirectBuffer:o,indirectFrameStamp:l}=this.compute;if(a>=0){let h;o?h=o.impl.buffer:h=i.indirectDispatchBuffer.impl.buffer;let f=a*cW;r.dispatchWorkgroupsIndirect(h,f)}else r.dispatchWorkgroups(t,e,s)}};var Lv=class{constructor(t){n(this,"device");n(this,"gpuIndirect",null);n(this,"gpuIndirectSigned",null);n(this,"storage",null);this.device=t}allocate(t){this.gpuIndirect&&this.gpuIndirect.length===5*t||(this.storage?.destroy(),this.gpuIndirect=new Uint32Array(5*t),this.gpuIndirectSigned=new Int32Array(this.gpuIndirect.buffer),this.storage=new Ee(this.device,this.gpuIndirect.byteLength,264))}add(t,e,s,i,r=0,a=0){let o=t*5;this.gpuIndirect[o+0]=e,this.gpuIndirect[o+1]=s,this.gpuIndirect[o+2]=i,this.gpuIndirectSigned[o+3]=r,this.gpuIndirect[o+4]=a}update(t){if(this.storage&&t>0){let s=t*5;this.storage.write(0,this.gpuIndirect,0,s)}return 0}destroy(){this.storage?.destroy(),this.storage=null}};var Mv=class{constructor(t){n(this,"availableStagingBuffers",[]);n(this,"pendingStagingBuffers",[]);n(this,"_destroyed",!1);n(this,"_lastUploadSubmitVersion",-1);this.uploadStream=t,this.useSingleBuffer=t.useSingleBuffer}_onDeviceLost(){}destroy(){this._destroyed=!0,this.availableStagingBuffers.forEach(t=>t.destroy()),this.pendingStagingBuffers.forEach(t=>t.destroy())}update(t){let e=this.pendingStagingBuffers;for(let i=0;i{this._destroyed?r.destroy():this.availableStagingBuffers.push(r)})}e.length=0;let s=this.availableStagingBuffers;for(let i=s.length-1;i>=0;i--)s[i].size0,this.update(o);let l=this.availableStagingBuffers.pop()??this.uploadStream.device.wgpu.createBuffer({size:o,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,mappedAtCreation:!0}),h=l.getMappedRange();new Uint8Array(h).set(new Uint8Array(t.buffer,t.byteOffset,o)),l.unmap(),r.getCommandEncoder().copyBufferToBuffer(l,0,e.impl.buffer,a,o),this.pendingStagingBuffers.push(l),this._lastUploadSubmitVersion=r.submitVersion}};var Ov=class{constructor(t){n(this,"_binding",null);n(this,"_layer",null);n(this,"_cachedFramebufferSize",new B);this.xrBridge=t}destroy(t){this._binding=null,this._layer=null,this._cachedFramebufferSize.set(0,0),t._clearXrState()}beginFrame(t,e){let s=this.xrBridge.device;if(s._clearXrState(),!this._binding||!this._layer||!e)return;let i=t.getViewerPose(e);if(!i||!i.views?.length)return;let r=s.xrSubImages;for(let o=0;o0&&r>0){e.set(i,r);return}}if(this._cachedFramebufferSize.x>0&&this._cachedFramebufferSize.y>0){e.copy(this._cachedFramebufferSize);return}e.set(0,0)}getViewport(t,e){if(this._binding&&this._layer)try{let s=this._binding.getViewSubImage(this._layer,e);if(s?.viewport)return s.viewport}catch{}return{x:0,y:0,width:0,height:0}}attachPresentation(t,e){let s=globalThis.XRGPUBinding;if(typeof s>"u"){this.xrBridge._onBindingError?.(new Error("XRGPUBinding is not available in this browser."));return}let r=this.xrBridge.device.wgpu;try{this._binding=new s(t,r)}catch(l){this.xrBridge._onBindingError?.(l);return}let o={colorFormat:this._binding.getPreferredColorFormat(),scaleFactor:e.framebufferScaleFactor};try{this._layer=this._binding.createProjectionLayer({...o,textureType:"texture-array"})}catch{this._layer=this._binding.createProjectionLayer({...o,textureType:"texture"})}t.updateRenderState({layers:[this._layer],depthNear:e.depthNear,depthFar:e.depthFar})}syncCameraColorTexture(t,e){if(!this._binding?.getCameraImage)return;let s=this._binding.getCameraImage(t);if(!s)return;let i=e.impl?.gpuTexture;if(!i)return;let a=this.xrBridge.device.getCommandEncoder(),o=t.width,l=t.height;a.copyTextureToTexture({texture:s},{texture:i},[o,l,1])}syncCameraDepthTexture(t,e,s){t?.texture}releasePresentation(){this._binding=null}onGraphicsDeviceLost(){let t=this.xrBridge,e=t._session;if(!e)return;let s=e.renderState,i=t.device;this._binding=null,this._layer=null,this._cachedFramebufferSize.set(0,0),i._clearXrState(),e.updateRenderState({layers:[],depthNear:s.depthNear,depthFar:s.depthFar})}onGraphicsDeviceRestored(){let t=this.xrBridge;if(!t._session)return;let e=t.eventHandler;setTimeout(()=>{if(t._session)try{let s=t._session.renderState;t.attachPresentation(t._session,{framebufferScaleFactor:t._framebufferScaleFactor,depthNear:s.depthNear,depthFar:s.depthFar,onBindingError:t._onBindingError})}catch(s){e.fire("error",s)}},0)}};var VP=new Map,eL=20,hW=12,Kd=class extends tt{constructor(e,s={}){super(e,s);n(this,"_deferredDestroys",[]);n(this,"renderPipeline",new iv(this));n(this,"computePipeline",new rv(this));n(this,"_indirectDrawBuffer",null);n(this,"_indirectDrawBufferCount",0);n(this,"_indirectDrawNextIndex",0);n(this,"_indirectDispatchBuffer",null);n(this,"_indirectDispatchBufferCount",0);n(this,"_indirectDispatchNextIndex",0);n(this,"clearRenderer");n(this,"mipmapRenderer");n(this,"pipeline",null);n(this,"bindGroupFormats",[]);n(this,"emptyBindGroup");n(this,"submitVersion",0);n(this,"xrColorTexture",null);n(this,"xrColorTextureViewFormat",null);n(this,"xrColorTextureViewDescriptor",null);n(this,"xrSubImages",[]);n(this,"xrCurrentViewIndex",-1);n(this,"externalBackbuffer",null);n(this,"commandEncoder",null);n(this,"commandBuffers",[]);n(this,"limits");n(this,"glslang",null);n(this,"twgsl",null);s=this.initOptions,s.alpha=s.alpha??!0,this.backBufferAntialias=s.antialias??!1,this.isWebGPU=!0,this._deviceType=Ig,this.featureLevel=s.featureLevel,this.scope.resolve(yf).setValue(0)}destroy(){this.clearRenderer.destroy(),this.clearRenderer=null,this.mipmapRenderer.destroy(),this.mipmapRenderer=null,this.resolver.destroy(),this.resolver=null,this._clearXrState(),this.externalBackbuffer=null,super.destroy()}_clearXrState(){this.xrColorTexture=null,this.xrColorTextureViewFormat=null,this.xrColorTextureViewDescriptor=null,this.xrSubImages.length=0,this.xrCurrentViewIndex=-1}initDeviceCaps(){let e=this.wgpu?.limits;this.limits=e,this.precision="highp",this.maxPrecision="highp",this.maxSamples=4,this.maxTextures=16,this.maxTextureSize=e.maxTextureDimension2D,this.maxCubeMapSize=e.maxTextureDimension2D,this.maxVolumeSize=e.maxTextureDimension3D,this.maxColorAttachments=e.maxColorAttachments,this.maxPixelRatio=1,this.maxAnisotropy=16,this.fragmentUniformsCount=e.maxUniformBufferBindingSize/16,this.vertexUniformsCount=e.maxUniformBufferBindingSize/16,this.supportsUniformBuffers=!0,this.supportsAreaLights=!0,this.supportsGpuParticles=!0,this.supportsCompute=!0,this.textureFloatRenderable=!0,this.textureHalfFloatRenderable=!0,this.supportsImageBitmap=!0,this.samples=this.backBufferAntialias?4:1;let s=window.navigator.gpu.wgslLanguageFeatures;this.supportsStorageTextureRead=s?.has("readonly_and_readwrite_storage_textures"),this.supportsSubgroupUniformity=s?.has("subgroup_uniformity"),this.supportsSubgroupId=s?.has("subgroup_id"),this.supportsLinearIndexing=s?.has("linear_indexing"),this.supportsUnrestrictedPointerParameters=s?.has("unrestricted_pointer_parameters"),this.supportsPointerCompositeAccess=s?.has("pointer_composite_access"),this.supportsPacked4x8IntegerDotProduct=s?.has("packed_4x8_integer_dot_product"),this.supportsTextureAndSamplerLet=s?.has("texture_and_sampler_let"),this.initCapsDefines()}async initWebGpu(e,s){if(!window.navigator.gpu)throw Yx("WebGPU"),new Error("Unable to retrieve GPU. Ensure you are using a browser that supports WebGPU rendering.");if(e&&s){let i=window.document?.baseURI??window.location.href,r=f=>new URL(f,i).toString(),a=r(s),o=r(s.replace(".js",".wasm")),l=r(e),h=await Promise.all([new Function("modulePath","return import(modulePath)")(`${a}`).then(()=>twgsl(o)),new Function("modulePath","return import(modulePath)")(`${l}`).then(f=>f.default())]);this.twgsl=h[0],this.glslang=h[1]}return this.createDevice()}async createDevice(){let e={powerPreference:this.initOptions.powerPreference!=="default"?this.initOptions.powerPreference:void 0,xrCompatible:!!this.initOptions.xrCompatible};this.gpuAdapter=await window.navigator.gpu.requestAdapter(e);let i=this.initOptions.featureLevel==="bare",r=[],a=i?()=>!1:p=>{let m=this.gpuAdapter.features.has(p);return m&&r.push(p),m};this.textureFloatFilterable=a("float32-filterable"),this.textureFloatBlendable=a("float32-blendable"),this.extCompressedTextureS3TC=a("texture-compression-bc"),this.extCompressedTextureS3TCSliced3D=a("texture-compression-bc-sliced-3d"),this.extCompressedTextureETC=a("texture-compression-etc2"),this.extCompressedTextureASTC=a("texture-compression-astc"),this.extCompressedTextureASTCSliced3D=a("texture-compression-astc-sliced-3d"),this.supportsTimestampQuery=a("timestamp-query"),this.supportsDepthClip=a("depth-clip-control"),this.supportsDepth32Stencil=a("depth32float-stencil8"),this.supportsIndirectFirstInstance=a("indirect-first-instance"),this.supportsShaderF16=a("shader-f16"),this.supportsStorageRGBA8=a("bgra8unorm-storage"),this.textureRG11B10Renderable=a("rg11b10ufloat-renderable"),this.supportsClipDistances=a("clip-distances"),this.supportsTextureFormatTier1=a("texture-format-tier1"),this.supportsTextureFormatTier2=a("texture-format-tier2"),this.supportsTextureFormatTier1||(this.supportsTextureFormatTier1=this.supportsTextureFormatTier2),this.supportsPrimitiveIndex=a("primitive-index"),this.supportsSubgroups=a("subgroups"),this.maxSubgroupSize=this.supportsSubgroups?this.gpuAdapter?.info?.subgroupMaxSize??0:0,this.minSubgroupSize=this.supportsSubgroups?this.gpuAdapter?.info?.subgroupMinSize??0:0;let o=window.navigator.gpu.wgslLanguageFeatures?Array.from(window.navigator.gpu.wgslLanguageFeatures):[],l={};if(!i){let p=this.gpuAdapter?.limits;if(p)for(let m in p)m==="minSubgroupSize"||m==="maxSubgroupSize"||(l[m]=p[m])}let h={requiredFeatures:r,requiredLimits:l,defaultQueue:{label:"Default Queue"}};this.wgpu=await this.gpuAdapter.requestDevice(h),this.supportsHtmlTextures=typeof this.wgpu.queue?.copyElementImageToTexture=="function",this.wgpu.lost?.then(this.handleDeviceLost.bind(this)),this.wgpu.addEventListener?.("uncapturederror",p=>{let m=p.error}),this.initDeviceCaps(),this.gpuContext=this.canvas.getContext("webgpu");let f="standard",u=window.navigator.gpu.getPreferredCanvasFormat(),d=this.initOptions.displayFormat;return this.backBufferFormat=u==="rgba8unorm"?d===Md?st:ce:d===Md?ic:tc,this.backBufferViewFormat=d===Md?`${u}-srgb`:u,d===mP&&this.textureFloatFilterable&&window.matchMedia("(dynamic-range: high)")?.matches&&(this.backBufferFormat=Me,this.backBufferViewFormat="rgba16float",u="rgba16float",this.isHdr=!0,f="extended"),this.canvasConfig={device:this.wgpu,colorSpace:"srgb",alphaMode:this.initOptions.alpha?"premultiplied":"opaque",format:u,toneMapping:{mode:f},usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST,viewFormats:d===Md?[this.backBufferViewFormat]:[]},this.gpuContext?.configure(this.canvasConfig),this.createBackbuffer(),this.clearRenderer=new Ev(this),this.mipmapRenderer=new Av(this),this.resolver=new bv(this),this.postInit(),this}async handleDeviceLost(e){e.reason!=="destroyed"&&(super.loseContext(),this.fire("devicelost"),await this.createDevice(),super.restoreContext(),this.fire("devicerestored"))}postInit(){super.postInit(),this.initializeRenderState(),this.setupPassEncoderDefaults(),this.gpuProfiler=new Rv(this),this.dynamicBuffers=new wv(this,100*1024,this.limits.minUniformBufferOffsetAlignment),this.emptyBindGroup=new ji(this,new Ue(this,[])),this.emptyBindGroup.update()}createBackbuffer(){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new me({name:"WebgpuFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.backBuffer.impl.isBackbuffer=!0}frameStart(){super.frameStart(),this.gpuProfiler.frameStart(),this.submit();let e=this.xrColorTexture??this.gpuContext?.getCurrentTexture?.()??this.externalBackbuffer?.impl.gpuTexture;(this.backBufferSize.x!==e.width||this.backBufferSize.y!==e.height)&&(this.backBufferSize.set(e.width,e.height),this.backBuffer.destroy(),this.backBuffer=null,this.createBackbuffer());let s=this.backBuffer,i=s.impl,r=e===this.xrColorTexture&&this.xrColorTextureViewFormat?this.xrColorTextureViewFormat:this.backBufferViewFormat;i.setColorAttachment(0,void 0,r),s._width=e.width,s._height=e.height,this.initRenderTarget(s),i.assignColorTexture(e,r)}frameEnd(){super.frameEnd(),this.gpuProfiler.frameEnd(),this.submit(),this.contextLost||this.gpuProfiler.request(),this._indirectDrawNextIndex=0,this._indirectDispatchNextIndex=0}createBufferImpl(e){return new Lo(e)}createUniformBufferImpl(e){return new dv(e)}createVertexBufferImpl(e,s,i){return new pv(e,s,i)}createIndexBufferImpl(e,s){return new Jx(e,s)}createShaderImpl(e){return new fv(e)}createDrawCommandImpl(e){return new Lv(this)}createTextureImpl(e){return this.textures.add(e),new uv(e)}createXrBridgeImpl(e){return new Ov(e)}createRenderTargetImpl(e){return new nv(e)}createUploadStreamImpl(e){return new Mv(e)}createBindGroupFormatImpl(e){return new Qx(e)}createBindGroupImpl(e){return new Zx}createComputeImpl(e){return new Dv(e)}get indirectDrawBuffer(){return this.allocateIndirectDrawBuffer(),this._indirectDrawBuffer}allocateIndirectDrawBuffer(){this._indirectDrawNextIndex===0&&this._indirectDrawBufferCount{let{elements:a}=r.format;for(let o=0;o{(e._needsUpload||e._needsMipmapsUpload)&&e.upload()}),this.texturesToUpload.clear()}setupTimeStampWrites(e,s){if(this.gpuProfiler._enabled&&this.gpuProfiler.timestampQueriesSet){let i=this.gpuProfiler.getSlot(s);i===-1||(e=e??{},e.timestampWrites={querySet:this.gpuProfiler.timestampQueriesSet.querySet,beginningOfPassWriteIndex:i*2,endOfPassWriteIndex:i*2+1})}return e}startRenderPass(e){this._uploadDirtyTextures();let s=e.renderTarget||this.backBuffer;this.renderTarget=s;let i=s.impl;s!==this.backBuffer&&this.initRenderTarget(s),i.setupForRenderPass(e,s);let r=i.renderPassDescriptor;this.setupTimeStampWrites(r,e.name);let a=this.getCommandEncoder();this.passEncoder=a.beginRenderPass(r),this.passEncoder.label=`${e.name}-PassEncoder RT:${s.name}`,this.setupPassEncoderDefaults();let{width:o,height:l}=s;this.setViewport(0,0,o,l),this.setScissor(0,0,o,l),this.insideRenderPass=!0}endRenderPass(e){this.passEncoder.end(),this.passEncoder=null,this.insideRenderPass=!1,this.bindGroupFormats.length=0;let s=this.renderTarget;if(s&&s.depthBuffer&&e.depthStencilOps.resolveDepth&&e.samples>1&&s.autoResolve){let i=s.impl.depthAttachment,r=s.depthBuffer.impl.gpuTexture;i&&r&&this.resolver.resolveDepth(this.commandEncoder,i.multisampledDepthBuffer,r)}for(let i=0;i0&&(this.dynamicBuffers.submit(),this.wgpu.queue.submit(this.commandBuffers),this.commandBuffers.length=0,this.submitVersion++,this.dynamicBuffers.onCommandBuffersSubmitted());let e=this._deferredDestroys;if(e.length>0){for(let s=0;s{let h=()=>{a?.mapAsync(GPUMapMode.READ).then(()=>{i??(i=new Uint8Array(s));let f=a.getMappedRange(0,s),u=i.constructor;i.set(new u(f)),a.unmap(),e.destroy(this),o(i)})};r?(this.submit(),h()):setTimeout(()=>{h()})})}writeStorageBuffer(e,s=0,i,r=0,a){this.wgpu.queue.writeBuffer(e.buffer,s,i,r,a)}copyRenderTarget(e,s,i,r){let a={width:e?e.width:s.width,height:e?e.height:s.height,depthOrArrayLayers:1},o=this.getCommandEncoder();if(i){let l={texture:e?e.colorBuffer.impl.gpuTexture:this.backBuffer.impl.assignedColorTexture,mipLevel:e?e.mipLevel:0},h={texture:s?s.colorBuffer.impl.gpuTexture:this.backBuffer.impl.assignedColorTexture,mipLevel:s?s.mipLevel:0};o.copyTextureToTexture(l,h,a)}if(r){let l=e||this.renderTarget,h=l.impl.depthAttachment.depthTexture,f=l.mipLevel;if(e.samples>1){let u=s.colorBuffer.impl.gpuTexture;this.resolver.resolveDepth(o,h,u)}else{let u=s?s.depthBuffer.impl.gpuTexture:this.renderTarget.impl.depthAttachment.depthTexture,d=s?s.mipLevel:this.renderTarget.mipLevel,p={texture:h,mipLevel:f},m={texture:u,mipLevel:d};o.copyTextureToTexture(p,m,a)}}return!0}get hasTranspilers(){return this.glslang&&this.twgsl}};var jd=class{constructor(){n(this,"bufferId",null)}destroy(t){this.bufferId&&(t.gl.deleteBuffer(this.bufferId),this.bufferId=null)}get initialized(){return!!this.bufferId}loseContext(){this.bufferId=null}unlock(t,e,s,i){let r=t.gl;if(this.bufferId)r.bindBuffer(s,this.bufferId),r.bufferSubData(s,0,i);else{let a;switch(e){case 0:a=r.STATIC_DRAW;break;case 1:a=r.DYNAMIC_DRAW;break;case 2:a=r.STREAM_DRAW;break;case 3:a=r.DYNAMIC_COPY;break}this.bufferId=r.createBuffer(),r.bindBuffer(s,this.bufferId),r.bufferData(s,i,a)}}};var Fv=class extends jd{constructor(){super(...arguments);n(this,"vao",null)}destroy(e){super.destroy(e),e.unbindVertexArray()}loseContext(){super.loseContext(),this.vao=null}unlock(e){let s=e.device;super.unlock(s,e.usage,s.gl.ARRAY_BUFFER,e.storage)}};var Nv=class extends jd{constructor(t){super();let e=t.device.gl,s=t.format;s===0?this.glFormat=e.UNSIGNED_BYTE:s===1?this.glFormat=e.UNSIGNED_SHORT:s===2&&(this.glFormat=e.UNSIGNED_INT)}unlock(t){let e=t.device;super.unlock(e,t.usage,e.gl.ELEMENT_ARRAY_BUFFER,t.storage)}};var Bv=class{constructor(t,e,s,i){if(this.locationId=i,this.scopeId=t.scope.resolve(e),this.version=new Nd,e.substring(e.length-3)==="[0]")switch(s){case Te:s=On;break;case bi:s=Fa;break;case pe:s=Bn;break;case wo:s=Un;break;case pr:s=Fn;break;case jr:s=Na;break;case Ma:s=kn;break;case Dn:s=zn;break;case Kt:s=Nn;break;case Di:s=Ba;break;case Oa:s=Gn;break;case Ln:s=Vn;break;case oi:s=gf;break;case qr:s=cc;break;case Li:s=Sf;break;case Mn:s=xf;break}this.dataType=s,this.value=[null,null,null,null],this.array=[]}};var tL=new Set(["gl_VertexID","gl_InstanceID","gl_DrawID","gl_BaseVertex","gl_BaseInstance"]),HP=class{constructor(){n(this,"map",new Map)}destroy(t){this.map.forEach(e=>{t.gl.deleteShader(e)})}loseContext(t){this.map.clear()}},fW=new et,uW=new et,Uv=class{constructor(t){n(this,"compileDuration",0);this.init(),this.compile(t.device,t),this.link(t.device,t),t.device.shaders.push(t)}destroy(t){this.glProgram&&(t.device.gl.deleteProgram(this.glProgram),this.glProgram=null)}init(){this.uniforms=[],this.samplers=[],this.attributes=[],this.glProgram=null,this.glVertexShader=null,this.glFragmentShader=null}loseContext(){this.init()}restoreContext(t,e){this.compile(t,e),this.link(t,e)}compile(t,e){let s=e.definition;this.glVertexShader=this._compileShaderSource(t,s.vshader,!0),this.glFragmentShader=this._compileShaderSource(t,s.fshader,!1)}link(t,e){if(this.glProgram)return;let s=t.gl;if(s.isContextLost())return;let i=0,r=s.createProgram();this.glProgram=r,s.attachShader(r,this.glVertexShader),s.attachShader(r,this.glFragmentShader);let a=e.definition,o=a.attributes;if(a.useTransformFeedback){let h=a.feedbackVaryings;if(!h){h=[];for(let f in o)o.hasOwnProperty(f)&&h.push(`out_${f}`)}s.transformFeedbackVaryings(r,h,s.INTERLEAVED_ATTRIBS)}let l={};for(let h in o)if(o.hasOwnProperty(h)){let f=o[h],u=ze[f];l[u]=h,s.bindAttribLocation(r,u,h)}s.linkProgram(r)}_compileShaderSource(t,e,s){let i=t.gl;if(i.isContextLost())return null;let a=(s?fW:uW).get(t,()=>new HP),o=a.map.get(e);return o||(o=i.createShader(s?i.VERTEX_SHADER:i.FRAGMENT_SHADER),i.shaderSource(o,e),i.compileShader(o),a.map.set(e,o)),o}finalize(t,e){let s=t.gl;if(s.isContextLost())return!0;let i=this.glProgram,r=e.definition,a=0;if(!s.getProgramParameter(i,s.LINK_STATUS)){if(!this._isCompiled(t,e,this.glVertexShader,r.vshader,"vertex")||!this._isCompiled(t,e,this.glFragmentShader,r.fshader,"fragment"))return!1;let u=`Failed to link shader program. Error: ${s.getProgramInfoLog(i)}`;return!1}let l=s.getProgramParameter(i,s.ACTIVE_ATTRIBUTES);e.attributes.clear();for(let u=0;unew URL(e,window.location.href).toString(),s=await Promise.all([Function("modulePath","return import(modulePath)")(`${i(t)}`).then(e=>twgsl(t.replace(".js",".wasm"))),Function("modulePath","return import(modulePath)")(`${i(e)}`).then(e=>e.default())]);this.twgsl=s[0],this.glslang=s[1];}return this.createDevice()}async createDevice(){let e={powerPreference:"default"!==this.initOptions.powerPreference?this.initOptions.powerPreference:void 0,xrCompatible:this.initOptions.xrCompatible};this.gpuAdapter=await window.navigator.gpu.requestAdapter(e);let t="bare"===this.initOptions.featureLevel,i=[],s=t?()=>false:e=>{let t=this.gpuAdapter.features.has(e);return t&&i.push(e),t};this.textureFloatFilterable=s("float32-filterable"),this.textureFloatBlendable=s("float32-blendable"),this.extCompressedTextureS3TC=s("texture-compression-bc"),this.extCompressedTextureS3TCSliced3D=s("texture-compression-bc-sliced-3d"),this.extCompressedTextureETC=s("texture-compression-etc2"),this.extCompressedTextureASTC=s("texture-compression-astc"),this.extCompressedTextureASTCSliced3D=s("texture-compression-astc-sliced-3d"),this.supportsTimestampQuery=s("timestamp-query"),this.supportsDepthClip=s("depth-clip-control"),this.supportsDepth32Stencil=s("depth32float-stencil8"),this.supportsIndirectFirstInstance=s("indirect-first-instance"),this.supportsShaderF16=s("shader-f16"),this.supportsStorageRGBA8=s("bgra8unorm-storage"),this.textureRG11B10Renderable=s("rg11b10ufloat-renderable"),this.supportsClipDistances=s("clip-distances"),this.supportsTextureFormatTier1=s("texture-format-tier1"),this.supportsTextureFormatTier2=s("texture-format-tier2"),this.supportsTextureFormatTier1||(this.supportsTextureFormatTier1=this.supportsTextureFormatTier2),this.supportsPrimitiveIndex=s("primitive-index"),this.supportsSubgroups=s("subgroups");let r={};if(!t){let e=this.gpuAdapter?.limits;if(e)for(let t in e)"minSubgroupSize"!==t&&"maxSubgroupSize"!==t&&(r[t]=e[t]);}this.wgpu=await this.gpuAdapter.requestDevice({requiredFeatures:i,requiredLimits:r,defaultQueue:{label:"Default Queue"}}),this.wgpu.lost?.then(this.handleDeviceLost.bind(this)),this.computePerfIndex=await rB.run(this.wgpu,this.supportsTimestampQuery),this.initDeviceCaps(),this.gpuContext=this.canvas.getContext("webgpu");let a="standard",n=window.navigator.gpu.getPreferredCanvasFormat(),o=this.initOptions.displayFormat;if(this.backBufferFormat="rgba8unorm"===n?o===t$?20:7:o===t$?64:31,this.backBufferViewFormat=o===t$?`${n}-srgb`:n,"hdr"===o&&this.textureFloatFilterable){let e=window.matchMedia("(dynamic-range: high)");e?.matches&&(this.backBufferFormat=12,this.backBufferViewFormat="rgba16float",n="rgba16float",this.isHdr=true,a="extended");}return this.canvasConfig={device:this.wgpu,colorSpace:"srgb",alphaMode:this.initOptions.alpha?"premultiplied":"opaque",format:n,toneMapping:{mode:a},usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST,viewFormats:o===t$?[this.backBufferViewFormat]:[]},this.gpuContext?.configure(this.canvasConfig),this.createBackbuffer(),this.clearRenderer=new rE(this),this.mipmapRenderer=new rw(this),this.resolver=new rR(this),this.postInit(),this}async handleDeviceLost(e){"destroyed"!==e.reason&&(super.loseContext(),await this.createDevice(),super.restoreContext());}postInit(){super.postInit(),this.initializeRenderState(),this.setupPassEncoderDefaults(),this.gpuProfiler=new rD(this),this.dynamicBuffers=new rA(this,102400,this.limits.minUniformBufferOffsetAlignment),this.emptyBindGroup=new iv(this,new ii(this,[])),this.emptyBindGroup.update();}createBackbuffer(){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new iG({name:"WebgpuFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.backBuffer.impl.isBackbuffer=true;}frameStart(){super.frameStart(),this.gpuProfiler.frameStart(),this.submit();let e=this.gpuContext?.getCurrentTexture?.()??this.externalBackbuffer?.impl.gpuTexture;(this.backBufferSize.x!==e.width||this.backBufferSize.y!==e.height)&&(this.backBufferSize.set(e.width,e.height),this.backBuffer.destroy(),this.backBuffer=null,this.createBackbuffer());let t=this.backBuffer,i=t.impl;i.setColorAttachment(0,void 0,this.backBufferViewFormat),this.initRenderTarget(t),i.assignColorTexture(this,e);}frameEnd(){super.frameEnd(),this.gpuProfiler.frameEnd(),this.submit(),this.contextLost||this.gpuProfiler.request(),this._indirectDrawNextIndex=0,this._indirectDispatchNextIndex=0;}createBufferImpl(e){return new i$(e)}createUniformBufferImpl(e){return new sK(e)}createVertexBufferImpl(e,t,i){return new s$(e,t,i)}createIndexBufferImpl(e,t){return new iZ(e,t)}createShaderImpl(e){return new sX(e)}createDrawCommandImpl(e){return new rF(this)}createTextureImpl(e){return this.textures.add(e),new sj(e)}createRenderTargetImpl(e){return new sp(e)}createUploadStreamImpl(e){return new rN(e)}createBindGroupFormatImpl(e){return new iK(e)}createBindGroupImpl(e){return new iH}createComputeImpl(e){return new rL(e)}get indirectDrawBuffer(){return this.allocateIndirectDrawBuffer(),this._indirectDrawBuffer}allocateIndirectDrawBuffer(){0===this._indirectDrawNextIndex&&this._indirectDrawBufferCount{let{elements:t}=e.format;for(let e=0;e{(e._needsUpload||e._needsMipmapsUpload)&&e.upload();}),this.texturesToUpload.clear();}setupTimeStampWrites(e,t){if(this.gpuProfiler._enabled&&this.gpuProfiler.timestampQueriesSet){let i=this.gpuProfiler.getSlot(t);-1===i||((e=e??{}).timestampWrites={querySet:this.gpuProfiler.timestampQueriesSet.querySet,beginningOfPassWriteIndex:2*i,endOfPassWriteIndex:2*i+1});}return e}startRenderPass(e){this._uploadDirtyTextures();let t=e.renderTarget||this.backBuffer;this.renderTarget=t;let i=t.impl;t!==this.backBuffer&&this.initRenderTarget(t),i.setupForRenderPass(e,t);let s=i.renderPassDescriptor;this.setupTimeStampWrites(s,e.name);let r=this.getCommandEncoder();this.passEncoder=r.beginRenderPass(s),this.passEncoder.label=`${e.name}-PassEncoder RT:${t.name}`,this.setupPassEncoderDefaults();let{width:a,height:n}=t;this.setViewport(0,0,a,n),this.setScissor(0,0,a,n),this.insideRenderPass=true;}endRenderPass(e){this.passEncoder.end(),this.passEncoder=null,this.insideRenderPass=false,this.bindGroupFormats.length=0;let t=this.renderTarget;if(t&&t.depthBuffer&&e.depthStencilOps.resolveDepth&&e.samples>1&&t.autoResolve){let e=t.impl.depthAttachment,i=t.depthBuffer.impl.gpuTexture;e&&i&&this.resolver.resolveDepth(this.commandEncoder,e.multisampledDepthBuffer,i);}for(let t=0;t0&&(this.dynamicBuffers.submit(),this.wgpu.queue.submit(this.commandBuffers),this.commandBuffers.length=0,this.submitVersion++,this.dynamicBuffers.onCommandBuffersSubmitted());let e=this._deferredDestroys;if(e.length>0){for(let t=0;t{let o=()=>{r?.mapAsync(GPUMapMode.READ).then(()=>{i??(i=new Uint8Array(t));let s=r.getMappedRange(0,t),n=i.constructor;i.set(new n(s)),r.unmap(),e.destroy(this),a(i);});};s?(this.submit(),o()):setTimeout(()=>{o();});})}writeStorageBuffer(e,t=0,i,s=0,r){this.wgpu.queue.writeBuffer(e.buffer,t,i,s,r);}copyRenderTarget(e,t,i,s){let r={width:e?e.width:t.width,height:e?e.height:t.height,depthOrArrayLayers:1},a=this.getCommandEncoder();if(i){let i={texture:e?e.colorBuffer.impl.gpuTexture:this.backBuffer.impl.assignedColorTexture,mipLevel:e?e.mipLevel:0},s={texture:t?t.colorBuffer.impl.gpuTexture:this.backBuffer.impl.assignedColorTexture,mipLevel:t?t.mipLevel:0};a.copyTextureToTexture(i,s,r);}if(s){let i=e||this.renderTarget,s=i.impl.depthAttachment.depthTexture,n=i.mipLevel;if(e.samples>1){let e=t.colorBuffer.impl.gpuTexture;this.resolver.resolveDepth(a,s,e);}else {let e=t?t.depthBuffer.impl.gpuTexture:this.renderTarget.impl.depthAttachment.depthTexture,i=t?t.mipLevel:this.renderTarget.mipLevel;a.copyTextureToTexture({texture:s,mipLevel:n},{texture:e,mipLevel:i},r);}}return true}get hasTranspilers(){return this.glslang&&this.twgsl}constructor(e,t={}){super(e,t),this._deferredDestroys=[],this.renderPipeline=new si(this),this.computePipeline=new sr(this),this._indirectDrawBuffer=null,this._indirectDrawBufferCount=0,this._indirectDrawNextIndex=0,this._indirectDispatchBuffer=null,this._indirectDispatchBufferCount=0,this._indirectDispatchNextIndex=0,this.pipeline=null,this.bindGroupFormats=[],this.submitVersion=0,this.commandEncoder=null,this.commandBuffers=[],this.glslang=null,this.twgsl=null,(t=this.initOptions).alpha=t.alpha??true,this.backBufferAntialias=t.antialias??false,this.isWebGPU=true,this._deviceType=tq,this.featureLevel=t.featureLevel,this.scope.resolve(tJ).setValue(0);}}class rz{destroy(e){this.bufferId&&(e.gl.deleteBuffer(this.bufferId),this.bufferId=null);}get initialized(){return !!this.bufferId}loseContext(){this.bufferId=null;}unlock(e,t,i,s){let r=e.gl;if(this.bufferId)r.bindBuffer(i,this.bufferId),r.bufferSubData(i,0,s);else {let e;switch(t){case 0:e=r.STATIC_DRAW;break;case 1:e=r.DYNAMIC_DRAW;break;case 2:e=r.STREAM_DRAW;break;case 3:e=r.DYNAMIC_COPY;}this.bufferId=r.createBuffer(),r.bindBuffer(i,this.bufferId),r.bufferData(i,s,e);}}constructor(){this.bufferId=null;}}class rV extends rz{destroy(e){super.destroy(e),e.unbindVertexArray();}loseContext(){super.loseContext(),this.vao=null;}unlock(e){let t=e.device;super.unlock(t,e.usage,t.gl.ARRAY_BUFFER,e.storage);}constructor(...e){super(...e),this.vao=null;}}class rG extends rz{unlock(e){let t=e.device;super.unlock(t,e.usage,t.gl.ELEMENT_ARRAY_BUFFER,e.storage);}constructor(e){super();let t=e.device.gl,i=e.format;0===i?this.glFormat=t.UNSIGNED_BYTE:1===i?this.glFormat=t.UNSIGNED_SHORT:2===i&&(this.glFormat=t.UNSIGNED_INT);}}class rH{constructor(e,t,i,s){if(this.locationId=s,this.scopeId=e.scope.resolve(t),this.version=new ib,"[0]"===t.substring(t.length-3))switch(i){case 2:i=17;break;case 1:i=30;break;case 26:i=31;break;case 0:i=32;break;case 3:i=21;break;case 6:i=33;break;case 27:i=34;break;case 9:i=35;break;case 4:i=22;break;case 7:i=36;break;case 28:i=37;break;case 10:i=38;break;case 5:i=23;break;case 8:i=39;break;case 29:i=40;break;case 11:i=41;}this.dataType=i,this.value=[null,null,null,null],this.array=[];}}let rW=new Set(["gl_VertexID","gl_InstanceID","gl_DrawID","gl_BaseVertex","gl_BaseInstance"]);class rX{destroy(e){this.map.forEach(t=>{e.gl.deleteShader(t);});}loseContext(e){this.map.clear();}constructor(){this.map=new Map;}}let rY=new is,rq=new is;class rj{destroy(e){this.glProgram&&(e.device.gl.deleteProgram(this.glProgram),this.glProgram=null);}init(){this.uniforms=[],this.samplers=[],this.attributes=[],this.glProgram=null,this.glVertexShader=null,this.glFragmentShader=null;}loseContext(){this.init();}restoreContext(e,t){this.compile(e,t),this.link(e,t);}compile(e,t){let i=t.definition;this.glVertexShader=this._compileShaderSource(e,i.vshader,true),this.glFragmentShader=this._compileShaderSource(e,i.fshader,false);}link(e,t){if(this.glProgram)return;let i=e.gl;if(i.isContextLost())return;let s=i.createProgram();this.glProgram=s,i.attachShader(s,this.glVertexShader),i.attachShader(s,this.glFragmentShader);let r=t.definition,a=r.attributes;if(r.useTransformFeedback){let e=r.feedbackVaryings;if(!e)for(let t in e=[],a)a.hasOwnProperty(t)&&e.push(`out_${t}`);i.transformFeedbackVaryings(s,e,i.INTERLEAVED_ATTRIBS);}for(let e in a)if(a.hasOwnProperty(e)){let t=t5[a[e]];i.bindAttribLocation(s,t,e);}i.linkProgram(s);}_compileShaderSource(e,t,i){let s=e.gl;if(s.isContextLost())return null;let r=(i?rY:rq).get(e,()=>new rX),a=r.map.get(t);return a||(a=s.createShader(i?s.VERTEX_SHADER:s.FRAGMENT_SHADER),s.shaderSource(a,t),s.compileShader(a),r.map.set(t,a)),a}finalize(e,t){let i=e.gl;if(i.isContextLost())return true;let s=this.glProgram,r=t.definition;if(!i.getProgramParameter(s,i.LINK_STATUS))return !!this._isCompiled(e,t,this.glVertexShader,r.vshader,"vertex")&&!!this._isCompiled(e,t,this.glFragmentShader,r.fshader,"fragment")&&(i.getProgramInfoLog(s),false);let a=i.getProgramParameter(s,i.ACTIVE_ATTRIBUTES);t.attributes.clear();for(let e=0;e ":" ";s+=`${t}${e+1}: ${r[e]} -`;}i.source=e;}return [s,i]}constructor(e){this.compileDuration=0,this.init(),this.compile(e.device,e),this.link(e.device,e),e.device.shaders.push(e);}}class rK{allocate(e){this.glCounts&&this.glCounts.length===e||(this.glCounts=new Int32Array(e),this.glOffsetsBytes=new Int32Array(e),this.glInstanceCounts=new Int32Array(e));}add(e,t,i,s){this.glCounts[e]=t,this.glOffsetsBytes[e]=s*this.indexSizeBytes,this.glInstanceCounts[e]=i;}update(e){return 0}constructor(e){this.glCounts=null,this.glOffsetsBytes=null,this.glInstanceCounts=null,this.indexSizeBytes=e;}}function r$(e,t){let i=e.width,s=e.height;if(i>t||s>t){let r=t/Math.max(i,s),a=Math.floor(i*r),n=Math.floor(s*r),o=document.createElement("canvas");return o.width=a,o.height=n,o.getContext("2d").drawImage(e,0,0,i,s,0,0,a,n),o}return e}class rZ{destroy(e){if(this._glTexture){for(let t=0;te.maxCubeMapSize||s.height>e.maxCubeMapSize)&&(s=r$(s,e.maxCubeMapSize),0===a&&(t._width=s.width,t._height=s.height)),e.setUnpackFlipY(false),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),this._glCreated?r.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,a,0,0,this._glFormat,this._glPixelType,s):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,a,this._glInternalFormat,this._glFormat,this._glPixelType,s);}else for(n=0,s=1/Math.pow(2,a);n<6;n++){if(!t._levelsUpdated[0][n])continue;let o=i[n];t._compressed?this._glCreated&&o?r.compressedTexSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,a,0,0,Math.max(t._width*s,1),Math.max(t._height*s,1),this._glInternalFormat,o):r.compressedTexImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,a,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,o):(e.setUnpackFlipY(false),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),e.setUnpackAlignment(1),this._glCreated&&o?r.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,a,0,0,Math.max(t._width*s,1),Math.max(t._height*s,1),this._glFormat,this._glPixelType,o):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,a,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,this._glFormat,this._glPixelType,o));}}else if(t._volume)t._compressed?r.compressedTexImage3D(r.TEXTURE_3D,a,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),Math.max(t._depth*s,1),0,i):(e.setUnpackFlipY(false),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),e.setUnpackAlignment(1),r.texImage3D(r.TEXTURE_3D,a,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),Math.max(t._depth*s,1),0,this._glFormat,this._glPixelType,i));else if(t.array){if(Array.isArray(i)&&t._arrayLength===i.length)if(t._compressed)for(let e=0;ee.maxTextureSize||i.height>e.maxTextureSize)&&(i=r$(i,e.maxTextureSize),0===a&&(t._width=i.width,t._height=i.height));let s=i.width||i.videoWidth,n=i.height||i.videoHeight;e.setUnpackFlipY(t._flipY),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),this._glCreated&&t._width===s&&t._height===n&&!e._isImageVideoInterface(i)?r.texSubImage2D(r.TEXTURE_2D,a,0,0,this._glFormat,this._glPixelType,i):(r.texImage2D(r.TEXTURE_2D,a,this._glInternalFormat,this._glFormat,this._glPixelType,i),0===a&&(t._width=s,t._height=n));}else s=1/Math.pow(2,a),t._compressed?this._glCreated&&i?r.compressedTexSubImage2D(r.TEXTURE_2D,a,0,0,Math.max(Math.floor(t._width*s),1),Math.max(Math.floor(t._height*s),1),this._glInternalFormat,i):r.compressedTexImage2D(r.TEXTURE_2D,a,this._glInternalFormat,Math.max(Math.floor(t._width*s),1),Math.max(Math.floor(t._height*s),1),0,i):(e.setUnpackFlipY(false),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),e.setUnpackAlignment(1),this._glCreated&&i?r.texSubImage2D(r.TEXTURE_2D,a,0,0,Math.max(t._width*s,1),Math.max(t._height*s,1),this._glFormat,this._glPixelType,i):r.texImage2D(r.TEXTURE_2D,a,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,this._glFormat,this._glPixelType,i));0===a?t._mipmapsUploaded=false:t._mipmapsUploaded=true;}a++;}if(t._needsUpload)if(t._cubemap)for(let e=0;e<6;e++)t._levelsUpdated[0][e]=false;else t._levelsUpdated[0]=false;!t._compressed&&!t._integerFormat&&t._mipmaps&&t._needsMipmapsUpload&&1===t._levels.length&&(r.generateMipmap(this._glTarget),t._mipmapsUploaded=true),t._gpuSize&&t.adjustVramSizeTracking(e._vram,-t._gpuSize),t._gpuSize=t.gpuSize,t.adjustVramSizeTracking(e._vram,t._gpuSize),this._glCreated=true;}uploadImmediate(e,t){(t._needsUpload||t._needsMipmapsUpload)&&(e.setTexture(t,0),t._needsUpload=false,t._needsMipmapsUpload=false);}read(e,t,i,s,r){let a=this.texture;return a.device.readTextureAsync(a,e,t,i,s,r)}write(e,t,i,s,r){let{texture:a}=this,{device:n}=a;return n.setTexture(a,0),n.writeTextureAsync(a,e,t,i,s,r)}constructor(e){this._glTexture=null,this.dirtyParameterFlags=0,this.texture=e;}}let rQ=new is;class rJ{destroy(e){this.msaaFB&&(e.deleteRenderbuffer(this.msaaFB),this.msaaFB=null),this.resolveFB&&(e.deleteRenderbuffer(this.resolveFB),this.resolveFB=null);}constructor(e,t){this.msaaFB=e,this.resolveFB=t;}}class r0{destroy(e){let t=e.gl;this._isInitialized=false,this._glFrameBuffer&&(this._glFrameBuffer!==this.suppliedColorFramebuffer&&t.deleteFramebuffer(this._glFrameBuffer),this._glFrameBuffer=null),this._glDepthBuffer&&(t.deleteRenderbuffer(this._glDepthBuffer),this._glDepthBuffer=null),this._glResolveFrameBuffer&&(this._glResolveFrameBuffer!==this.suppliedColorFramebuffer&&t.deleteFramebuffer(this._glResolveFrameBuffer),this._glResolveFrameBuffer=null),this._glMsaaColorBuffers.forEach(e=>{t.deleteRenderbuffer(e);}),this._glMsaaColorBuffers.length=0,this.colorMrtFramebuffers?.forEach(e=>{e.destroy(t);}),this.colorMrtFramebuffers=null,this._glMsaaDepthBuffer&&(this._glMsaaDepthBuffer=null,this.msaaDepthBufferKey&&sc(e).release(this.msaaDepthBufferKey)),this.suppliedColorFramebuffer=void 0;}get initialized(){return this._isInitialized}init(e,t){let i=e.gl;this._isInitialized=true;let s=[];if(void 0!==this.suppliedColorFramebuffer)this._glFrameBuffer=this.suppliedColorFramebuffer;else {this._glFrameBuffer=i.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer);let r=t._colorBuffers?.length??0,a=i.COLOR_ATTACHMENT0;for(let n=0;n1)){this._glDepthBuffer||(this._glDepthBuffer=i.createRenderbuffer());let e=t._stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT32F;i.bindRenderbuffer(i.RENDERBUFFER,this._glDepthBuffer),i.renderbufferStorage(i.RENDERBUFFER,e,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,s,i.RENDERBUFFER,this._glDepthBuffer),i.bindRenderbuffer(i.RENDERBUFFER,null);}}}if(t._samples>1){this._glResolveFrameBuffer=this._glFrameBuffer,this._glFrameBuffer=i.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer);let r=t._colorBuffers?.length??0;if(void 0!==this.suppliedColorFramebuffer){let s=i.createRenderbuffer();this._glMsaaColorBuffers.push(s);let r=7===e.backBufferFormat?i.RGBA8:i.RGB8;i.bindRenderbuffer(i.RENDERBUFFER,s),i.renderbufferStorageMultisample(i.RENDERBUFFER,t._samples,r,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,s);}else for(let e=0;e1&&(this._createMsaaMrtFramebuffers(e,t,r),e.setFramebuffer(this._glFrameBuffer),i.drawBuffers(s));}}_createMsaaMrtFramebuffers(e,t,i){let s=e.gl;this.colorMrtFramebuffers=[];for(let r=0;re?.format??-1).join(",")??"",r=t._depth?t._depthBuffer?`dt${t._depthBuffer.format}`:t._stencil?"ds":"d":"",a=`${i}:${s}:${r}:${t._samples}`,n=rQ.get(e,()=>{let e=new Set;return e.loseContext=()=>e.clear(),e});if(n.has(a))return;let o=e.gl,l=o.checkFramebufferStatus(o.FRAMEBUFFER);switch(l){case o.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:case o.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:case o.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:case o.FRAMEBUFFER_UNSUPPORTED:}l===o.FRAMEBUFFER_COMPLETE&&n.add(a);}loseContext(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this._glMsaaColorBuffers.length=0,this._glMsaaDepthBuffer=null,this.msaaDepthBufferKey=void 0,this.colorMrtFramebuffers=null,this.suppliedColorFramebuffer=void 0,this._isInitialized=false;}internalResolve(e,t,i,s,r){e.setScissor(0,0,s.width,s.height);let a=e.gl;a.bindFramebuffer(a.READ_FRAMEBUFFER,t),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,i),a.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,r,a.NEAREST);}resolve(e,t,i,s){let r=e.gl;if(this.colorMrtFramebuffers){if(i)for(let i=0;ie.deleteBuffer(t.pbo)),this.pendingPBOs.forEach(t=>{t.sync&&e.deleteSync(t.sync),e.deleteBuffer(t.pbo);});}_onDeviceLost(){this.availablePBOs.length=0,this.pendingPBOs.length=0;}update(e){let t=this.uploadStream.device.gl,i=this.pendingPBOs;for(let e=i.length-1;e>=0;e--){let s=i[e],r=t.clientWaitSync(s.sync,0,0);(r===t.CONDITION_SATISFIED||r===t.ALREADY_SIGNALED)&&(t.deleteSync(s.sync),this.availablePBOs.push({pbo:s.pbo,size:s.size}),i.splice(e,1));}let s=this.availablePBOs;for(let i=s.length-1;i>=0;i--)s[i].sizee.deleteQuery(t)),this.queries=null;}constructor(){this.queries=[];}}class r3 extends rP{destroy(){this.freeQueries.forEach(e=>this.device.gl.deleteQuery(e)),this.frameQueries.forEach(e=>this.device.gl.deleteQuery(e)),this.previousFrameQueries.forEach(e=>e.destroy(this.device.gl)),this.freeQueries=null,this.frameQueries=null,this.previousFrameQueries=null;}loseContext(){super.loseContext(),this.freeQueries=[],this.frameQueries=[],this.previousFrameQueries=[];}restoreContext(){this.ext=this.device.extDisjointTimerQuery;}getQuery(){return this.freeQueries.pop()??this.device.gl.createQuery()}start(e){if(this.ext){let t=this.getSlot(e),i=this.getQuery();return this.frameQueries[t]=i,this.device.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,i),t}}end(e){ void 0!==e&&this.device.gl.endQuery(this.ext.TIME_ELAPSED_EXT);}frameStart(){this.processEnableRequest(),this._enabled&&(this.frameGPUMarkerSlot=this.start("GpuFrame"));}frameEnd(){this._enabled&&this.end(this.frameGPUMarkerSlot);}request(){if(this._enabled){let e=this.ext,t=this.device.gl,i=this.device.renderVersion,s=this.frameQueries;if(s.length>0){this.frameQueries=[];let e=new r2;e.queries=s,e.renderVersion=i,this.previousFrameQueries.push(e);}if(this.previousFrameQueries.length>0){let i=this.previousFrameQueries[0],s=i.queries,r=s[s.length-1],a=t.getQueryParameter(r,t.QUERY_RESULT_AVAILABLE),n=t.getParameter(e.GPU_DISJOINT_EXT);if(a&&!n){this.previousFrameQueries.shift();let e=this.timings;e.length=0;for(let i=0;i{this.report(e.renderVersion,null),e.destroy(t);}),this.previousFrameQueries.length=0);}super.request(i);}}constructor(e){super(),this.freeQueries=[],this.frameQueries=[],this.previousFrameQueries=[],this.timings=[],this.device=e,this.ext=e.extDisjointTimerQuery;}}let r4=[];class r5 extends iz{postInit(){super.postInit(),this.gpuProfiler=new r3(this);}destroy(){super.destroy();let e=this.gl;this.feedback&&e.deleteTransformFeedback(this.feedback),this.clearVertexArrayObjectCache(),this.canvas.removeEventListener("webglcontextlost",this._contextLostHandler,false),this.canvas.removeEventListener("webglcontextrestored",this._contextRestoredHandler,false),this._contextLostHandler=null,this._contextRestoredHandler=null,this.gl=null,super.postDestroy();}createBackbuffer(e){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new iG({name:"WebglFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.backBuffer.impl.suppliedColorFramebuffer=e;}updateBackbufferFormat(e){let t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,e);let i=this.gl.getParameter(this.gl.ALPHA_BITS);this.backBufferFormat=i?7:6;}updateBackbuffer(){let e=this.canvas.width!==this.backBufferSize.x||this.canvas.height!==this.backBufferSize.y;(this._defaultFramebufferChanged||e)&&(this._defaultFramebufferChanged&&this.updateBackbufferFormat(this._defaultFramebuffer),this._defaultFramebufferChanged=false,this.backBufferSize.set(this.canvas.width,this.canvas.height),this.backBuffer.destroy(),this.createBackbuffer(this._defaultFramebuffer));}createVertexBufferImpl(e,t){return new rV}createIndexBufferImpl(e){return new rG(e)}createShaderImpl(e){return new rj(e)}createDrawCommandImpl(e){return new rK(e.indexSizeBytes)}createTextureImpl(e){return this.textures.add(e),new rZ(e)}createRenderTargetImpl(e){return new r0}createUploadStreamImpl(e){return new r1(e)}getPrecision(){let e=this.gl,t="highp";if(e.getShaderPrecisionFormat){let i=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT),s=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT),r=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT),a=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT);if(i&&s&&r&&a){let e=i.precision>0&&r.precision>0,n=s.precision>0&&a.precision>0;e||(t=n?"mediump":"lowp");}}return t}getExtension(){for(let e=0;etypeof navigator?navigator.userAgent:"";this.maxPrecision=this.precision=this.getPrecision();let s=t.getContextAttributes();this.supportsMsaa=s?.antialias??false,this.supportsStencil=s?.stencil??false,this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.maxCubeMapSize=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxRenderBufferSize=t.getParameter(t.MAX_RENDERBUFFER_SIZE),this.maxTextures=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.maxCombinedTextures=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.vertexUniformsCount=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),this.fragmentUniformsCount=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),this.maxColorAttachments=t.getParameter(t.MAX_COLOR_ATTACHMENTS),this.maxVolumeSize=t.getParameter(t.MAX_3D_TEXTURE_SIZE),e=this.extDebugRendererInfo,this.unmaskedRenderer=e?t.getParameter(e.UNMASKED_RENDERER_WEBGL):"",this.unmaskedVendor=e?t.getParameter(e.UNMASKED_VENDOR_WEBGL):"",this.supportsGpuParticles=!("ARM"===this.unmaskedVendor&&i.match(/SM-[a-zA-Z0-9]+/))&&!this.unmaskedRenderer.match(/\bMali-G52+/),e=this.extTextureFilterAnisotropic,this.maxAnisotropy=e?t.getParameter(e.MAX_TEXTURE_MAX_ANISOTROPY_EXT):1;let r=!this.forceDisableMultisampling;this.maxSamples=r?t.getParameter(t.MAX_SAMPLES):1,this.maxSamples=Math.min(this.maxSamples,4),this.samples=r&&this.backBufferAntialias?this.maxSamples:1,this.supportsAreaLights=!k.android,this.maxTextures<=8&&(this.supportsAreaLights=false),this.initCapsDefines();}initializeRenderState(){super.initializeRenderState();let e=this.gl;e.disable(e.BLEND),e.blendFunc(e.ONE,e.ZERO),e.blendEquation(e.FUNC_ADD),e.colorMask(true,true,true,true),e.blendColor(0,0,0,0),e.enable(e.CULL_FACE),this.cullFace=e.BACK,e.cullFace(e.BACK),e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.depthMask(true),this.stencil=false,e.disable(e.STENCIL_TEST),this.stencilFuncFront=this.stencilFuncBack=7,this.stencilRefFront=this.stencilRefBack=0,this.stencilMaskFront=this.stencilMaskBack=255,e.stencilFunc(e.ALWAYS,0,255),this.stencilFailFront=this.stencilFailBack=0,this.stencilZfailFront=this.stencilZfailBack=0,this.stencilZpassFront=this.stencilZpassBack=0,this.stencilWriteMaskFront=255,this.stencilWriteMaskBack=255,e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.stencilMask(255),this.alphaToCoverage=false,this.raster=true,e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.disable(e.RASTERIZER_DISCARD),this.depthBiasEnabled=false,e.disable(e.POLYGON_OFFSET_FILL),this.clearDepth=1,e.clearDepth(1),this.clearColor=new es(0,0,0,0),e.clearColor(0,0,0,0),this.clearStencil=0,e.clearStencil(0),e.hint(e.FRAGMENT_SHADER_DERIVATIVE_HINT,e.NICEST),e.enable(e.SCISSOR_TEST),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),this.unpackFlipY=false,e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,false),this.unpackPremultiplyAlpha=false,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false),this.unpackAlignment=1,e.pixelStorei(e.UNPACK_ALIGNMENT,1);}initTextureUnits(e=16){this.textureUnits=[];for(let t=0;t0&&e.fullSizeClearRect&&s.invalidateFramebuffer(s.DRAW_FRAMEBUFFER,r4),i&&e.colorOps?.resolve&&e.samples>1&&t.autoResolve&&t.resolve(true,false),t.depthBuffer&&e.depthStencilOps.resolveDepth&&e.samples>1&&t.autoResolve&&t.resolve(false,true);for(let s=0;s1&&e.autoResolve&&e.resolve();let t=e._colorBuffer;t&&t.impl._glTexture&&t.mipmaps&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(t),this.gl.generateMipmap(t.impl._glTarget));}}setUnpackFlipY(e){if(this.unpackFlipY!==e){this.unpackFlipY=e;let t=this.gl;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,e);}}setUnpackPremultiplyAlpha(e){if(this.unpackPremultiplyAlpha!==e){this.unpackPremultiplyAlpha=e;let t=this.gl;t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e);}}setUnpackAlignment(e){this.unpackAlignment!==e&&(this.unpackAlignment=e,this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT,e));}activeTexture(e){this.textureUnit!==e&&(this.gl.activeTexture(this.gl.TEXTURE0+e),this.textureUnit=e);}bindTexture(e){let t=e.impl,i=t._glTarget,s=t._glTexture,r=this.textureUnit,a=this.targetToSlot[i];this.textureUnits[r][a]!==s&&(this.gl.bindTexture(i,s),this.textureUnits[r][a]=s);}bindTextureOnUnit(e,t){let i=e.impl,s=i._glTarget,r=i._glTexture,a=this.targetToSlot[s];this.textureUnits[t][a]!==r&&(this.activeTexture(t),this.gl.bindTexture(s,r),this.textureUnits[t][a]=r);}setTextureParameters(e){let t=this.gl,i=e.impl.dirtyParameterFlags,s=e.impl._glTarget;if(1&i){let i=e._minFilter;(!e._mipmaps||e._compressed&&1===e._levels.length)&&(2===i||3===i?i=0:(4===i||5===i)&&(i=1)),t.texParameteri(s,t.TEXTURE_MIN_FILTER,this.glFilter[i]);}if(2&i&&t.texParameteri(s,t.TEXTURE_MAG_FILTER,this.glFilter[e._magFilter]),4&i&&t.texParameteri(s,t.TEXTURE_WRAP_S,this.glAddress[e._addressU]),8&i&&t.texParameteri(s,t.TEXTURE_WRAP_T,this.glAddress[e._addressV]),16&i&&t.texParameteri(s,t.TEXTURE_WRAP_R,this.glAddress[e._addressW]),32&i&&t.texParameteri(s,t.TEXTURE_COMPARE_MODE,e._compareOnRead?t.COMPARE_REF_TO_TEXTURE:t.NONE),64&i&&t.texParameteri(s,t.TEXTURE_COMPARE_FUNC,this.glComparison[e._compareFunc]),128&i){let i=this.extTextureFilterAnisotropic;i&&t.texParameterf(s,i.TEXTURE_MAX_ANISOTROPY_EXT,ei.clamp(Math.round(e._anisotropy),1,this.maxAnisotropy));}}setTexture(e,t){let i=e.impl;i._glTexture||i.initialize(this,e),i.dirtyParameterFlags>0||e._needsUpload||e._needsMipmapsUpload?(this.activeTexture(t),this.bindTexture(e),i.dirtyParameterFlags&&(this.setTextureParameters(e),i.dirtyParameterFlags=0),(e._needsUpload||e._needsMipmapsUpload)&&(i.upload(this,e),e._needsUpload=false,e._needsMipmapsUpload=false)):this.bindTextureOnUnit(e,t);}createVertexArray(e){let t,i,s=e.length>1;if(s){t="";for(let i=0;i0)for(let i=0;i0)for(let s=0;s0?this.extMultiDraw.multiDrawElementsInstancedWEBGL(c,r.glCounts,0,e,r.glOffsetsBytes,0,r.glInstanceCounts,0,s.count):this.extMultiDraw.multiDrawElementsWEBGL(c,r.glCounts,0,e,r.glOffsetsBytes,0,s.count);}else i>0?this.extMultiDraw.multiDrawArraysInstancedWEBGL(c,r.glOffsetsBytes,0,r.glCounts,0,r.glInstanceCounts,0,s.count):this.extMultiDraw.multiDrawArraysWEBGL(c,r.glOffsetsBytes,0,r.glCounts,0,s.count);}else this._multiDrawLoopFallback(c,e,t,i,s);else if(e.indexed){let s=t.impl.glFormat,r=e.base*t.bytesPerIndex;i>0?a.drawElementsInstanced(c,d,s,r,i):a.drawElements(c,d,s,r);}else {let t=e.base;i>0?a.drawArraysInstanced(c,t,d,i):a.drawArrays(c,t,d);}this.transformFeedbackBuffer&&(a.endTransformFeedback(),a.bindBufferBase(a.TRANSFORM_FEEDBACK_BUFFER,0,null)),this._drawCallsPerFrame++;}a&&this.clearVertexBuffer();}clear(e){let t=this.defaultClearOptions,i=(e=e||t).flags??t.flags;if(0!==i){let s=this.gl;if(1&i){let i=e.color??t.color,s=i[0],r=i[1],a=i[2],n=i[3],o=this.clearColor;(s!==o.r||r!==o.g||a!==o.b||n!==o.a)&&(this.gl.clearColor(s,r,a,n),this.clearColor.set(s,r,a,n)),this.setBlendState(iy.NOBLEND);}if(2&i){let i=e.depth??t.depth;i!==this.clearDepth&&(this.gl.clearDepth(i),this.clearDepth=i),this.setDepthState(iT.WRITEDEPTH);}if(4&i){let i=e.stencil??t.stencil;i!==this.clearStencil&&(this.gl.clearStencil(i),this.clearStencil=i),s.stencilMask(255),this.stencilWriteMaskFront=255,this.stencilWriteMaskBack=255;}s.clear(this.glClearFlag[i]);}}submit(){this.gl.flush();}readPixels(e,t,i,s,r){let a=this.gl;a.readPixels(e,t,i,s,a.RGBA,a.UNSIGNED_BYTE,r);}clientWaitAsync(e,t){let i=this.gl,s=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);return this.submit(),new Promise((r,a)=>{!function n(){let o=i.clientWaitSync(s,e,0);o===i.TIMEOUT_EXPIRED?setTimeout(n,t):(i.deleteSync(s),o===i.WAIT_FAILED?a(Error("webgl clientWaitSync sync failed")):r());}();})}async readPixelsAsync(e,t,i,s,r,a=false){let n,o,l=this.gl;if(a)n=l.RGBA,o=l.UNSIGNED_BYTE;else {let e=this.renderTarget.colorBuffer?.impl;n=e?._glFormat??l.RGBA,o=e?._glPixelType??l.UNSIGNED_BYTE;}let h=l.createBuffer();return l.bindBuffer(l.PIXEL_PACK_BUFFER,h),l.bufferData(l.PIXEL_PACK_BUFFER,r.byteLength,l.STREAM_READ),l.readPixels(e,t,i,s,n,o,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),await this.clientWaitAsync(0,16),l.bindBuffer(l.PIXEL_PACK_BUFFER,h),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,r),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(h),r}readTextureAsync(e,t,i,s,r,a){let n=a.face??0,o=a.mipLevel??0,l=a.renderTarget??new iG({colorBuffer:e,depth:false,face:n,mipLevel:o}),h=(e=>{switch(e){case 52:return 1;case 53:return 2;default:return 0}})(e._format),c=h>0,d=e6(e._format),u=a.data??new d(ir.calcLevelGpuSize(s,r,1,e._format)/d.BYTES_PER_ELEMENT),f=c?new Uint8Array(s*r*4):u;return this.setRenderTarget(l),this.initRenderTarget(l),this.setFramebuffer(l.impl._glFrameBuffer),a.immediate&&this.gl.flush(),new Promise((e,n)=>{this.readPixelsAsync(t,i,s,r,f,c).then(t=>{if(!this._destroyed)if(a.renderTarget||l.destroy(),c){let i=s*r;for(let e=0;e{e.deleteVertexArray(t);}),this._vaoMap.clear();}set fullscreen(e){e?this.gl.canvas.requestFullscreen():document.exitFullscreen();}get fullscreen(){return !!document.fullscreenElement}constructor(e,t={}){let i,s,r,a,n;super(e,t),this._defaultFramebuffer=null,this._defaultFramebufferChanged=false,t=this.initOptions,this.updateClientRect(),this.initTextureUnits(),this.contextLost=false,this._contextLostHandler=e=>{e.preventDefault(),this.loseContext(),this.fire("devicelost");},this._contextRestoredHandler=()=>{this.restoreContext(),this.fire("devicerestored");};let o="u">typeof navigator&&navigator.userAgent;if(this.forceDisableMultisampling=o&&o.includes("AppleWebKit")&&(o.includes("15.4")||o.includes("15_4")),this.forceDisableMultisampling&&(t.antialias=false),"firefox"===k.browserName){let e=("u">typeof navigator?navigator.userAgent:"").match(/Firefox\/(\d+(\.\d+)*)/),i=e?e[1]:null;if(i){let e=parseFloat(i);("windows"===k.name&&(e>=120||115===e)||"android"===k.name&&e>=132)&&(t.antialias=false);}}this.backBufferAntialias=t.antialias??false,t.antialias=false;let l=t.gl??e.getContext("webgl2",t);if(!l)throw Error("WebGL not supported");this.gl=l,this.isWebGL2=true,this._deviceType=tY,this.updateBackbufferFormat(null);let h="chrome"===k.browserName,c="safari"===k.browserName,d=k.browser&&-1!==navigator.appVersion.indexOf("Mac");this._tempEnableSafariTextureUnitWorkaround=c,this._tempMacChromeBlitFramebufferWorkaround=d&&h&&!t.alpha,e.addEventListener("webglcontextlost",this._contextLostHandler,false),e.addEventListener("webglcontextrestored",this._contextRestoredHandler,false),this.initializeExtensions(),this.initializeCapabilities(),this.initializeRenderState(),this.initializeContextCaches(),this.createBackbuffer(null),this.supportsImageBitmap=!c&&"u">typeof ImageBitmap,this._samplerTypes=new Set([l.SAMPLER_2D,l.SAMPLER_CUBE,l.UNSIGNED_INT_SAMPLER_2D,l.INT_SAMPLER_2D,l.SAMPLER_2D_SHADOW,l.SAMPLER_CUBE_SHADOW,l.SAMPLER_3D,l.INT_SAMPLER_3D,l.UNSIGNED_INT_SAMPLER_3D,l.SAMPLER_2D_ARRAY,l.INT_SAMPLER_2D_ARRAY,l.UNSIGNED_INT_SAMPLER_2D_ARRAY]),this.glAddress=[l.REPEAT,l.CLAMP_TO_EDGE,l.MIRRORED_REPEAT],this.glBlendEquation=[l.FUNC_ADD,l.FUNC_SUBTRACT,l.FUNC_REVERSE_SUBTRACT,l.MIN,l.MAX],this.glBlendFunctionColor=[l.ZERO,l.ONE,l.SRC_COLOR,l.ONE_MINUS_SRC_COLOR,l.DST_COLOR,l.ONE_MINUS_DST_COLOR,l.SRC_ALPHA,l.SRC_ALPHA_SATURATE,l.ONE_MINUS_SRC_ALPHA,l.DST_ALPHA,l.ONE_MINUS_DST_ALPHA,l.CONSTANT_COLOR,l.ONE_MINUS_CONSTANT_COLOR],this.glBlendFunctionAlpha=[l.ZERO,l.ONE,l.SRC_COLOR,l.ONE_MINUS_SRC_COLOR,l.DST_COLOR,l.ONE_MINUS_DST_COLOR,l.SRC_ALPHA,l.SRC_ALPHA_SATURATE,l.ONE_MINUS_SRC_ALPHA,l.DST_ALPHA,l.ONE_MINUS_DST_ALPHA,l.CONSTANT_ALPHA,l.ONE_MINUS_CONSTANT_ALPHA],this.glComparison=[l.NEVER,l.LESS,l.EQUAL,l.LEQUAL,l.GREATER,l.NOTEQUAL,l.GEQUAL,l.ALWAYS],this.glStencilOp=[l.KEEP,l.ZERO,l.REPLACE,l.INCR,l.INCR_WRAP,l.DECR,l.DECR_WRAP,l.INVERT],this.glClearFlag=[0,l.COLOR_BUFFER_BIT,l.DEPTH_BUFFER_BIT,l.COLOR_BUFFER_BIT|l.DEPTH_BUFFER_BIT,l.STENCIL_BUFFER_BIT,l.STENCIL_BUFFER_BIT|l.COLOR_BUFFER_BIT,l.STENCIL_BUFFER_BIT|l.DEPTH_BUFFER_BIT,l.STENCIL_BUFFER_BIT|l.COLOR_BUFFER_BIT|l.DEPTH_BUFFER_BIT],this.glCull=[0,l.BACK,l.FRONT,l.FRONT_AND_BACK],this.glFrontFace=[l.CCW,l.CW],this.glFilter=[l.NEAREST,l.LINEAR,l.NEAREST_MIPMAP_NEAREST,l.NEAREST_MIPMAP_LINEAR,l.LINEAR_MIPMAP_NEAREST,l.LINEAR_MIPMAP_LINEAR],this.glPrimitive=[l.POINTS,l.LINES,l.LINE_LOOP,l.LINE_STRIP,l.TRIANGLES,l.TRIANGLE_STRIP,l.TRIANGLE_FAN],this.glType=[l.BYTE,l.UNSIGNED_BYTE,l.SHORT,l.UNSIGNED_SHORT,l.INT,l.UNSIGNED_INT,l.FLOAT,l.HALF_FLOAT],this.pcUniformType={},this.pcUniformType[l.BOOL]=0,this.pcUniformType[l.INT]=1,this.pcUniformType[l.FLOAT]=2,this.pcUniformType[l.FLOAT_VEC2]=3,this.pcUniformType[l.FLOAT_VEC3]=4,this.pcUniformType[l.FLOAT_VEC4]=5,this.pcUniformType[l.INT_VEC2]=6,this.pcUniformType[l.INT_VEC3]=7,this.pcUniformType[l.INT_VEC4]=8,this.pcUniformType[l.BOOL_VEC2]=9,this.pcUniformType[l.BOOL_VEC3]=10,this.pcUniformType[l.BOOL_VEC4]=11,this.pcUniformType[l.FLOAT_MAT2]=12,this.pcUniformType[l.FLOAT_MAT3]=13,this.pcUniformType[l.FLOAT_MAT4]=14,this.pcUniformType[l.SAMPLER_2D]=15,this.pcUniformType[l.SAMPLER_CUBE]=16,this.pcUniformType[l.UNSIGNED_INT]=26,this.pcUniformType[l.UNSIGNED_INT_VEC2]=27,this.pcUniformType[l.UNSIGNED_INT_VEC3]=28,this.pcUniformType[l.UNSIGNED_INT_VEC4]=29,this.pcUniformType[l.SAMPLER_2D_SHADOW]=18,this.pcUniformType[l.SAMPLER_CUBE_SHADOW]=19,this.pcUniformType[l.SAMPLER_2D_ARRAY]=25,this.pcUniformType[l.SAMPLER_3D]=20,this.pcUniformType[l.INT_SAMPLER_2D]=42,this.pcUniformType[l.UNSIGNED_INT_SAMPLER_2D]=43,this.pcUniformType[l.INT_SAMPLER_CUBE]=44,this.pcUniformType[l.UNSIGNED_INT_SAMPLER_2D]=45,this.pcUniformType[l.INT_SAMPLER_3D]=46,this.pcUniformType[l.UNSIGNED_INT_SAMPLER_3D]=47,this.pcUniformType[l.INT_SAMPLER_2D_ARRAY]=48,this.pcUniformType[l.UNSIGNED_INT_SAMPLER_2D_ARRAY]=49,this.targetToSlot={},this.targetToSlot[l.TEXTURE_2D]=0,this.targetToSlot[l.TEXTURE_CUBE_MAP]=1,this.targetToSlot[l.TEXTURE_3D]=2,this.commitFunction=[],this.commitFunction[0]=function(e,t){e.value!==t&&(l.uniform1i(e.locationId,t),e.value=t);},this.commitFunction[1]=this.commitFunction[0],this.commitFunction[2]=function(e,t){e.value!==t&&(l.uniform1f(e.locationId,t),e.value=t);},this.commitFunction[3]=function(e,t){n=e.value,i=t[0],s=t[1],(n[0]!==i||n[1]!==s)&&(l.uniform2fv(e.locationId,t),n[0]=i,n[1]=s);},this.commitFunction[4]=function(e,t){n=e.value,i=t[0],s=t[1],r=t[2],(n[0]!==i||n[1]!==s||n[2]!==r)&&(l.uniform3fv(e.locationId,t),n[0]=i,n[1]=s,n[2]=r);},this.commitFunction[5]=function(e,t){n=e.value,i=t[0],s=t[1],r=t[2],a=t[3],(n[0]!==i||n[1]!==s||n[2]!==r||n[3]!==a)&&(l.uniform4fv(e.locationId,t),n[0]=i,n[1]=s,n[2]=r,n[3]=a);},this.commitFunction[6]=function(e,t){n=e.value,i=t[0],s=t[1],(n[0]!==i||n[1]!==s)&&(l.uniform2iv(e.locationId,t),n[0]=i,n[1]=s);},this.commitFunction[9]=this.commitFunction[6],this.commitFunction[7]=function(e,t){n=e.value,i=t[0],s=t[1],r=t[2],(n[0]!==i||n[1]!==s||n[2]!==r)&&(l.uniform3iv(e.locationId,t),n[0]=i,n[1]=s,n[2]=r);},this.commitFunction[10]=this.commitFunction[7],this.commitFunction[8]=function(e,t){n=e.value,i=t[0],s=t[1],r=t[2],a=t[3],(n[0]!==i||n[1]!==s||n[2]!==r||n[3]!==a)&&(l.uniform4iv(e.locationId,t),n[0]=i,n[1]=s,n[2]=r,n[3]=a);},this.commitFunction[11]=this.commitFunction[8],this.commitFunction[12]=function(e,t){l.uniformMatrix2fv(e.locationId,false,t);},this.commitFunction[13]=function(e,t){l.uniformMatrix3fv(e.locationId,false,t);},this.commitFunction[14]=function(e,t){l.uniformMatrix4fv(e.locationId,false,t);},this.commitFunction[17]=function(e,t){l.uniform1fv(e.locationId,t);},this.commitFunction[21]=function(e,t){l.uniform2fv(e.locationId,t);},this.commitFunction[22]=function(e,t){l.uniform3fv(e.locationId,t);},this.commitFunction[23]=function(e,t){l.uniform4fv(e.locationId,t);},this.commitFunction[26]=function(e,t){e.value!==t&&(l.uniform1ui(e.locationId,t),e.value=t);},this.commitFunction[27]=function(e,t){n=e.value,i=t[0],s=t[1],(n[0]!==i||n[1]!==s)&&(l.uniform2uiv(e.locationId,t),n[0]=i,n[1]=s);},this.commitFunction[28]=function(e,t){n=e.value,i=t[0],s=t[1],r=t[2],(n[0]!==i||n[1]!==s||n[2]!==r)&&(l.uniform3uiv(e.locationId,t),n[0]=i,n[1]=s,n[2]=r);},this.commitFunction[29]=function(e,t){n=e.value,i=t[0],s=t[1],r=t[2],a=t[3],(n[0]!==i||n[1]!==s||n[2]!==r||n[3]!==a)&&(l.uniform4uiv(e.locationId,t),n[0]=i,n[1]=s,n[2]=r,n[3]=a);},this.commitFunction[30]=function(e,t){l.uniform1iv(e.locationId,t);},this.commitFunction[31]=function(e,t){l.uniform1uiv(e.locationId,t);},this.commitFunction[32]=this.commitFunction[30],this.commitFunction[33]=function(e,t){l.uniform2iv(e.locationId,t);},this.commitFunction[34]=function(e,t){l.uniform2uiv(e.locationId,t);},this.commitFunction[35]=this.commitFunction[33],this.commitFunction[36]=function(e,t){l.uniform3iv(e.locationId,t);},this.commitFunction[37]=function(e,t){l.uniform3uiv(e.locationId,t);},this.commitFunction[38]=this.commitFunction[36],this.commitFunction[39]=function(e,t){l.uniform4iv(e.locationId,t);},this.commitFunction[40]=function(e,t){l.uniform4uiv(e.locationId,t);},this.commitFunction[41]=this.commitFunction[39],this.commitFunction[24]=function(e,t){l.uniformMatrix4fv(e.locationId,false,t);},this.constantTexSource=this.scope.resolve("source"),this.postInit();}}class r6{unlock(e){}}class r8{destroy(e){}init(e,t){}loseContext(){}resolve(e,t,i,s){}}class r9{destroy(e){}loseContext(){}restoreContext(e,t){}}class r7{destroy(e){}propertyChanged(e){}loseContext(){}}class ae{destroy(e){}unlock(e){}}class at{add(e,t,i,s){}}class ai extends iz{destroy(){super.destroy();}initDeviceCaps(){this.disableParticleSystem=true,this.precision="highp",this.maxPrecision="highp",this.maxSamples=4,this.maxTextures=16,this.maxTextureSize=4096,this.maxCubeMapSize=4096,this.maxVolumeSize=4096,this.maxColorAttachments=8,this.maxPixelRatio=1,this.maxAnisotropy=16,this.supportsUniformBuffers=false,this.supportsAreaLights=true,this.supportsGpuParticles=false,this.textureFloatRenderable=true,this.textureHalfFloatRenderable=true,this.supportsImageBitmap=false;}postInit(){super.postInit();}frameStart(){super.frameStart();}frameEnd(){super.frameEnd();}updateBegin(){}updateEnd(){}readPixels(e,t,i,s,r){}createVertexBufferImpl(e,t){return new ae(e,t)}createIndexBufferImpl(e){return new r6(e)}createShaderImpl(e){return new r9(e)}createTextureImpl(e){return new r7(e)}createRenderTargetImpl(e){return new r8(e)}createDrawCommandImpl(e){return new at}createUploadStreamImpl(e){return null}draw(e,t,i,s,r=true,a=true){}setShader(e,t=false){}setBlendState(e){}setDepthState(e){}setStencilState(e,t){}setBlendColor(e,t,i,s){}setCullMode(e){}setFrontFace(e){}setAlphaToCoverage(e){}initializeContextCaches(){super.initializeContextCaches();}clear(e){}setViewport(e,t,i,s){}setScissor(e,t,i,s){}copyRenderTarget(e,t,i,s){return true}constructor(e,t={}){super(e,t),t=this.initOptions,this.isNull=true,this._deviceType=tK,this.samples=1,this.backBuffer=new iG({name:"Framebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.initDeviceCaps();}}class as{constructor(){this.scopeId=null;}}class ar{setParameter(e,t){let i=this.parameters.get(e);i||((i=new as).scopeId=this.device.scope.resolve(e),this.parameters.set(e,i)),i.value=t;}getParameter(e){return this.parameters.get(e)?.value}deleteParameter(e){this.parameters.delete(e);}destroy(){this.impl?.destroy(),this.impl=null;}applyParameters(){for(let[,e]of this.parameters)e.scopeId.setValue(e.value);}setupDispatch(e,t,i){this.countX=e,this.countY=t,this.countZ=i,this.indirectSlotIndex=-1,this.indirectBuffer=null;}setupIndirectDispatch(e,t=null){this.indirectSlotIndex=e,this.indirectBuffer=t,this.indirectFrameStamp=this.device.renderVersion;}static calcDispatchSize(e,t,i=65535){if(e<=i)return t.set(e,1);let s=Math.ceil(e/i);return t.set(Math.ceil(e/s),s)}constructor(e,t,i="Unnamed"){this.shader=null,this.parameters=new Map,this.countX=1,this.indirectSlotIndex=-1,this.indirectBuffer=null,this.indirectFrameStamp=0,this.device=e,this.shader=t,this.name=i,e.supportsCompute&&(this.impl=e.createComputeImpl(this));}}class aa{get maxCount(){return this._maxCount}get count(){return this._count}destroy(){this.impl?.destroy?.(),this.impl=null;}allocate(e){this._maxCount=e,this.impl.allocate?.(e);}add(e,t,i,s,r=0,a=0){this.impl.add(e,t,i,s,r,a);}update(e){this._count=e,this.primitiveCount=this.impl.update?.(e)??0;}constructor(e,t=0){this._maxCount=0,this.impl=null,this._count=1,this.slotIndex=0,this.primitiveCount=0,this.device=e,this.indexSizeBytes=t,this.impl=e.createDrawCommandImpl(this);}}class an{set name(e){this._name=e;}get name(){return this._name||(this._name=this.constructor.name),this._name}set enabled(e){this._enabled!==e&&(this._enabled=e,e?this.onEnable():this.onDisable());}get enabled(){return this._enabled}onEnable(){}onDisable(){}frameUpdate(){}before(){}execute(){}after(){}destroy(){}render(){this.enabled&&(this.before(),this.executeEnabled&&this.execute(),this.after(),this.device.renderPassIndex++);}constructor(e){this._enabled=true,this._skipStart=false,this._skipEnd=false,this.executeEnabled=true,this.requiresCubemaps=false,this.beforePasses=[],this.afterPasses=[],this.device=e;}}class ao{constructor(){this.clearValue=new es(0,0,0,1),this.clearValueLinear=new es(0,0,0,1),this.clear=false,this.store=false,this.resolve=true,this.genMipmaps=false;}}class al{constructor(){this.clearDepthValue=1,this.clearStencilValue=0,this.clearDepth=false,this.clearStencil=false,this.storeDepth=false,this.resolveDepth=false,this.storeStencil=false;}}class ah extends an{get colorOps(){return this.colorArrayOps[0]}set scaleX(e){this._options.scaleX=e;}get scaleX(){return this._options.scaleX}set scaleY(e){this._options.scaleY=e;}get scaleY(){return this._options.scaleY}set options(e){this._options=e,e&&(this.scaleX=this.scaleX??1,this.scaleY=this.scaleY??1);}get options(){return this._options}init(e=null,t){this.options=t,this.renderTarget=e,this.samples=Math.max(this.renderTarget?this.renderTarget.samples:this.device.samples,1),this.allocateAttachments(),this.postInit();}allocateAttachments(){let e=this.renderTarget;this.depthStencilOps=new al,e?.depthBuffer&&(this.depthStencilOps.storeDepth=true);let t=e?e._colorBuffers?.length??0:1;this.colorArrayOps.length=0;for(let e=0;ethis.vertexBuffer.numVertices&&(i=this.vertexBuffer.numVertices);let e=s.numComponents;if(this.vertexBuffer.getFormat().interleaved){let r=0;for(let a=0;ai*e){let r=i*e;if(ArrayBuffer.isView(t))t=t.subarray(0,r),s.array.set(t);else for(let e=0;e0?this.wheelDelta=1:t.deltaY<0&&(this.wheelDelta=-1)),aM()?(this.dx=t.movementX||t.webkitMovementX||t.mozMovementX||0,this.dy=t.movementY||t.webkitMovementY||t.mozMovementY||0):(this.dx=this.x-e._lastX,this.dy=this.y-e._lastY),("mousedown"===t.type||"mouseup"===t.type)&&(this.button=t.button),this.buttons=e._buttons.slice(0),this.element=t.target,this.ctrlKey=t.ctrlKey??false,this.altKey=t.altKey??false,this.shiftKey=t.shiftKey??false,this.metaKey=t.metaKey??false,this.event=t;}}class aF extends X{static isPointerLocked(){return aM()}attach(e){if(this._target=e,this._attached)return;this._attached=true;let t=!!k.passiveEvents&&{passive:false};window.addEventListener("mouseup",this._upHandler,t),window.addEventListener("mousedown",this._downHandler,t),window.addEventListener("mousemove",this._moveHandler,t),window.addEventListener("wheel",this._wheelHandler,t);}detach(){if(!this._attached)return;this._attached=false,this._target=null;let e=!!k.passiveEvents&&{passive:false};window.removeEventListener("mouseup",this._upHandler,e),window.removeEventListener("mousedown",this._downHandler,e),window.removeEventListener("mousemove",this._moveHandler,e),window.removeEventListener("wheel",this._wheelHandler,e);}disableContextMenu(){this._target&&this._target.addEventListener("contextmenu",this._contextMenuHandler);}enableContextMenu(){this._target&&this._target.removeEventListener("contextmenu",this._contextMenuHandler);}enablePointerLock(e,t){if(!document.body.requestPointerLock){t&&t();return}let i=()=>{e(),document.removeEventListener("pointerlockchange",i);},s=()=>{t(),document.removeEventListener("pointerlockerror",s);};e&&document.addEventListener("pointerlockchange",i,false),t&&document.addEventListener("pointerlockerror",s,false),document.body.requestPointerLock();}disablePointerLock(e){if(!document.exitPointerLock)return;let t=()=>{e(),document.removeEventListener("pointerlockchange",t);};e&&document.addEventListener("pointerlockchange",t,false),document.exitPointerLock();}update(){this._lastbuttons[0]=this._buttons[0],this._lastbuttons[1]=this._buttons[1],this._lastbuttons[2]=this._buttons[2];}isPressed(e){return this._buttons[e]}wasPressed(e){return this._buttons[e]&&!this._lastbuttons[e]}wasReleased(e){return !this._buttons[e]&&this._lastbuttons[e]}_handleUp(e){this._buttons[e.button]=false;let t=new aO(this,e);t.event&&this.fire("mouseup",t);}_handleDown(e){this._buttons[e.button]=true;let t=new aO(this,e);t.event&&this.fire("mousedown",t);}_handleMove(e){let t=new aO(this,e);t.event&&(this.fire("mousemove",t),this._lastX=t.x,this._lastY=t.y);}_handleWheel(e){let t=new aO(this,e);t.event&&this.fire("mousewheel",t);}_getTargetCoords(e){let t=this._target.getBoundingClientRect(),i=Math.floor(t.left),s=Math.floor(t.top);return e.clientX=i+this._target.clientWidth||e.clientY=s+this._target.clientHeight?null:{x:e.clientX-i,y:e.clientY-s}}constructor(e){super(),this._lastX=0,this._lastY=0,this._buttons=[false,false,false],this._lastbuttons=[false,false,false],this._target=null,this._attached=false,this._upHandler=this._handleUp.bind(this),this._downHandler=this._handleDown.bind(this),this._moveHandler=this._handleMove.bind(this),this._wheelHandler=this._handleWheel.bind(this),this._contextMenuHandler=e=>{e.preventDefault();},this.attach(e);}}aF.EVENT_MOUSEMOVE="mousemove",aF.EVENT_MOUSEDOWN="mousedown",aF.EVENT_MOUSEUP="mouseup",aF.EVENT_MOUSEWHEEL="mousewheel";let aN=Object.freeze([]),aB=function(){return aN};"u">typeof navigator&&(aB=(navigator.getGamepads||navigator.webkitGetGamepads||aB).bind(navigator));let ak={PAD_FACE_1:0,PAD_FACE_2:1,PAD_FACE_3:2,PAD_FACE_4:3,PAD_L_SHOULDER_1:4,PAD_R_SHOULDER_1:5,PAD_L_SHOULDER_2:6,PAD_R_SHOULDER_2:7,PAD_SELECT:8,PAD_START:9,PAD_L_STICK_BUTTON:10,PAD_R_STICK_BUTTON:11,PAD_UP:12,PAD_DOWN:13,PAD_LEFT:14,PAD_RIGHT:15,PAD_VENDOR:16,XRPAD_TRIGGER:0,XRPAD_SQUEEZE:1,XRPAD_TOUCHPAD_BUTTON:2,XRPAD_STICK_BUTTON:3,XRPAD_A:4,XRPAD_B:5},aU={PAD_L_STICK_X:0,PAD_L_STICK_Y:1,PAD_R_STICK_X:2,PAD_R_STICK_Y:3,XRPAD_TOUCHPAD_X:0,XRPAD_TOUCHPAD_Y:1,XRPAD_STICK_X:2,XRPAD_STICK_Y:3},az={DEFAULT:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"]},DEFAULT_DUAL:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"],synthesizedButtons:{PAD_UP:{axis:0,min:0,max:1},PAD_DOWN:{axis:0,min:-1,max:0},PAD_LEFT:{axis:0,min:-1,max:0},PAD_RIGHT:{axis:0,min:0,max:1}}},PS3:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_4","PAD_FACE_3","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"],mapping:"standard"},DEFAULT_XR:{buttons:["XRPAD_TRIGGER","XRPAD_SQUEEZE","XRPAD_TOUCHPAD_BUTTON","XRPAD_STICK_BUTTON","XRPAD_A","XRPAD_B"],axes:["XRPAD_TOUCHPAD_X","XRPAD_TOUCHPAD_Y","XRPAD_STICK_X","XRPAD_STICK_Y"],mapping:"xr-standard"}},aV={"Product: 0268":"PS3"},aG={};function aH(e){let t=aG[e.id];if(t)return t;for(let t in aV)if(-1!==e.id.indexOf(t)){let i=aV[t];if(!e.mapping){let e=az[`RAW_${i}`];if(e)return e}return az[i]}if("xr-standard"===e.mapping)return az.DEFAULT_XR;let i=az.DEFAULT,s=e.buttons.length0;this.wasPressed=!this.pressed&&i,this.wasReleased=this.pressed&&!i,this.wasTouched=!this.touched&&s,this.value=t,this.pressed=i,this.touched=s;}constructor(e,t){this.value=0,this.pressed=false,this.touched=false,this.wasPressed=false,this.wasReleased=false,this.wasTouched=false,"number"==typeof e?(this.value=e,this.pressed=1===e,this.touched=e>0):(this.value=e.value,this.pressed=e.pressed,this.touched=e.touched??e.value>0),t&&("number"==typeof t?(this.wasPressed=1!==t&&this.pressed,this.wasReleased=1===t&&!this.pressed,this.wasTouched=0===t&&this.touched):(this.wasPressed=!t.pressed&&this.pressed,this.wasReleased=t.pressed&&!this.pressed,this.wasTouched=!(t.touched??t.value>0)&&this.touched));}}let aY=Object.freeze(new aX(0));class aq{get connected(){return this.pad.connected}_compileMapping(){let{axes:e,buttons:t}=this._compiledMapping;e.length=0,t.length=0,this.map.axes&&this.map.axes.forEach((t,i)=>{e[aU[t]]=()=>this.pad.axes[i]||0;});for(let t=0,i=e.length;t0);let i=this.map.buttons;i&&i.forEach((e,i)=>{t[ak[e]]=()=>this._buttons[i]||aY;});let s=this.map.synthesizedButtons;s&&Object.entries(s).forEach(e=>{let{axis:i,max:s,min:r}=e[1];t[ak[e[0]]]=()=>new aX(Math.abs(ei.clamp(this._axes[i]??0,r,s)),Math.abs(ei.clamp(this._previousAxes[i]??0,r,s)));});for(let e=0,i=t.length;eaY);}update(e){this.pad=e;let t=this._previousAxes,i=this._axes;t.length=0,t.push(...i),i.length=0,i.push(...e.axes);let s=this._buttons;for(let t=0,i=s.length;te())}get buttons(){return this._compiledMapping.buttons.map(e=>e())}async pulse(e,t,i){let s=this.pad.vibrationActuator?[this.pad.vibrationActuator]:this.pad.hapticActuators||aN;if(s.length){let r=i?.startDelay??0,a=i?.strongMagnitude??e,n=i?.weakMagnitude??e;return (await Promise.all(s.map(async i=>{if(!i)return true;if(i.playEffect)return i.playEffect(i.type,{duration:t,startDelay:r,strongMagnitude:a,weakMagnitude:n});if(i.pulse)return await new Promise(e=>{setTimeout(e,r);}),i.pulse(e,t);return false}))).some(e=>true===e||"complete"===e)}return false}getButton(e){let t=this._compiledMapping.buttons[e];return t?t():aY}isPressed(e){return this.getButton(e).pressed}wasPressed(e){return this.getButton(e).wasPressed}wasReleased(e){return this.getButton(e).wasReleased}isTouched(e){return this.getButton(e).touched}wasTouched(e){return this.getButton(e).wasTouched}getValue(e){return this.getButton(e).value}getAxis(e){let t=this.axes[e];return t&&Math.abs(t)>aW?t:0}constructor(e,t){this._compiledMapping={buttons:[],axes:[]},this.id=e.id,this.index=e.index,this._buttons=e.buttons.map(e=>new aX(e)),this._axes=[...e.axes],this._previousAxes=[...e.axes],this.mapping=t.mapping,this.map=t,this.hand=e.hand||"none",this.pad=e,this._compileMapping();}}class aj extends X{set deadZone(e){aW=e;}get deadZone(){return aW}get previous(){let e=this.current;for(let t=0,i=e.length;te.index===t.index);for(;-1!==s;)i.splice(s,1),s=i.findIndex(e=>e.index===t.index);i.push(t),this.fire("gamepadconnected",t);}_ongamepaddisconnected(e){let t=this.current,i=t.findIndex(t=>t.index===e.gamepad.index);-1!==i&&(this.fire("gamepaddisconnected",t[i]),t.splice(i,1));}update(){this.poll();}poll(e=[]){e.length>0&&(e.length=0);let t=aB();for(let i=0,s=t.length;is.pulse(e,t,i)))}findById(e){return this.current.find(t=>t&&t.id===e)||null}findByIndex(e){return this.current.find(t=>t&&t.index===e)||null}constructor(){super(),this.gamepadsSupported=k.gamepads,this.current=[],this._previous=[],this._ongamepadconnectedHandler=this._ongamepadconnected.bind(this),this._ongamepaddisconnectedHandler=this._ongamepaddisconnected.bind(this),window.addEventListener("gamepadconnected",this._ongamepadconnectedHandler,false),window.addEventListener("gamepaddisconnected",this._ongamepaddisconnectedHandler,false),this.poll();}}function aK(e){let t=0,i=0,s=e.target;for(;!(s instanceof HTMLElement)&&s;)s=s.parentNode;for(;s;)t+=s.offsetLeft-s.scrollLeft,i+=s.offsetTop-s.scrollTop,s=s.offsetParent;return {x:e.pageX-t,y:e.pageY-i}}aj.EVENT_GAMEPADCONNECTED="gamepadconnected",aj.EVENT_GAMEPADDISCONNECTED="gamepaddisconnected";class a${constructor(e){let t=aK(e);this.id=e.identifier,this.x=t.x,this.y=t.y,this.target=e.target,this.touch=e;}}class aZ{getTouchById(e,t){return t.find(t=>t.id===e)||null}constructor(e,t){this.touches=[],this.changedTouches=[],this.element=t.target,this.event=t,this.touches=Array.from(t.touches).map(e=>new a$(e)),this.changedTouches=Array.from(t.changedTouches).map(e=>new a$(e));}}class aQ extends X{attach(e){this._element&&this.detach(),this._element=e,this._element.addEventListener("touchstart",this._startHandler,false),this._element.addEventListener("touchend",this._endHandler,false),this._element.addEventListener("touchmove",this._moveHandler,false),this._element.addEventListener("touchcancel",this._cancelHandler,false);}detach(){this._element&&(this._element.removeEventListener("touchstart",this._startHandler,false),this._element.removeEventListener("touchend",this._endHandler,false),this._element.removeEventListener("touchmove",this._moveHandler,false),this._element.removeEventListener("touchcancel",this._cancelHandler,false)),this._element=null;}_handleTouchStart(e){this.fire("touchstart",new aZ(this,e));}_handleTouchEnd(e){this.fire("touchend",new aZ(this,e));}_handleTouchMove(e){e.preventDefault(),this.fire("touchmove",new aZ(this,e));}_handleTouchCancel(e){this.fire("touchcancel",new aZ(this,e));}constructor(e){super(),this._element=null,this._startHandler=this._handleTouchStart.bind(this),this._endHandler=this._handleTouchEnd.bind(this),this._moveHandler=this._handleTouchMove.bind(this),this._cancelHandler=this._handleTouchCancel.bind(this),this.attach(e);}}aQ.EVENT_TOUCHSTART="touchstart",aQ.EVENT_TOUCHEND="touchend",aQ.EVENT_TOUCHMOVE="touchmove",aQ.EVENT_TOUCHCANCEL="touchcancel";class aJ{get(e,t,i){"function"==typeof t&&(i=t,t={});let s=this.request("GET",e,t,i),{progress:r}=t;if(r){let e=e=>{e.lengthComputable&&r.fire("progress",e.loaded,e.total);},t=i=>{e(i),s.removeEventListener("loadstart",e),s.removeEventListener("progress",e),s.removeEventListener("loadend",t);};s.addEventListener("loadstart",e),s.addEventListener("progress",e),s.addEventListener("loadend",t);}return s}post(e,t,i,s){return "function"==typeof i&&(s=i,i={}),i.postdata=t,this.request("POST",e,i,s)}put(e,t,i,s){return "function"==typeof i&&(s=i,i={}),i.postdata=t,this.request("PUT",e,i,s)}del(e,t,i){return "function"==typeof t&&(i=t,t={}),this.request("DELETE",e,t,i)}request(e,t,i,s){let r,a,n,o=false;if("function"==typeof i&&(s=i,i={}),i.retry&&(i=Object.assign({retries:0,maxRetries:5},i)),i.callback=s,null==i.async&&(i.async=true),null==i.headers&&(i.headers={}),null!=i.postdata)if(i.postdata instanceof Document)n=i.postdata;else if(i.postdata instanceof FormData)n=i.postdata;else if(i.postdata instanceof Object){let e=i.headers["Content-Type"];switch(void 0===e&&(i.headers["Content-Type"]=aJ.ContentType.FORM_URLENCODED,e=i.headers["Content-Type"]),e){case aJ.ContentType.FORM_URLENCODED:{n="";let e=true;for(let t in i.postdata)if(i.postdata.hasOwnProperty(t)){e?e=false:n+="&";let s=encodeURIComponent(t),r=encodeURIComponent(i.postdata[t]);n+=`${s}=${r}`;}break}default:case aJ.ContentType.JSON:null==e&&(i.headers["Content-Type"]=aJ.ContentType.JSON),n=JSON.stringify(i.postdata);}}else n=i.postdata;if(false===i.cache){let e=Q();(r=new ee(t)).query?r.query=`${r.query}&ts=${e}`:r.query=`ts=${e}`,t=r.toString();}i.query&&(a=C((r=new ee(t)).getQuery(),i.query),r.setQuery(a),t=r.toString());let l=new XMLHttpRequest;for(let s in l.open(e,t,i.async),l.withCredentials=void 0!==i.withCredentials&&i.withCredentials,l.responseType=i.responseType||this._guessResponseType(t),i.headers)i.headers.hasOwnProperty(s)&&l.setRequestHeader(s,i.headers[s]);l.onreadystatechange=()=>{this._onReadyStateChange(e,t,i,l);},l.onerror=()=>{this._onError(e,t,i,l),o=true;};try{l.send(n);}catch(e){o||i.error(l.status,l,e);}return l}_guessResponseType(e){let t=new ee(e),i=P.getExtension(t.path).toLowerCase();return aJ.binaryExtensions.indexOf(i)>=0?aJ.ResponseType.ARRAY_BUFFER:".json"===i?aJ.ResponseType.JSON:".xml"===i?aJ.ResponseType.DOCUMENT:aJ.ResponseType.TEXT}_isBinaryContentType(e){return [aJ.ContentType.BASIS,aJ.ContentType.BIN,aJ.ContentType.DDS,aJ.ContentType.GLB,aJ.ContentType.MP3,aJ.ContentType.MP4,aJ.ContentType.OGG,aJ.ContentType.OPUS,aJ.ContentType.WAV].indexOf(e)>=0}_isBinaryResponseType(e){return e===aJ.ResponseType.ARRAY_BUFFER||e===aJ.ResponseType.BLOB||e===aJ.ResponseType.JSON}_onReadyStateChange(e,t,i,s){if(4===s.readyState)switch(s.status){case 0:s.responseURL&&s.responseURL.startsWith("file:///")?this._onSuccess(e,t,i,s):this._onError(e,t,i,s);break;case 200:case 201:case 206:case 304:this._onSuccess(e,t,i,s);break;default:this._onError(e,t,i,s);}}_onSuccess(e,t,i,s){let r,a,n=s.getResponseHeader("Content-Type");n&&(a=n.split(";")[0].trim());try{r=this._isBinaryContentType(a)||this._isBinaryResponseType(s.responseType)?s.response:a===aJ.ContentType.JSON||t.split("?")[0].endsWith(".json")?JSON.parse(s.responseText):s.responseType===aJ.ResponseType.DOCUMENT||a===aJ.ContentType.XML?s.responseXML:s.responseText,i.callback(null,r);}catch(e){i.callback(e);}}_onError(e,t,i,s){i.retrying||(i.retry&&i.retries{i.retrying=false,this.request(e,t,i,i.callback);},ei.clamp(Math.pow(2,i.retries)*aJ.retryDelay,0,i.maxRetryDelay||5e3))):i.callback(0===s.status?"Network error":s.status,null));}}aJ.ContentType={AAC:"audio/aac",BASIS:"image/basis",BIN:"application/octet-stream",DDS:"image/dds",FORM_URLENCODED:"application/x-www-form-urlencoded",GIF:"image/gif",GLB:"model/gltf-binary",JPEG:"image/jpeg",JSON:"application/json",MP3:"audio/mpeg",MP4:"audio/mp4",OGG:"audio/ogg",OPUS:'audio/ogg; codecs="opus"',PNG:"image/png",TEXT:"text/plain",WAV:"audio/x-wav",XML:"application/xml"},aJ.ResponseType={TEXT:"text",ARRAY_BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json"},aJ.binaryExtensions=[".model",".wav",".ogg",".mp3",".mp4",".m4a",".aac",".dds",".basis",".glb",".opus"],aJ.retryDelay=100;let a0=new aJ,a1="linear",a2="inverse",a3="exponential";class a4{getPosition(){return this.position}setPosition(e){this.position.copy(e);let t=this.listener;t&&("positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z));}setOrientation(e){this.orientation.copy(e);let t=this.listener;if(t){let i=e.data;"forwardX"in t?(t.forwardX.value=-i[8],t.forwardY.value=-i[9],t.forwardZ.value=-i[10],t.upX.value=i[4],t.upY.value=i[5],t.upZ.value=i[6]):t.setOrientation&&t.setOrientation(-i[8],-i[9],-i[10],i[4],i[5],i[6]);}}getOrientation(){return this.orientation}get listener(){let e=this._manager.context;return e?e.listener:null}constructor(e){this.position=new ed,this.orientation=new ey,this._manager=e;}}let a5="running",a6=["click","touchstart","mousedown"];class a8 extends X{set volume(e){e=ei.clamp(e,0,1),this._volume=e,this.fire("volumechange",e);}get volume(){return this._volume}get suspended(){return this._userSuspended}get context(){return !this._context&&this.AudioContext&&(this._context=new this.AudioContext,this._context.state!==a5&&this._registerUnlockListeners()),this._context}suspend(){!this._userSuspended&&(this._userSuspended=true,this._context&&this._context.state===a5&&this._suspend());}resume(){this._userSuspended&&(this._userSuspended=false,this._context&&this._context.state!==a5&&this._resume());}destroy(){this.fire("destroy"),this._context&&(this._removeUnlockListeners(),this._context?.close(),this._context=null);}_resume(){this._context.resume().then(()=>{let e=this._context.createBufferSource();e.buffer=this._context.createBuffer(1,1,this._context.sampleRate),e.connect(this._context.destination),e.start(0),e.onended=t=>{e.disconnect(0),this.fire("resume");};},e=>{}).catch(e=>{});}_suspend(){this._context.suspend().then(()=>{this.fire("suspend");},e=>{}).catch(e=>{});}_unlockHandler(){this._removeUnlockListeners(),this._userSuspended||this._context.state===a5||this._resume();}_registerUnlockListeners(){a6.forEach(e=>{window.addEventListener(e,this._unlockHandlerFunc,false);});}_removeUnlockListeners(){a6.forEach(e=>{window.removeEventListener(e,this._unlockHandlerFunc,false);});}constructor(){super(),this._context=null,this.AudioContext="u">typeof AudioContext&&AudioContext||"u">typeof webkitAudioContext&&webkitAudioContext,this.AudioContext,this._unlockHandlerFunc=this._unlockHandler.bind(this),this._userSuspended=false,this.listener=new a4(this),this._volume=1;}}class a9{get duration(){let e=0;return this.buffer?e=this.buffer.duration:this.audio&&(e=this.audio.duration),e||0}constructor(e){e instanceof Audio?this.audio=e:this.buffer=e;}}function a7(){return "u">typeof AudioContext||"u">typeof webkitAudioContext}class ne extends X{set currentTime(e){if(!(e<0))if(0===this._state){let t=this._suspendInstanceEvents;this._suspendInstanceEvents=true,this.stop(),this._startOffset=e,this.play(),this._suspendInstanceEvents=t;}else this._startOffset=e,this._currentTime=e;}get currentTime(){return null!==this._startOffset?this._startOffset:1===this._state?this._currentTime:2!==this._state&&this.source?(this._updateCurrentTime(),this._currentTime):0}set duration(e){this._duration=Math.max(0,Number(e)||0);let t=0===this._state;this.stop(),t&&this.play();}get duration(){if(!this._sound)return 0;if(this._duration)return this._duration%this._sound.duration||0;return this._sound.duration}get isPaused(){return 1===this._state}get isPlaying(){return 0===this._state}get isStopped(){return 2===this._state}get isSuspended(){return this._suspended}set loop(e){this._loop=!!e,this.source&&(this.source.loop=this._loop);}get loop(){return this._loop}set pitch(e){this._currentOffset=this.currentTime,this._startedAt=this._manager.context.currentTime,this._pitch=Math.max(Number(e)||0,.01),this.source&&(this.source.playbackRate.value=this._pitch);}get pitch(){return this._pitch}set sound(e){this._sound=e,2!==this._state?this.stop():this._createSource();}get sound(){return this._sound}set startTime(e){this._startTime=Math.max(0,Number(e)||0);let t=0===this._state;this.stop(),t&&this.play();}get startTime(){return this._startTime}set volume(e){e=ei.clamp(e,0,1),this._volume=e,this.gain&&(this.gain.gain.value=e*this._manager.volume);}get volume(){return this._volume}_onPlay(){this.fire("play"),this._onPlayCallback&&this._onPlayCallback(this);}_onPause(){this.fire("pause"),this._onPauseCallback&&this._onPauseCallback(this);}_onResume(){this.fire("resume"),this._onResumeCallback&&this._onResumeCallback(this);}_onStop(){this.fire("stop"),this._onStopCallback&&this._onStopCallback(this);}_onEnded(){this._suspendEndEvent>0?this._suspendEndEvent--:(this.fire("end"),this._onEndCallback&&this._onEndCallback(this),this.stop());}_onManagerVolumeChange(){this.volume=this._volume;}_onManagerSuspend(){0!==this._state||this._suspended||(this._suspended=true,this.pause());}_onManagerResume(){this._suspended&&(this._suspended=false,this.resume());}_initializeNodes(){this.gain=this._manager.context.createGain(),this._inputNode=this.gain,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination);}play(){return 2!==this._state&&this.stop(),this._state=0,this._playWhenLoaded=false,!this._waitingContextSuspension&&(this._manager.suspended?(this._manager.once("resume",this._playAudioImmediate,this),this._waitingContextSuspension=true,false):(this._playAudioImmediate(),true))}_playAudioImmediate(){if(this._waitingContextSuspension=false,0!==this._state)return;this.source||this._createSource();let e=this._startOffset%this.duration||0;e=(this._startTime+e)%this._sound.duration||0,this._startOffset=null,this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentTime=0,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._suspendInstanceEvents||this._onPlay();}pause(){return this._playWhenLoaded=false,0===this._state&&(this._state=1,!!this._waitingContextSuspension||(this._updateCurrentTime(),this._suspendEndEvent++,this.source.stop(0),this.source=null,this._startOffset=null,this._suspendInstanceEvents||this._onPause(),true))}resume(){if(1!==this._state)return false;let e=this.currentTime;if(this._state=0,this._waitingContextSuspension)return true;(this.source||this._createSource(),null!==this._startOffset)&&(e=this._startOffset%this.duration||0,e=(this._startTime+e)%this._sound.duration||0,this._startOffset=null);return this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._playWhenLoaded=false,this._suspendInstanceEvents||this._onResume(),true}stop(){if(this._playWhenLoaded=false,2===this._state)return false;let e=0===this._state;return this._state=2,!!this._waitingContextSuspension||(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._startOffset=null,this._suspendEndEvent++,e&&this.source&&this.source.stop(0),this.source=null,this._suspendInstanceEvents||this._onStop(),true)}setExternalNodes(e,t){if(!e)return;t||(t=e);let i=this._manager.context.destination;this._firstNode!==e&&(this._firstNode?this._connectorNode.disconnect(this._firstNode):this._connectorNode.disconnect(i),this._firstNode=e,this._connectorNode.connect(e)),this._lastNode!==t&&(this._lastNode&&this._lastNode.disconnect(i),this._lastNode=t,this._lastNode.connect(i));}clearExternalNodes(){let e=this._manager.context.destination;this._firstNode&&(this._connectorNode.disconnect(this._firstNode),this._firstNode=null),this._lastNode&&(this._lastNode.disconnect(e),this._lastNode=null),this._connectorNode.connect(e);}getExternalNodes(){return [this._firstNode,this._lastNode]}_createSource(){if(!this._sound)return null;let e=this._manager.context;this._sound.buffer&&(this.source=e.createBufferSource(),this.source.buffer=this._sound.buffer,this.source.connect(this._inputNode),this.source.onended=this._endedHandler,this.source.loopStart=this._startTime%this.source.buffer.duration||0,this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,(this._startTime+this._duration)%this.source.buffer.duration||0)));return this.source}_updateCurrentTime(){this._currentTime=((this._manager.context.currentTime-this._startedAt)*this._pitch+this._currentOffset)%this.duration||0;}_onManagerDestroy(){this.source&&0===this._state&&(this.source.stop(0),this.source=null);}constructor(e,t,i){super(),this.source=null,this._manager=e,this._volume=void 0!==i.volume?ei.clamp(Number(i.volume)||0,0,1):1,this._pitch=void 0!==i.pitch?Math.max(.01,Number(i.pitch)||0):1,this._loop=!!(void 0!==i.loop&&i.loop),this._sound=t,this._state=2,this._suspended=false,this._suspendEndEvent=0,this._suspendInstanceEvents=false,this._playWhenLoaded=true,this._startTime=Math.max(0,Number(i.startTime)||0),this._duration=Math.max(0,Number(i.duration)||0),this._startOffset=null,this._onPlayCallback=i.onPlay,this._onPauseCallback=i.onPause,this._onResumeCallback=i.onResume,this._onStopCallback=i.onStop,this._onEndCallback=i.onEnd,a7()?(this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._inputNode=null,this._connectorNode=null,this._firstNode=null,this._lastNode=null,this._waitingContextSuspension=false,this._initializeNodes(),this._endedHandler=this._onEnded.bind(this)):(this._isReady=false,this._loadedMetadataHandler=this._onLoadedMetadata.bind(this),this._timeUpdateHandler=this._onTimeUpdate.bind(this),this._endedHandler=this._onEnded.bind(this),this._createSource());}}ne.EVENT_PLAY="play",ne.EVENT_PAUSE="pause",ne.EVENT_RESUME="resume",ne.EVENT_STOP="stop",ne.EVENT_END="end",a7()||(Object.assign(ne.prototype,{play:function(){return 2!==this._state&&this.stop(),(!!this.source||!!this._createSource())&&(this.volume=this._volume,this.pitch=this._pitch,this.loop=this._loop,this.source.play(),this._state=0,this._playWhenLoaded=false,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._manager.suspended&&this._onManagerSuspend(),this._suspendInstanceEvents||this._onPlay(),true)},pause:function(){return !!this.source&&0===this._state&&(this._suspendEndEvent++,this.source.pause(),this._playWhenLoaded=false,this._state=1,this._startOffset=null,this._suspendInstanceEvents||this._onPause(),true)},resume:function(){return !!this.source&&1===this._state&&(this._state=0,this._playWhenLoaded=false,this.source.paused&&(this.source.play(),this._suspendInstanceEvents||this._onResume()),true)},stop:function(){return !!this.source&&2!==this._state&&(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._suspendEndEvent++,this.source.pause(),this._playWhenLoaded=false,this._state=2,this._startOffset=null,this._suspendInstanceEvents||this._onStop(),true)},setExternalNodes:function(){},clearExternalNodes:function(){},getExternalNodes:function(){return [null,null]},_onLoadedMetadata:function(){this.source.removeEventListener("loadedmetadata",this._loadedMetadataHandler),this._isReady=true;let e=this._startOffset%this.duration||0;e=(this._startTime+e)%this._sound.duration||0,this._startOffset=null,this.source.currentTime=e;},_createSource:function(){return this._sound&&this._sound.audio&&(this._isReady=false,this.source=this._sound.audio.cloneNode(true),this.source.addEventListener("loadedmetadata",this._loadedMetadataHandler),this.source.addEventListener("timeupdate",this._timeUpdateHandler),this.source.onended=this._endedHandler),this.source},_onTimeUpdate:function(){this._duration&&this.source.currentTime>((this._startTime+this._duration)%this.source.duration||0)&&(this.loop?this.source.currentTime=this._startTime%this.source.duration||0:(this.source.removeEventListener("timeupdate",this._timeUpdateHandler),this.source.pause(),this._onEnded()));},_onManagerDestroy:function(){this.source&&this.source.pause();}}),Object.defineProperty(ne.prototype,"volume",{get:function(){return this._volume},set:function(e){e=ei.clamp(e,0,1),this._volume=e,this.source&&(this.source.volume=e*this._manager.volume);}}),Object.defineProperty(ne.prototype,"pitch",{get:function(){return this._pitch},set:function(e){this._pitch=Math.max(Number(e)||0,.01),this.source&&(this.source.playbackRate=this._pitch);}}),Object.defineProperty(ne.prototype,"sound",{get:function(){return this._sound},set:function(e){this.stop(),this._sound=e;}}),Object.defineProperty(ne.prototype,"currentTime",{get:function(){return null!==this._startOffset?this._startOffset:2!==this._state&&this.source?this.source.currentTime-this._startTime:0},set:function(e){!(e<0)&&(this._startOffset=e,this.source&&this._isReady)&&(this.source.currentTime=(this._startTime+(e%this.duration||0))%this._sound.duration||0,this._startOffset=null);}}));class nt extends ne{_initializeNodes(){this.gain=this._manager.context.createGain(),this.panner=this._manager.context.createPanner(),this.panner.connect(this.gain),this._inputNode=this.panner,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination);}set position(e){this._position.copy(e);let t=this.panner;"positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z);}get position(){return this._position}set velocity(e){this._velocity.copy(e);}get velocity(){return this._velocity}set maxDistance(e){this.panner.maxDistance=e;}get maxDistance(){return this.panner.maxDistance}set refDistance(e){this.panner.refDistance=e;}get refDistance(){return this.panner.refDistance}set rollOffFactor(e){this.panner.rolloffFactor=e;}get rollOffFactor(){return this.panner.rolloffFactor}set distanceModel(e){this.panner.distanceModel=e;}get distanceModel(){return this.panner.distanceModel}constructor(e,t,i={}){super(e,t,i),this._position=new ed,this._velocity=new ed,i.position&&(this.position=i.position),this.maxDistance=void 0!==i.maxDistance?Number(i.maxDistance):1e4,this.refDistance=void 0!==i.refDistance?Number(i.refDistance):1,this.rollOffFactor=void 0!==i.rollOffFactor?Number(i.rollOffFactor):1,this.distanceModel=void 0!==i.distanceModel?i.distanceModel:a1;}}if(!a7()){let e=new ed,t=function(t,i,s,r,a,n){let o=(e=e.sub2(t,i)).length();if(or)return 0;let l=0;return n===a1?l=1-a*(o-s)/(r-s):n===a2?l=s/(s+a*(o-s)):n===a3&&(l=Math.pow(o/s,-a)),ei.clamp(l,0,1)};Object.defineProperty(nt.prototype,"position",{get:function(){return this._position},set:function(e){if(this._position.copy(e),this.source){let e=t(this._manager.listener.getPosition(),this._position,this.refDistance,this.maxDistance,this.rollOffFactor,this.distanceModel),i=this.volume;this.source.volume=i*e*this._manager.volume;}}}),Object.defineProperty(nt.prototype,"maxDistance",{get:function(){return this._maxDistance},set:function(e){this._maxDistance=e;}}),Object.defineProperty(nt.prototype,"refDistance",{get:function(){return this._refDistance},set:function(e){this._refDistance=e;}}),Object.defineProperty(nt.prototype,"rollOffFactor",{get:function(){return this._rollOffFactor},set:function(e){this._rollOffFactor=e;}}),Object.defineProperty(nt.prototype,"distanceModel",{get:function(){return this._distanceModel},set:function(e){this._distanceModel=e;}});}let ni={0:"SUBTRACTIVE",1:"ADDITIVE",2:"NORMAL",3:"NONE",4:"PREMULTIPLIED",5:"MULTIPLICATIVE",6:"ADDITIVEALPHA",7:"MULTIPLICATIVE2X",8:"SCREEN",9:"MIN",10:"MAX"},ns="none",nr="linear",na={0:"NONE",2:"SCHLICK"},nn={0:"DIRECTIONAL",1:"OMNI",2:"SPOT"},no={0:"PUNCTUAL",1:"RECT",2:"DISK",3:"SPHERE"},nl={0:"LINEAR",1:"INVERSESQUARED"},nh=new Map([[5,{name:"PCF1_32F",kind:"PCF1",format:16,pcf:true}],[0,{name:"PCF3_32F",kind:"PCF3",format:16,pcf:true}],[4,{name:"PCF5_32F",kind:"PCF5",format:16,pcf:true}],[7,{name:"PCF1_16F",kind:"PCF1",format:69,pcf:true}],[8,{name:"PCF3_16F",kind:"PCF3",format:69,pcf:true}],[9,{name:"PCF5_16F",kind:"PCF5",format:69,pcf:true}],[2,{name:"VSM_16F",kind:"VSM",format:12,vsm:true}],[3,{name:"VSM_32F",kind:"VSM",format:14,vsm:true}],[6,{name:"PCSS_32F",kind:"PCSS",format:15,pcss:true}]]),nc={0:"NONE",1:"BOX"},nd={0:"NONE",1:"SRGB"},nu=["LINEAR","FILMIC","HEJL","ACES","ACES2","NEUTRAL","NONE"],nf={0:"NONE",1:"AO",2:"GLOSSDEPENDENT"},np="none",nm="envAtlas",n_="envAtlasHQ",ng="cubeMap",nv="sphereMap",nS={[np]:"NONE",[nm]:"ENVATLAS",[n_]:"ENVATLASHQ",[ng]:"CUBEMAP",[nv]:"SPHEREMAP"},ny="ambientSH",nx="envAtlas",nT="constant",nE={[ny]:"AMBIENTSH",[nx]:"ENVALATLAS",[nT]:"CONSTANT"},nw={0:"SIMPLE",1:"SLICED",2:"TILED"},nb="infinite",nC="dome",nA="none",nP="bayer8",nI="bluenoise",nD="ignnoise",nR={[nA]:"NONE",[nP]:"BAYER8",[nI]:"BLUENOISE",[nD]:"IGNNOISE"},nL="prerender",nM="postrender",nO="prerender:layer",nF="postrender:layer",nN="precull",nB="postcull",nk="cull:end",nU="pcShadowCamera",nz="compact";class nV{hasUniform(e){for(let t=0;tt.name===e)}generateKey(e){let t=JSON.stringify(this.uniformFormats)+JSON.stringify(this.bindGroupFormats);return e.isWebGPU&&(t+=this.vertexFormat?.shaderProcessingHashString),t}constructor(e,t,i){this.uniformFormats=[],this.bindGroupFormats=[],this.uniformFormats[0]=e,this.bindGroupFormats[0]=t,this.vertexFormat=i;}}let nG=new is;function nH(e){return nG.get(e)}class nW{static definesHash(e){return iL(JSON.stringify(Array.from(e).sort((e,t)=>e[0]>t[0]?1:-1)))}}let nX=new is;class nY{buildShaderDefines(){let e;this.isShadow?e="SHADOW":this.isForward?e="FORWARD":3===this.index?e="PICK":4===this.index&&(e="PICK",this.defines.set("DEPTH_PICK_PASS","")),this.defines.set(`${e}_PASS`,""),this.defines.set(`${this.name.toUpperCase()}_PASS`,"");}constructor(e,t,i={}){this.defines=new Map,this.name=e,this.index=t,Object.assign(this,i),this.buildShaderDefines();}}class nq{static get(e){return nX.get(e,()=>new nq)}allocate(e,t){let i=this.passesNamed.get(e);return void 0===i&&(i=new nY(e,this.nextIndex,t),this.passesNamed.set(i.name,i),this.passesIndexed[i.index]=i,this.nextIndex++),i}getByIndex(e){return this.passesIndexed[e]}getByName(e){return this.passesNamed.get(e)}constructor(){this.passesNamed=new Map,this.passesIndexed=[],this.nextIndex=0;let e=(e,t,i)=>{this.allocate(e,i);};e("forward",0,{isForward:true}),e("prepass"),e("shadow"),e("pick"),e("depth_pick");}}class nj extends Map{set(e,t){return this.has(e)&&this.get(e)===t||this.markDirty(),super.set(e,t)}add(e,t=true){for(let[i,s]of Object.entries(e))(t||!this.has(i))&&this.set(i,s);return this}delete(e){let t=this.has(e),i=super.delete(e);return t&&i&&this.markDirty(),i}clear(){this.size>0&&this.markDirty(),super.clear();}markDirty(){this._dirty=true,this._keyDirty=true;}isDirty(){return this._dirty}resetDirty(){this._dirty=false;}get key(){return this._keyDirty&&(this._keyDirty=false,this._key=Array.from(this.entries()).sort(([e],[t])=>et)).map(([e,t])=>`${e}=${iL(t)}`).join(",")),this._key}copy(e){for(let[t,i]of(this.clear(),e))this.set(t,i);return this}constructor(e){super(),this._keyDirty=false,this._key="",this._validations=e;}}let nK=new is;class n${static get(e,t=tz){let i=nK.get(e,()=>new n$);return t===tz?i.glsl:i.wgsl}static registerValidation(e,t){}get useWGSL(){return 0===this.glsl.size||this.wgsl.size>0}get key(){return `GLSL:${this.glsl.key}|WGSL:${this.wgsl.key}|API:${this.version}`}isDirty(){return this.glsl.isDirty()||this.wgsl.isDirty()}resetDirty(){this.glsl.resetDirty(),this.wgsl.resetDirty();}copy(e){return this.version=e.version,this.glsl.copy(e.glsl),this.wgsl.copy(e.wgsl),this}constructor(){this.glsl=new nj(n$._validations),this.wgsl=new nj(n$._validations),this.version="";}}n$._validations=new Map;class nZ{static merge(...e){let t=new Map(e[0]??[]);for(let i=1;ii.set(t,e)),nq.get(t.device).getByIndex(t.pass).defines.forEach((e,t)=>i.set(t,e)),i}static processShader(e,t){let i=e.definition,s=i.name??"shader",r=new nQ(`${s}-id-${e.id}`,i),a="shader",n=nH(e.device);n.register(a,r);let o=n.getProgram(a,{},t);return n.unregister(a),o}static addScreenDepthChunkDefines(e,t,i){t.sceneDepthMapLinear&&i.set("SCENE_DEPTHMAP_LINEAR",""),e.textureFloatRenderable&&i.set("SCENE_DEPTHMAP_FLOAT","");}}let n0={type:4,base:0,count:6,indexed:true},n1=new ep,n2=new ep,n3=new ig;class n4{destroy(){this.uniformBuffer?.destroy(),this.uniformBuffer=null,this.bindGroup?.destroy(),this.bindGroup=null;}render(e,t,i){let s=this.shader.device;e&&(n1.set(s.vx,s.vy,s.vw,s.vh),n2.set(s.sx,s.sy,s.sw,s.sh),t=t??e,s.setViewport(e.x,e.y,e.z,e.w),s.setScissor(t.x,t.y,t.z,t.w)),s.setVertexBuffer(s.quadVertexBuffer);let r=this.shader;if(s.setShader(r),s.supportsUniformBuffers){s.setBindGroup(0,s.emptyBindGroup);let e=this.bindGroup;e.update(),s.setBindGroup(1,e);let t=this.uniformBuffer;t?(t.update(n3),s.setBindGroup(2,n3.bindGroup,n3.offsets)):s.setBindGroup(2,s.emptyBindGroup);}s.draw(n0,s.quadIndexBuffer,i),e&&(s.setViewport(n1.x,n1.y,n1.z,n1.w),s.setScissor(n2.x,n2.y,n2.z,n2.w));}constructor(e){let t=e.device;if(this.shader=e,t.supportsUniformBuffers){let i=new nV;this.shader=nJ.processShader(e,i);let s=this.shader.meshUniformBufferFormat;s&&(this.uniformBuffer=new rx(t,s,false));let r=this.shader.meshBindGroupFormat;this.bindGroup=new iv(t,r);}}}class n5 extends ah{execute(){let{device:e}=this;e.setDrawStates(e.blendState),this.quad.render(this.rect,this.scissorRect);}constructor(e,t,i,s){super(e),this.quad=t,this.rect=i,this.scissorRect=s;}}let n6=new ep;function n8(e,t,i,s,r){let a=new n4(i);s||((s=n6).x=0,s.y=0,s.z=t?t.width:e.width,s.w=t?t.height:e.height);let n=new n5(e,a,s,r);n.init(t),n.colorOps.clear=false,n.depthStencilOps.clearDepth=false,e.isWebGPU&&null===t&&e.samples>1&&(n.colorOps.store=true),n.render(),a.destroy();}class n9{destroy(e,t){this.meshInstance&&(this.removeFromLayers(e,t),this.meshInstance.destroy(),this.meshInstance=null);}addToLayers(e,t){for(let i=0;i=0;e--)this.matrices[e].mulAffine2(oe,this.bones[e].getWorldTransform()),this.matrices[e].mulAffine2(this.matrices[e],this.skin.inverseBindPose[e]);}}updateMatrices(e,t){this._updateBeforeCull&&this._updateMatrices(e,t);}updateMatrixPalette(e,t){this._updateMatrices(e,t);let i=this.matrixPalette,s=this.bones.length;for(let e=0;e0){let m=_.array[_.index+f];if(d[m]=true,t=p.array[p.index],i=p.array[p.index+1],s=p.array[p.index+2],r=c[m],(a=h[m]).x>t&&(a.x=t),a.y>i&&(a.y=i),a.z>s&&(a.z=s),r.xh&&(a.x=h),a.y>c&&(a.y=c),a.z>d&&(a.z=d),r.xe.name===e8);if(v&&v.normalize){let e=(()=>{switch(v.dataType){case 0:return e=>Math.max(e/127,-1);case 1:return e=>e/255;case 2:return e=>Math.max(e/32767,-1);case 3:return e=>e/65535;default:return e=>e}})();for(let t=0;t0&&this.indexBuffer[0]&&(this._geometryData.indexCount=this.indexBuffer[0].numIndices,this._geometryData.maxIndices=this.indexBuffer[0].numIndices));}clear(e,t,i=0,s=0){this._initGeometryData(),this._geometryData.initDefaults(),this._geometryData.recreate=true,this._geometryData.maxVertices=i,this._geometryData.maxIndices=s,this._geometryData.verticesUsage=+!e,this._geometryData.indicesUsage=+!t;}setVertexStream(e,t,i,s,r=6,a=false,n=false){this._initGeometryData();let o=s||t.length/i;this._geometryData._changeVertexCount(o,e),this._geometryData.vertexStreamsUpdated=true,this._geometryData.vertexStreamDictionary[e]=new oa(t,i,r,a,n);}getVertexStream(e,t){let i=0,s=false;if(this._geometryData){let r=this._geometryData.vertexStreamDictionary[e];r&&(s=true,i=this._geometryData.vertexCount,ArrayBuffer.isView(t)?t.set(r.data):(t.length=0,t.push(r.data)));}return !s&&this.vertexBuffer&&(i=new aE(this.vertexBuffer).readData(e,t)),i}setPositions(e,t=or.DEFAULT_COMPONENTS_POSITION,i){this.setVertexStream(e8,e,t,i,6,false);}setNormals(e,t=or.DEFAULT_COMPONENTS_NORMAL,i){this.setVertexStream(e9,e,t,i,6,false);}setUvs(e,t,i=or.DEFAULT_COMPONENTS_UV,s){this.setVertexStream(ts+e,t,i,s,6,false);}setColors(e,t=or.DEFAULT_COMPONENTS_COLORS,i){this.setVertexStream(ti,e,t,i,6,false);}setColors32(e,t){this.setVertexStream(ti,e,or.DEFAULT_COMPONENTS_COLORS,t,1,true);}setIndices(e,t){this._initGeometryData(),this._geometryData.indexStreamUpdated=true,this._geometryData.indices=e,this._geometryData.indexCount=t||e.length;}getPositions(e){return this.getVertexStream(e8,e)}getNormals(e){return this.getVertexStream(e9,e)}getUvs(e,t){return this.getVertexStream(ts+e,t)}getColors(e){return this.getVertexStream(ti,e)}getIndices(e){let t=0;if(this._geometryData&&this._geometryData.indices){let i=this._geometryData.indices;if(t=this._geometryData.indexCount,ArrayBuffer.isView(e))e.set(i);else {e.length=0;for(let t=0,s=i.length;t0&&this.indexBuffer[0]&&(t=this.indexBuffer[0].readData(e));return t}update(e=4,t=true){if(this._geometryData){if(t){let e=this._geometryData.vertexStreamDictionary[e8];e&&3===e.componentCount&&(this._aabb.compute(e.data,this._geometryData.vertexCount),this._aabbVer++);}let i=this._geometryData.recreate;this._geometryData.vertexCount>this._geometryData.maxVertices&&(i=true,this._geometryData.maxVertices=this._geometryData.vertexCount),i&&this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);let s=this._geometryData.recreate;this._geometryData.indexCount>this._geometryData.maxIndices&&(s=true,this._geometryData.maxIndices=this._geometryData.indexCount),s&&this.indexBuffer.length>0&&this.indexBuffer[0]&&(this.indexBuffer[0].destroy(),this.indexBuffer[0]=null),this._geometryData.vertexStreamsUpdated&&this._updateVertexBuffer(),this._geometryData.indexStreamUpdated&&this._updateIndexBuffer(),this.primitive[0].type=e,this.indexBuffer.length>0&&this.indexBuffer[0]?this._geometryData.indexStreamUpdated&&(this.primitive[0].count=this._geometryData.indexCount,this.primitive[0].indexed=true):this._geometryData.vertexStreamsUpdated&&(this.primitive[0].count=this._geometryData.vertexCount,this.primitive[0].indexed=false),this._geometryData.vertexCount=0,this._geometryData.indexCount=0,this._geometryData.vertexStreamsUpdated=false,this._geometryData.indexStreamUpdated=false,this._geometryData.recreate=false,this.updateRenderStates();}}_buildVertexFormat(e){let t=[];for(let e in this._geometryData.vertexStreamDictionary){let i=this._geometryData.vertexStreamDictionary[e];t.push({semantic:e,components:i.componentCount,type:i.dataType,normalize:i.dataTypeNormalize,asInt:i.asInt});}return new iB(this.device,t,e)}_updateVertexBuffer(){if(!this.vertexBuffer){let e=this._geometryData.maxVertices,t=this._buildVertexFormat(e);this.vertexBuffer=new iR(this.device,t,e,{usage:this._geometryData.verticesUsage,storage:this._storageVertex});}let e=new aE(this.vertexBuffer),t=this._geometryData.vertexCount;for(let i in this._geometryData.vertexStreamDictionary){let s=this._geometryData.vertexStreamDictionary[i];e.writeData(i,s.data,t),delete this._geometryData.vertexStreamDictionary[i];}e.end();}_updateIndexBuffer(){if(this.indexBuffer.length<=0||!this.indexBuffer[0]){let e=this._geometryData.maxVertices,t=this._storageIndex?{storage:true}:void 0;this.indexBuffer[0]=new iw(this.device,e>65535||0===e?2:1,this._geometryData.maxIndices,this._geometryData.indicesUsage,void 0,t);}let e=this._geometryData.indices;e&&(this.indexBuffer[0].writeData(e,this._geometryData.indexCount),this._geometryData.indices=null);}prepareRenderState(e){1===e?this.generateWireframe():2===e&&(this.primitive[2]={type:0,base:0,baseVertex:0,count:this.vertexBuffer?this.vertexBuffer.numVertices:0,indexed:false});}updateRenderStates(){this.primitive[2]&&this.prepareRenderState(2),this.primitive[1]&&this.prepareRenderState(1);}generateWireframe(){let e,t;this._destroyIndexBuffer(1);let i=this.vertexBuffer.numVertices;if(this.indexBuffer.length>0&&this.indexBuffer[0]){let s=[[0,1],[1,2],[2,0]],r=this.primitive[0].base,a=this.primitive[0].count,n=this.primitive[0].baseVertex||0,o=this.indexBuffer[0],l=t2[o.format],h=new l(o.storage),c=new l(2*a),d=new Set,u=0;for(let e=r;ea?a*i+r:r*i+a;d.has(o)||(d.add(o),c[u++]=r,c[u++]=a);}d.clear(),t=o.format,e=c.slice(0,u);}else {let s=i-i%3,r=s/3*6;t=r>65535?2:1,e=r>65535?new Uint32Array(r):new Uint16Array(r);let a=0;for(let t=0;t{t.destroy();}),this.cache.clear();}incRef(e){let t=(this.cache.get(e)||0)+1;this.cache.set(e,t);}decRef(e){if(e){let t=this.cache.get(e);t&&(0==--t?(this.cache.delete(e),e.destroy()):this.cache.set(e,t));}}constructor(){this.cache=new Map;}};class oc{get(){return this._counter++}constructor(){this._counter=0;}}let od=new oc,ou=new eA,of=new eA,op=new eD,om=new Set,o_=new Uint32Array(4);class og{destroy(){this._destroyVertexBuffer&&this.vertexBuffer?.destroy(),this.vertexBuffer=null;}constructor(e){this.vertexBuffer=null,this._destroyVertexBuffer=false,this.count=e;}}class ov{getBindGroup(e){if(!this.bindGroup){let t=this.shader.meshBindGroupFormat;this.bindGroup=new iv(e,t);}return this.bindGroup}getUniformBuffer(e){if(!this.uniformBuffer){let t=this.shader.meshUniformBufferFormat;this.uniformBuffer=new rx(e,t,false);}return this.uniformBuffer}destroy(){this.bindGroup?.destroy(),this.bindGroup=null,this.uniformBuffer?.destroy(),this.uniformBuffer=null;}constructor(){this.bindGroup=null,this.uniformBuffer=null;}}class oS{set drawBucket(e){this._drawBucket=255&Math.floor(e),this.updateKey();}get drawBucket(){return this._drawBucket}set renderStyle(e){this._renderStyle=e,this.mesh.prepareRenderState(e);}get renderStyle(){return this._renderStyle}set mesh(e){e!==this._mesh&&(this._mesh&&this._mesh.decRefCount(),this._mesh=e,e&&e.incRefCount());}get mesh(){return this._mesh}set aabb(e){this._aabb=e;}get aabb(){if(!this._updateAabb)return this._aabb;if(this._updateAabbFunc)return this._updateAabbFunc(this._aabb);let e=this._customAabb,t=!!e;if(!e){if(e=ou,this.skinInstance){if(!this.mesh.boneAabb){let e=this._morphInstance?this._morphInstance.morph._targets:null;this.mesh._initBoneAabbs(e);}let i=this.mesh.boneUsed,s=true;for(let t=0;t{e.destroy();}),this._shaderCache.clear();}getShaderInstance(e,t,i,s,r,a,n){let o=this._shaderDefs;o_[0]=e,o_[1]=t,o_[2]=o,o_[3]=s.hash;let l=iM(o_),h=this._shaderCache.get(l);if(!h){let t=this._material;if((h=new ov).shader=t.variants.get(l),h.hashes=new Uint32Array(o_),!h.shader){let c=t.getShaderVariant({device:this.mesh.device,scene:i,objDefs:o,cameraShaderParams:s,pass:e,sortedLights:n,viewUniformFormat:r,viewBindGroupFormat:a,vertexFormat:this.mesh.vertexBuffer?.format});t.variants.set(l,c),h.shader=c;}this._shaderCache.set(l,h);}return h}set material(e){this.clearShaders();let t=this._material;t&&t.removeMeshInstanceRef(this),this._material=e,e&&(e.addMeshInstanceRef(this),this.transparent=e.transparent,this.updateKey());}get material(){return this._material}_updateShaderDefs(e){e!==this._shaderDefs&&(this._shaderDefs=e,this.clearShaders());}set calculateSortDistance(e){this._calculateSortDistance=e;}get calculateSortDistance(){return this._calculateSortDistance}set receiveShadow(e){this._receiveShadow!==e&&(this._receiveShadow=e,this._updateShaderDefs(e?-2&this._shaderDefs:1|this._shaderDefs));}get receiveShadow(){return this._receiveShadow}set batching(e){this._updateShaderDefs(e?16384|this._shaderDefs:-16385&this._shaderDefs);}get batching(){return (16384&this._shaderDefs)!=0}set skinInstance(e){this._skinInstance=e,this._updateShaderDefs(e?2|this._shaderDefs:-3&this._shaderDefs),this._setupSkinUpdate();}get skinInstance(){return this._skinInstance}set morphInstance(e){this._morphInstance?.destroy(),this._morphInstance=e;let t=this._shaderDefs;t=e&&e.morph.morphPositions?1024|t:-1025&t,t=e&&e.morph.morphNormals?2048|t:-2049&t,t=e&&e.morph.intRenderFormat?8192|t:-8193&t,this._updateShaderDefs(t);}get morphInstance(){return this._morphInstance}set screenSpace(e){this._screenSpace!==e&&(this._screenSpace=e,this._updateShaderDefs(e?256|this._shaderDefs:-257&this._shaderDefs));}get screenSpace(){return this._screenSpace}set key(e){this._sortKeyForward=e;}get key(){return this._sortKeyForward}set mask(e){let t=65535&this._shaderDefs;this._updateShaderDefs(t|e<<16);}get mask(){return this._shaderDefs>>16}set instancingCount(e){this.instancingData&&(this.instancingData.count=e);}get instancingCount(){return this.instancingData?this.instancingData.count:0}destroy(){let e=this.mesh;e&&(this.mesh=null,e.refCount<1&&e.destroy()),this.setRealtimeLightmap(oS.lightmapParamNames[0],null),this.setRealtimeLightmap(oS.lightmapParamNames[1],null),this._skinInstance?.destroy(),this._skinInstance=null,this.morphInstance?.destroy(),this.morphInstance=null,this.clearShaders(),this.material=null,this.instancingData?.destroy(),this.destroyDrawCommands();}destroyDrawCommands(){if(this.drawCommands){for(let e of this.drawCommands.values())e?.destroy();this.drawCommands=null;}}static _prepareRenderStyleForArray(e,t){if(e){for(let i=0;i0))}updateKey(){let{material:e}=this;this._sortKeyForward=this._drawBucket<<23|(e.alphaToCoverage||e.alphaTest?4194304:0)|4194303&e.id;}setInstancing(e,t=false){e?(true===e?this.instancingData=new og(0):(this.instancingData=new og(e.numVertices),this.instancingData.vertexBuffer=e,e.format.instancing=true),this.cull=t):(this.instancingData=null,this.cull=true),this._updateShaderDefs(e instanceof iR?32|this._shaderDefs:-33&this._shaderDefs);}setIndirect(e,t,i=1){let s=e?.camera??null;if(-1===t)this._deleteDrawCommandsKey(s);else {this.drawCommands??(this.drawCommands=new Map);let e=this.drawCommands.get(s)??new aa(this.mesh.device);e.slotIndex=t,e.update(i),this.drawCommands.set(s,e),this.mesh.device.mapsToClear.add(this.drawCommands);}}setMultiDraw(e,t=1){let i,s=e?.camera??null;if(0===t)this._deleteDrawCommandsKey(s);else {if(this.drawCommands??(this.drawCommands=new Map),!(i=this.drawCommands.get(s))){let e=this.mesh.indexBuffer?.[0],t=e?.format,r=void 0!==t?eW[t]:0;i=new aa(this.mesh.device,r),this.drawCommands.set(s,i);}i.allocate(t);}return i}_deleteDrawCommandsKey(e){let t=this.drawCommands;if(t){let i=t.get(e);i?.destroy(),t.delete(e),0===t.size&&this.destroyDrawCommands();}}getDrawCommands(e){let t=this.drawCommands;if(t)return t.get(e)??t.get(null)}getIndirectMetaData(){let e=this.mesh?.primitive[this.renderStyle],t=this.meshMetaData??(this.meshMetaData=new Int32Array(4));return t[0]=e.count,t[1]=e.base,t[2]=e.baseVertex,t}ensureMaterial(e){this.material||(this.material=ol(e));}clearParameters(){this.parameters={};}getParameters(){return this.parameters}getParameter(e){return this.parameters[e]}setParameter(e,t,i=0xffffffff){let s=this.parameters[e];s?(s.data=t,s.passFlags=i):this.parameters[e]={scopeId:null,data:t,passFlags:i};}setRealtimeLightmap(e,t){let i=this.getParameter(e);i!==t&&(i&&oh.decRef(i.data),t?(oh.incRef(t),this.setParameter(e,t)):this.deleteParameter(e));}deleteParameter(e){this.parameters[e]&&delete this.parameters[e];}setParameters(e,t){let i=this.parameters;for(let s in i){let r=i[s];r.passFlags&t&&(r.scopeId||(r.scopeId=e.scope.resolve(s)),r.scopeId.setValue(r.data));}}setLightmapped(e){e?this.mask=(2|this.mask)&-6:(this.setRealtimeLightmap(oS.lightmapParamNames[0],null),this.setRealtimeLightmap(oS.lightmapParamNames[1],null),this._shaderDefs&=-4289,this.mask=(1|this.mask)&-7);}setCustomAabb(e){e?this._customAabb?this._customAabb.copy(e):this._customAabb=e.clone():(this._customAabb=null,this._aabbVer=-1),this._setupSkinUpdate();}_setupSkinUpdate(){this._skinInstance&&(this._skinInstance._updateBeforeCull=!this._customAabb);}constructor(e,t,i=null){if(this.castShadow=false,this.shadowCascadeMask=255,this.cull=true,this.drawOrder=0,this._drawBucket=127,this.visible=true,this.visibleThisFrame=false,this.flipFacesFactor=1,this.gsplatInstance=null,this.id=od.get(),this.isVisibleFunc=null,this.instancingData=null,this.indirectData=null,this.drawCommands=null,this.meshMetaData=null,this.parameters={},this.pick=true,this.stencilFront=null,this.stencilBack=null,this.transparent=false,this._aabb=new eA,this._aabbVer=-1,this._aabbMeshVer=-1,this._customAabb=null,this._updateAabb=true,this._updateAabbFunc=null,this._sortKeyShadow=0,this._sortKeyForward=0,this._sortKeyDynamic=0,this._layer=15,this._material=null,this._skinInstance=null,this._morphInstance=null,this._receiveShadow=true,this._renderStyle=0,this._screenSpace=false,this._shaderCache=new Map,this._shaderDefs=65536,this._calculateSortDistance=null,this.node=i,this._mesh=e,e.incRefCount(),this.material=t,e.vertexBuffer){let t=e.vertexBuffer.format;this._shaderDefs|=4*!!t.hasUv0,this._shaderDefs|=8*!!t.hasUv1,this._shaderDefs|=16*!!t.hasColor,this._shaderDefs|=512*!!t.hasTangents;}this.updateKey();}}oS.lightmapParamNames=["texture_lightMap","texture_dirLightMap"];let oy=[0,1,3,2,3,1],ox=[0,1,3,0,3,2],oT=new eu;function oE(e,t){if(e&&!t||!e&&t)return false;if((e=e.data)===(t=t.data))return true;if(e instanceof Float32Array&&t instanceof Float32Array){if(e.length!==t.length)return false;for(let i=0;ithis._dirtyGroups.indexOf(e)&&this._dirtyGroups.push(e);}getGroupByName(e){let t=this._batchGroups;for(let i in t)if(t.hasOwnProperty(i)&&t[i].name===e)return t[i];return null}getGroupById(e){return this._batchGroups[e]??null}getBatches(e){let t=[],i=this._batchList.length;for(let s=0;ss._obj[e].indexOf(i)&&(s._obj[e].push(i),this.markGroupDirty(t));}remove(e,t,i){let s=this._batchGroups[t];if(s){let r=s._obj[e].indexOf(i);r>=0&&(s._obj[e].splice(r,1),this.markGroupDirty(t));}}_filterBatchableInstances(e,t){let i=false;for(let t=0;t0?(t.push(e.element._text._model.meshInstances[0]),e.element.removeModelFromLayers(e.element._text._model),s=true):e.element._image&&(t.push(e.element._image._renderable.meshInstance),e.element.removeModelFromLayers(e.element._image._renderable.model),e.element._image._renderable.unmaskMeshInstance&&(t.push(e.element._image._renderable.unmaskMeshInstance),e.element._image._renderable.unmaskMeshInstance.stencilFront&&e.element._image._renderable.unmaskMeshInstance.stencilBack||(e.element._dirtifyMask(),e.element._onPrerender())),s=true),s&&(i._ui=true);}_collectAndRemoveMeshInstances(e,t){for(let i=0;ie.indexOf(this._batchList[t].batchGroupId)){n.push(this._batchList[t]);continue}this.destroyBatch(this._batchList[t]);}if(this._batchList=n,this._collectAndRemoveMeshInstances(a,e),e===this._dirtyGroups)this._dirtyGroups.length=0;else {let t=[];for(let i=0;ie.indexOf(this._dirtyGroups[i])&&t.push(this._dirtyGroups[i]);this._dirtyGroups=t;}for(let e in a)if(a.hasOwnProperty(e)&&(t=a[e],s=this._batchGroups[e])){i=this.prepare(t,s.dynamic,s.maxAabbSize,s._ui||s._sprite);for(let t=0;te.drawOrder-t.drawOrder);let u=e,f=s?function(e){h?h.add(e.aabb):h=e.aabb.clone(),a.push(e);}:function(e){a.push(e);};for(;u.length>0;){c[d]=[u[0]],a=[];let e=u[0].material,i=u[0].layer,p=u[0]._shaderDefs,m=u[0].parameters,_=u[0].stencilFront,g=u[0].mesh.vertexBuffer.getNumVertices(),v=u[0].drawOrder;o.copy(u[0].aabb);let S=ow(u[0]),y=u[0].mesh.vertexBuffer.format.batchingHash,x=u[0].mesh.primitive[0].indexed,T=u[0].castShadow,E=u[0].shadowCascadeMask;h=null;for(let w=1;w=1024){a=a.concat(u.slice(w));break}if(e!==b.material||i!==b.layer||y!==b.mesh.vertexBuffer.format.batchingHash||x!==b.mesh.primitive[0].indexed||p!==b._shaderDefs||g+b.mesh.vertexBuffer.getNumVertices()>0xffffffff||(l.copy(o),l.add(b.aabb),l.halfExtents.x>n||l.halfExtents.y>n||l.halfExtents.z>n||_&&(!(r=b.stencilFront)||_.func!==r.func||_.zpass!==r.zpass)||S!==ow(b)||T!==b.castShadow||E!==b.shadowCascadeMask||!function(e,t){for(let i in e)if(e.hasOwnProperty(i)&&!oE(e[i],t[i]))return false;for(let i in t)if(t.hasOwnProperty(i)&&!oE(t[i],e[i]))return false;return true}(m,b.parameters)||s&&h&&h.intersects(b.aabb)&&b.drawOrder!==v)){f(b);continue}o.add(b.aabb),g+=b.mesh.vertexBuffer.getNumVertices(),c[d].push(b);}d++,u=a;}return c}collectBatchedMeshData(e,t){let i=null,s=0,r=0,a=null;for(let n=0;n=3){if(s===e8){let t,s,r,a=f.data,o=a[0],l=a[1],h=a[2],c=a[4],d=a[5],u=a[6],p=a[8],m=a[9],_=a[10],g=a[12],v=a[13],S=a[14];for(let a=0;a0&&r.setIndices(y),r.update(4,false),t&&(m=m.clone()).update();let x=new oS(r,m,this.rootNode);x.castShadow=o.origMeshInstances[0].castShadow,x.parameters=o.origMeshInstances[0].parameters,x.layer=o.origMeshInstances[0].layer,x._shaderDefs=o.origMeshInstances[0]._shaderDefs,x.batching=true,x.cull=o.origMeshInstances[0].cull;let T=this._batchGroups[i];if(T&&T._ui&&(x.cull=false),t){let e=[];for(let t=0;t0&&this.generate(this._dirtyGroups);for(let e=0;e1&&(r=15,s=false);let a=e.renderTarget?.depthBuffer??e.renderTarget?.colorBuffer;this.shouldReallocate(this.depthRenderTarget,a)&&(this.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=this.allocateRenderTarget(this.depthRenderTarget,e.renderTarget,t,r,s));let n=s?this.depthRenderTarget.depthBuffer:this.depthRenderTarget.colorBuffer;t.scope.resolve(oP).setValue(n);}execute(){let e=this.device;if(e.isWebGL2&&e.renderTarget.samples>1){let t=e.renderTarget.impl._glFrameBuffer,i=this.depthRenderTarget;e.renderTarget=i,e.updateBegin(),this.depthRenderTarget.impl.internalResolve(e,t,i.impl._glFrameBuffer,this.depthRenderTarget,e.gl.DEPTH_BUFFER_BIT);}else e.copyRenderTarget(e.renderTarget,this.depthRenderTarget,false,true);}constructor(e,t){super(e),this.depthRenderTarget=null,this.camera=null,this.camera=t;}}class oD{get hash(){if(void 0===this._hash){let e=`${this.gammaCorrection}_${this.toneMapping}_${this.srgbRenderTarget}_${this.fog}_${this.ssaoEnabled}_${this.sceneDepthMapLinear}`;this._hash=iL(e);}return this._hash}get defines(){let e=this._defines;return this._definesDirty&&(this._definesDirty=false,e.clear(),this._sceneDepthMapLinear&&e.set("SCENE_DEPTHMAP_LINEAR",""),1===this.shaderOutputGamma&&e.set("SCENE_COLORMAP_GAMMA",""),e.set("FOG",this._fog.toUpperCase()),e.set("TONEMAP",nu[this._toneMapping]),e.set("GAMMA",nd[this.shaderOutputGamma])),e}markDirty(){this._hash=void 0,this._definesDirty=true;}set fog(e){this._fog!==e&&(this._fog=e,this.markDirty());}get fog(){return this._fog}set ssaoEnabled(e){this._ssaoEnabled!==e&&(this._ssaoEnabled=e,this.markDirty());}get ssaoEnabled(){return this._ssaoEnabled}set gammaCorrection(e){this._gammaCorrectionAssigned=true,this._gammaCorrection!==e&&(this._gammaCorrection=e,this.markDirty());}get gammaCorrection(){return this._gammaCorrection}set toneMapping(e){this._toneMapping!==e&&(this._toneMapping=e,this.markDirty());}get toneMapping(){return this._toneMapping}set srgbRenderTarget(e){this._srgbRenderTarget!==e&&(this._srgbRenderTarget=e,this.markDirty());}get srgbRenderTarget(){return this._srgbRenderTarget}set sceneDepthMapLinear(e){this._sceneDepthMapLinear!==e&&(this._sceneDepthMapLinear=e,this.markDirty());}get sceneDepthMapLinear(){return this._sceneDepthMapLinear}get shaderOutputGamma(){return +(1===this._gammaCorrection&&!this._srgbRenderTarget)}constructor(){this._gammaCorrection=1,this._toneMapping=0,this._srgbRenderTarget=false,this._ssaoEnabled=false,this._fog=ns,this._sceneDepthMapLinear=false,this._defines=new Map,this._definesDirty=true;}}let oR=new ed,oL=new ed,oM=new ed,oO=new ey,oF=[new ed,new ed,new ed,new ed,new ed,new ed,new ed,new ed];class oN{destroy(){this.renderPassColorGrab?.destroy(),this.renderPassColorGrab=null,this.renderPassDepthGrab?.destroy(),this.renderPassDepthGrab=null,this.framePasses.length=0;}_storeShaderMatrices(e,t,i,s){this._shaderMatricesVersion!==s&&(this._shaderMatricesVersion=s,this._viewProjPrevious.copy(this._viewProjCurrent??e),this._viewProjCurrent??(this._viewProjCurrent=new ey),this._viewProjCurrent.copy(e),this._viewProjInverse.invert(e),this._jitters[2]=this._jitters[0],this._jitters[3]=this._jitters[1],this._jitters[0]=t,this._jitters[1]=i);}get fullSizeClearRect(){let e=this._scissorRectClear?this.scissorRect:this._rect;return 0===e.x&&0===e.y&&1===e.z&&1===e.w}set aspectRatio(e){this._aspectRatio!==e&&(this._aspectRatio=e,this._projMatDirty=true);}get aspectRatio(){return this.xr?.active?this._xrProperties.aspectRatio:this._aspectRatio}set aspectRatioMode(e){this._aspectRatioMode!==e&&(this._aspectRatioMode=e,this._projMatDirty=true);}get aspectRatioMode(){return this._aspectRatioMode}set calculateProjection(e){this._calculateProjection=e,this._projMatDirty=true;}get calculateProjection(){return this._calculateProjection}set calculateTransform(e){this._calculateTransform=e;}get calculateTransform(){return this._calculateTransform}set clearColor(e){this._clearColor.copy(e);}get clearColor(){return this._clearColor}set clearColorBuffer(e){this._clearColorBuffer=e;}get clearColorBuffer(){return this._clearColorBuffer}set clearDepth(e){this._clearDepth=e;}get clearDepth(){return this._clearDepth}set clearDepthBuffer(e){this._clearDepthBuffer=e;}get clearDepthBuffer(){return this._clearDepthBuffer}set clearStencil(e){this._clearStencil=e;}get clearStencil(){return this._clearStencil}set clearStencilBuffer(e){this._clearStencilBuffer=e;}get clearStencilBuffer(){return this._clearStencilBuffer}set cullFaces(e){this._cullFaces=e;}get cullFaces(){return this._cullFaces}set farClip(e){this._farClip!==e&&(this._farClip=e,this._projMatDirty=true);}get farClip(){return this.xr?.active?this._xrProperties.farClip:this._farClip}set flipFaces(e){this._flipFaces=e;}get flipFaces(){return this._flipFaces}set fov(e){this._fov!==e&&(this._fov=e,this._projMatDirty=true);}get fov(){return this.xr?.active?this._xrProperties.fov:this._fov}set frustumCulling(e){this._frustumCulling=e;}get frustumCulling(){return this._frustumCulling}set horizontalFov(e){this._horizontalFov!==e&&(this._horizontalFov=e,this._projMatDirty=true);}get horizontalFov(){return this.xr?.active?this._xrProperties.horizontalFov:this._horizontalFov}set layers(e){this._layers=e.slice(0),this._layersSet=new Set(this._layers);}get layers(){return this._layers}get layersSet(){return this._layersSet}set nearClip(e){this._nearClip!==e&&(this._nearClip=e,this._projMatDirty=true);}get nearClip(){return this.xr?.active?this._xrProperties.nearClip:this._nearClip}set node(e){this._node=e;}get node(){return this._node}set orthoHeight(e){this._orthoHeight!==e&&(this._orthoHeight=e,this._projMatDirty=true);}get orthoHeight(){return this._orthoHeight}set projection(e){this._projection!==e&&(this._projection=e,this._projMatDirty=true);}get projection(){return this._projection}get projectionMatrix(){return this._evaluateProjectionMatrix(),this._projMat}set rect(e){this._rect.copy(e);}get rect(){return this._rect}set renderTarget(e){this._renderTarget=e;}get renderTarget(){return this._renderTarget}set scissorRect(e){this._scissorRect.copy(e);}get scissorRect(){return this._scissorRect}get viewMatrix(){if(this._viewMatDirty){let e=this._node.getWorldTransform();this._viewMat.copy(e).invert(),this._viewMatDirty=false;}return this._viewMat}set aperture(e){this._aperture=e;}get aperture(){return this._aperture}set sensitivity(e){this._sensitivity=e;}get sensitivity(){return this._sensitivity}set shutter(e){this._shutter=e;}get shutter(){return this._shutter}set xr(e){this._xr!==e&&(this._xr=e,this._projMatDirty=true);}get xr(){return this._xr}clone(){return new oN().copy(this)}copy(e){return this._aspectRatio=e._aspectRatio,this._farClip=e._farClip,this._fov=e._fov,this._horizontalFov=e._horizontalFov,this._nearClip=e._nearClip,this._xrProperties.aspectRatio=e._xrProperties.aspectRatio,this._xrProperties.farClip=e._xrProperties.farClip,this._xrProperties.fov=e._xrProperties.fov,this._xrProperties.horizontalFov=e._xrProperties.horizontalFov,this._xrProperties.nearClip=e._xrProperties.nearClip,this.aspectRatioMode=e.aspectRatioMode,this.calculateProjection=e.calculateProjection,this.calculateTransform=e.calculateTransform,this.clearColor=e.clearColor,this.clearColorBuffer=e.clearColorBuffer,this.clearDepth=e.clearDepth,this.clearDepthBuffer=e.clearDepthBuffer,this.clearStencil=e.clearStencil,this.clearStencilBuffer=e.clearStencilBuffer,this.cullFaces=e.cullFaces,this.flipFaces=e.flipFaces,this.frustumCulling=e.frustumCulling,this.layers=e.layers,this.orthoHeight=e.orthoHeight,this.projection=e.projection,this.rect=e.rect,this.renderTarget=e.renderTarget,this.scissorRect=e.scissorRect,this.aperture=e.aperture,this.shutter=e.shutter,this.sensitivity=e.sensitivity,this.shaderPassInfo=e.shaderPassInfo,this.jitter=e.jitter,this._projMatDirty=true,this}_enableRenderPassColorGrab(e,t){t?this.renderPassColorGrab||(this.renderPassColorGrab=new oA(e)):(this.renderPassColorGrab?.destroy(),this.renderPassColorGrab=null);}_enableRenderPassDepthGrab(e,t,i){i?this.renderPassDepthGrab||(this.renderPassDepthGrab=new oI(e,this)):(this.renderPassDepthGrab?.destroy(),this.renderPassDepthGrab=null);}_updateViewProjMat(){(this._projMatDirty||this._viewMatDirty||this._viewProjMatDirty)&&(this._viewProjMat.mul2(this.projectionMatrix,this.viewMatrix),this._viewProjMatDirty=false);}worldToScreen(e,t,i,s=new ed){this._updateViewProjMat(),this._viewProjMat.transformPoint(e,s);let r=this._viewProjMat.data,a=e.x*r[3]+e.y*r[7]+e.z*r[11]+ +r[15];s.x=(s.x/a+1)*.5,s.y=(1-s.y/a)*.5;let{x:n,y:o,z:l,w:h}=this._rect;return s.x=s.x*l*t+n*t,s.y=s.y*h*i+(1-o-h)*i,s}screenToWorld(e,t,i,s,r,a=new ed){let{x:n,y:o,z:l,w:h}=this._rect,c=this.farClip-this.nearClip;if(oR.set((e-n*s)/(l*s),1-(t-(1-o-h)*r)/(h*r),i/c),oR.mulScalar(2),oR.sub(ed.ONE),0===this._projection){ey._getPerspectiveHalfSize(oL,this.fov,this.aspectRatio,this.nearClip,this.horizontalFov),oL.x*=oR.x,oL.y*=oR.y;let e=this._node.getWorldTransform();oL.z=-this.nearClip,e.transformPoint(oL,oM);let t=this._node.getPosition();a.sub2(oM,t),a.normalize(),a.mulScalar(i),a.add(t);}else this._updateViewProjMat(),oO.copy(this._viewProjMat).invert(),oO.transformPoint(oR,a);return a}_evaluateProjectionMatrix(){if(this._projMatDirty){if(0===this._projection)this._projMat.setPerspective(this.fov,this.aspectRatio,this.nearClip,this.farClip,this.horizontalFov),this._projMatSkybox.copy(this._projMat);else {let e=this._orthoHeight,t=e*this.aspectRatio;this._projMat.setOrtho(-t,t,-e,e,this.nearClip,this.farClip),this._projMatSkybox.setPerspective(this.fov,this.aspectRatio,this.nearClip,this.farClip);}this._projMatDirty=false;}}getProjectionMatrixSkybox(){return this._evaluateProjectionMatrix(),this._projMatSkybox}getExposure(){return 1/(1.2*Math.pow(2,Math.log2(this._aperture*this._aperture/this._shutter*100/this._sensitivity)))}getScreenSize(e){if(0===this._projection){let t=this._node.getPosition().distance(e.center);return t{let s=i[e];return s instanceof Function&&(s=s()),s===t}}class oJ extends X{get right(){return this._right||(this._right=new ed),this.getWorldTransform().getX(this._right).normalize()}get up(){return this._up||(this._up=new ed),this.getWorldTransform().getY(this._up).normalize()}get forward(){return this._forward||(this._forward=new ed),this.getWorldTransform().getZ(this._forward).normalize().mulScalar(-1)}get normalMatrix(){let e=this._normalMatrix;return this._dirtyNormal&&(e.invertMat4(this.getWorldTransform()).transpose(),this._dirtyNormal=false),e}set enabled(e){this._enabled!==e&&(this._enabled=e,(e&&this._parent?.enabled||!e)&&this._notifyHierarchyStateChanged(this,e));}get enabled(){return this._enabled&&this._enabledInHierarchy}get parent(){return this._parent}get path(){let e=this._parent;if(!e)return "";let t=this.name;for(;e&&e._parent;)t=`${e.name}/${t}`,e=e._parent;return t}get root(){let e=this;for(;e._parent;)e=e._parent;return e}get children(){return this._children}get graphDepth(){return this._graphDepth}_notifyHierarchyStateChanged(e,t){e._onHierarchyStateChanged(t);let i=e._children;for(let e=0,s=i.length;e{s(e)&&i.push(e);}),i}findOne(e,t){return function e(t,i){if(i(t))return t;let s=t._children,r=s.length;for(let t=0;t{r&&s.tags.has(...e)&&t.push(s);for(let e=0;ei.name===t[e])))return null;return i}forEach(e,t){e.call(t,this);let i=this._children,s=i.length;for(let r=0;r=0?e.insertChild(this,t):e.addChild(this));}setLocalEulerAngles(e,t,i){this.localRotation.setFromEulerAngles(e,t,i),this._dirtyLocal||this._dirtifyLocal();}setLocalPosition(e,t,i){e instanceof ed?this.localPosition.copy(e):this.localPosition.set(e,t,i),this._dirtyLocal||this._dirtifyLocal();}setLocalRotation(e,t,i,s){e instanceof ex?this.localRotation.copy(e):this.localRotation.set(e,t,i,s),this._dirtyLocal||this._dirtifyLocal();}setLocalScale(e,t,i){e instanceof ed?this.localScale.copy(e):this.localScale.set(e,t,i),this._dirtyLocal||this._dirtifyLocal();}_dirtifyLocal(){!this._dirtyLocal&&(this._dirtyLocal=true,this._dirtyWorld||this._dirtifyWorld());}_unfreezeParentToRoot(){let e=this._parent;for(;e;)e._frozen=false,e=e._parent;}_dirtifyWorld(){this._dirtyWorld||this._unfreezeParentToRoot(),this._dirtifyWorldInternal();}_dirtifyWorldInternal(){if(!this._dirtyWorld){this._frozen=false,this._dirtyWorld=true;for(let e=0;eObject.keys(e).map(i=>`#define {${t}${i}} ${e[i]}`).join("\n"),le=` +${o} +${l} while rendering undefined`;return!1}return!0}isLinked(t){let{extParallelShaderCompile:e}=t;return e?t.gl.getProgramParameter(this.glProgram,e.COMPLETION_STATUS_KHR):!0}_processError(t,e){let s={},i="";if(t){let r=t.split(` +`),a=0,o=r.length;if(e&&e.startsWith("ERROR:")){let l=e.match(/^ERROR:\s(\d+):(\d+):\s*(.+)/);l&&(s.message=l[3],s.line=parseInt(l[2],10),a=Math.max(0,s.line-6),o=Math.min(r.length,s.line+5))}for(let l=a;l ":" ";i+=`${h}${l+1}: ${r[l]} +`}s.source=t}return[i,s]}};var kv=class{constructor(t){n(this,"indexSizeBytes");n(this,"glCounts",null);n(this,"glOffsetsBytes",null);n(this,"glInstanceCounts",null);this.indexSizeBytes=t}allocate(t){this.glCounts&&this.glCounts.length===t||(this.glCounts=new Int32Array(t),this.glOffsetsBytes=new Int32Array(t),this.glInstanceCounts=new Int32Array(t))}add(t,e,s,i){this.glCounts[t]=e,this.glOffsetsBytes[t]=i*this.indexSizeBytes,this.glInstanceCounts[t]=s}update(t){return 0}};function sL(c,t){let e=c.width,s=c.height;if(e>t||s>t){let i=t/Math.max(e,s),r=Math.floor(e*i),a=Math.floor(s*i),o=document.createElement("canvas");return o.width=r,o.height=a,o.getContext("2d").drawImage(c,0,0,e,s,0,0,r,a),o}return c}var zv=class{constructor(t){n(this,"_glTexture",null);n(this,"_glTarget");n(this,"_glFormat");n(this,"_glInternalFormat");n(this,"_glPixelType");n(this,"_glCreated");n(this,"dirtyParameterFlags",0);this.texture=t}destroy(t){if(this._glTexture){for(let e=0;et.maxCubeMapSize||h.height>t.maxCubeMapSize)&&(h=sL(h,t.maxCubeMapSize),i===0&&(e._width=h.width,e._height=h.height)),t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),this._glCreated?s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,i,0,0,this._glFormat,this._glPixelType,h):s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,i,this._glInternalFormat,this._glFormat,this._glPixelType,h)}else for(a=1/Math.pow(2,i),l=0;l<6;l++){if(!e._levelsUpdated[0][l])continue;let h=r[l];e._compressed?this._glCreated&&h?s.compressedTexSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,i,0,0,Math.max(e._width*a,1),Math.max(e._height*a,1),this._glInternalFormat,h):s.compressedTexImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,i,this._glInternalFormat,Math.max(e._width*a,1),Math.max(e._height*a,1),0,h):(t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),t.setUnpackAlignment(1),this._glCreated&&h?s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,i,0,0,Math.max(e._width*a,1),Math.max(e._height*a,1),this._glFormat,this._glPixelType,h):s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,i,this._glInternalFormat,Math.max(e._width*a,1),Math.max(e._height*a,1),0,this._glFormat,this._glPixelType,h))}}else if(e._volume)e._compressed?s.compressedTexImage3D(s.TEXTURE_3D,i,this._glInternalFormat,Math.max(e._width*a,1),Math.max(e._height*a,1),Math.max(e._depth*a,1),0,r):(t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),t.setUnpackAlignment(1),s.texImage3D(s.TEXTURE_3D,i,this._glInternalFormat,Math.max(e._width*a,1),Math.max(e._height*a,1),Math.max(e._depth*a,1),0,this._glFormat,this._glPixelType,r));else if(e.array){if(Array.isArray(r)&&e._arrayLength===r.length)if(e._compressed)for(let l=0;lt.maxTextureSize||r.height>t.maxTextureSize)&&(r=sL(r,t.maxTextureSize),i===0&&(e._width=r.width,e._height=r.height));let l=r.width||r.videoWidth,h=r.height||r.videoHeight;t.setUnpackFlipY(e._flipY),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),this._glCreated&&e._width===l&&e._height===h&&!t._isImageVideoInterface(r)?s.texSubImage2D(s.TEXTURE_2D,i,0,0,this._glFormat,this._glPixelType,r):(s.texImage2D(s.TEXTURE_2D,i,this._glInternalFormat,this._glFormat,this._glPixelType,r),i===0&&(e._width=l,e._height=h))}else a=1/Math.pow(2,i),e._compressed?this._glCreated&&r?s.compressedTexSubImage2D(s.TEXTURE_2D,i,0,0,Math.max(Math.floor(e._width*a),1),Math.max(Math.floor(e._height*a),1),this._glInternalFormat,r):s.compressedTexImage2D(s.TEXTURE_2D,i,this._glInternalFormat,Math.max(Math.floor(e._width*a),1),Math.max(Math.floor(e._height*a),1),0,r):(t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),t.setUnpackAlignment(1),this._glCreated&&r?s.texSubImage2D(s.TEXTURE_2D,i,0,0,Math.max(e._width*a,1),Math.max(e._height*a,1),this._glFormat,this._glPixelType,r):s.texImage2D(s.TEXTURE_2D,i,this._glInternalFormat,Math.max(e._width*a,1),Math.max(e._height*a,1),0,this._glFormat,this._glPixelType,r));i===0?e._mipmapsUploaded=!1:e._mipmapsUploaded=!0}i++}if(e._needsUpload)if(e._cubemap)for(let l=0;l<6;l++)e._levelsUpdated[0][l]=!1;else e._levelsUpdated[0]=!1;!e._compressed&&!e._integerFormat&&e._mipmaps&&e._needsMipmapsUpload&&e._levels.length===1&&(s.generateMipmap(this._glTarget),e._mipmapsUploaded=!0),e._gpuSize&&e.adjustVramSizeTracking(t._vram,-e._gpuSize),e._gpuSize=e.gpuSize,e.adjustVramSizeTracking(t._vram,e._gpuSize),e.releaseSourceAfterUpload&&e.releaseImageSources(),this._glCreated=!0}uploadImmediate(t,e){(e._needsUpload||e._needsMipmapsUpload)&&(t.setTexture(e,0),e._needsUpload=!1,e._needsMipmapsUpload=!1)}read(t,e,s,i,r){let a=this.texture;return a.device.readTextureAsync(a,t,e,s,i,r)}write(t,e,s,i,r){let{texture:a}=this,{device:o}=a;return o.setTexture(a,0),o.writeTextureAsync(a,t,e,s,i,r)}};var dW=new et,WP=class{constructor(t,e){n(this,"msaaFB");n(this,"resolveFB");this.msaaFB=t,this.resolveFB=e}destroy(t){this.msaaFB&&(t.deleteRenderbuffer(this.msaaFB),this.msaaFB=null),this.resolveFB&&(t.deleteRenderbuffer(this.resolveFB),this.resolveFB=null)}},Gv=class{constructor(){n(this,"_glFrameBuffer",null);n(this,"_glDepthBuffer",null);n(this,"_glResolveFrameBuffer",null);n(this,"colorMrtFramebuffers",null);n(this,"_glMsaaColorBuffers",[]);n(this,"_glMsaaDepthBuffer",null);n(this,"msaaDepthBufferKey");n(this,"suppliedColorFramebuffer");n(this,"_isInitialized",!1)}destroy(t){let e=t.gl;this._isInitialized=!1,this._glFrameBuffer&&(this._glFrameBuffer!==this.suppliedColorFramebuffer&&e.deleteFramebuffer(this._glFrameBuffer),this._glFrameBuffer=null),this._glDepthBuffer&&(e.deleteRenderbuffer(this._glDepthBuffer),this._glDepthBuffer=null),this._glResolveFrameBuffer&&(this._glResolveFrameBuffer!==this.suppliedColorFramebuffer&&e.deleteFramebuffer(this._glResolveFrameBuffer),this._glResolveFrameBuffer=null),this._glMsaaColorBuffers.forEach(s=>{e.deleteRenderbuffer(s)}),this._glMsaaColorBuffers.length=0,this.colorMrtFramebuffers?.forEach(s=>{s.destroy(e)}),this.colorMrtFramebuffers=null,this._glMsaaDepthBuffer&&(this._glMsaaDepthBuffer=null,this.msaaDepthBufferKey&&Af(t).release(this.msaaDepthBufferKey)),this.suppliedColorFramebuffer=void 0}get initialized(){return this._isInitialized}init(t,e){let s=t.gl;this._isInitialized=!0;let i=[];if(this.suppliedColorFramebuffer!==void 0)this._glFrameBuffer=this.suppliedColorFramebuffer;else{this._glFrameBuffer=s.createFramebuffer(),t.setFramebuffer(this._glFrameBuffer);let r=e._colorBuffers?.length??0,a=s.COLOR_ATTACHMENT0;for(let l=0;l1)){this._glDepthBuffer||(this._glDepthBuffer=s.createRenderbuffer());let f=e._stencil?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT32F;s.bindRenderbuffer(s.RENDERBUFFER,this._glDepthBuffer),s.renderbufferStorage(s.RENDERBUFFER,f,e.width,e.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,l,s.RENDERBUFFER,this._glDepthBuffer),s.bindRenderbuffer(s.RENDERBUFFER,null)}}}if(e._samples>1){this._glResolveFrameBuffer=this._glFrameBuffer,this._glFrameBuffer=s.createFramebuffer(),t.setFramebuffer(this._glFrameBuffer);let r=e._colorBuffers?.length??0;if(this.suppliedColorFramebuffer!==void 0){let a=s.createRenderbuffer();this._glMsaaColorBuffers.push(a);let o=t.backBufferFormat===ce?s.RGBA8:s.RGB8;s.bindRenderbuffer(s.RENDERBUFFER,a),s.renderbufferStorageMultisample(s.RENDERBUFFER,e._samples,o,e.width,e.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.RENDERBUFFER,a)}else for(let a=0;a1&&(this._createMsaaMrtFramebuffers(t,e,r),t.setFramebuffer(this._glFrameBuffer),s.drawBuffers(i))}}_createMsaaMrtFramebuffers(t,e,s){let i=t.gl;this.colorMrtFramebuffers=[];for(let r=0;ru?.format??-1).join(",")??"",r=e._depth?e._depthBuffer?`dt${e._depthBuffer.format}`:e._stencil?"ds":"d":"",a=`${s}:${i}:${r}:${e._samples}`,o=dW.get(t,()=>{let u=new Set;return u.loseContext=()=>u.clear(),u});if(o.has(a))return;let l=t.gl,h=l.checkFramebufferStatus(l.FRAMEBUFFER),f;switch(h){case l.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:f="FRAMEBUFFER_INCOMPLETE_ATTACHMENT";break;case l.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:f="FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";break;case l.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:f="FRAMEBUFFER_INCOMPLETE_DIMENSIONS";break;case l.FRAMEBUFFER_UNSUPPORTED:f="FRAMEBUFFER_UNSUPPORTED";break}h===l.FRAMEBUFFER_COMPLETE&&o.add(a)}loseContext(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this._glMsaaColorBuffers.length=0,this._glMsaaDepthBuffer=null,this.msaaDepthBufferKey=void 0,this.colorMrtFramebuffers=null,this.suppliedColorFramebuffer=void 0,this._isInitialized=!1}internalResolve(t,e,s,i,r){t.setScissor(0,0,i.width,i.height);let a=t.gl;a.bindFramebuffer(a.READ_FRAMEBUFFER,e),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,s),a.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r,a.NEAREST)}resolve(t,e,s,i){let r=t.gl;if(this.colorMrtFramebuffers){if(s)for(let a=0;at.deleteBuffer(e.pbo)),this.pendingPBOs.forEach(e=>{e.sync&&t.deleteSync(e.sync),t.deleteBuffer(e.pbo)})}_onDeviceLost(){this.availablePBOs.length=0,this.pendingPBOs.length=0}update(t){let e=this.uploadStream.device.gl,s=this.pendingPBOs;for(let r=s.length-1;r>=0;r--){let a=s[r],o=e.clientWaitSync(a.sync,0,0);(o===e.CONDITION_SATISFIED||o===e.ALREADY_SIGNALED)&&(e.deleteSync(a.sync),this.availablePBOs.push({pbo:a.pbo,size:a.size}),s.splice(r,1))}let i=this.availablePBOs;for(let r=i.length-1;r>=0;r--)i[r].size{t._session&&e.gl.makeXRCompatible().then(()=>{if(!t._session)return;let i=t._session.renderState;t.attachPresentation(t._session,{framebufferScaleFactor:t._framebufferScaleFactor,depthNear:i.depthNear,depthFar:i.depthFar,onBindingError:t._onBindingError})}).catch(i=>{s.fire("error",i)})},0)}};var pW={type:Yt,base:0,count:6,indexed:!0},mW=` + attribute vec2 vertex_position; + varying vec2 pcTexCoord; + void main() { + gl_Position = vec4(vertex_position, 0.0, 1.0); + pcTexCoord = vertex_position * 0.5 + 0.5; + } +`,_W=` + uniform sampler2D pcSource; + varying vec2 pcTexCoord; + void main() { + gl_FragColor = texture2D(pcSource, pcTexCoord); + } +`,Wv=class{constructor(t){n(this,"_device");n(this,"_shader",null);n(this,"_scratchTex",null);n(this,"_scratchRt",null);n(this,"_sourceId",null);this._device=t}_getShader(){if(!this._shader){let t=this._device;this._shader=new Be(t,ns.createDefinition(t,{name:"XrMsaaCopy",attributes:{vertex_position:ee},vertexCode:mW,fragmentCode:_W})),this._sourceId=t.scope.resolve("pcSource")}return this._shader}_ensureScratch(t,e){let s=this._device;this._scratchTex&&(this._scratchTex.width!==t||this._scratchTex.height!==e)&&(this._scratchRt.destroy(),this._scratchRt=null,this._scratchTex.destroy(),this._scratchTex=null),this._scratchTex||(this._scratchTex=Z.createDataTexture2D(s,"XrMsaaScratch",t,e,s.backBufferFormat),this._scratchRt=new me({colorBuffer:this._scratchTex,depth:!1,stencil:!1})),this._scratchRt.impl.initialized||this._scratchRt.impl.init(s,this._scratchRt)}copy(t,e,s,i){this._ensureScratch(s,i);let r=this._device,a=r.gl;a.bindFramebuffer(a.READ_FRAMEBUFFER,t),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._scratchRt.impl._glFrameBuffer),a.blitFramebuffer(0,0,s,i,0,0,s,i,a.COLOR_BUFFER_BIT,a.NEAREST),r.setDrawStates(Oe.NOBLEND,Pt.NODEPTH),r.setFramebuffer(e),r.setShader(this._getShader()),r.clearVertexBuffer(),r.setVertexBuffer(r.quadVertexBuffer),this._sourceId.setValue(this._scratchTex);let{vx:o,vy:l,vw:h,vh:f,sx:u,sy:d,sw:p,sh:m}=r;r.setViewport(0,0,s,i),r.setScissor(0,0,s,i),r.draw(pW,r.quadIndexBuffer),r.setViewport(o,l,h,f),r.setScissor(u,d,p,m),r.setFramebuffer(t)}destroy(){this._shader?.destroy(),this._shader=null,this._scratchRt?.destroy(),this._scratchRt=null,this._scratchTex?.destroy(),this._scratchTex=null,this._sourceId=null}};var XP=class{constructor(){n(this,"renderVersion");n(this,"queries",[])}destroy(t){this.queries.forEach(e=>t.deleteQuery(e)),this.queries=null}},Xv=class extends Yd{constructor(e){super();n(this,"device");n(this,"freeQueries",[]);n(this,"frameQueries",[]);n(this,"previousFrameQueries",[]);n(this,"timings",[]);this.device=e,this.ext=e.extDisjointTimerQuery}destroy(){this.freeQueries.forEach(e=>this.device.gl.deleteQuery(e)),this.frameQueries.forEach(e=>this.device.gl.deleteQuery(e)),this.previousFrameQueries.forEach(e=>e.destroy(this.device.gl)),this.freeQueries=null,this.frameQueries=null,this.previousFrameQueries=null}loseContext(){super.loseContext(),this.freeQueries=[],this.frameQueries=[],this.previousFrameQueries=[]}restoreContext(){this.ext=this.device.extDisjointTimerQuery}getQuery(){return this.freeQueries.pop()??this.device.gl.createQuery()}start(e){if(this.ext){let s=this.getSlot(e),i=this.getQuery();return this.frameQueries[s]=i,this.device.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,i),s}}end(e){e!==void 0&&this.device.gl.endQuery(this.ext.TIME_ELAPSED_EXT)}frameStart(){this.processEnableRequest(),this._enabled&&(this.frameGPUMarkerSlot=this.start("GpuFrame"))}frameEnd(){this._enabled&&this.end(this.frameGPUMarkerSlot)}request(){if(this._enabled){let e=this.ext,s=this.device.gl,i=this.device.renderVersion,r=this.frameQueries;if(r.length>0){this.frameQueries=[];let a=new XP;a.queries=r,a.renderVersion=i,this.previousFrameQueries.push(a)}if(this.previousFrameQueries.length>0){let a=this.previousFrameQueries[0],o=a.queries,l=o[o.length-1],h=s.getQueryParameter(l,s.QUERY_RESULT_AVAILABLE),f=s.getParameter(e.GPU_DISJOINT_EXT);if(h&&!f){this.previousFrameQueries.shift();let u=this.timings;u.length=0;for(let d=0;d{this.report(u.renderVersion,null),u.destroy(s)}),this.previousFrameQueries.length=0)}super.request(i)}}};var gW=c=>{switch(c){case Wr:return 1;case Po:return 2;default:return 0}},qd=[],pc=class extends tt{constructor(e,s={}){super(e,s);n(this,"gl");n(this,"_defaultFramebuffer",null);n(this,"_defaultFramebufferChanged",!1);n(this,"_xrMsaaCopy",null);s=this.initOptions,this.updateClientRect(),this.initTextureUnits(),this.contextLost=!1,this._contextLostHandler=m=>{m.preventDefault(),this.loseContext()},this._contextRestoredHandler=()=>{this.restoreContext()};let i=typeof navigator<"u"&&navigator.userAgent;if(this.forceDisableMultisampling=i&&i.includes("AppleWebKit")&&(i.includes("15.4")||i.includes("15_4")),this.forceDisableMultisampling&&(s.antialias=!1),ue.browserName==="firefox"){let _=(typeof navigator<"u"?navigator.userAgent:"").match(/Firefox\/(\d+(\.\d+)*)/),S=_?_[1]:null;if(S){let g=parseFloat(S);(ue.name==="windows"&&(g>=120||g===115)||ue.name==="android"&&g>=132)&&(s.antialias=!1)}}this.backBufferAntialias=s.antialias??!1,s.antialias=!1;let r=s.gl??e.getContext("webgl2",s);if(!r)throw new Error("WebGL not supported");this.gl=r,this.isWebGL2=!0,this._deviceType=vf,this.updateBackbufferFormat(null);let a=ue.browserName==="chrome",o=ue.browserName==="safari",l=ue.browser&&navigator.appVersion.indexOf("Mac")!==-1;this._tempEnableSafariTextureUnitWorkaround=o,this._tempMacChromeBlitFramebufferWorkaround=l&&a&&!s.alpha,e.addEventListener("webglcontextlost",this._contextLostHandler,!1),e.addEventListener("webglcontextrestored",this._contextRestoredHandler,!1),this.initializeExtensions(),this.initializeCapabilities(),this.initializeRenderState(),this.initializeContextCaches(),this.createBackbuffer(null),this.supportsImageBitmap=!o&&typeof ImageBitmap<"u",this._samplerTypes=new Set([r.SAMPLER_2D,r.SAMPLER_CUBE,r.UNSIGNED_INT_SAMPLER_2D,r.INT_SAMPLER_2D,r.SAMPLER_2D_SHADOW,r.SAMPLER_CUBE_SHADOW,r.SAMPLER_3D,r.INT_SAMPLER_3D,r.UNSIGNED_INT_SAMPLER_3D,r.SAMPLER_2D_ARRAY,r.INT_SAMPLER_2D_ARRAY,r.UNSIGNED_INT_SAMPLER_2D_ARRAY]),this.glAddress=[r.REPEAT,r.CLAMP_TO_EDGE,r.MIRRORED_REPEAT],this.glBlendEquation=[r.FUNC_ADD,r.FUNC_SUBTRACT,r.FUNC_REVERSE_SUBTRACT,r.MIN,r.MAX],this.glBlendFunctionColor=[r.ZERO,r.ONE,r.SRC_COLOR,r.ONE_MINUS_SRC_COLOR,r.DST_COLOR,r.ONE_MINUS_DST_COLOR,r.SRC_ALPHA,r.SRC_ALPHA_SATURATE,r.ONE_MINUS_SRC_ALPHA,r.DST_ALPHA,r.ONE_MINUS_DST_ALPHA,r.CONSTANT_COLOR,r.ONE_MINUS_CONSTANT_COLOR],this.glBlendFunctionAlpha=[r.ZERO,r.ONE,r.SRC_COLOR,r.ONE_MINUS_SRC_COLOR,r.DST_COLOR,r.ONE_MINUS_DST_COLOR,r.SRC_ALPHA,r.SRC_ALPHA_SATURATE,r.ONE_MINUS_SRC_ALPHA,r.DST_ALPHA,r.ONE_MINUS_DST_ALPHA,r.CONSTANT_ALPHA,r.ONE_MINUS_CONSTANT_ALPHA],this.glComparison=[r.NEVER,r.LESS,r.EQUAL,r.LEQUAL,r.GREATER,r.NOTEQUAL,r.GEQUAL,r.ALWAYS],this.glStencilOp=[r.KEEP,r.ZERO,r.REPLACE,r.INCR,r.INCR_WRAP,r.DECR,r.DECR_WRAP,r.INVERT],this.glClearFlag=[0,r.COLOR_BUFFER_BIT,r.DEPTH_BUFFER_BIT,r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT,r.STENCIL_BUFFER_BIT,r.STENCIL_BUFFER_BIT|r.COLOR_BUFFER_BIT,r.STENCIL_BUFFER_BIT|r.DEPTH_BUFFER_BIT,r.STENCIL_BUFFER_BIT|r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT],this.glCull=[0,r.BACK,r.FRONT,r.FRONT_AND_BACK],this.glFrontFace=[r.CCW,r.CW],this.glFilter=[r.NEAREST,r.LINEAR,r.NEAREST_MIPMAP_NEAREST,r.NEAREST_MIPMAP_LINEAR,r.LINEAR_MIPMAP_NEAREST,r.LINEAR_MIPMAP_LINEAR],this.glPrimitive=[r.POINTS,r.LINES,r.LINE_LOOP,r.LINE_STRIP,r.TRIANGLES,r.TRIANGLE_STRIP,r.TRIANGLE_FAN],this.glType=[r.BYTE,r.UNSIGNED_BYTE,r.SHORT,r.UNSIGNED_SHORT,r.INT,r.UNSIGNED_INT,r.FLOAT,r.HALF_FLOAT],this.pcUniformType={},this.pcUniformType[r.BOOL]=wo,this.pcUniformType[r.INT]=bi,this.pcUniformType[r.FLOAT]=Te,this.pcUniformType[r.FLOAT_VEC2]=pr,this.pcUniformType[r.FLOAT_VEC3]=Kt,this.pcUniformType[r.FLOAT_VEC4]=oi,this.pcUniformType[r.INT_VEC2]=jr,this.pcUniformType[r.INT_VEC3]=Di,this.pcUniformType[r.INT_VEC4]=qr,this.pcUniformType[r.BOOL_VEC2]=Dn,this.pcUniformType[r.BOOL_VEC3]=Ln,this.pcUniformType[r.BOOL_VEC4]=Mn,this.pcUniformType[r.FLOAT_MAT2]=lc,this.pcUniformType[r.FLOAT_MAT3]=La,this.pcUniformType[r.FLOAT_MAT4]=as,this.pcUniformType[r.SAMPLER_2D]=eP,this.pcUniformType[r.SAMPLER_CUBE]=tP,this.pcUniformType[r.UNSIGNED_INT]=pe,this.pcUniformType[r.UNSIGNED_INT_VEC2]=Ma,this.pcUniformType[r.UNSIGNED_INT_VEC3]=Oa,this.pcUniformType[r.UNSIGNED_INT_VEC4]=Li,this.pcUniformType[r.SAMPLER_2D_SHADOW]=sP,this.pcUniformType[r.SAMPLER_CUBE_SHADOW]=iP,this.pcUniformType[r.SAMPLER_2D_ARRAY]=aP,this.pcUniformType[r.SAMPLER_3D]=rP,this.pcUniformType[r.INT_SAMPLER_2D]=oP,this.pcUniformType[r.UNSIGNED_INT_SAMPLER_2D]=nP,this.pcUniformType[r.INT_SAMPLER_CUBE]=lP,this.pcUniformType[r.UNSIGNED_INT_SAMPLER_2D]=cP,this.pcUniformType[r.INT_SAMPLER_3D]=hP,this.pcUniformType[r.UNSIGNED_INT_SAMPLER_3D]=fP,this.pcUniformType[r.INT_SAMPLER_2D_ARRAY]=uP,this.pcUniformType[r.UNSIGNED_INT_SAMPLER_2D_ARRAY]=dP,this.targetToSlot={},this.targetToSlot[r.TEXTURE_2D]=0,this.targetToSlot[r.TEXTURE_CUBE_MAP]=1,this.targetToSlot[r.TEXTURE_3D]=2;let h,f,u,d,p;this.commitFunction=[],this.commitFunction[wo]=function(m,_){m.value!==_&&(r.uniform1i(m.locationId,_),m.value=_)},this.commitFunction[bi]=this.commitFunction[wo],this.commitFunction[Te]=function(m,_){m.value!==_&&(r.uniform1f(m.locationId,_),m.value=_)},this.commitFunction[pr]=function(m,_){p=m.value,h=_[0],f=_[1],(p[0]!==h||p[1]!==f)&&(r.uniform2fv(m.locationId,_),p[0]=h,p[1]=f)},this.commitFunction[Kt]=function(m,_){p=m.value,h=_[0],f=_[1],u=_[2],(p[0]!==h||p[1]!==f||p[2]!==u)&&(r.uniform3fv(m.locationId,_),p[0]=h,p[1]=f,p[2]=u)},this.commitFunction[oi]=function(m,_){p=m.value,h=_[0],f=_[1],u=_[2],d=_[3],(p[0]!==h||p[1]!==f||p[2]!==u||p[3]!==d)&&(r.uniform4fv(m.locationId,_),p[0]=h,p[1]=f,p[2]=u,p[3]=d)},this.commitFunction[jr]=function(m,_){p=m.value,h=_[0],f=_[1],(p[0]!==h||p[1]!==f)&&(r.uniform2iv(m.locationId,_),p[0]=h,p[1]=f)},this.commitFunction[Dn]=this.commitFunction[jr],this.commitFunction[Di]=function(m,_){p=m.value,h=_[0],f=_[1],u=_[2],(p[0]!==h||p[1]!==f||p[2]!==u)&&(r.uniform3iv(m.locationId,_),p[0]=h,p[1]=f,p[2]=u)},this.commitFunction[Ln]=this.commitFunction[Di],this.commitFunction[qr]=function(m,_){p=m.value,h=_[0],f=_[1],u=_[2],d=_[3],(p[0]!==h||p[1]!==f||p[2]!==u||p[3]!==d)&&(r.uniform4iv(m.locationId,_),p[0]=h,p[1]=f,p[2]=u,p[3]=d)},this.commitFunction[Mn]=this.commitFunction[qr],this.commitFunction[lc]=function(m,_){r.uniformMatrix2fv(m.locationId,!1,_)},this.commitFunction[La]=function(m,_){r.uniformMatrix3fv(m.locationId,!1,_)},this.commitFunction[as]=function(m,_){r.uniformMatrix4fv(m.locationId,!1,_)},this.commitFunction[On]=function(m,_){r.uniform1fv(m.locationId,_)},this.commitFunction[Fn]=function(m,_){r.uniform2fv(m.locationId,_)},this.commitFunction[Nn]=function(m,_){r.uniform3fv(m.locationId,_)},this.commitFunction[gf]=function(m,_){r.uniform4fv(m.locationId,_)},this.commitFunction[pe]=function(m,_){m.value!==_&&(r.uniform1ui(m.locationId,_),m.value=_)},this.commitFunction[Ma]=function(m,_){p=m.value,h=_[0],f=_[1],(p[0]!==h||p[1]!==f)&&(r.uniform2uiv(m.locationId,_),p[0]=h,p[1]=f)},this.commitFunction[Oa]=function(m,_){p=m.value,h=_[0],f=_[1],u=_[2],(p[0]!==h||p[1]!==f||p[2]!==u)&&(r.uniform3uiv(m.locationId,_),p[0]=h,p[1]=f,p[2]=u)},this.commitFunction[Li]=function(m,_){p=m.value,h=_[0],f=_[1],u=_[2],d=_[3],(p[0]!==h||p[1]!==f||p[2]!==u||p[3]!==d)&&(r.uniform4uiv(m.locationId,_),p[0]=h,p[1]=f,p[2]=u,p[3]=d)},this.commitFunction[Fa]=function(m,_){r.uniform1iv(m.locationId,_)},this.commitFunction[Bn]=function(m,_){r.uniform1uiv(m.locationId,_)},this.commitFunction[Un]=this.commitFunction[Fa],this.commitFunction[Na]=function(m,_){r.uniform2iv(m.locationId,_)},this.commitFunction[kn]=function(m,_){r.uniform2uiv(m.locationId,_)},this.commitFunction[zn]=this.commitFunction[Na],this.commitFunction[Ba]=function(m,_){r.uniform3iv(m.locationId,_)},this.commitFunction[Gn]=function(m,_){r.uniform3uiv(m.locationId,_)},this.commitFunction[Vn]=this.commitFunction[Ba],this.commitFunction[cc]=function(m,_){r.uniform4iv(m.locationId,_)},this.commitFunction[Sf]=function(m,_){r.uniform4uiv(m.locationId,_)},this.commitFunction[xf]=this.commitFunction[cc],this.commitFunction[wg]=function(m,_){r.uniformMatrix4fv(m.locationId,!1,_)},this.constantTexSource=this.scope.resolve("source"),this.postInit()}postInit(){super.postInit(),this.gpuProfiler=new Xv(this)}destroy(){super.destroy();let e=this.gl;this.feedback&&e.deleteTransformFeedback(this.feedback),this.clearVertexArrayObjectCache(),this._xrMsaaCopy?.destroy(),this._xrMsaaCopy=null,this.canvas.removeEventListener("webglcontextlost",this._contextLostHandler,!1),this.canvas.removeEventListener("webglcontextrestored",this._contextRestoredHandler,!1),this._contextLostHandler=null,this._contextRestoredHandler=null,this.gl=null,super.postDestroy()}createBackbuffer(e){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new me({name:"WebglFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.backBuffer.impl.suppliedColorFramebuffer=e}updateBackbufferFormat(e){let s=this.gl;s.bindFramebuffer(s.FRAMEBUFFER,e);let i=this.gl.getParameter(this.gl.ALPHA_BITS);this.backBufferFormat=i?ce:Ss}updateBackbuffer(){let e=this.canvas.width!==this.backBufferSize.x||this.canvas.height!==this.backBufferSize.y;(this._defaultFramebufferChanged||e)&&(this._defaultFramebufferChanged&&this.updateBackbufferFormat(this._defaultFramebuffer),this._defaultFramebufferChanged=!1,this.backBufferSize.set(this.canvas.width,this.canvas.height),this.backBuffer.destroy(),this.createBackbuffer(this._defaultFramebuffer))}createVertexBufferImpl(e,s){return new Fv}createIndexBufferImpl(e){return new Nv(e)}createShaderImpl(e){return new Uv(e)}createDrawCommandImpl(e){return new kv(e.indexSizeBytes)}createTextureImpl(e){return this.textures.add(e),new zv(e)}createXrBridgeImpl(e){return new Hv(e)}createRenderTargetImpl(e){return new Gv}createUploadStreamImpl(e){return new Vv(e)}getPrecision(){let e=this.gl,s="highp";if(e.getShaderPrecisionFormat){let i=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT),r=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT),a=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT),o=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT);if(i&&r&&a&&o){let l=i.precision>0&&a.precision>0,h=r.precision>0&&o.precision>0;l||(h?s="mediump":s="lowp")}}return s}getExtension(){for(let e=0;e0&&e.fullSizeClearRect&&r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER,qd),i&&e.colorOps?.resolve&&e.samples>1&&s.autoResolve&&s.resolve(!0,!1),s.depthBuffer&&e.depthStencilOps.resolveDepth&&e.samples>1&&s.autoResolve&&s.resolve(!1,!0);for(let a=0;a1&&e.autoResolve&&e.resolve();let s=e._colorBuffer;s&&s.impl._glTexture&&s.mipmaps&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(s),this.gl.generateMipmap(s.impl._glTarget))}}setUnpackFlipY(e){if(this.unpackFlipY!==e){this.unpackFlipY=e;let s=this.gl;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,e)}}setUnpackPremultiplyAlpha(e){if(this.unpackPremultiplyAlpha!==e){this.unpackPremultiplyAlpha=e;let s=this.gl;s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e)}}setUnpackAlignment(e){this.unpackAlignment!==e&&(this.unpackAlignment=e,this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT,e))}activeTexture(e){this.textureUnit!==e&&(this.gl.activeTexture(this.gl.TEXTURE0+e),this.textureUnit=e)}bindTexture(e){let s=e.impl,i=s._glTarget,r=s._glTexture,a=this.textureUnit,o=this.targetToSlot[i];this.textureUnits[a][o]!==r&&(this.gl.bindTexture(i,r),this.textureUnits[a][o]=r)}bindTextureOnUnit(e,s){let i=e.impl,r=i._glTarget,a=i._glTexture,o=this.targetToSlot[r];this.textureUnits[s][o]!==a&&(this.activeTexture(s),this.gl.bindTexture(r,a),this.textureUnits[s][o]=a)}setTextureParameters(e){let s=this.gl,i=e.impl.dirtyParameterFlags,r=e.impl._glTarget;if(i&Od){let a=e._minFilter;(!e._mipmaps||e._compressed&&e._levels.length===1)&&(a===2||a===3?a=0:(a===4||a===5)&&(a=1)),s.texParameteri(r,s.TEXTURE_MIN_FILTER,this.glFilter[a])}if(i&Rg&&s.texParameteri(r,s.TEXTURE_MAG_FILTER,this.glFilter[e._magFilter]),i&bg&&s.texParameteri(r,s.TEXTURE_WRAP_S,this.glAddress[e._addressU]),i&Dg&&s.texParameteri(r,s.TEXTURE_WRAP_T,this.glAddress[e._addressV]),i&Lg&&s.texParameteri(r,s.TEXTURE_WRAP_R,this.glAddress[e._addressW]),i&Mg&&s.texParameteri(r,s.TEXTURE_COMPARE_MODE,e._compareOnRead?s.COMPARE_REF_TO_TEXTURE:s.NONE),i&Og&&s.texParameteri(r,s.TEXTURE_COMPARE_FUNC,this.glComparison[e._compareFunc]),i&Fg){let a=this.extTextureFilterAnisotropic;a&&s.texParameterf(r,a.TEXTURE_MAX_ANISOTROPY_EXT,R.clamp(Math.round(e._anisotropy),1,this.maxAnisotropy))}}setTexture(e,s){let i=e.impl;i._glTexture||i.initialize(this,e),i.dirtyParameterFlags>0||e._needsUpload||e._needsMipmapsUpload?(this.activeTexture(s),this.bindTexture(e),i.dirtyParameterFlags&&(this.setTextureParameters(e),i.dirtyParameterFlags=0),(e._needsUpload||e._needsMipmapsUpload)&&(i.upload(this,e),e._needsUpload=!1,e._needsMipmapsUpload=!1)):this.bindTextureOnUnit(e,s)}createVertexArray(e){let s,i,r=e.length>1;if(r){s="";for(let a=0;a0)for(let p=0;p0)for(let d=0;d0?this.extMultiDraw.multiDrawElementsInstancedWEBGL(p,_.glCounts,0,S,_.glOffsetsBytes,0,_.glInstanceCounts,0,r.count):this.extMultiDraw.multiDrawElementsWEBGL(p,_.glCounts,0,S,_.glOffsetsBytes,0,r.count)}else i>0?this.extMultiDraw.multiDrawArraysInstancedWEBGL(p,_.glOffsetsBytes,0,_.glCounts,0,_.glInstanceCounts,0,r.count):this.extMultiDraw.multiDrawArraysWEBGL(p,_.glOffsetsBytes,0,_.glCounts,0,r.count)}else this._multiDrawLoopFallback(p,e,s,i,r);else if(e.indexed){let _=s.impl.glFormat,S=e.base*s.bytesPerIndex;i>0?h.drawElementsInstanced(p,m,_,S,i):h.drawElements(p,m,_,S)}else{let _=e.base;i>0?h.drawArraysInstanced(p,_,m,i):h.drawArrays(p,_,m)}this.transformFeedbackBuffer&&(h.endTransformFeedback(),h.bindBufferBase(h.TRANSFORM_FEEDBACK_BUFFER,0,null)),this._drawCallsPerFrame++}o&&this.clearVertexBuffer()}clear(e){let s=this.defaultClearOptions;e=e||s;let i=e.flags??s.flags;if(i!==0){let r=this.gl;if(i&1){let a=e.color??s.color,o=a[0],l=a[1],h=a[2],f=a[3],u=this.clearColor;(o!==u.r||l!==u.g||h!==u.b||f!==u.a)&&(this.gl.clearColor(o,l,h,f),this.clearColor.set(o,l,h,f)),this.setBlendState(Oe.NOBLEND)}if(i&2){let a=e.depth??s.depth;a!==this.clearDepth&&(this.gl.clearDepth(a),this.clearDepth=a),this.setDepthState(Pt.WRITEDEPTH)}if(i&4){let a=e.stencil??s.stencil;a!==this.clearStencil&&(this.gl.clearStencil(a),this.clearStencil=a),r.stencilMask(255),this.stencilWriteMaskFront=255,this.stencilWriteMaskBack=255}r.clear(this.glClearFlag[i])}}submit(){this.gl.flush()}readPixels(e,s,i,r,a){let o=this.gl;o.readPixels(e,s,i,r,o.RGBA,o.UNSIGNED_BYTE,a)}clientWaitAsync(e,s){let i=this.gl,r=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);return this.submit(),new Promise((a,o)=>{function l(){let h=i.clientWaitSync(r,e,0);h===i.TIMEOUT_EXPIRED?setTimeout(l,s):(i.deleteSync(r),h===i.WAIT_FAILED?o(new Error("webgl clientWaitSync sync failed")):a())}l()})}async readPixelsAsync(e,s,i,r,a,o=!1){let l=this.gl,h,f;if(o)h=l.RGBA,f=l.UNSIGNED_BYTE;else{let d=this.renderTarget.colorBuffer?.impl;h=d?._glFormat??l.RGBA,f=d?._glPixelType??l.UNSIGNED_BYTE}let u=l.createBuffer();return l.bindBuffer(l.PIXEL_PACK_BUFFER,u),l.bufferData(l.PIXEL_PACK_BUFFER,a.byteLength,l.STREAM_READ),l.readPixels(e,s,i,r,h,f,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),await this.clientWaitAsync(0,16),l.bindBuffer(l.PIXEL_PACK_BUFFER,u),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,a),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(u),a}readTextureAsync(e,s,i,r,a,o){let l=o.face??0,h=o.mipLevel??0,f=o.renderTarget??new me({colorBuffer:e,depth:!1,face:l,mipLevel:h}),u=gW(e._format),d=u>0,p=pf(e._format),m=o.data??new p(gt.calcLevelGpuSize(r,a,1,e._format)/p.BYTES_PER_ELEMENT),_=d?new Uint8Array(r*a*4):m;return this.setRenderTarget(f),this.initRenderTarget(f),this.setFramebuffer(f.impl._glFrameBuffer),o.immediate&&this.gl.flush(),new Promise((S,g)=>{this.readPixelsAsync(s,i,r,a,_,d).then(C=>{if(!this._destroyed)if(o.renderTarget||f.destroy(),d){let v=r*a;for(let E=0;E{e.deleteVertexArray(s)}),this._vaoMap.clear()}set fullscreen(e){e?this.gl.canvas.requestFullscreen():document.exitFullscreen()}get fullscreen(){return!!document.fullscreenElement}};var Yv=class{unlock(t){}};var Kv=class{destroy(t){}init(t,e){}loseContext(){}resolve(t,e,s,i){}};var jv=class{destroy(t){}loseContext(){}restoreContext(t,e){}};var qv=class{destroy(t){}propertyChanged(t){}loseContext(){}};var $v=class{destroy(t){}unlock(t){}};var Zv=class{add(t,e,s,i){}};var $d=class extends tt{constructor(t,e={}){super(t,e),e=this.initOptions,this.isNull=!0,this._deviceType=Tf,this.samples=1,this.backBuffer=new me({name:"Framebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.initDeviceCaps()}destroy(){super.destroy()}initDeviceCaps(){this.disableParticleSystem=!0,this.precision="highp",this.maxPrecision="highp",this.maxSamples=4,this.maxTextures=16,this.maxTextureSize=4096,this.maxCubeMapSize=4096,this.maxVolumeSize=4096,this.maxColorAttachments=8,this.maxPixelRatio=1,this.maxAnisotropy=16,this.supportsUniformBuffers=!1,this.supportsAreaLights=!0,this.supportsGpuParticles=!1,this.textureFloatRenderable=!0,this.textureHalfFloatRenderable=!0,this.supportsImageBitmap=!1}postInit(){super.postInit()}frameStart(){super.frameStart()}frameEnd(){super.frameEnd()}updateBegin(){}updateEnd(){}readPixels(t,e,s,i,r){}createVertexBufferImpl(t,e){return new $v(t,e)}createIndexBufferImpl(t){return new Yv(t)}createShaderImpl(t){return new jv(t)}createTextureImpl(t){return new qv(t)}createRenderTargetImpl(t){return new Kv(t)}createDrawCommandImpl(t){return new Zv}createUploadStreamImpl(t){return null}draw(t,e,s,i,r=!0,a=!0){}setShader(t,e=!1){}setBlendState(t){}setDepthState(t){}setStencilState(t,e){}setBlendColor(t,e,s,i){}setCullMode(t){}setFrontFace(t){}setAlphaToCoverage(t){}initializeContextCaches(){super.initializeContextCaches()}clear(t){}setViewport(t,e,s,i){}setScissor(t,e,s,i){}copyRenderTarget(t,e,s,i){return!0}};function iL(c,t={}){let e=t.deviceTypes??[];e.includes(vf)||e.push(vf),e.includes(Tf)||e.push(Tf);let s=[];for(let i=0;inew Kd(c,{...t,featureLevel:a}).initWebGpu(t.glslangUrl,t.twgslUrl))}r===vf&&s.push(()=>new pc(c,t)),r===Tf&&s.push(()=>new $d(c,t))}return new Promise((i,r)=>{let a=0,o=()=>{a>=s.length?r(new Error("Failed to create a graphics device")):Promise.resolve(s[a++]()).then(l=>{l?i(l):o()}).catch(l=>{o()})};o()})}var YP=class{constructor(){n(this,"value");n(this,"scopeId",null)}},Ye=class{constructor(t,e,s="Unnamed"){n(this,"shader",null);n(this,"name");n(this,"parameters",new Map);n(this,"countX",1);n(this,"countY");n(this,"countZ");n(this,"indirectSlotIndex",-1);n(this,"indirectBuffer",null);n(this,"indirectFrameStamp",0);this.device=t,this.shader=e,this.name=s,t.supportsCompute&&(this.impl=t.createComputeImpl(this))}setParameter(t,e){let s=this.parameters.get(t);s||(s=new YP,s.scopeId=this.device.scope.resolve(t),this.parameters.set(t,s)),s.value=e}getParameter(t){return this.parameters.get(t)?.value}deleteParameter(t){this.parameters.delete(t)}destroy(){this.impl?.destroy(),this.impl=null}applyParameters(){for(let[,t]of this.parameters)t.scopeId.setValue(t.value)}setupDispatch(t,e,s){this.countX=t,this.countY=e,this.countZ=s,this.indirectSlotIndex=-1,this.indirectBuffer=null}setupIndirectDispatch(t,e=null){this.indirectSlotIndex=t,this.indirectBuffer=e,this.indirectFrameStamp=this.device.renderVersion}static calcDispatchSize(t,e,s=65535){if(t<=s)return e.set(t,1);let i=Math.ceil(t/s);return e.set(Math.ceil(t/i),i)}};var Cf=class{constructor(t,e=0){n(this,"device");n(this,"indexSizeBytes");n(this,"_maxCount",0);n(this,"impl",null);n(this,"_count",1);n(this,"slotIndex",0);n(this,"primitiveCount",0);this.device=t,this.indexSizeBytes=e,this.impl=t.createDrawCommandImpl(this)}get maxCount(){return this._maxCount}get count(){return this._count}destroy(){this.impl?.destroy?.(),this.impl=null}allocate(t){this._maxCount=t,this.impl.allocate?.(t)}add(t,e,s,i,r=0,a=0){this.impl.add(t,e,s,i,r,a)}update(t){this._count=t,this.primitiveCount=this.impl.update?.(t)??0}};var Nt=class{constructor(t){n(this,"_name");n(this,"device");n(this,"_enabled",!0);n(this,"_skipStart",!1);n(this,"_skipEnd",!1);n(this,"executeEnabled",!0);n(this,"requiresCubemaps",!1);n(this,"beforePasses",[]);n(this,"afterPasses",[]);this.device=t}set name(t){this._name=t}get name(){return this._name||(this._name=this.constructor.name),this._name}set enabled(t){this._enabled!==t&&(this._enabled=t,t?this.onEnable():this.onDisable())}get enabled(){return this._enabled}onEnable(){}onDisable(){}frameUpdate(){}before(){}execute(){}after(){}destroy(){}render(){this.enabled&&(this.before(),this.executeEnabled&&this.execute(),this.after(),this.device.renderPassIndex++)}};var KP=class{constructor(){n(this,"clearValue",new F(0,0,0,1));n(this,"clearValueLinear",new F(0,0,0,1));n(this,"clear",!1);n(this,"store",!1);n(this,"resolve",!0);n(this,"genMipmaps",!1)}},jP=class{constructor(){n(this,"clearDepthValue",1);n(this,"clearStencilValue",0);n(this,"clearDepth",!1);n(this,"clearStencil",!1);n(this,"storeDepth",!1);n(this,"resolveDepth",!1);n(this,"storeStencil",!1)}},yt=class extends Nt{constructor(){super(...arguments);n(this,"renderTarget");n(this,"_options");n(this,"samples",0);n(this,"colorArrayOps",[]);n(this,"depthStencilOps");n(this,"requiresCubemaps",!0);n(this,"fullSizeClearRect",!0)}get colorOps(){return this.colorArrayOps[0]}set scaleX(e){this._options.scaleX=e}get scaleX(){return this._options.scaleX}set scaleY(e){this._options.scaleY=e}get scaleY(){return this._options.scaleY}set options(e){this._options=e,e&&(this.scaleX=this.scaleX??1,this.scaleY=this.scaleY??1)}get options(){return this._options}init(e=null,s){this.options=s,this.renderTarget=e,this.samples=Math.max(this.renderTarget?this.renderTarget.samples:this.device.samples,1),this.allocateAttachments(),this.postInit()}allocateAttachments(){let e=this.renderTarget;this.depthStencilOps=new jP,e?.depthBuffer&&(this.depthStencilOps.storeDepth=!0);let s=e?e._colorBuffers?.length??0:1;this.colorArrayOps.length=0;for(let i=0;ithis.vertexBuffer.numVertices&&(s=this.vertexBuffer.numVertices);let r=i.numComponents;if(this.vertexBuffer.getFormat().interleaved){let a=0;for(let o=0;os*r){let a=s*r;if(ArrayBuffer.isView(e))e=e.subarray(0,a),i.array.set(e);else for(let o=0;o0?this.wheelDelta=1:e.deltaY<0&&(this.wheelDelta=-1)),tT()?(this.dx=e.movementX||e.webkitMovementX||e.mozMovementX||0,this.dy=e.movementY||e.webkitMovementY||e.mozMovementY||0):(this.dx=this.x-t._lastX,this.dy=this.y-t._lastY),(e.type==="mousedown"||e.type==="mouseup")&&(this.button=e.button),this.buttons=t._buttons.slice(0),this.element=e.target,this.ctrlKey=e.ctrlKey??!1,this.altKey=e.altKey??!1,this.shiftKey=e.shiftKey??!1,this.metaKey=e.metaKey??!1,this.event=e}};var qi=class extends J{constructor(e){super();n(this,"_lastX",0);n(this,"_lastY",0);n(this,"_buttons",[!1,!1,!1]);n(this,"_lastbuttons",[!1,!1,!1]);n(this,"_target",null);n(this,"_attached",!1);n(this,"_upHandler");n(this,"_downHandler");n(this,"_moveHandler");n(this,"_wheelHandler");n(this,"_contextMenuHandler");this._upHandler=this._handleUp.bind(this),this._downHandler=this._handleDown.bind(this),this._moveHandler=this._handleMove.bind(this),this._wheelHandler=this._handleWheel.bind(this),this._contextMenuHandler=s=>{s.preventDefault()},this.attach(e)}static isPointerLocked(){return tT()}attach(e){if(this._target=e,this._attached)return;this._attached=!0;let s={passive:!1},i=ue.passiveEvents?s:!1;window.addEventListener("mouseup",this._upHandler,i),window.addEventListener("mousedown",this._downHandler,i),window.addEventListener("mousemove",this._moveHandler,i),window.addEventListener("wheel",this._wheelHandler,i)}detach(){if(!this._attached)return;this._attached=!1,this._target=null;let e={passive:!1},s=ue.passiveEvents?e:!1;window.removeEventListener("mouseup",this._upHandler,s),window.removeEventListener("mousedown",this._downHandler,s),window.removeEventListener("mousemove",this._moveHandler,s),window.removeEventListener("wheel",this._wheelHandler,s)}disableContextMenu(){this._target&&this._target.addEventListener("contextmenu",this._contextMenuHandler)}enableContextMenu(){this._target&&this._target.removeEventListener("contextmenu",this._contextMenuHandler)}enablePointerLock(e,s){if(!document.body.requestPointerLock){s&&s();return}let i=()=>{e(),document.removeEventListener("pointerlockchange",i)},r=()=>{s(),document.removeEventListener("pointerlockerror",r)};e&&document.addEventListener("pointerlockchange",i,!1),s&&document.addEventListener("pointerlockerror",r,!1),document.body.requestPointerLock()}disablePointerLock(e){if(!document.exitPointerLock)return;let s=()=>{e(),document.removeEventListener("pointerlockchange",s)};e&&document.addEventListener("pointerlockchange",s,!1),document.exitPointerLock()}update(){this._lastbuttons[0]=this._buttons[0],this._lastbuttons[1]=this._buttons[1],this._lastbuttons[2]=this._buttons[2]}isPressed(e){return this._buttons[e]}wasPressed(e){return this._buttons[e]&&!this._lastbuttons[e]}wasReleased(e){return!this._buttons[e]&&this._lastbuttons[e]}_handleUp(e){this._buttons[e.button]=!1;let s=new za(this,e);s.event&&this.fire("mouseup",s)}_handleDown(e){this._buttons[e.button]=!0;let s=new za(this,e);s.event&&this.fire("mousedown",s)}_handleMove(e){let s=new za(this,e);s.event&&(this.fire("mousemove",s),this._lastX=s.x,this._lastY=s.y)}_handleWheel(e){let s=new za(this,e);s.event&&this.fire("mousewheel",s)}_getTargetCoords(e){let s=this._target.getBoundingClientRect(),i=Math.floor(s.left),r=Math.floor(s.top);return e.clientX=i+this._target.clientWidth||e.clientY=r+this._target.clientHeight?null:{x:e.clientX-i,y:e.clientY-r}}};n(qi,"EVENT_MOUSEMOVE","mousemove"),n(qi,"EVENT_MOUSEDOWN","mousedown"),n(qi,"EVENT_MOUSEUP","mouseup"),n(qi,"EVENT_MOUSEWHEEL","mousewheel");var sT=class{constructor(t,e={}){n(this,"_keyboard");n(this,"_mouse");n(this,"_gamepads");n(this,"_element",null);n(this,"_actions",{});n(this,"_axes",{});n(this,"_axesValues",{});this._keyboard=e.keyboard||null,this._mouse=e.mouse||null,this._gamepads=e.gamepads||null,t&&this.attach(t)}attach(t){this._element=t,this._keyboard&&this._keyboard.attach(t),this._mouse&&this._mouse.attach(t)}detach(){this._keyboard&&this._keyboard.detach(),this._mouse&&this._mouse.detach(),this._element=null}disableContextMenu(){this._mouse||this._enableMouse(),this._mouse.disableContextMenu()}enableContextMenu(){this._mouse||this._enableMouse(),this._mouse.enableContextMenu()}update(t){this._keyboard&&this._keyboard.update(),this._mouse&&this._mouse.update(),this._gamepads&&this._gamepads.update(),this._axesValues={};for(let e in this._axes)this._axesValues[e]=[]}appendAction(t,e){this._actions[t]=this._actions[t]||[],this._actions[t].push(e)}registerKeys(t,e){if(this._keyboard||this._enableKeyboard(),this._actions[t])throw new Error(`Action: ${t} already registered`);if(e===void 0)throw new Error("Invalid button");e.length||(e=[e]),this.appendAction(t,{type:zg,keys:e})}registerMouse(t,e){if(this._mouse||this._enableMouse(),e===void 0)throw new Error("Invalid button");this.appendAction(t,{type:kg,button:e})}registerPadButton(t,e,s){if(s===void 0)throw new Error("Invalid button");this.appendAction(t,{type:Gg,button:s,pad:e})}registerAxis(t){let e=t.name;this._axes[e]||(this._axes[e]=[]);let s=this._axes[e].push(e);t=t||{},t.pad=t.pad||0;let i=function(r,a,o,l){switch(a){case"mousex":r._mouse.on("mousemove",h=>{r._axesValues[e][s]=h.dx/10});break;case"mousey":r._mouse.on("mousemove",h=>{r._axesValues[e][s]=h.dy/10});break;case"key":r._axes[e].push(()=>r._keyboard.isPressed(l)?o:0);break;case"padrx":r._axes[e].push(()=>r._gamepads.getAxis(t.pad,2));break;case"padry":r._axes[e].push(()=>r._gamepads.getAxis(t.pad,3));break;case"padlx":r._axes[e].push(()=>r._gamepads.getAxis(t.pad,0));break;case"padly":r._axes[e].push(()=>r._gamepads.getAxis(t.pad,1));break;default:throw new Error("Unknown axis")}};i(this,t.positive,1,t.positiveKey),(t.negativeKey||t.negative!==t.positive)&&i(this,t.negative,-1,t.negativeKey)}isPressed(t){if(!this._actions[t])return!1;let e=this._actions[t].length;for(let s=0;sMath.abs(e)&&(e=r)}else this._axesValues[t]&&Math.abs(this._axesValues[t][i])>Math.abs(e)&&(e=this._axesValues[t][i])}return e}_enableMouse(){if(this._mouse=new qi,!this._element)throw new Error("Controller must be attached to an Element");this._mouse.attach(this._element)}_enableKeyboard(){if(this._keyboard=new mc,!this._element)throw new Error("Controller must be attached to an Element");this._keyboard.attach(this._element)}};var nL=Object.freeze([]),sw=function(){return nL};typeof navigator<"u"&&(sw=(navigator.getGamepads||navigator.webkitGetGamepads||sw).bind(navigator));var aL={buttons:{PAD_FACE_1:0,PAD_FACE_2:1,PAD_FACE_3:2,PAD_FACE_4:3,PAD_L_SHOULDER_1:4,PAD_R_SHOULDER_1:5,PAD_L_SHOULDER_2:6,PAD_R_SHOULDER_2:7,PAD_SELECT:8,PAD_START:9,PAD_L_STICK_BUTTON:10,PAD_R_STICK_BUTTON:11,PAD_UP:12,PAD_DOWN:13,PAD_LEFT:14,PAD_RIGHT:15,PAD_VENDOR:16,XRPAD_TRIGGER:0,XRPAD_SQUEEZE:1,XRPAD_TOUCHPAD_BUTTON:2,XRPAD_STICK_BUTTON:3,XRPAD_A:4,XRPAD_B:5},axes:{PAD_L_STICK_X:0,PAD_L_STICK_Y:1,PAD_R_STICK_X:2,PAD_R_STICK_Y:3,XRPAD_TOUCHPAD_X:0,XRPAD_TOUCHPAD_Y:1,XRPAD_STICK_X:2,XRPAD_STICK_Y:3}},Vg={DEFAULT:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"]},DEFAULT_DUAL:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"],synthesizedButtons:{PAD_UP:{axis:0,min:0,max:1},PAD_DOWN:{axis:0,min:-1,max:0},PAD_LEFT:{axis:0,min:-1,max:0},PAD_RIGHT:{axis:0,min:0,max:1}}},PS3:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_4","PAD_FACE_3","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"],mapping:"standard"},DEFAULT_XR:{buttons:["XRPAD_TRIGGER","XRPAD_SQUEEZE","XRPAD_TOUCHPAD_BUTTON","XRPAD_STICK_BUTTON","XRPAD_A","XRPAD_B"],axes:["XRPAD_TOUCHPAD_X","XRPAD_TOUCHPAD_Y","XRPAD_STICK_X","XRPAD_STICK_Y"],mapping:"xr-standard"}},oL={"Product: 0268":"PS3"},iT={};function lL(c){let t=iT[c.id];if(t)return t;for(let i in oL)if(c.id.indexOf(i)!==-1){let r=oL[i];if(!c.mapping){let a=Vg[`RAW_${r}`];if(a)return a}return Vg[r]}if(c.mapping==="xr-standard")return Vg.DEFAULT_XR;let e=Vg.DEFAULT,s=c.buttons.length{setTimeout(t,c)})}var Hg=class{constructor(t,e){n(this,"value",0);n(this,"pressed",!1);n(this,"touched",!1);n(this,"wasPressed",!1);n(this,"wasReleased",!1);n(this,"wasTouched",!1);typeof t=="number"?(this.value=t,this.pressed=t===1,this.touched=t>0):(this.value=t.value,this.pressed=t.pressed,this.touched=t.touched??t.value>0),e&&(typeof e=="number"?(this.wasPressed=e!==1&&this.pressed,this.wasReleased=e===1&&!this.pressed,this.wasTouched=e===0&&this.touched):(this.wasPressed=!e.pressed&&this.pressed,this.wasReleased=e.pressed&&!this.pressed,this.wasTouched=!(e.touched??e.value>0)&&this.touched))}update(t){let{value:e,pressed:s}=t,i=t.touched??e>0;this.wasPressed=!this.pressed&&s,this.wasReleased=this.pressed&&!s,this.wasTouched=!this.touched&&i,this.value=e,this.pressed=s,this.touched=i}},tw=Object.freeze(new Hg(0)),rT=class{constructor(t,e){n(this,"_compiledMapping",{buttons:[],axes:[]});n(this,"id");n(this,"index");n(this,"_buttons");n(this,"_axes");n(this,"_previousAxes");n(this,"mapping");n(this,"map");n(this,"hand");n(this,"pad");this.id=t.id,this.index=t.index,this._buttons=t.buttons.map(s=>new Hg(s)),this._axes=[...t.axes],this._previousAxes=[...t.axes],this.mapping=e.mapping,this.map=e,this.hand=t.hand||"none",this.pad=t,this._compileMapping()}get connected(){return this.pad.connected}_compileMapping(){let{axes:t,buttons:e}=this._compiledMapping,s=aL.axes,i=aL.buttons;t.length=0,e.length=0,this.map.axes&&this.map.axes.forEach((l,h)=>{t[s[l]]=()=>this.pad.axes[h]||0});for(let l=0,h=t.length;l0);let a=this.map.buttons;a&&a.forEach((l,h)=>{e[i[l]]=()=>this._buttons[h]||tw});let o=this.map.synthesizedButtons;o&&Object.entries(o).forEach(l=>{let{axis:h,max:f,min:u}=l[1];e[i[l[0]]]=()=>new Hg(Math.abs(R.clamp(this._axes[h]??0,u,f)),Math.abs(R.clamp(this._previousAxes[h]??0,u,f)))});for(let l=0,h=e.length;ltw)}update(t){this.pad=t;let e=this._previousAxes,s=this._axes;e.length=0,e.push(...s),s.length=0,s.push(...t.axes);let i=this._buttons;for(let r=0,a=i.length;rt())}get buttons(){return this._compiledMapping.buttons.map(t=>t())}async pulse(t,e,s){let i=this.pad.vibrationActuator?[this.pad.vibrationActuator]:this.pad.hapticActuators||nL;if(i.length){let r=s?.startDelay??0,a=s?.strongMagnitude??t,o=s?.weakMagnitude??t;return(await Promise.all(i.map(async h=>h?h.playEffect?h.playEffect(h.type,{duration:e,startDelay:r,strongMagnitude:a,weakMagnitude:o}):h.pulse?(await fX(r),h.pulse(t,e)):!1:!0))).some(h=>h===!0||h==="complete")}return!1}getButton(t){let e=this._compiledMapping.buttons[t];return e?e():tw}isPressed(t){return this.getButton(t).pressed}wasPressed(t){return this.getButton(t).wasPressed}wasReleased(t){return this.getButton(t).wasReleased}isTouched(t){return this.getButton(t).touched}wasTouched(t){return this.getButton(t).wasTouched}getValue(t){return this.getButton(t).value}getAxis(t){let e=this.axes[t];return e&&Math.abs(e)>iw?e:0}},Qd=class extends J{constructor(){super();n(this,"gamepadsSupported");n(this,"current",[]);n(this,"_previous",[]);n(this,"_ongamepadconnectedHandler");n(this,"_ongamepaddisconnectedHandler");this.gamepadsSupported=ue.gamepads,this._ongamepadconnectedHandler=this._ongamepadconnected.bind(this),this._ongamepaddisconnectedHandler=this._ongamepaddisconnected.bind(this),window.addEventListener("gamepadconnected",this._ongamepadconnectedHandler,!1),window.addEventListener("gamepaddisconnected",this._ongamepaddisconnectedHandler,!1),this.poll()}set deadZone(e){iw=e}get deadZone(){return iw}get previous(){let e=this.current;for(let s=0,i=e.length;sa.index===s.index);for(;r!==-1;)i.splice(r,1),r=i.findIndex(a=>a.index===s.index);i.push(s),this.fire("gamepadconnected",s)}_ongamepaddisconnected(e){let s=this.current,i=s.findIndex(r=>r.index===e.gamepad.index);i!==-1&&(this.fire("gamepaddisconnected",s[i]),s.splice(i,1))}update(){this.poll()}poll(e=[]){e.length>0&&(e.length=0);let s=sw();for(let i=0,r=s.length;ir.pulse(e,s,i)))}findById(e){return this.current.find(s=>s&&s.id===e)||null}findByIndex(e){return this.current.find(s=>s&&s.index===e)||null}};n(Qd,"EVENT_GAMEPADCONNECTED","gamepadconnected"),n(Qd,"EVENT_GAMEPADDISCONNECTED","gamepaddisconnected");function Pf(c){let t=0,e=0,s=c.target;for(;!(s instanceof HTMLElement)&&s;)s=s.parentNode;for(;s;)t+=s.offsetLeft-s.scrollLeft,e+=s.offsetTop-s.scrollTop,s=s.offsetParent;return{x:c.pageX-t,y:c.pageY-e}}var Jd=class{constructor(t){n(this,"id");n(this,"x");n(this,"y");n(this,"target");n(this,"touch");let e=Pf(t);this.id=t.identifier,this.x=e.x,this.y=e.y,this.target=t.target,this.touch=t}},qn=class{constructor(t,e){n(this,"element");n(this,"event");n(this,"touches",[]);n(this,"changedTouches",[]);this.element=e.target,this.event=e,this.touches=Array.from(e.touches).map(s=>new Jd(s)),this.changedTouches=Array.from(e.changedTouches).map(s=>new Jd(s))}getTouchById(t,e){return e.find(s=>s.id===t)||null}};var _c=class extends J{constructor(e){super();n(this,"_element",null);n(this,"_startHandler");n(this,"_endHandler");n(this,"_moveHandler");n(this,"_cancelHandler");this._startHandler=this._handleTouchStart.bind(this),this._endHandler=this._handleTouchEnd.bind(this),this._moveHandler=this._handleTouchMove.bind(this),this._cancelHandler=this._handleTouchCancel.bind(this),this.attach(e)}attach(e){this._element&&this.detach(),this._element=e,this._element.addEventListener("touchstart",this._startHandler,!1),this._element.addEventListener("touchend",this._endHandler,!1),this._element.addEventListener("touchmove",this._moveHandler,!1),this._element.addEventListener("touchcancel",this._cancelHandler,!1)}detach(){this._element&&(this._element.removeEventListener("touchstart",this._startHandler,!1),this._element.removeEventListener("touchend",this._endHandler,!1),this._element.removeEventListener("touchmove",this._moveHandler,!1),this._element.removeEventListener("touchcancel",this._cancelHandler,!1)),this._element=null}_handleTouchStart(e){this.fire("touchstart",new qn(this,e))}_handleTouchEnd(e){this.fire("touchend",new qn(this,e))}_handleTouchMove(e){e.preventDefault(),this.fire("touchmove",new qn(this,e))}_handleTouchCancel(e){this.fire("touchcancel",new qn(this,e))}};n(_c,"EVENT_TOUCHSTART","touchstart"),n(_c,"EVENT_TOUCHEND","touchend"),n(_c,"EVENT_TOUCHMOVE","touchmove"),n(_c,"EVENT_TOUCHCANCEL","touchcancel");var nt=class nt{get(t,e,s){typeof e=="function"&&(s=e,e={});let i=this.request("GET",t,e,s),{progress:r}=e;if(r){let a=l=>{l.lengthComputable&&r.fire("progress",l.loaded,l.total)},o=l=>{a(l),i.removeEventListener("loadstart",a),i.removeEventListener("progress",a),i.removeEventListener("loadend",o)};i.addEventListener("loadstart",a),i.addEventListener("progress",a),i.addEventListener("loadend",o)}return i}post(t,e,s,i){return typeof s=="function"&&(i=s,s={}),s.postdata=e,this.request("POST",t,s,i)}put(t,e,s,i){return typeof s=="function"&&(i=s,s={}),s.postdata=e,this.request("PUT",t,s,i)}del(t,e,s){return typeof e=="function"&&(s=e,e={}),this.request("DELETE",t,e,s)}request(t,e,s,i){let r,a,o,l=!1;if(typeof s=="function"&&(i=s,s={}),s.retry&&(s=Object.assign({retries:0,maxRetries:5},s)),s.callback=i,s.async==null&&(s.async=!0),s.headers==null&&(s.headers={}),s.postdata!=null)if(s.postdata instanceof Document)o=s.postdata;else if(s.postdata instanceof FormData)o=s.postdata;else if(s.postdata instanceof Object){let f=s.headers["Content-Type"];switch(f===void 0&&(s.headers["Content-Type"]=nt.ContentType.FORM_URLENCODED,f=s.headers["Content-Type"]),f){case nt.ContentType.FORM_URLENCODED:{o="";let u=!0;for(let d in s.postdata)if(s.postdata.hasOwnProperty(d)){u?u=!1:o+="&";let p=encodeURIComponent(d),m=encodeURIComponent(s.postdata[d]);o+=`${p}=${m}`}break}default:case nt.ContentType.JSON:f==null&&(s.headers["Content-Type"]=nt.ContentType.JSON),o=JSON.stringify(s.postdata);break}}else o=s.postdata;if(s.cache===!1){let f=Tt();r=new jl(e),r.query?r.query=`${r.query}&ts=${f}`:r.query=`ts=${f}`,e=r.toString()}s.query&&(r=new jl(e),a=Wl(r.getQuery(),s.query),r.setQuery(a),e=r.toString());let h=new XMLHttpRequest;h.open(t,e,s.async),h.withCredentials=s.withCredentials!==void 0?s.withCredentials:!1,h.responseType=s.responseType||this._guessResponseType(e);for(let f in s.headers)s.headers.hasOwnProperty(f)&&h.setRequestHeader(f,s.headers[f]);h.onreadystatechange=()=>{this._onReadyStateChange(t,e,s,h)},h.onerror=()=>{this._onError(t,e,s,h),l=!0};try{h.send(o)}catch(f){l||s.error(h.status,h,f)}return h}_guessResponseType(t){let e=new jl(t),s=xe.getExtension(e.path).toLowerCase();return nt.binaryExtensions.indexOf(s)>=0?nt.ResponseType.ARRAY_BUFFER:s===".json"?nt.ResponseType.JSON:s===".xml"?nt.ResponseType.DOCUMENT:nt.ResponseType.TEXT}_isBinaryContentType(t){return[nt.ContentType.BASIS,nt.ContentType.BIN,nt.ContentType.DDS,nt.ContentType.GLB,nt.ContentType.MP3,nt.ContentType.MP4,nt.ContentType.OGG,nt.ContentType.OPUS,nt.ContentType.WAV].indexOf(t)>=0}_isBinaryResponseType(t){return t===nt.ResponseType.ARRAY_BUFFER||t===nt.ResponseType.BLOB||t===nt.ResponseType.JSON}_onReadyStateChange(t,e,s,i){if(i.readyState===4)switch(i.status){case 0:{i.responseURL&&i.responseURL.startsWith("file:///")?this._onSuccess(t,e,s,i):this._onError(t,e,s,i);break}case 200:case 201:case 206:case 304:{this._onSuccess(t,e,s,i);break}default:{this._onError(t,e,s,i);break}}}_onSuccess(t,e,s,i){let r,a,o=i.getResponseHeader("Content-Type");o&&(a=o.split(";")[0].trim());try{this._isBinaryContentType(a)||this._isBinaryResponseType(i.responseType)?r=i.response:a===nt.ContentType.JSON||e.split("?")[0].endsWith(".json")?r=JSON.parse(i.responseText):i.responseType===nt.ResponseType.DOCUMENT||a===nt.ContentType.XML?r=i.responseXML:r=i.responseText,s.callback(null,r)}catch(l){s.callback(l)}}_onError(t,e,s,i){if(!s.retrying)if(s.retry&&s.retries{s.retrying=!1,this.request(t,e,s,s.callback)},r)}else s.callback(i.status===0?"Network error":i.status,null)}};n(nt,"ContentType",{AAC:"audio/aac",BASIS:"image/basis",BIN:"application/octet-stream",DDS:"image/dds",FORM_URLENCODED:"application/x-www-form-urlencoded",GIF:"image/gif",GLB:"model/gltf-binary",JPEG:"image/jpeg",JSON:"application/json",MP3:"audio/mpeg",MP4:"audio/mp4",OGG:"audio/ogg",OPUS:'audio/ogg; codecs="opus"',PNG:"image/png",TEXT:"text/plain",WAV:"audio/x-wav",XML:"application/xml"}),n(nt,"ResponseType",{TEXT:"text",ARRAY_BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json"}),n(nt,"binaryExtensions",[".model",".wav",".ogg",".mp3",".mp4",".m4a",".aac",".dds",".basis",".glb",".opus"]),n(nt,"retryDelay",100);var Vt=nt,Le=new Vt;var ep="linear",uX="inverse",dX="exponential";var aT=class{constructor(t){n(this,"_manager");n(this,"position",new x);n(this,"orientation",new W);this._manager=t}getPosition(){return this.position}setPosition(t){this.position.copy(t);let e=this.listener;e&&("positionX"in e?(e.positionX.value=t.x,e.positionY.value=t.y,e.positionZ.value=t.z):e.setPosition&&e.setPosition(t.x,t.y,t.z))}setOrientation(t){this.orientation.copy(t);let e=this.listener;if(e){let s=t.data;"forwardX"in e?(e.forwardX.value=-s[8],e.forwardY.value=-s[9],e.forwardZ.value=-s[10],e.upX.value=s[4],e.upY.value=s[5],e.upZ.value=s[6]):e.setOrientation&&e.setOrientation(-s[8],-s[9],-s[10],s[4],s[5],s[6])}}getOrientation(){return this.orientation}get listener(){let t=this._manager.context;return t?t.listener:null}};var oT="running",cL=["click","touchstart","mousedown"],tp=class extends J{constructor(){super();n(this,"_context",null);n(this,"_unlockHandlerFunc");n(this,"_userSuspended",!1);n(this,"listener");n(this,"_volume",1);this._unlockHandlerFunc=this._unlockHandler.bind(this),this.listener=new aT(this)}set volume(e){e=R.clamp(e,0,1),this._volume=e,this.fire("volumechange",e)}get volume(){return this._volume}get suspended(){return this._userSuspended}get context(){if(!this._context){let e=typeof AudioContext<"u"&&AudioContext||typeof webkitAudioContext<"u"&&webkitAudioContext;if(!e)return null;this._context=new e,this._context.state!==oT&&this._registerUnlockListeners()}return this._context}suspend(){this._userSuspended||(this._userSuspended=!0,this._context&&this._context.state===oT&&this._suspend())}resume(){this._userSuspended&&(this._userSuspended=!1,this._context&&this._context.state!==oT&&this._resume())}destroy(){this.fire("destroy");let e=this._context;e&&(this._removeUnlockListeners(),e.close(),this._context=null)}_resume(){let e=this._context;e&&e.resume().then(()=>{let s=e.createBufferSource();s.buffer=e.createBuffer(1,1,e.sampleRate),s.connect(e.destination),s.start(0),s.onended=i=>{s.disconnect(0),this.fire("resume")}},s=>{}).catch(s=>{})}_suspend(){let e=this._context;e&&e.suspend().then(()=>{this.fire("suspend")},s=>{}).catch(s=>{})}_unlockHandler(){this._removeUnlockListeners(),!this._userSuspended&&this._context&&this._context.state!==oT&&this._resume()}_registerUnlockListeners(){cL.forEach(e=>{window.addEventListener(e,this._unlockHandlerFunc,!1)})}_removeUnlockListeners(){cL.forEach(e=>{window.removeEventListener(e,this._unlockHandlerFunc,!1)})}};var sp=class{constructor(t){n(this,"buffer");this.buffer=t}get duration(){return this.buffer&&this.buffer.duration||0}};var Ga=0,nT=1,wf=2;function gc(c,t){return c%t||0}var _r=class extends J{constructor(e,s,i){super();n(this,"source",null);this._manager=e,this._volume=i.volume!==void 0?R.clamp(Number(i.volume)||0,0,1):1,this._pitch=i.pitch!==void 0?Math.max(.01,Number(i.pitch)||0):1,this._loop=!!(i.loop!==void 0&&i.loop),this._sound=s,this._state=wf,this._suspended=!1,this._suspendEndEvent=0,this._suspendInstanceEvents=!1,this._playWhenLoaded=!0,this._startTime=Math.max(0,Number(i.startTime)||0),this._duration=Math.max(0,Number(i.duration)||0),this._startOffset=null,this._onPlayCallback=i.onPlay,this._onPauseCallback=i.onPause,this._onResumeCallback=i.onResume,this._onStopCallback=i.onStop,this._onEndCallback=i.onEnd,this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._inputNode=null,this._connectorNode=null,this._firstNode=null,this._lastNode=null,this._waitingContextSuspension=!1,this._manager.context&&(this._initializeNodes(),this._endedHandler=this._onEnded.bind(this))}set currentTime(e){if(!(e<0))if(this._state===Ga){let s=this._suspendInstanceEvents;this._suspendInstanceEvents=!0,this.stop(),this._startOffset=e,this.play(),this._suspendInstanceEvents=s}else this._startOffset=e,this._currentTime=e}get currentTime(){return this._startOffset!==null?this._startOffset:this._state===nT?this._currentTime:this._state===wf||!this.source?0:(this._updateCurrentTime(),this._currentTime)}set duration(e){this._duration=Math.max(0,Number(e)||0);let s=this._state===Ga;this.stop(),s&&this.play()}get duration(){return this._sound?this._duration?gc(this._duration,this._sound.duration):this._sound.duration:0}get isPaused(){return this._state===nT}get isPlaying(){return this._state===Ga}get isStopped(){return this._state===wf}get isSuspended(){return this._suspended}set loop(e){this._loop=!!e,this.source&&(this.source.loop=this._loop)}get loop(){return this._loop}set pitch(e){this._manager.context&&(this._currentOffset=this.currentTime,this._startedAt=this._manager.context.currentTime),this._pitch=Math.max(Number(e)||0,.01),this.source&&(this.source.playbackRate.value=this._pitch)}get pitch(){return this._pitch}set sound(e){this._sound=e,this._state!==wf?this.stop():this._createSource()}get sound(){return this._sound}set startTime(e){this._startTime=Math.max(0,Number(e)||0);let s=this._state===Ga;this.stop(),s&&this.play()}get startTime(){return this._startTime}set volume(e){e=R.clamp(e,0,1),this._volume=e,this.gain&&(this.gain.gain.value=e*this._manager.volume)}get volume(){return this._volume}_onPlay(){this.fire("play"),this._onPlayCallback&&this._onPlayCallback(this)}_onPause(){this.fire("pause"),this._onPauseCallback&&this._onPauseCallback(this)}_onResume(){this.fire("resume"),this._onResumeCallback&&this._onResumeCallback(this)}_onStop(){this.fire("stop"),this._onStopCallback&&this._onStopCallback(this)}_onEnded(){if(this._suspendEndEvent>0){this._suspendEndEvent--;return}this.fire("end"),this._onEndCallback&&this._onEndCallback(this),this.stop()}_onManagerVolumeChange(){this.volume=this._volume}_onManagerSuspend(){this._state===Ga&&!this._suspended&&(this._suspended=!0,this.pause())}_onManagerResume(){this._suspended&&(this._suspended=!1,this.resume())}_initializeNodes(){this.gain=this._manager.context.createGain(),this._inputNode=this.gain,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)}play(){return!this._manager.context||(this._state!==wf&&this.stop(),this._state=Ga,this._playWhenLoaded=!1,this._waitingContextSuspension)?!1:this._manager.suspended?(this._manager.once("resume",this._playAudioImmediate,this),this._waitingContextSuspension=!0,!1):(this._playAudioImmediate(),!0)}_playAudioImmediate(){if(this._waitingContextSuspension=!1,this._state!==Ga)return;this.source||this._createSource();let e=gc(this._startOffset,this.duration);e=gc(this._startTime+e,this._sound.duration),this._startOffset=null,this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentTime=0,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._suspendInstanceEvents||this._onPlay()}pause(){return this._playWhenLoaded=!1,this._state!==Ga?!1:(this._state=nT,this._waitingContextSuspension||(this._updateCurrentTime(),this._suspendEndEvent++,this.source.stop(0),this.source=null,this._startOffset=null,this._suspendInstanceEvents||this._onPause()),!0)}resume(){if(this._state!==nT)return!1;let e=this.currentTime;return this._state=Ga,this._waitingContextSuspension||(this.source||this._createSource(),this._startOffset!==null&&(e=gc(this._startOffset,this.duration),e=gc(this._startTime+e,this._sound.duration),this._startOffset=null),this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._playWhenLoaded=!1,this._suspendInstanceEvents||this._onResume()),!0}stop(){if(this._playWhenLoaded=!1,this._state===wf)return!1;let e=this._state===Ga;return this._state=wf,this._waitingContextSuspension||(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._startOffset=null,this._suspendEndEvent++,e&&this.source&&this.source.stop(0),this.source=null,this._suspendInstanceEvents||this._onStop()),!0}setExternalNodes(e,s){if(!e||!this._connectorNode)return;s||(s=e);let i=this._manager.context.destination;this._firstNode!==e&&(this._firstNode?this._connectorNode.disconnect(this._firstNode):this._connectorNode.disconnect(i),this._firstNode=e,this._connectorNode.connect(e)),this._lastNode!==s&&(this._lastNode&&this._lastNode.disconnect(i),this._lastNode=s,this._lastNode.connect(i))}clearExternalNodes(){if(!this._connectorNode)return;let e=this._manager.context.destination;this._firstNode&&(this._connectorNode.disconnect(this._firstNode),this._firstNode=null),this._lastNode&&(this._lastNode.disconnect(e),this._lastNode=null),this._connectorNode.connect(e)}getExternalNodes(){return[this._firstNode,this._lastNode]}_createSource(){if(!this._sound)return null;let e=this._manager.context;return e?(this._sound.buffer&&(this.source=e.createBufferSource(),this.source.buffer=this._sound.buffer,this.source.connect(this._inputNode),this.source.onended=this._endedHandler,this.source.loopStart=gc(this._startTime,this.source.buffer.duration),this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,gc(this._startTime+this._duration,this.source.buffer.duration)))),this.source):null}_updateCurrentTime(){this._currentTime=gc((this._manager.context.currentTime-this._startedAt)*this._pitch+this._currentOffset,this.duration)}_onManagerDestroy(){this.source&&this._state===Ga&&(this.source.stop(0),this.source=null)}};n(_r,"EVENT_PLAY","play"),n(_r,"EVENT_PAUSE","pause"),n(_r,"EVENT_RESUME","resume"),n(_r,"EVENT_STOP","stop"),n(_r,"EVENT_END","end");var pX=1e4,ip=class extends _r{constructor(e,s,i={}){super(e,s,i);n(this,"_position",new x);n(this,"_velocity",new x);e.context&&(i.position&&(this.position=i.position),this.maxDistance=i.maxDistance!==void 0?Number(i.maxDistance):pX,this.refDistance=i.refDistance!==void 0?Number(i.refDistance):1,this.rollOffFactor=i.rollOffFactor!==void 0?Number(i.rollOffFactor):1,this.distanceModel=i.distanceModel!==void 0?i.distanceModel:ep)}_initializeNodes(){this.gain=this._manager.context.createGain(),this.panner=this._manager.context.createPanner(),this.panner.connect(this.gain),this._inputNode=this.panner,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)}set position(e){this._position.copy(e);let s=this.panner;s&&("positionX"in s?(s.positionX.value=e.x,s.positionY.value=e.y,s.positionZ.value=e.z):s.setPosition&&s.setPosition(e.x,e.y,e.z))}get position(){return this._position}set velocity(e){this._velocity.copy(e)}get velocity(){return this._velocity}set maxDistance(e){this.panner&&(this.panner.maxDistance=e)}get maxDistance(){return this.panner?this.panner.maxDistance:0}set refDistance(e){this.panner&&(this.panner.refDistance=e)}get refDistance(){return this.panner?this.panner.refDistance:0}set rollOffFactor(e){this.panner&&(this.panner.rolloffFactor=e)}get rollOffFactor(){return this.panner?this.panner.rolloffFactor:0}set distanceModel(e){this.panner&&(this.panner.distanceModel=e)}get distanceModel(){return this.panner?this.panner.distanceModel:ep}};var rp=0,ea=1,ls=2,wt=3,Ms=4,ap=5,op=6,np=7,lp=8,cp=9,hp=10,Wg={[rp]:"SUBTRACTIVE",[ea]:"ADDITIVE",[ls]:"NORMAL",[wt]:"NONE",[Ms]:"PREMULTIPLIED",[ap]:"MULTIPLICATIVE",[op]:"ADDITIVEALPHA",[np]:"MULTIPLICATIVE2X",[lp]:"SCREEN",[cp]:"MIN",[hp]:"MAX"},Mi="none",rw="linear",mX="exp",_X="exp2",hL=0,Sc=2,aw={[hL]:"NONE",[Sc]:"SCHLICK"},ow=0,gX=1,Xg=15,Os=0,Zt=1,$n=2,Zn=3,Va=4,Ce=0,We=1,SX=We,je=2,xX=3,lT={[Ce]:"DIRECTIONAL",[We]:"OMNI",[je]:"SPOT"},If=100,$i=0,cT=1,hT=2,fT=3,nw={[$i]:"PUNCTUAL",[cT]:"RECT",[hT]:"DISK",[fT]:"SPHERE"},uT=0,dT=1,lw={[uT]:"LINEAR",[dT]:"INVERSESQUARED"},Oi=0,vX=0,Yg=2,TX=2,fp=3,yX=3,fL=4,EX=4,pT=5,AX=5,xc=6,mT=7,_T=8,uL=9,Fi=new Map([[pT,{name:"PCF1_32F",kind:"PCF1",format:Ys,pcf:!0}],[Oi,{name:"PCF3_32F",kind:"PCF3",format:Ys,pcf:!0}],[fL,{name:"PCF5_32F",kind:"PCF5",format:Ys,pcf:!0}],[mT,{name:"PCF1_16F",kind:"PCF1",format:Xr,pcf:!0}],[_T,{name:"PCF3_16F",kind:"PCF3",format:Xr,pcf:!0}],[uL,{name:"PCF5_16F",kind:"PCF5",format:Xr,pcf:!0}],[Yg,{name:"VSM_16F",kind:"VSM",format:Me,vsm:!0}],[fp,{name:"VSM_32F",kind:"VSM",format:ke,vsm:!0}],[xc,{name:"PCSS_32F",kind:"PCSS",format:Mt,pcss:!0}]]),CX=1,PX=2,wX=4,IX=8,cw=255,RX=0,Kg=1,up=0,bX=1,DX=2,LX=3,jg=0,MX=1,Ni=0,hw=1,vc=0,fw=1,OX=2,ts=0,ni=1,Oo=0,Fo=1,dp=2,pp=0,gT=1,uw={[pp]:"NONE",[gT]:"BOX"},ST="mul",FX="add",NX="screen",BX="overlay",UX="min",kX="max",Zi=0,No=1,qg={[Zi]:"NONE",[No]:"SRGB"},Qn=0,zX=1,GX=2,VX=3,HX=4,WX=5,Rf=6,bf=["LINEAR","FILMIC","HEJL","ACES","ACES2","NEUTRAL","NONE"],xT=0,Bo=1,vT=2,dw={[xT]:"NONE",[Bo]:"AO",[vT]:"GLOSSDEPENDENT"},gr="none",Df="envAtlas",Lf="envAtlasHQ",Mf="cubeMap",TT="sphereMap",pw={[gr]:"NONE",[Df]:"ENVATLAS",[Lf]:"ENVATLASHQ",[Mf]:"CUBEMAP",[TT]:"SPHEREMAP"},mp="ambientSH",_p="envAtlas",gp="constant",mw={[mp]:"AMBIENTSH",[_p]:"ENVALATLAS",[gp]:"CONSTANT"},Tc=1,Uo=2,Of=4,$g=8,Zg=16,ko=32,yc=64,Ff=128,Ec=256,Nf=512,zo=1024,Go=2048,Bf=4096,Vo=8192,Uf=16384,$s=0,Qi=1,Qg=2,cs=1,xi=2,vi=4,Sr=0,xr=1,kf=2,ta=3,Sp=4,XX="forward",YX="debug_albedo",KX="debug_world_normal",jX="debug_opacity",qX="debug_specularity",$X="debug_gloss",ZX="debug_metalness",QX="debug_ao",JX="debug_emission",eY="debug_lighting",tY="debug_uv0",Ti=0,It=1,Rt=2,_w={[Ti]:"SIMPLE",[It]:"SLICED",[Rt]:"TILED"},sY=0,zf=1,xp=0,iY=1,rY=2,Ho=0,gw=1,yT=2,Jg=3,Sw=4,xw=5,Ac=0,vp=1,Ge=0,dt=1,Jn="infinite",vw="box",Tw="dome",Bi="none",dL="bayer8",pL="bluenoise",mL="ignnoise",eS={[Bi]:"NONE",[dL]:"BAYER8",[pL]:"BLUENOISE",[mL]:"IGNNOISE"},yw="prerender",Ew="postrender",Aw="prerender:layer",Cw="postrender:layer",tS="precull",sS="postcull",Pw="cull:end",Fs=1,el=2,Gf="pcShadowCamera",Tp=0,ww=1,Iw=2,Rw=0,Vf=1,aY="large",iS="compact",ET=0,tl=1,Cc=2,Hf=3,Wf=0,Pc=1,yp=2,Ep=3,AT=4,CT=5,PT=0,bw=1,wT=2;var sa=class{constructor(t,e,s){n(this,"uniformFormats",[]);n(this,"bindGroupFormats",[]);n(this,"vertexFormat");this.uniformFormats[Io]=t,this.bindGroupFormats[Io]=e,this.vertexFormat=s}hasUniform(t){for(let e=0;ee.name===t)}generateKey(t){let e=JSON.stringify(this.uniformFormats)+JSON.stringify(this.bindGroupFormats);return t.isWebGPU&&(e+=this.vertexFormat?.shaderProcessingHashString),e}};var _L=new et;function Ji(c){return _L.get(c)}function gL(c,t){_L.get(c,()=>t)}var yi=class{static definesHash(t){let e=Array.from(t).sort((s,i)=>s[0]>i[0]?1:-1);return xt(JSON.stringify(e))}};var oY=new et,Dw=class{constructor(t,e,s={}){n(this,"index");n(this,"name");n(this,"defines",new Map);this.name=t,this.index=e,Object.assign(this,s),this.buildShaderDefines()}buildShaderDefines(){let t;this.isShadow?t="SHADOW":this.isForward?t="FORWARD":this.index===ta?t="PICK":this.index===Sp&&(t="PICK",this.defines.set("DEPTH_PICK_PASS","")),this.defines.set(`${t}_PASS`,""),this.defines.set(`${this.name.toUpperCase()}_PASS`,"")}},Ns=class c{constructor(){n(this,"passesNamed",new Map);n(this,"passesIndexed",[]);n(this,"nextIndex",0);let t=(e,s,i)=>{let r=this.allocate(e,i)};t("forward",Sr,{isForward:!0}),t("prepass",xr),t("shadow",kf),t("pick",ta),t("depth_pick",Sp)}static get(t){return oY.get(t,()=>new c)}allocate(t,e){let s=this.passesNamed.get(t);return s===void 0&&(s=new Dw(t,this.nextIndex,e),this.passesNamed.set(s.name,s),this.passesIndexed[s.index]=s,this.nextIndex++),s}getByIndex(t){return this.passesIndexed[t]}getByName(t){return this.passesNamed.get(t)}};var rS=class extends Map{constructor(e){super();n(this,"_validations");n(this,"_keyDirty",!1);n(this,"_key","");this._validations=e}set(e,s){return(!this.has(e)||this.get(e)!==s)&&this.markDirty(),super.set(e,s)}add(e,s=!0){for(let[i,r]of Object.entries(e))(s||!this.has(i))&&this.set(i,r);return this}delete(e){let s=this.has(e),i=super.delete(e);return s&&i&&this.markDirty(),i}clear(){this.size>0&&this.markDirty(),super.clear()}markDirty(){this._dirty=!0,this._keyDirty=!0}isDirty(){return this._dirty}resetDirty(){this._dirty=!1}get key(){return this._keyDirty&&(this._keyDirty=!1,this._key=Array.from(this.entries()).sort(([e],[s])=>es?1:0).map(([e,s])=>`${e}=${xt(s)}`).join(",")),this._key}copy(e){for(let s of this.keys())e.has(s)||this.delete(s);for(let[s,i]of e)this.set(s,i);return this}};var nY=new et,Ap=class Ap{constructor(){n(this,"glsl",new rS(Ap._validations));n(this,"wgsl",new rS(Ap._validations));n(this,"version","")}static get(t,e=fe){let s=nY.get(t,()=>new Ap);return e===fe?s.glsl:s.wgsl}static registerValidation(t,e){}get useWGSL(){return this.glsl.size===0||this.wgsl.size>0}get key(){return`GLSL:${this.glsl.key}|WGSL:${this.wgsl.key}|API:${this.version}`}isDirty(){return this.glsl.isDirty()||this.wgsl.isDirty()}resetDirty(){this.glsl.resetDirty(),this.wgsl.resetDirty()}copy(t){return this.version=t.version,this.glsl.copy(t.glsl),this.wgsl.copy(t.wgsl),this}};n(Ap,"_validations",new Map);var ne=Ap;var Ha=class{static merge(...t){let e=new Map(t[0]??[]);for(let s=1;ss.set(a,r)),Ns.get(e.device).getByIndex(e.pass).defines.forEach((r,a)=>s.set(a,r)),s}static processShader(t,e){let s=t.definition,r=`${s.name??"shader"}-id-${t.id}`,a=new Lw(r,s),o="shader",l=Ji(t.device);l.register(o,a);let h=l.getProgram(o,{},e);return l.unregister(o),h}static addScreenDepthChunkDefines(t,e,s){e.sceneDepthMapLinear&&s.set("SCENE_DEPTHMAP_LINEAR",""),t.textureFloatRenderable&&s.set("SCENE_DEPTHMAP_FLOAT","")}};function SL(c,t,e,s=!1,i={}){}function xL(c,t,e,s,i,r=!1,a={}){typeof r=="boolean"?a.useTransformFeedback=r:typeof r=="object"&&(a={...a,...r});let o=Ji(c),l=o.getCachedShader(s);return l||(l=new Be(c,ns.createDefinition(c,{...a,name:s,vertexCode:t,fragmentCode:e,attributes:i})),o.setCachedShader(s,l)),l}var lY={type:Yt,base:0,count:6,indexed:!0},aS=new Q,oS=new Q,Mw=new hc,hs=class{constructor(t){n(this,"uniformBuffer");n(this,"bindGroup");let e=t.device;if(this.shader=t,e.supportsUniformBuffers){let s=new sa;this.shader=Se.processShader(t,s);let i=this.shader.meshUniformBufferFormat;i&&(this.uniformBuffer=new Qr(e,i,!1));let r=this.shader.meshBindGroupFormat;this.bindGroup=new ji(e,r)}}destroy(){this.uniformBuffer?.destroy(),this.uniformBuffer=null,this.bindGroup?.destroy(),this.bindGroup=null}render(t,e,s){let i=this.shader.device;t&&(aS.set(i.vx,i.vy,i.vw,i.vh),oS.set(i.sx,i.sy,i.sw,i.sh),e=e??t,i.setViewport(t.x,t.y,t.z,t.w),i.setScissor(e.x,e.y,e.z,e.w)),i.setVertexBuffer(i.quadVertexBuffer);let r=this.shader;if(i.setShader(r),i.supportsUniformBuffers){i.setBindGroup(Io,i.emptyBindGroup);let a=this.bindGroup;a.update(),i.setBindGroup(Ua,a);let o=this.uniformBuffer;o?(o.update(Mw),i.setBindGroup($r,Mw.bindGroup,Mw.offsets)):i.setBindGroup($r,i.emptyBindGroup)}i.draw(lY,i.quadIndexBuffer,s),t&&(i.setViewport(aS.x,aS.y,aS.z,aS.w),i.setScissor(oS.x,oS.y,oS.z,oS.w))}};var Cp=class extends yt{constructor(t,e,s,i){super(t),this.quad=e,this.rect=s,this.scissorRect=i}execute(){let{device:t}=this;t.setDrawStates(t.blendState),this.quad.render(this.rect,this.scissorRect)}};var cY=new Q;function Qt(c,t,e,s,i){let r=arguments[5],a=new hs(e);s||(s=cY,s.x=0,s.y=0,s.z=t?t.width:c.width,s.w=t?t.height:c.height);let o=new Cp(c,a,s,i);o.init(t),o.colorOps.clear=!1,o.depthStencilOps.clearDepth=!1,c.isWebGPU&&t===null&&c.samples>1&&(o.colorOps.store=!0),o.render(),a.destroy()}var Xf=class{constructor(t,e,s){n(this,"_aabb",new ge);n(this,"origMeshInstances");n(this,"meshInstance",null);n(this,"dynamic");n(this,"batchGroupId");this.origMeshInstances=t,this.dynamic=e,this.batchGroupId=s}destroy(t,e){this.meshInstance&&(this.removeFromLayers(t,e),this.meshInstance.destroy(),this.meshInstance=null)}addToLayers(t,e){for(let s=0;s=0;s--)this.matrices[s].mulAffine2(vL,this.bones[s].getWorldTransform()),this.matrices[s].mulAffine2(this.matrices[s],this.skin.inverseBindPose[s])}}updateMatrices(t,e){this._updateBeforeCull&&this._updateMatrices(t,e)}updateMatrixPalette(t,e){this._updateMatrices(t,e);let s=this.matrixPalette,i=this.bones.length;for(let r=0;r0){let A=T.array[T.index+y];if(f[A]=!0,s=S.array[S.index],i=S.array[S.index+1],r=S.array[S.index+2],a=h[A],o=l[A],o.x>s&&(o.x=s),o.y>i&&(o.y=i),o.z>r&&(o.z=r),a.xw&&(o.x=w),o.y>I&&(o.y=I),o.z>D&&(o.z=D),a.xE.name===ee);if(v&&v.normalize){let E=(()=>{switch(v.dataType){case js:return y=>Math.max(y/127,-1);case ai:return y=>y/255;case qs:return y=>Math.max(y/32767,-1);case Ri:return y=>y/65535;default:return y=>y}})();for(let y=0;y0&&this.indexBuffer[0]&&(this._geometryData.indexCount=this.indexBuffer[0].numIndices,this._geometryData.maxIndices=this.indexBuffer[0].numIndices))}clear(e,s,i=0,r=0){this._initGeometryData(),this._geometryData.initDefaults(),this._geometryData.recreate=!0,this._geometryData.maxVertices=i,this._geometryData.maxIndices=r,this._geometryData.verticesUsage=e?0:1,this._geometryData.indicesUsage=s?0:1}setVertexStream(e,s,i,r,a=ye,o=!1,l=!1){this._initGeometryData();let h=r||s.length/i;this._geometryData._changeVertexCount(h,e),this._geometryData.vertexStreamsUpdated=!0,this._geometryData.vertexStreamDictionary[e]=new Ow(s,i,a,o,l)}getVertexStream(e,s){let i=0,r=!1;if(this._geometryData){let a=this._geometryData.vertexStreamDictionary[e];a&&(r=!0,i=this._geometryData.vertexCount,ArrayBuffer.isView(s)?s.set(a.data):(s.length=0,s.push(a.data)))}return r||this.vertexBuffer&&(i=new Jr(this.vertexBuffer).readData(e,s)),i}setPositions(e,s=ia.DEFAULT_COMPONENTS_POSITION,i){this.setVertexStream(ee,e,s,i,ye,!1)}setNormals(e,s=ia.DEFAULT_COMPONENTS_NORMAL,i){this.setVertexStream(Ot,e,s,i,ye,!1)}setUvs(e,s,i=ia.DEFAULT_COMPONENTS_UV,r){this.setVertexStream(Ux+e,s,i,r,ye,!1)}setColors(e,s=ia.DEFAULT_COMPONENTS_COLORS,i){this.setVertexStream(Ct,e,s,i,ye,!1)}setColors32(e,s){this.setVertexStream(Ct,e,ia.DEFAULT_COMPONENTS_COLORS,s,ai,!0)}setIndices(e,s){this._initGeometryData(),this._geometryData.indexStreamUpdated=!0,this._geometryData.indices=e,this._geometryData.indexCount=s||e.length}getPositions(e){return this.getVertexStream(ee,e)}getNormals(e){return this.getVertexStream(Ot,e)}getUvs(e,s){return this.getVertexStream(Ux+e,s)}getColors(e){return this.getVertexStream(Ct,e)}getIndices(e){let s=0;if(this._geometryData&&this._geometryData.indices){let i=this._geometryData.indices;if(s=this._geometryData.indexCount,ArrayBuffer.isView(e))e.set(i);else{e.length=0;for(let r=0,a=i.length;r0&&this.indexBuffer[0]&&(s=this.indexBuffer[0].readData(e));return s}update(e=Yt,s=!0){if(this._geometryData){if(s){let a=this._geometryData.vertexStreamDictionary[ee];a&&a.componentCount===3&&(this._aabb.compute(a.data,this._geometryData.vertexCount),this._aabbVer++)}let i=this._geometryData.recreate;this._geometryData.vertexCount>this._geometryData.maxVertices&&(i=!0,this._geometryData.maxVertices=this._geometryData.vertexCount),i&&this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);let r=this._geometryData.recreate;this._geometryData.indexCount>this._geometryData.maxIndices&&(r=!0,this._geometryData.maxIndices=this._geometryData.indexCount),r&&this.indexBuffer.length>0&&this.indexBuffer[0]&&(this.indexBuffer[0].destroy(),this.indexBuffer[0]=null),this._geometryData.vertexStreamsUpdated&&this._updateVertexBuffer(),this._geometryData.indexStreamUpdated&&this._updateIndexBuffer(),this.primitive[0].type=e,this.indexBuffer.length>0&&this.indexBuffer[0]?this._geometryData.indexStreamUpdated&&(this.primitive[0].count=this._geometryData.indexCount,this.primitive[0].indexed=!0):this._geometryData.vertexStreamsUpdated&&(this.primitive[0].count=this._geometryData.vertexCount,this.primitive[0].indexed=!1),this._geometryData.vertexCount=0,this._geometryData.indexCount=0,this._geometryData.vertexStreamsUpdated=!1,this._geometryData.indexStreamUpdated=!1,this._geometryData.recreate=!1,this.updateRenderStates()}}_buildVertexFormat(e){let s=[];for(let i in this._geometryData.vertexStreamDictionary){let r=this._geometryData.vertexStreamDictionary[i];s.push({semantic:i,components:r.componentCount,type:r.dataType,normalize:r.dataTypeNormalize,asInt:r.asInt})}return new Ft(this.device,s,e)}_updateVertexBuffer(){if(!this.vertexBuffer){let i=this._geometryData.maxVertices,r=this._buildVertexFormat(i);this.vertexBuffer=new ft(this.device,r,i,{usage:this._geometryData.verticesUsage,storage:this._storageVertex})}let e=new Jr(this.vertexBuffer),s=this._geometryData.vertexCount;for(let i in this._geometryData.vertexStreamDictionary){let r=this._geometryData.vertexStreamDictionary[i];e.writeData(i,r.data,s),delete this._geometryData.vertexStreamDictionary[i]}e.end()}_updateIndexBuffer(){if(this.indexBuffer.length<=0||!this.indexBuffer[0]){let s=this._geometryData.maxVertices,i=s>65535||s===0?2:1,r=this._storageIndex?{storage:!0}:void 0;this.indexBuffer[0]=new os(this.device,i,this._geometryData.maxIndices,this._geometryData.indicesUsage,void 0,r)}let e=this._geometryData.indices;e&&(this.indexBuffer[0].writeData(e,this._geometryData.indexCount),this._geometryData.indices=null)}prepareRenderState(e){e===Fo?this.generateWireframe():e===dp&&(this.primitive[dp]={type:Aa,base:0,baseVertex:0,count:this.vertexBuffer?this.vertexBuffer.numVertices:0,indexed:!1})}updateRenderStates(){this.primitive[dp]&&this.prepareRenderState(dp),this.primitive[Fo]&&this.prepareRenderState(Fo)}generateWireframe(){this._destroyIndexBuffer(Fo);let e=this.vertexBuffer.numVertices,s,i;if(this.indexBuffer.length>0&&this.indexBuffer[0]){let a=[[0,1],[1,2],[2,0]],o=this.primitive[Oo].base,l=this.primitive[Oo].count,h=this.primitive[Oo].baseVertex||0,f=this.indexBuffer[Oo],u=Ef[f.format],d=new u(f.storage),p=new u(l*2),m=new Set,_=0;for(let S=o;SC?C*e+T:T*e+C;m.has(v)||(m.add(v),p[_++]=T,p[_++]=C)}m.clear(),i=f.format,s=p.slice(0,_)}else{let a=e-e%3,o=a/3*6;i=o>65535?2:1,s=o>65535?new Uint32Array(o):new Uint16Array(o);let l=0;for(let h=0;h{let s=e[c];return s instanceof Function&&(s=s()),s===t}}function wL(c,t){if(t(c))return c;let e=c._children,s=e.length;for(let i=0;i{r(a)&&i.push(a)}),i}findOne(e,s){let i=PL(e,s);return wL(this,i)}findByTag(...e){let s=[],i=(r,a)=>{a&&r.tags.has(...e)&&s.push(r);for(let o=0;oo.name===s[r]),!i)return null;return i}forEach(e,s){e.call(s,this);let i=this._children,r=i.length;for(let a=0;a=0?e.insertChild(this,s):e.addChild(this))}setLocalEulerAngles(e,s,i){this.localRotation.setFromEulerAngles(e,s,i),this._dirtyLocal||this._dirtifyLocal()}setLocalPosition(e,s,i){e instanceof x?this.localPosition.copy(e):this.localPosition.set(e,s,i),this._dirtyLocal||this._dirtifyLocal()}setLocalRotation(e,s,i,r){e instanceof $?this.localRotation.copy(e):this.localRotation.set(e,s,i,r),this._dirtyLocal||this._dirtifyLocal()}setLocalScale(e,s,i){e instanceof x?this.localScale.copy(e):this.localScale.set(e,s,i),this._dirtyLocal||this._dirtifyLocal()}_dirtifyLocal(){this._dirtyLocal||(this._dirtyLocal=!0,this._dirtyWorld||this._dirtifyWorld())}_unfreezeParentToRoot(){let e=this._parent;for(;e;)e._frozen=!1,e=e._parent}_dirtifyWorld(){this._dirtyWorld||this._unfreezeParentToRoot(),this._dirtifyWorldInternal()}_dirtifyWorldInternal(){if(!this._dirtyWorld){this._frozen=!1,this._dirtyWorld=!0;for(let e=0;et)}var RT=class{constructor(){n(this,"cache",new Map)}destroy(){this.cache.forEach((t,e)=>{e.destroy()}),this.cache.clear()}incRef(t){let e=(this.cache.get(t)||0)+1;this.cache.set(t,e)}decRef(t){if(t){let e=this.cache.get(t);e&&(e--,e===0?(this.cache.delete(t),t.destroy()):this.cache.set(t,e))}}};var yr=class{static incRef(t){this.cache.incRef(t)}static decRef(t){this.cache.decRef(t)}static destroy(){this.cache.destroy()}};n(yr,"cache",new RT);var wp=class{constructor(){n(this,"_counter",0)}get(){return this._counter++}};var bT=new wp;var dY=new ge,DT=new ge,Uw=new Br,kw=new Set,Ip=new Uint32Array(4),LT=class{constructor(t){n(this,"vertexBuffer",null);n(this,"_destroyVertexBuffer",!1);this.count=t}destroy(){this._destroyVertexBuffer&&this.vertexBuffer?.destroy(),this.vertexBuffer=null}},zw=class{constructor(){n(this,"shader");n(this,"bindGroup",null);n(this,"uniformBuffer",null);n(this,"hashes")}getBindGroup(t){if(!this.bindGroup){let s=this.shader.meshBindGroupFormat;this.bindGroup=new ji(t,s)}return this.bindGroup}getUniformBuffer(t){if(!this.uniformBuffer){let s=this.shader.meshUniformBufferFormat;this.uniformBuffer=new Qr(t,s,!1)}return this.uniformBuffer}destroy(){this.bindGroup?.destroy(),this.bindGroup=null,this.uniformBuffer?.destroy(),this.uniformBuffer=null}},Kf=class Kf{constructor(t,e,s=null){n(this,"castShadow",!1);n(this,"shadowCascadeMask",cw);n(this,"cull",!0);n(this,"drawOrder",0);n(this,"_drawBucket",127);n(this,"node");n(this,"visible",!0);n(this,"visibleThisFrame",!1);n(this,"flipFacesFactor",1);n(this,"gsplatInstance",null);n(this,"id",bT.get());n(this,"isVisibleFunc",null);n(this,"instancingData",null);n(this,"indirectData",null);n(this,"drawCommands",null);n(this,"meshMetaData",null);n(this,"parameters",{});n(this,"pick",!0);n(this,"stencilFront",null);n(this,"stencilBack",null);n(this,"transparent",!1);n(this,"_aabb",new ge);n(this,"_aabbVer",-1);n(this,"_aabbMeshVer",-1);n(this,"_customAabb",null);n(this,"_updateAabb",!0);n(this,"_updateAabbFunc",null);n(this,"_sortKeyShadow",0);n(this,"_sortKeyForward",0);n(this,"_sortKeyDynamic",0);n(this,"_layer",Xg);n(this,"_material",null);n(this,"_skinInstance",null);n(this,"_morphInstance",null);n(this,"_receiveShadow",!0);n(this,"_renderStyle",Oo);n(this,"_screenSpace",!1);n(this,"_shaderCache",new Map);n(this,"_shaderDefs",cs<<16);n(this,"_calculateSortDistance",null);if(this.node=s,this._mesh=t,t.incRefCount(),this.material=e,t.vertexBuffer){let i=t.vertexBuffer.format;this._shaderDefs|=i.hasUv0?Of:0,this._shaderDefs|=i.hasUv1?$g:0,this._shaderDefs|=i.hasColor?Zg:0,this._shaderDefs|=i.hasTangents?Nf:0}this.updateKey()}set drawBucket(t){this._drawBucket=Math.floor(t)&255,this.updateKey()}get drawBucket(){return this._drawBucket}set renderStyle(t){this._renderStyle=t,this.mesh.prepareRenderState(t)}get renderStyle(){return this._renderStyle}set mesh(t){t!==this._mesh&&(this._mesh&&this._mesh.decRefCount(),this._mesh=t,t&&t.incRefCount())}get mesh(){return this._mesh}set aabb(t){this._aabb=t}get aabb(){if(!this._updateAabb)return this._aabb;if(this._updateAabbFunc)return this._updateAabbFunc(this._aabb);let t=this._customAabb,e=!!t;if(!t){if(t=dY,this.skinInstance){if(!this.mesh.boneAabb){let r=this._morphInstance?this._morphInstance.morph._targets:null;this.mesh._initBoneAabbs(r)}let s=this.mesh.boneUsed,i=!0;for(let r=0;r{t.destroy()}),this._shaderCache.clear()}getShaderInstance(t,e,s,i,r,a,o){let l=this._shaderDefs;Ip[0]=t,Ip[1]=e,Ip[2]=l,Ip[3]=i.hash;let h=dc(Ip),f=this._shaderCache.get(h);if(!f){let u=this._material;if(f=new zw,f.shader=u.variants.get(h),f.hashes=new Uint32Array(Ip),!f.shader){let d=u.getShaderVariant({device:this.mesh.device,scene:s,objDefs:l,cameraShaderParams:i,pass:t,sortedLights:o,viewUniformFormat:r,viewBindGroupFormat:a,vertexFormat:this.mesh.vertexBuffer?.format});u.variants.set(h,d),f.shader=d}this._shaderCache.set(h,f)}return f}set material(t){this.clearShaders();let e=this._material;e&&e.removeMeshInstanceRef(this),this._material=t,t&&(t.addMeshInstanceRef(this),this.transparent=t.transparent,this.updateKey())}get material(){return this._material}_updateShaderDefs(t){t!==this._shaderDefs&&(this._shaderDefs=t,this.clearShaders())}set calculateSortDistance(t){this._calculateSortDistance=t}get calculateSortDistance(){return this._calculateSortDistance}set receiveShadow(t){this._receiveShadow!==t&&(this._receiveShadow=t,this._updateShaderDefs(t?this._shaderDefs&~Tc:this._shaderDefs|Tc))}get receiveShadow(){return this._receiveShadow}set batching(t){this._updateShaderDefs(t?this._shaderDefs|Uf:this._shaderDefs&~Uf)}get batching(){return(this._shaderDefs&Uf)!==0}set skinInstance(t){this._skinInstance=t,this._updateShaderDefs(t?this._shaderDefs|Uo:this._shaderDefs&~Uo),this._setupSkinUpdate()}get skinInstance(){return this._skinInstance}set morphInstance(t){this._morphInstance?.destroy(),this._morphInstance=t;let e=this._shaderDefs;e=t&&t.morph.morphPositions?e|zo:e&~zo,e=t&&t.morph.morphNormals?e|Go:e&~Go,e=t&&t.morph.intRenderFormat?e|Vo:e&~Vo,this._updateShaderDefs(e)}get morphInstance(){return this._morphInstance}set screenSpace(t){this._screenSpace!==t&&(this._screenSpace=t,this._updateShaderDefs(t?this._shaderDefs|Ec:this._shaderDefs&~Ec))}get screenSpace(){return this._screenSpace}set key(t){this._sortKeyForward=t}get key(){return this._sortKeyForward}set mask(t){let e=this._shaderDefs&65535;this._updateShaderDefs(e|t<<16)}get mask(){return this._shaderDefs>>16}set instancingCount(t){this.instancingData&&(this.instancingData.count=t)}get instancingCount(){return this.instancingData?this.instancingData.count:0}destroy(){let t=this.mesh;t&&(this.mesh=null,t.refCount<1&&t.destroy()),this.setRealtimeLightmap(Kf.lightmapParamNames[0],null),this.setRealtimeLightmap(Kf.lightmapParamNames[1],null),this._skinInstance?.destroy(),this._skinInstance=null,this.morphInstance?.destroy(),this.morphInstance=null,this.clearShaders(),this.material=null,this.instancingData?.destroy(),this.destroyDrawCommands()}destroyDrawCommands(){if(this.drawCommands){for(let t of this.drawCommands.values())t?.destroy();this.drawCommands=null}}static _prepareRenderStyleForArray(t,e){if(t){for(let s=0;s0):!1}updateKey(){let{material:t}=this;this._sortKeyForward=this._drawBucket<<23|(t.alphaToCoverage||t.alphaTest?4194304:0)|t.id&4194303}setInstancing(t,e=!1){t?(t===!0?this.instancingData=new LT(0):(this.instancingData=new LT(t.numVertices),this.instancingData.vertexBuffer=t,t.format.instancing=!0),this.cull=e):(this.instancingData=null,this.cull=!0),this._updateShaderDefs(t instanceof ft?this._shaderDefs|ko:this._shaderDefs&~ko)}setIndirect(t,e,s=1){let i=t?.camera??null;if(e===-1)this._deleteDrawCommandsKey(i);else{this.drawCommands??(this.drawCommands=new Map);let r=this.drawCommands.get(i)??new Cf(this.mesh.device);r.slotIndex=e,r.update(s),this.drawCommands.set(i,r),this.mesh.device.mapsToClear.add(this.drawCommands)}}setMultiDraw(t,e=1){let s=t?.camera??null,i;if(e===0)this._deleteDrawCommandsKey(s);else{if(this.drawCommands??(this.drawCommands=new Map),i=this.drawCommands.get(s),!i){let a=this.mesh.indexBuffer?.[0]?.format,o=a!==void 0?XC[a]:0;i=new Cf(this.mesh.device,o),this.drawCommands.set(s,i)}i.allocate(e)}return i}_deleteDrawCommandsKey(t){let e=this.drawCommands;e&&(e.get(t)?.destroy(),e.delete(t),e.size===0&&this.destroyDrawCommands())}getDrawCommands(t){let e=this.drawCommands;if(e)return e.get(t)??e.get(null)}getIndirectMetaData(){let t=this.mesh?.primitive[this.renderStyle],e=this.meshMetaData??(this.meshMetaData=new Int32Array(4));return e[0]=t.count,e[1]=t.base,e[2]=t.baseVertex,e}ensureMaterial(t){this.material||(this.material=ra(t))}clearParameters(){this.parameters={}}getParameters(){return this.parameters}getParameter(t){return this.parameters[t]}setParameter(t,e,s=4294967295){let i=this.parameters[t];i?(i.data=e,i.passFlags=s):this.parameters[t]={scopeId:null,data:e,passFlags:s}}setRealtimeLightmap(t,e){let s=this.getParameter(t);s!==e&&(s&&yr.decRef(s.data),e?(yr.incRef(e),this.setParameter(t,e)):this.deleteParameter(t))}deleteParameter(t){this.parameters[t]&&delete this.parameters[t]}setParameters(t,e){let s=this.parameters;for(let i in s){let r=s[i];r.passFlags&e&&(r.scopeId||(r.scopeId=t.scope.resolve(i)),r.scopeId.setValue(r.data))}}setLightmapped(t){t?this.mask=(this.mask|xi)&~(cs|vi):(this.setRealtimeLightmap(Kf.lightmapParamNames[0],null),this.setRealtimeLightmap(Kf.lightmapParamNames[1],null),this._shaderDefs&=~(yc|Ff|Bf),this.mask=(this.mask|cs)&~(xi|vi))}setCustomAabb(t){t?this._customAabb?this._customAabb.copy(t):this._customAabb=t.clone():(this._customAabb=null,this._aabbVer=-1),this._setupSkinUpdate()}_setupSkinUpdate(){this._skinInstance&&(this._skinInstance._updateBeforeCull=!this._customAabb)}};n(Kf,"lightmapParamNames",["texture_lightMap","texture_dirLightMap"]);var we=Kf;var pY=[0,1,3,2,3,1],mY=[0,1,3,0,3,2],bL=new Ws;function DL(c,t){if(c&&!t||!c&&t)return!1;if(c=c.data,t=t.data,c===t)return!0;if(c instanceof Float32Array&&t instanceof Float32Array){if(c.length!==t.length)return!1;for(let e=0;e=0&&(i._obj[t].splice(r,1),this.markGroupDirty(e))}}_filterBatchableInstances(t,e){let s=!1,i=!1;for(let r=0;r0?(e.push(t.element._text._model.meshInstances[0]),t.element.removeModelFromLayers(t.element._text._model),i=!0):t.element._image&&(e.push(t.element._image._renderable.meshInstance),t.element.removeModelFromLayers(t.element._image._renderable.model),t.element._image._renderable.unmaskMeshInstance&&(e.push(t.element._image._renderable.unmaskMeshInstance),(!t.element._image._renderable.unmaskMeshInstance.stencilFront||!t.element._image._renderable.unmaskMeshInstance.stencilBack)&&(t.element._dirtifyMask(),t.element._onPrerender())),i=!0),i&&(s._ui=!0)}_collectAndRemoveMeshInstances(t,e){for(let s=0;sg.drawOrder-T.drawOrder);let m=t,_,S=i?function(g){f?f.add(g.aabb):f=g.aabb.clone(),_.push(g)}:function(g){_.push(g)};for(;m.length>0;){d[p]=[m[0]],_=[];let g=m[0].material,T=m[0].layer,C=m[0]._shaderDefs,v=m[0].parameters,E=m[0].stencilFront,y=m[0].mesh.vertexBuffer.getNumVertices(),P=m[0].drawOrder;l.copy(m[0].aabb);let A=Gw(m[0]),w=m[0].mesh.vertexBuffer.format.batchingHash,I=m[0].mesh.primitive[0].indexed,D=m[0].castShadow,O=m[0].shadowCascadeMask;f=null;for(let G=1;G=a){_=_.concat(m.slice(G));break}if(g!==M.material||T!==M.layer||w!==M.mesh.vertexBuffer.format.batchingHash||I!==M.mesh.primitive[0].indexed||C!==M._shaderDefs||y+M.mesh.vertexBuffer.getNumVertices()>o){S(M);continue}if(h.copy(l),h.add(M.aabb),h.halfExtents.x>r||h.halfExtents.y>r||h.halfExtents.z>r){S(M);continue}if(E&&(!(u=M.stencilFront)||E.func!==u.func||E.zpass!==u.zpass)){S(M);continue}if(A!==Gw(M)){S(M);continue}if(D!==M.castShadow||O!==M.shadowCascadeMask){S(M);continue}if(!_Y(v,M.parameters)){S(M);continue}if(i&&f&&f.intersects(M.aabb)&&M.drawOrder!==P){S(M);continue}l.add(M.aabb),y+=M.mesh.vertexBuffer.getNumVertices(),d[p].push(M)}p++,m=_}return d}collectBatchedMeshData(t,e){let s=null,i=0,r=0,a=null;for(let o=0;o=3){if(r===ee){let O=v.data,G=O[0],M=O[1],H=O[2],U=O[4],L=O[5],b=O[6],N=O[8],k=O[9],z=O[10],V=O[12],q=O[13],re=O[14],te,j,oe;for(let be=0;be0&&a.setIndices(y),a.update(Yt,!1),e&&(u=u.clone(),u.update());let P=new we(a,u,this.rootNode);P.castShadow=l.origMeshInstances[0].castShadow,P.parameters=l.origMeshInstances[0].parameters,P.layer=l.origMeshInstances[0].layer,P._shaderDefs=l.origMeshInstances[0]._shaderDefs,P.batching=!0,P.cull=l.origMeshInstances[0].cull;let A=this._batchGroups[s];if(A&&A._ui&&(P.cull=!1),e){let w=[];for(let I=0;I0&&this.generate(this._dirtyGroups);for(let t=0;t1&&(a=Mt,r=!1);let o=e.renderTarget?.depthBuffer??e.renderTarget?.colorBuffer;this.shouldReallocate(this.depthRenderTarget,o)&&(this.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=this.allocateRenderTarget(this.depthRenderTarget,e.renderTarget,s,a,r));let l=r?this.depthRenderTarget.depthBuffer:this.depthRenderTarget.colorBuffer;s.scope.resolve(ML).setValue(l)}execute(){let e=this.device;if(e.isWebGL2&&e.renderTarget.samples>1){let s=e.renderTarget.impl._glFrameBuffer,i=this.depthRenderTarget;e.renderTarget=i,e.updateBegin(),this.depthRenderTarget.impl.internalResolve(e,s,i.impl._glFrameBuffer,this.depthRenderTarget,e.gl.DEPTH_BUFFER_BIT)}else e.copyRenderTarget(e.renderTarget,this.depthRenderTarget,!1,!0)}};var bp=class{constructor(){n(this,"_gammaCorrection",No);n(this,"_toneMapping",Qn);n(this,"_srgbRenderTarget",!1);n(this,"_ssaoEnabled",!1);n(this,"_fog",Mi);n(this,"_sceneDepthMapLinear",!1);n(this,"_hash");n(this,"_defines",new Map);n(this,"_definesDirty",!0)}get hash(){if(this._hash===void 0){let t=`${this.gammaCorrection}_${this.toneMapping}_${this.srgbRenderTarget}_${this.fog}_${this.ssaoEnabled}_${this.sceneDepthMapLinear}`;this._hash=xt(t)}return this._hash}get defines(){let t=this._defines;return this._definesDirty&&(this._definesDirty=!1,t.clear(),this._sceneDepthMapLinear&&t.set("SCENE_DEPTHMAP_LINEAR",""),this.shaderOutputGamma===No&&t.set("SCENE_COLORMAP_GAMMA",""),t.set("FOG",this._fog.toUpperCase()),t.set("TONEMAP",bf[this._toneMapping]),t.set("GAMMA",qg[this.shaderOutputGamma])),t}markDirty(){this._hash=void 0,this._definesDirty=!0}set fog(t){this._fog!==t&&(this._fog=t,this.markDirty())}get fog(){return this._fog}set ssaoEnabled(t){this._ssaoEnabled!==t&&(this._ssaoEnabled=t,this.markDirty())}get ssaoEnabled(){return this._ssaoEnabled}set gammaCorrection(t){this._gammaCorrectionAssigned=!0,this._gammaCorrection!==t&&(this._gammaCorrection=t,this.markDirty())}get gammaCorrection(){return this._gammaCorrection}set toneMapping(t){this._toneMapping!==t&&(this._toneMapping=t,this.markDirty())}get toneMapping(){return this._toneMapping}set srgbRenderTarget(t){this._srgbRenderTarget!==t&&(this._srgbRenderTarget=t,this.markDirty())}get srgbRenderTarget(){return this._srgbRenderTarget}set sceneDepthMapLinear(t){this._sceneDepthMapLinear!==t&&(this._sceneDepthMapLinear=t,this.markDirty())}get sceneDepthMapLinear(){return this._sceneDepthMapLinear}get shaderOutputGamma(){return this._gammaCorrection===No&&!this._srgbRenderTarget?No:Zi}};var Dp=new x,lS=new x,OL=new x,FL=new W,gY=[new x,new x,new x,new x,new x,new x,new x,new x],Wa=class Wa{constructor(t){n(this,"shaderPassInfo",null);n(this,"renderPassColorGrab",null);n(this,"renderPassDepthGrab",null);n(this,"fogParams",null);n(this,"shaderParams",new bp);n(this,"framePasses",[]);n(this,"beforePasses",[]);n(this,"jitter",0);n(this,"device");this.device=t,this._aspectRatio=16/9,this._aspectRatioMode=Ac,this._calculateProjection=null,this._calculateTransform=null,this._clearColor=new F(.75,.75,.75,1),this._clearColorBuffer=!0,this._clearDepth=1,this._clearDepthBuffer=!0,this._clearStencil=0,this._clearStencilBuffer=!0,this._cullFaces=!0,this._farClip=1e3,this._flipFaces=!1,this._fov=45,this._frustumCulling=!0,this._horizontalFov=!1,this._layers=[Os,Zt,$n,Va,Zn],this._layersSet=new Set(this._layers),this._nearClip=.1,this._node=null,this._orthoHeight=10,this._projection=ts,this._rect=new Q(0,0,1,1),this._renderTarget=null,this._scissorRect=new Q(0,0,1,1),this._scissorRectClear=!1,this._aperture=16,this._shutter=1/1e3,this._sensitivity=1e3,this._projMat=new W,this._projMatDirty=!0,this._projMatSkybox=new W,this._viewMat=new W,this._viewMatDirty=!0,this._viewProjMat=new W,this._viewProjMatDirty=!0,this._shaderMatricesVersion=0,this._viewProjInverse=new W,this._viewProjCurrent=null,this._viewProjPrevious=new W,this._jitters=[0,0,0,0],this.frustum=new So,this._xr=null,this._xrProperties={horizontalFov:this._horizontalFov,fov:this._fov,aspectRatio:this._aspectRatio,farClip:this._farClip,nearClip:this._nearClip}}static applyShaderProjectionTransform(t,e,s,i){if(!s&&!i)return e.copy(t),e;if(s&&i){let r=Wa._applyShaderProjectionScratch;return r.mul2(Wa._flipYProjectionMatrix,t),e.mul2(Wa._webGpuDepthRangeMatrix,r),e}return s?(e.mul2(Wa._flipYProjectionMatrix,t),e):(e.mul2(Wa._webGpuDepthRangeMatrix,t),e)}destroy(){this.renderPassColorGrab?.destroy(),this.renderPassColorGrab=null,this.renderPassDepthGrab?.destroy(),this.renderPassDepthGrab=null,this.framePasses.length=0}_storeShaderMatrices(t,e,s,i){this._shaderMatricesVersion!==i&&(this._shaderMatricesVersion=i,this._viewProjPrevious.copy(this._viewProjCurrent??t),this._viewProjCurrent??(this._viewProjCurrent=new W),this._viewProjCurrent.copy(t),this._viewProjInverse.invert(t),this._jitters[2]=this._jitters[0],this._jitters[3]=this._jitters[1],this._jitters[0]=e,this._jitters[1]=s)}get fullSizeClearRect(){let t=this._scissorRectClear?this.scissorRect:this._rect;return t.x===0&&t.y===0&&t.z===1&&t.w===1}set aspectRatio(t){this._aspectRatio!==t&&(this._aspectRatio=t,this._projMatDirty=!0)}get aspectRatio(){if(this.xr?.active)return this._xrProperties.aspectRatio;if(this._aspectRatioMode===Ac){let t=this.calculateAspectRatio();this._aspectRatio!==t&&(this._aspectRatio=t,this._projMatDirty=!0)}return this._aspectRatio}set aspectRatioMode(t){this._aspectRatioMode!==t&&(this._aspectRatioMode=t,this._projMatDirty=!0)}get aspectRatioMode(){return this._aspectRatioMode}set calculateProjection(t){this._calculateProjection=t,this._projMatDirty=!0}get calculateProjection(){return this._calculateProjection}set calculateTransform(t){this._calculateTransform=t}get calculateTransform(){return this._calculateTransform}set clearColor(t){this._clearColor.copy(t)}get clearColor(){return this._clearColor}set clearColorBuffer(t){this._clearColorBuffer=t}get clearColorBuffer(){return this._clearColorBuffer}set clearDepth(t){this._clearDepth=t}get clearDepth(){return this._clearDepth}set clearDepthBuffer(t){this._clearDepthBuffer=t}get clearDepthBuffer(){return this._clearDepthBuffer}set clearStencil(t){this._clearStencil=t}get clearStencil(){return this._clearStencil}set clearStencilBuffer(t){this._clearStencilBuffer=t}get clearStencilBuffer(){return this._clearStencilBuffer}set cullFaces(t){this._cullFaces=t}get cullFaces(){return this._cullFaces}set farClip(t){this._farClip!==t&&(this._farClip=t,this._projMatDirty=!0)}get farClip(){return this.xr?.active?this._xrProperties.farClip:this._farClip}set flipFaces(t){this._flipFaces=t}get flipFaces(){return this._flipFaces}set fov(t){this._fov!==t&&(this._fov=t,this._projMatDirty=!0)}get fov(){return this.xr?.active?this._xrProperties.fov:this._fov}set frustumCulling(t){this._frustumCulling=t}get frustumCulling(){return this._frustumCulling}set horizontalFov(t){this._horizontalFov!==t&&(this._horizontalFov=t,this._projMatDirty=!0)}get horizontalFov(){return this.xr?.active?this._xrProperties.horizontalFov:this._horizontalFov}set layers(t){this._layers=t.slice(0),this._layersSet=new Set(this._layers)}get layers(){return this._layers}get layersSet(){return this._layersSet}set nearClip(t){this._nearClip!==t&&(this._nearClip=t,this._projMatDirty=!0)}get nearClip(){return this.xr?.active?this._xrProperties.nearClip:this._nearClip}set node(t){this._node=t}get node(){return this._node}set orthoHeight(t){this._orthoHeight!==t&&(this._orthoHeight=t,this._projMatDirty=!0)}get orthoHeight(){return this._orthoHeight}set projection(t){this._projection!==t&&(this._projection=t,this._projMatDirty=!0)}get projection(){return this._projection}get projectionMatrix(){return this._evaluateProjectionMatrix(),this._projMat}set rect(t){this._rect.copy(t),this._projMatDirty=!0}get rect(){return this._rect}set renderTarget(t){this._renderTarget=t,this._projMatDirty=!0}get renderTarget(){return this._renderTarget}set scissorRect(t){this._scissorRect.copy(t)}get scissorRect(){return this._scissorRect}get viewMatrix(){if(this._viewMatDirty){let t=this._node.getWorldTransform();this._viewMat.copy(t).invert(),this._viewMatDirty=!1}return this._viewMat}set aperture(t){this._aperture=t}get aperture(){return this._aperture}set sensitivity(t){this._sensitivity=t}get sensitivity(){return this._sensitivity}set shutter(t){this._shutter=t}get shutter(){return this._shutter}set xr(t){this._xr!==t&&(this._xr=t,this._projMatDirty=!0)}get xr(){return this._xr}calculateAspectRatio(t){let e=t??this._renderTarget,s=e?e.width:this.device.width,i=e?e.height:this.device.height;return s*this._rect.z/(i*this._rect.w)}clone(){return new Wa(this.device).copy(this)}copy(t){return this._aspectRatio=t._aspectRatio,this._farClip=t._farClip,this._fov=t._fov,this._horizontalFov=t._horizontalFov,this._nearClip=t._nearClip,this._xrProperties.aspectRatio=t._xrProperties.aspectRatio,this._xrProperties.farClip=t._xrProperties.farClip,this._xrProperties.fov=t._xrProperties.fov,this._xrProperties.horizontalFov=t._xrProperties.horizontalFov,this._xrProperties.nearClip=t._xrProperties.nearClip,this.aspectRatioMode=t.aspectRatioMode,this.calculateProjection=t.calculateProjection,this.calculateTransform=t.calculateTransform,this.clearColor=t.clearColor,this.clearColorBuffer=t.clearColorBuffer,this.clearDepth=t.clearDepth,this.clearDepthBuffer=t.clearDepthBuffer,this.clearStencil=t.clearStencil,this.clearStencilBuffer=t.clearStencilBuffer,this.cullFaces=t.cullFaces,this.flipFaces=t.flipFaces,this.frustumCulling=t.frustumCulling,this.layers=t.layers,this.orthoHeight=t.orthoHeight,this.projection=t.projection,this.rect=t.rect,this.renderTarget=t.renderTarget,this.scissorRect=t.scissorRect,this.aperture=t.aperture,this.shutter=t.shutter,this.sensitivity=t.sensitivity,this.shaderPassInfo=t.shaderPassInfo,this.jitter=t.jitter,this._projMatDirty=!0,this}_enableRenderPassColorGrab(t,e){e?this.renderPassColorGrab||(this.renderPassColorGrab=new wc(t)):(this.renderPassColorGrab?.destroy(),this.renderPassColorGrab=null)}_enableRenderPassDepthGrab(t,e,s){s?this.renderPassDepthGrab||(this.renderPassDepthGrab=new MT(t,this)):(this.renderPassDepthGrab?.destroy(),this.renderPassDepthGrab=null)}_updateViewProjMat(){(this._projMatDirty||this._viewMatDirty||this._viewProjMatDirty)&&(this._viewProjMat.mul2(this.projectionMatrix,this.viewMatrix),this._viewProjMatDirty=!1)}worldToScreen(t,e,s,i=new x){this._updateViewProjMat(),this._viewProjMat.transformPoint(t,i);let r=this._viewProjMat.data,a=t.x*r[3]+t.y*r[7]+t.z*r[11]+1*r[15];i.x=(i.x/a+1)*.5,i.y=(1-i.y/a)*.5;let{x:o,y:l,z:h,w:f}=this._rect;return i.x=i.x*h*e+o*e,i.y=i.y*f*s+(1-l-f)*s,i}screenToWorld(t,e,s,i,r,a=new x){let{x:o,y:l,z:h,w:f}=this._rect,u=this.farClip-this.nearClip;if(Dp.set((t-o*i)/(h*i),1-(e-(1-l-f)*r)/(f*r),s/u),Dp.mulScalar(2),Dp.sub(x.ONE),this._projection===ts){W._getPerspectiveHalfSize(lS,this.fov,this.aspectRatio,this.nearClip,this.horizontalFov),lS.x*=Dp.x,lS.y*=Dp.y;let d=this._node.getWorldTransform();lS.z=-this.nearClip,d.transformPoint(lS,OL);let p=this._node.getPosition();a.sub2(OL,p),a.normalize(),a.mulScalar(s),a.add(p)}else this._updateViewProjMat(),FL.copy(this._viewProjMat).invert(),FL.transformPoint(Dp,a);return a}_evaluateProjectionMatrix(){let t=this.aspectRatio;if(this._projMatDirty){if(this._projection===ts)this._projMat.setPerspective(this.fov,t,this.nearClip,this.farClip,this.horizontalFov),this._projMatSkybox.copy(this._projMat);else{let e=this._orthoHeight,s=e*t;this._projMat.setOrtho(-s,s,-e,e,this.nearClip,this.farClip),this._projMatSkybox.setPerspective(this.fov,t,this.nearClip,this.farClip)}this._projMatDirty=!1}}getProjectionMatrixSkybox(){return this._evaluateProjectionMatrix(),this._projMatSkybox}getExposure(){let t=Math.log2(this._aperture*this._aperture/this._shutter*100/this._sensitivity);return 1/(Math.pow(2,t)*1.2)}getScreenSize(t){if(this._projection===ts){let e=this._node.getPosition().distance(t.center);if(eObject.keys(c).map(e=>`#define {${t}${e}} ${c[e]}`).join(` +`),zL=` - ${o7(o9,"CLUSTER_TEXTURE_")} - ${o7({LIGHTSHAPE_PUNCTUAL:"0u",LIGHTSHAPE_RECT:"1u",LIGHTSHAPE_DISK:"2u",LIGHTSHAPE_SPHERE:"3u",LIGHT_COLOR_DIVIDER:"100.0"},"")} -`;class lt{destroy(){this.lightsTexture?.destroy(),this.lightsTexture=null;}createTexture(e,t,i,s,r){return new ic(e,{name:r,width:t,height:i,mipmaps:false,format:s,addressU:1,addressV:1,type:tP,magFilter:0,minFilter:0,anisotropy:1})}setBounds(e,t){this.boundsMin.copy(e),this.boundsDelta.copy(t);}uploadTextures(){this.lightsTexture.lock().set(this.lightsFloat),this.lightsTexture.unlock();}updateUniforms(){this._lightsTextureId.setValue(this.lightsTexture);}getSpotDirection(e,t){t._node.getWorldTransform().getY(e).mulScalar(-1),e.normalize();}getLightAreaSizes(e){let t=e._node.getWorldTransform();return t.transformVector(o6,o4),o5[0]=o4.x,o5[1]=o4.y,o5[2]=o4.z,t.transformVector(o8,o4),o5[3]=o4.x,o5[4]=o4.y,o5[5]=o4.z,o5}addLightData(e,t){let i=2===e._type,s=e.atlasViewportAllocated,r=this.cookiesEnabled&&!!e._cookie&&s,a=this.areaLightsEnabled&&0!==e.shape,n=this.shadowsEnabled&&e.castShadows&&s,o=e._node.getPosition(),l=null,h=null;i?n?l=e.getRenderData(null,0).shadowMatrix:r&&(l=o3.evalSpotCookieMatrix(e)):(n||r)&&(h=e.atlasViewport);let c=this.lightsFloat,d=this.lightsUint,u=t*this.lightsTexture.width*4;c[u+4*o9.POSITION_RANGE+0]=o.x,c[u+4*o9.POSITION_RANGE+1]=o.y,c[u+4*o9.POSITION_RANGE+2]=o.z,c[u+4*o9.POSITION_RANGE+3]=e.attenuationEnd;let f=e.clusteredData;if(d[u+4*o9.COLOR_ANGLES_BIAS+0]=f[0],d[u+4*o9.COLOR_ANGLES_BIAS+1]=f[1],d[u+4*o9.COLOR_ANGLES_BIAS+2]=f[2],e.castShadows){let t=e.getRenderData(null,0),i=e._getUniformBiasValues(t),s=eh.float2Half(i.bias),r=eh.float2Half(i.normalBias);d[u+4*o9.COLOR_ANGLES_BIAS+3]=s|r<<16;}if(i&&(this.getSpotDirection(o4,e),c[u+4*o9.DIRECTION_FLAGS+0]=o4.x,c[u+4*o9.DIRECTION_FLAGS+1]=o4.y,c[u+4*o9.DIRECTION_FLAGS+2]=o4.z),d[u+4*o9.DIRECTION_FLAGS+3]=e.getClusteredFlags(n,r),l){let e=l.data;for(let t=0;t<16;t++)c[u+4*o9.PROJ_MAT_0+t]=e[t];}if(h&&(c[u+4*o9.ATLAS_VIEWPORT+0]=h.x,c[u+4*o9.ATLAS_VIEWPORT+1]=h.y,c[u+4*o9.ATLAS_VIEWPORT+2]=h.z/3),a){let t=this.getLightAreaSizes(e);c[u+4*o9.AREA_DATA_WIDTH+0]=t[0],c[u+4*o9.AREA_DATA_WIDTH+1]=t[1],c[u+4*o9.AREA_DATA_WIDTH+2]=t[2],c[u+4*o9.AREA_DATA_HEIGHT+0]=t[3],c[u+4*o9.AREA_DATA_HEIGHT+1]=t[4],c[u+4*o9.AREA_DATA_HEIGHT+2]=t[5];}}constructor(e){this.areaLightsEnabled=false,this.device=e,n$.get(e,tz).set("lightBufferDefinesPS",le),n$.get(e,tV).set("lightBufferDefinesPS",le),this.cookiesEnabled=false,this.shadowsEnabled=false,this.areaLightsEnabled=false,this.maxLights=255;let t=o9.COUNT;this.lightsFloat=new Float32Array(4*t*this.maxLights),this.lightsUint=new Uint32Array(this.lightsFloat.buffer),this.lightsTexture=this.createTexture(this.device,t,this.maxLights,14,"LightsTexture"),this._lightsTextureId=this.device.scope.resolve("lightsTexture"),this.invMaxColorValue=0,this.invMaxAttenuation=0,this.boundsMin=new ed,this.boundsDelta=new ed;}}let li=new ef,ls=new ed,lr=new ed,la=new ed,ln=new eA;class lo{constructor(){this.light=null,this.min=new ed,this.max=new ed;}}class ll{set maxCellLightCount(e){e!==this._maxCellLightCount&&(this._maxCellLightCount=e,this._cellsDirty=true);}get maxCellLightCount(){return this._maxCellLightCount}set cells(e){ls.copy(e).floor(),this._cells.equals(ls)||(this._cells.copy(ls),this._cellsLimit.copy(ls).sub(ed.ONE),this._cellsDirty=true);}get cells(){return this._cells}destroy(){this.lightsBuffer.destroy(),this.releaseClusterTexture();}releaseClusterTexture(){this.clusterTexture&&(this.clusterTexture.destroy(),this.clusterTexture=null);}registerUniforms(e){this._numClusteredLightsId=e.scope.resolve("numClusteredLights"),this._clusterMaxCellsId=e.scope.resolve("clusterMaxCells"),this._clusterWorldTextureId=e.scope.resolve("clusterWorldTexture"),this._clusterBoundsMinId=e.scope.resolve("clusterBoundsMin"),this._clusterBoundsMinData=new Float32Array(3),this._clusterBoundsDeltaId=e.scope.resolve("clusterBoundsDelta"),this._clusterBoundsDeltaData=new Float32Array(3),this._clusterCellsCountByBoundsSizeId=e.scope.resolve("clusterCellsCountByBoundsSize"),this._clusterCellsCountByBoundsSizeData=new Float32Array(3),this._clusterCellsDotId=e.scope.resolve("clusterCellsDot"),this._clusterCellsDotData=new Int32Array(3),this._clusterCellsMaxId=e.scope.resolve("clusterCellsMax"),this._clusterCellsMaxData=new Int32Array(3),this._clusterTextureWidthId=e.scope.resolve("clusterTextureWidth");}updateParams(e){e&&(this.cells=e.cells,this.maxCellLightCount=e.maxLightsPerCell,this.lightsBuffer.cookiesEnabled=e.cookiesEnabled,this.lightsBuffer.shadowsEnabled=e.shadowsEnabled,this.lightsBuffer.areaLightsEnabled=e.areaLightsEnabled);}updateCells(){if(this._cellsDirty){this._cellsDirty=false;let e=this._cells.x,t=this._cells.y,i=this._cells.z,s=e*t*i,r=this.maxCellLightCount*s,{x:a,y:n}=ir.calcTextureSize(r,li,this.maxCellLightCount);this._clusterCellsMaxData[0]=e,this._clusterCellsMaxData[1]=t,this._clusterCellsMaxData[2]=i,this._clusterCellsDotData[0]=this.maxCellLightCount,this._clusterCellsDotData[1]=e*i*this.maxCellLightCount,this._clusterCellsDotData[2]=e*this.maxCellLightCount,this.clusters=new Uint8ClampedArray(r),this.counts=new Int32Array(s),this.releaseClusterTexture(),this.clusterTexture=this.lightsBuffer.createTexture(this.device,a,n,33,"ClusterTexture");}}uploadTextures(){this.clusterTexture.lock().set(this.clusters),this.clusterTexture.unlock(),this.lightsBuffer.uploadTextures();}updateUniforms(){this._numClusteredLightsId.setValue(this._usedLights.length),this.lightsBuffer.updateUniforms(),this._clusterWorldTextureId.setValue(this.clusterTexture),this._clusterMaxCellsId.setValue(this.maxCellLightCount);let e=this.boundsDelta;this._clusterCellsCountByBoundsSizeData[0]=this._cells.x/e.x,this._clusterCellsCountByBoundsSizeData[1]=this._cells.y/e.y,this._clusterCellsCountByBoundsSizeData[2]=this._cells.z/e.z,this._clusterCellsCountByBoundsSizeId.setValue(this._clusterCellsCountByBoundsSizeData),this._clusterBoundsMinData[0]=this.boundsMin.x,this._clusterBoundsMinData[1]=this.boundsMin.y,this._clusterBoundsMinData[2]=this.boundsMin.z,this._clusterBoundsDeltaData[0]=e.x,this._clusterBoundsDeltaData[1]=e.y,this._clusterBoundsDeltaData[2]=e.z,this._clusterBoundsMinId.setValue(this._clusterBoundsMinData),this._clusterBoundsDeltaId.setValue(this._clusterBoundsDeltaData),this._clusterCellsDotId.setValue(this._clusterCellsDotData),this._clusterCellsMaxId.setValue(this._clusterCellsMaxData),this._clusterTextureWidthId.setValue(this.clusterTexture.width);}evalLightCellMinMax(e,t,i){t.copy(e.min),t.sub(this.boundsMin),t.div(this.boundsDelta),t.mul2(t,this.cells),t.floor(),i.copy(e.max),i.sub(this.boundsMin),i.div(this.boundsDelta),i.mul2(i,this.cells),i.ceil(),t.max(ed.ZERO),i.min(this._cellsLimit);}collectLights(e){let t=this.lightsBuffer.maxLights,i=this._usedLights,s=1;e.forEach(e=>{let r=!!(3&e.mask),a=2===e.type&&0===e._outerConeAngle;if(e.enabled&&0!==e.type&&e.visibleThisFrame&&e.intensity>0&&r&&!a&&s1){t.copy(e[1].min),i.copy(e[1].max);for(let s=2;s{if(!lh){let e=atob("muPIHORMLNDCz4DxVR/ZvYfAUVEFR47KRIC4nwAAAAAP7WxlhD6Ci+2HCe7BF8jRAPZwdH2UPpI5PdLCJdkvG4UTaNDJ/0crAzne71GCrb4kbdMjjCEGzdX6fNxDMLJq5xkeoIVTdfiZkodEeArmZmp/FQzFjD4x8iOW7Dg64n+3mWqyEwLxXT8zoJXfbw8QJKDCaarUYyTlMzNFHbgUe9IQV7g4YOgtSKpIFZJ0qERm7u4PpmiF89ktHWCywaGmD6h+hfh2/Zd8KYlKqqo4Cem4T42bT/Z9FpCQF1hhSjfBzZ5XFn/y3jegWC6u86KuELRundQS/1Rp+XuKKGIgRv3CvP5y749yqLlFO495JOT3+f2CXgd71npU0/KjjpkZucbJ5m78IVyuSrSozc9jgBUhDrz0hFsyb7LFUH9//wJbBgLdNWJZObfKxrNt8TliLA9w9sXFv6g26iXpf6r/BqcAusj/QzGBZuoUGeEtw8BCXCZ3jUiw4hvM18ZVqlUD3C40LAFXW6FRjuAZGRNstb0/qVk4skwyT+MHrvRorI4rKHVMWZmKyAkzL/78u/9pMQuX14pZN50b2PHn6fRxeaCQLsfT4dpvIkWWFuFVENZIh+8xgR6lU+85W0PPdAu1j99kcCG40JBQa4JMyRzq6qriOBLtqF87vpCJan0WEduVr/mOYkS00urVA0mA6M3031+GmGmW48PaJDYOEIb3bIXWPaLoAOEinX1TN3+/vwhG6nqJu0TdHpedS7QsGZIoxH3nQYYjQP1jmbahlbNngw5ogsGk1y50XZyUmQBY+/JBJ3Unu4dApm+WmPwHPU9gLb+4mHh4BiY6M86pq+WeTyWdI3s0CXPEtHGXZ8zMZgUoyRomBi1VdazzuN+WOmQ9Pa0Z0tlNopUi8AJ4x2Xn4mmOKEbXLxlbVsWu8XhuDGYFOGCRVdSqDPXrHU5SDdUlti3k5///SBwzTMwK3L4a1H7w4lnpEas6////AfX8asyIBfeFXVJ3tgvxQ/blZuUKyIODIfr/UzdWNu7pciLBpdZRZ4pIfZ1R6szq+XNxkGG///8EZFpu7VHAhFWqHEOrB9unw+YQa5o8/9IR/V5/zq+986rJSyfgJKt2u9hxU1wzyQWPjJGvzG9+eWWxGFOHVKqI4jBQALwZZswesnvZ2UmmkEXdiRpz8B+oWE7PY70ZTMndisYSXg2TqoI+3y9BxbnY2Y4EfbdcRhAvG59NqDENNYbxKvK5HJfPG5M+Wi2AcpLVJrD6caiEOzgSoVNSgQK8fm2M3zGcF4xtClv/8Hs9oD7C3jitTATYNQxmKqKf1LhIxzf1bmfiNn7UKFmcJu4sLqVLwxGSue3taBEyknkw5hXTsUCvqmmL/f8n/w0giR7Hu/9EHvpkz3yuu64TioMkzdTJ30i0+hFnQqW1+v9mMwq+z9qGX0UFu9MomvVG2xod6vc12AAAAACq7sGa5qptFR0jF3nQt/D+7PibKYahaxP3hEixPbGi9nwNf2LAa7LkEZRKxzXeCD64Xpii5n+8Kpg8eHIv7AWXZltgMoGltmoJ0XGdOCL8WkzphvR9N2o3ARSZ42l5e5Pe4B58MCRlP3EKv+mcloknH+fto5BWsmEutW6KvjOVsznFCktkSczVk4aGvj9VXlRcLeDoKG8RkBgdcNG2bf8HUL4MT2DM+ar7NImJhKpxakX4Vk0CnP+/XNhl5UsP0lXgeZXPoDBMSW5An+DXlTCO5FQGwSPYwHLKYVIimEdAoVe49rQLaaNcye5LxU2/c5TijTgJtD5eQQIe1snxauj5jZsxJBUJdoP/zqpjqv8qBruoPsVsP8N44PCUW5Dd0DzqjSS/Dl5mI9cn1w2ndN/0KAEm1QAAAACwu6KM/083IBbH5bPa/9oHUwcU8I9v3j6/v18QYammrf+P6VL///8BrpuM3fOLCxaLNOFNF1zPbPYTP65ni6njft4eVcyrVXRQFrs52tr35StiSp55edVDCBC0H5rIfac6nzUwxQSt7y15QoKb+5zebEQUmVbrPjXuUa19Ey7sqXMiSUKHaw72PJKDdrutJoQr3u6lEYJ8K0MakWKj9zjTFi4X94TsKYco0GrLeB60M6D8M/80rhXUW8iMequg8y5F838WI0+gp3GBN5Kj/xIOxTWQuUaPV/LwvARr1VH93BFgGZR1MFW0Ua30GbYmdnAgo9VWy8SQtpDUgGE2r2zq2eTEMCL7sMKmE1hchVhuF/TCq9iXKEm86kzOf3Rp9ZnCxbpDUj+FKNxVyXe6pVZkRXv/m95SnB/EB8aME29N85MtAcDoXWlor8De2Q5Dg1tar+8wgiZufbMam81j//ASUohoR/zSh2KG4bvT6mkIPz6C5/98DC3LaWlaEZ1zA5JORZRu6J/a0GY285sEYzw71YqOT1ihAG0z5SDt1xNiDQWZdFpndArp6xWhqSDkRb4kSJEHb9liPvw7uLV/6i5MVf//A9Qjr8xkAEUh+KDI+zdtJ68d6MBOktg1iyp/SCq8O9f5pbamn1VVVQPRTWqNBvhQKa07s6P0lc9Luu/3gw4HeyOUfz8MxMwV4UQhua+t9cr4bz/nIB2wnDSK1K7I94M+s6C84htaX/CNlMQUSs2KJO+yaebfTbkNX5yWcqEJevo0vbKUiETuFXiL019A3E+lmsyZMwXrXLLiQAZ5t9+jI3JobhJTMiDH5ZOQ+8Jau5555NMjHSscP9qCVaa40doh+1a3Ukf6jqBmLddgh79/fwTfCyqiuldNkUoy+nUp+4nerwg0OjtGv2x485PJOJvUEokNhYIdWjpx7BWk0VZGWOp3jSFTJ2bnu6KCduZtG/UcBC9RZ3W/jMSfSMw4Etr/DoD/XYP2V5Ovw+YoM3F5g2dGLdvuG6ZkVGLE6Dk5Zr+sdSyGliJP1y2OFf/KFO0RWO+3gsGhesTnfZVpTd8/HwgO216gwaqo+vY3TljfJWowY+i0p0Os4SLn/1wLqDHMlszggmT/D8MRFzs+pLv6LNJSsNZ/r41mWi/rF6ZcKp/yzJdK0VU44hskq3RGpgO6mIpJDsf/mZkFrz0yYOMLbuaj/wp1v7JMFM5eqvBhmTd7U8frQAtHtys4zgpjZmzUhOVTfNNLifElGXADlqHGKrkBT/nYwX8ZRm3RjvyPvjKyEqEGKUpVnvOGx+NKPHiWM//ZDpDVGvvrjmk8RPF/wiYZD3+Us8YCXjrVOfjdd1UPAfjLp8jgSn4me7DPTpz1Ggy9XL80guFO7ECT10AvILKfD18Qx+KY/f8aRqu0oOO8hfKRFZa9PUJwCsp6VdZz6LFkm2b9Pl2LIifCwzRy7TpdG2uAtOxP2OemY26bJMa9ZGSLIRlMsgpDpnDJwd0oa5pQ13x1hrHf52HpulUWonGWsfXZbSQYKu9bnEN76ciQih0opN3deDVrbrxorfVlnCmL1R9zq3ePGWIv21c7pW8kEiFTM5JX8dAw867s/60cf79/BH+MDFCZBHlz1L+qGOJf/1txhhmrf3//As+RIJwevDb+fgNXVeHw67QptZegayhrEwr5Gy+EPo1RLaMtPbqOZYoVzXzwzjMFWZxyUG9YUIf6////AQWy84iAygLk9COtXt92+0mT/xg0zMzMBeLkb8y9SL2TDXgSX422hDgpGNLJyuPioA+YJ91G8znrpNqHkwYyscaJDEc9Vc+j4cXle3hvcd2JqDQH2lBZxDn6mUTs0b75raMvbs727codX01Anj8f3wir9P2xQaQ22v/TxCMglKDFoTjaP01XTLgxnTvPv02JgEUrW6UDgOnobFpLdvKdlypgIzPcq14fgXU5tvVW0FEs7VRlsG1IyA69fN4n+awHhT34cE+xUvdj86C8LgAsFheTjI9Ht9EyYAAAAAAVBVKRx2wLgUTI0/2QfyJo2riRw3JDqzEShmx/Lifo6mRkQVbS7X53t+EvKxcXogtdts31e9MRHdcHgsA8rt4/mt2unlzQ/wsU8Gu7+W6Oj7eD8EQdDp5XlCsVaS/AV/t5ZpPOHR3rGpyAJe9IPV+xMrBL1Oz/8MQhFs31h0N1cVnq371uqIJYHyafKH1jteAK3VpMXBcuC+yt0ZeKyRUY4QhdrJJ4tJ1wg3Hu6kDsbovxupTMkGdRrm8oZSoYPbJ+PwH/xotgTdkA1205vUEfnqkI04T/fnnd1fiZW5AwNcggd7fi4j5zasmcntZexIxqFZQMzMJpfndmI5jn17cgn5EV5t9XN0C///8Q9wlJpMGXdoiaMTG2sVyHQsn8mWRISCLNG777S0OuDRP2GlLcJ2UeOg7Fo8hTNPeJ//iTJhyqxhKRUntdXOihq2wfKfH///8B0GGrwT+fSOQRdctKxjjGCSS11d6BlQ9BDfE0J6Z25FaNTKGpFKNCMr2G/041KpWwBLVe1k08vncseQbKZdXi8x1t9XA45U/Wd43D9wAh3Tal0aiLVzGPusOZ1F+W3TWoqlX/A95+dNef11TsuGful+ctGssldk3fqpfqh+43XTxL42+leSHoF/dWHYGX6maqUEuLX7UB+r/6Llr4LKocbVIeu+hB9QTPfz9fCP8RyWmX4SmbhMFsNtCijV7lVcwejLKlvl0GfCndnWV7/39VBrtTRuUx92oke3GBgKkC5fdGK0YvNK+xenKaDmsHDjNFUM3NMz3ZiXXFuLgojosPVCDEl2W5BjX3Ms+j0GSqACHmh0+RPWyuNm/Qe8vFf9AW7N1uRaxWirrUytqEJnJ4/Flm8hSoiZ2NQBsS6w/yQlC4gCaFo8q4nyY6AFdo4hiwhBXzbNKKvZvktCjSCukRR/BbYVbNwZi2Yh3hGodEacLW8qijiWJODf0P2bhfaiPspPT4lYJBgi/KfcFwCfvyUIgkJOv///8CG/JEepRBLaMFE+2TgrqsJXOVOWHt6g/bFwVLLMVBsMR50dis/39/AlBX+/rMTJkUQrnlxpR2iu0Tp8tATkRYGmDIrcAiRP8PjoWIlb7/0ecTdSCE9Y58+a+n/FovJQTVF4F2jAxMZhTgrM/KVS5BQu6bVbkWY5HXnxRshks3urDdW4RkWp4M4TeLmFK5KF/uHkkiO5Kv96RioH984v/CSDBnG+BwlnU9B+o7Y+0X0Nob+0pLsStxjvPXMy2eCpzhOWV4XbObBHN4UE2sLQ/DIqXhOzxVf38GlTi6aG7EnePO7TRJm9yOfUUcqq1I2iQHrVDqn3TUNRi/lMw8KbMW/3/nqCz/Ef8PoW5Qxcz2yHR/f78EPB2Stbd+ZFmfNTUYILzsb9YNhpaHcaymYrBiNHmFE3Y4ccYJ25Prqm7zHobGHED8/93ZNlWro9vcKivGZs31UiK1k5zjUhexUgbqJb+fUTjxce/7Zly8a5KMC1fX5nfjPgibdvzbXV1jRT2asXvmSAusaLdq1TSIJ8fXINk5AtT34EWPAsfP9IFQqM5K11O6saoHJA==");lh=Uint8Array.from(e,e=>e.charCodeAt(0));}};class ld{_next(){this.seed=(this.seed+4)%lh.length;}value(){return this._next(),lh[this.seed]/255}vec4(e=new ep){return this._next(),e.set(lh[this.seed],lh[this.seed+1],lh[this.seed+2],lh[this.seed+3]).mulScalar(1/255)}constructor(e=0){this.seed=0,this.seed=4*e,lc();}}let lu=[new ed(-1,0,0),new ed(1,0,0),new ed(0,-1,0),new ed(0,1,0),new ed(0,0,-1),new ed(0,0,1)];class lf{update(e,t){let i=this.colors,{r:s,g:r,b:a}=e;for(let e=0;e<6;e++)i[3*e]=s,i[3*e+1]=r,i[3*e+2]=a;for(let e=0;ee===s[t]))){this.version++,this.slots.length=0,this.atlasSplit.length=0,this.atlasSplit.push(...r);let e=this.atlasSplit[0];if(e>1){let t=1/e;for(let i=0;i1)for(let e=0;et.size-e.size);}}collectLights(e,t){let i=t.cookiesEnabled,s=t.shadowsEnabled,r=false,a=false;return l_.length=0,(i||s)&&(e=>{for(let t=0;tt.maxScreenSize-e.maxScreenSize),r&&this.allocateShadowAtlas(this.shadowAtlasResolution,t.shadowType),a&&this.allocateCookieAtlas(this.cookieAtlasResolution),(r||a)&&this.subdivide(l_.length,t),l_}setupSlot(e,t){e.atlasViewport.copy(t);let i=e.numShadowFaces;for(let s=0;s0){let e=this.slots;for(let t=0;tthis.defines.set(t,e)),this._shaderChunks=e.hasShaderChunks?new n$:null,this._shaderChunks?.copy(e._shaderChunks),this}clone(){return new this.constructor().copy(this)}_updateMeshInstanceKeys(){for(let e of this.meshInstances)e.updateKey();}updateUniforms(e,t){this._dirtyShader&&this.clearVariants();}getShaderVariant(e){}update(){if(Object.keys(this._oldChunks).length>0)for(let[e,t]of Object.entries(this._oldChunks))this.shaderChunks.glsl.set(e,t),delete this._oldChunks[e];(this._definesDirty||this._shaderChunks?.isDirty())&&(this._definesDirty=false,this._shaderChunks?.resetDirty(),this.clearVariants()),this.dirty=true;}clearParameters(){this.parameters={};}getParameters(){return this.parameters}clearVariants(){for(let e of(this.variants.clear(),this.meshInstances))e.clearShaders();}getParameter(e){return this.parameters[e]}_setParameterSimple(e,t){let i=this.parameters[e];i?i.data=t:this.parameters[e]={scopeId:null,data:t};}setParameter(e,t){if(void 0===t&&"object"==typeof e){let i=e;if(i.length){for(let e=0;e{e.forEach(e=>{e.destroy();});}),this.cache.clear();}getKey(e){let t=1===e._type,i=e._shadowType,s=e._shadowResolution;return `${t}-${i}-${s}`}get(e,t){let i=this.getKey(t),s=this.cache.get(i);if(s&&s.length)return s.pop();let r=lm.create(e,t);return r.cached=true,r}add(e,t){let i=this.getKey(e),s=this.cache.get(i);s?s.push(t):this.cache.set(i,[t]);}constructor(){this.cache=new Map;}}class lC extends ah{execute(){this.shadowRenderer.renderFace(this.light,null,this.face,false);}after(){this.applyVsm&&this.shadowRenderer.renderVsm(this.light,this.shadowCamera);}constructor(e,t,i,s,r){super(e),this.requiresCubemaps=false,this.shadowRenderer=t,this.light=i,this.face=s,this.applyVsm=r,this.shadowCamera=t.prepareFace(i,null,s),t.setupRenderPass(this,this.shadowCamera,true);}}class lA{cull(e,t,i=null){let s=this.renderer.scene.clusteredLightingEnabled;e.visibleThisFrame=true,s||e._shadowMap||(e._shadowMap=lm.create(this.device,e));let r=e._type,a=2===r?1:6;for(let n=0;np&&(p=t);}let m=l.right,_=l.up,g=l.forward,v=.25*e._shadowResolution/p,S=Math.ceil(lD.dot(_)*v)/v,y=Math.ceil(lD.dot(m)*v)/v,x=_.mulScalar(S),T=m.mulScalar(y),E=lD.dot(g),w=g.mulScalar(E);lD.add2(x,T).add(w),l.setPosition(lD),l.translateLocal(0,0,1e6),o.nearClip=.01,o.farClip=2e6,o.orthoHeight=p,this.renderer.updateCameraFrustum(o),this.shadowRenderer.cullShadowCasters(t,e,a.visibleCasters,o,s);let b=1<r&&(r=i);}return lM.min=s,lM.max=r,lM}(lR,lI.getMin(),lI.getMax());l.translateLocal(0,0,I.max+.1),o.farClip=I.max-I.min+.2,a.projectionCompensation=p;}}generateSplitDistances(e,t,i){e._shadowCascadeDistances.fill(i);for(let s=1;s1&&(this.renderer.scene.clusteredLightingEnabled&&0!==e._type||this.applyVsmBlur(e,t));}getVsmBlurShader(e,t){let i=this.blurVsmShader,s=i[e][t];if(!s){this.blurVsmWeights[t]=function(e){let t=(e-1)/6,i=(e-1)*.5,s=Array(e),r=0;for(let n=0;n{e.destroy();}),this._allocated.length=0;}get count(){return this._allocated.length}get empty(){if(!this._empty){let e=new ll(this.device);e.name="ClusterEmpty",e.update([]),this._empty=e;}return this._empty}assign(e){lG.push(...this._allocated),this._allocated.length=0,this._clusters.clear();let t=e.length;for(let i=0;ie.destroy()),lG.length=0;}update(e,t){this.assign(e),this._clusters.forEach(e=>{let i=e.layer;e.lightClusters.update(i.clusteredLightsSet,t);});}constructor(e){this._empty=null,this._allocated=[],this._clusters=new Map,this.device=e;}}let lW=new ep,lX=[];class lY extends ah{destroy(){this._quadRenderer2D?.destroy(),this._quadRenderer2D=null,this._quadRendererCube?.destroy(),this._quadRendererCube=null,this._evtDeviceRestored?.off(),this._evtDeviceRestored=null;}static create(e,t){let i=new lY(e.device,t);return i.init(e),i.colorOps.clear=false,i.depthStencilOps.clearDepth=false,i}onDeviceRestored(){this._forceCopy=true;}update(e){let t=this._filteredLights;this.filter(e,t),this.executeEnabled=t.length>0;}filter(e,t){for(let i=0;i1?this.quadRendererCube:this.quadRenderer2D;a>1&&this.initInvViewProjMatrices(),this.blitTextureId.setValue(r.cookie);for(let i=0;i1){let e=lW.z/3,s=t[i];lW.x+=e*s.x,lW.y+=e*s.y,lW.z=e,lW.w=e,this.invViewProjId.setValue(lX[i].data);}lW.mulScalar(e),n.render(lW);}}i.length=0;}constructor(e,t){super(e),this._quadRenderer2D=null,this._quadRendererCube=null,this._filteredLights=[],this._forceCopy=false,this._evtDeviceRestored=null,this._cubeSlotsOffsets=t,this.requiresCubemaps=false,this.blitTextureId=e.scope.resolve("blitTexture"),this.invViewProjId=e.scope.resolve("invViewProj"),this._evtDeviceRestored=e.on("devicerestored",this.onDeviceRestored,this);}}class lq extends ah{update(e){let t=this.shadowRendererLocal.shadowLights,i=this.shadowRendererLocal.prepareLights(t,e),s=t.length;this.enabled=s>0,s&&this.shadowRenderer.setupRenderPass(this,i,false);}execute(){let e=this.shadowRendererLocal.shadowLights,t=e.length;for(let i=0;i0){let e=t?t.width:this.device.width,i=t?t.height:this.device.height,l=l8[this.device.renderVersion%l8.length];n=a*(2*l.x-1)/e,o=a*(2*l.y-1)/i,(s=hi.copy(s)).data[8]=n,s.data[9]=o,(r=hs.copy(r)).data[8]=n,r.data[9]=o,this.blueNoiseJitterVersion!==this.device.renderVersion&&(this.blueNoiseJitterVersion=this.device.renderVersion,this.blueNoise.vec4(this.blueNoiseJitterVec));}let l=a>0?this.blueNoiseJitterVec:ep.ZERO;if(this.blueNoiseJitterData[0]=l.x,this.blueNoiseJitterData[1]=l.y,this.blueNoiseJitterData[2]=l.z,this.blueNoiseJitterData[3]=l.w,this.blueNoiseJitterId.setValue(this.blueNoiseJitterData),this.projId.setValue(s.data),this.projSkyboxId.setValue(r.data),e.calculateTransform)e.calculateTransform(lZ,0);else {let t=e._node.getPosition(),i=e._node.getRotation();lZ.setTRS(t,i,ed.ONE);}this.viewInvId.setValue(lZ.data),lQ.copy(lZ).invert(),this.viewId.setValue(lQ.data),lJ.setFromMat4(lQ),this.viewId3.setValue(lJ.data),l$.mul2(s,lQ),this.viewProjId.setValue(l$.data),e._storeShaderMatrices(l$,n,o,this.device.renderVersion),this.flipYId.setValue(i?-1:1),this.dispatchViewPos(e._node.getPosition()),e.frustum.setFromMat4(l$);}this.tbnBasis.setValue(i?-1:1),this.cameraParamsId.setValue(e.fillShaderParams(this.cameraParams));let r=t?t.width:this.device.width,a=t?t.height:this.device.height;return r*=e.rect.z,a*=e.rect.w,e.xr?.session&&2===e.xr.views.list.length&&(r*=.5),this.viewportSize[0]=r,this.viewportSize[1]=a,this.viewportSize[2]=1/r,this.viewportSize[3]=1/a,this.viewportSizeId.setValue(this.viewportSize),this.exposureId.setValue(this.scene.physicalUnits?e.getExposure():this.scene.exposure),s}clear(e,t,i,s){let r=(t??e._clearColorBuffer?1:0)|(i??e._clearDepthBuffer?2:0)|(s??e._clearStencilBuffer?4:0);r&&this.device.clear({color:[e._clearColor.r,e._clearColor.g,e._clearColor.b,e._clearColor.a],depth:e._clearDepth,stencil:e._clearStencil,flags:r});}setupCullModeAndFrontFace(e,t,i){let s=i.material,r=t*i.flipFacesFactor*i.node.worldScaleSign,a=s.frontFace;r<0&&(a=+(0===a)),this.device.setCullMode(e?s.cull:0),this.device.setFrontFace(a);}setupCullMode(e,t,i){this.setupCullModeAndFrontFace(e,t,i);}updateCameraFrustum(e){if(e.xr&&e.xr.views.list.length){let t=e.xr.views.list;l$.mul2(t[0].projMat,t[0].viewOffMat),e.frustum.setFromMat4(l$);for(let i=1;i0)&&this.alphaTestId.setValue(t.alphaTest);}updateCpuSkinMatrices(e){lK++;let t=e.length;if(0!==t)for(let i=0;i{let t,i=(lc(),lh),s=Math.sqrt(i.length/4);return (t=new ic(e,{name:`BlueNoise${s}`,width:s,height:s,format:7,addressU:0,addressV:0,type:tP,magFilter:0,minFilter:0,anisotropy:1,mipmaps:false})).lock().set(i),t.unlock(),t})));}beginFrame(e){let t=this.scene,i=t.updateShaders||this.device._shadersDirty,s=e.layerList,r=s.length;for(let e=0;e{e.defaultUniformBuffer.destroy(),e.destroy();}),this.viewBindGroups.length=0;}setupClears(e,t){this.clearColor=e?.clearColorBuffer||t.clearColorBuffer,this.clearDepth=e?.clearDepthBuffer||t.clearDepthBuffer,this.clearStencil=e?.clearStencilBuffer||t.clearStencilBuffer;}constructor(){this.camera=null,this.layer=null,this.transparent=false,this.renderTarget=null,this.lightClusters=null,this.clearColor=false,this.clearDepth=false,this.clearStencil=false,this.triggerPostprocess=false,this.firstCameraUse=false,this.lastCameraUse=false,this.viewBindGroups=[],this.useCameraPasses=false;}}class hh extends ah{get rendersAnything(){return this.renderActions.length>0}addRenderAction(e){this.renderActions.push(e);}addLayer(e,t,i,s=true){let r=new hl;if(r.renderTarget=this.renderTarget,r.camera=e,r.layer=t,r.transparent=i,s){let i=0===this.renderActions.length;r.setupClears(i?e:void 0,t);}this.addRenderAction(r);}addLayers(e,t,i,s,r,a=true){let{layerList:n,subLayerList:o}=e,l=s,h=i;for(;h{hf.drawCalls.push(e),hf.shaderInstances.push(t),hf.isNewMaterial.push(i),hf.lightMaskChanged.push(s);};hf.clear();let h=this.device,c=this.scene,d=c.clusteredLightingEnabled,u=r?.getLightHash(d)??0,f=null,p,m,_=i.length;for(let e=0;e<_;e++){let t=i[e],r=t.instancingData;if(r&&r.count<=0)continue;t.ensureMaterial(h);let n=t.material,d=t._shaderDefs,_=t.mask;n&&n===f&&d!==p&&(f=null),n!==f&&(this._materialSwitches++,n._scene=c,n.dirty&&(n.updateUniforms(h,c),n.dirty=false));let g=t.getShaderInstance(a,u,c,o,this.viewUniformFormat,this.viewBindGroupFormat,s);l(t,g,n!==f,!f||_!==m),f=n,p=d,m=_;}return hf}renderForwardInternal(e,t,i,s,r,a,n){let o=this.device,l=this.scene,h=1<{e.addRenderPass(t);});else {let c=1===l.id,d=c&&(h.renderSceneColorMap||h.renderSceneDepthMap);r&&(r=false,s=i,a=o.renderTarget);let u=n[i+1],f=!!u&&!u.useCameraPasses&&1===u.layer.id&&(h.renderSceneColorMap||h.renderSceneDepthMap),p=!!u&&u.firstCameraUse&&this.cameraDirShadowLights.has(u.camera.camera);if(!u||u.renderTarget!==a||p||f||d){if(c&&s===i||this.addMainRenderPass(e,t,a,s,i),c){if(h.renderSceneColorMap){let t=h.camera.renderPassColorGrab;t.source=h.renderTarget,e.addRenderPass(t);}h.renderSceneDepthMap&&e.addRenderPass(h.camera.renderPassDepthGrab);}if(o.triggerPostprocess&&h?.onPostprocessing){let t=new hc(this.device,this,o);e.addRenderPass(t);}r=true;}}}}addMainRenderPass(e,t,i,s,r){let a=new hh(this.device,t,this.scene,this);a.init(i);let n=t._renderActions;for(let e=s;e<=r;e++)a.addRenderAction(n[e]);e.addRenderPass(a);}update(e){this.frameUpdate(),this.shadowRenderer.frameUpdate(),this.scene._updateSkyMesh(),this.updateLayerComposition(e),this.collectLights(e),this.beginFrame(e),this.setSceneConstants(),this.gsplatDirector?.update(e),this.cullComposition(e),this.gpuUpdate(this.processingMeshInstances);}constructor(e,t){super(e,t);let i=this.device;this._forwardDrawCalls=0,this._materialSwitches=0,this._depthMapTime=0,this._forwardTime=0,this._sortTime=0;let s=i.scope;this.fogColorId=s.resolve("fog_color"),this.fogStartId=s.resolve("fog_start"),this.fogEndId=s.resolve("fog_end"),this.fogDensityId=s.resolve("fog_density"),this.ambientId=s.resolve("light_globalAmbient"),this.skyboxIntensityId=s.resolve("skyboxIntensity"),this.cubeMapRotationMatrixId=s.resolve("cubeMapRotationMatrix"),this.pcssDiskSamplesId=s.resolve("pcssDiskSamples[0]"),this.pcssSphereSamplesId=s.resolve("pcssSphereSamples[0]"),this.lightColorId=[],this.lightDir=[],this.lightDirId=[],this.lightShadowMapId=[],this.lightShadowMatrixId=[],this.lightShadowParamsId=[],this.lightShadowIntensity=[],this.lightRadiusId=[],this.lightPos=[],this.lightPosId=[],this.lightWidth=[],this.lightWidthId=[],this.lightHeight=[],this.lightHeightId=[],this.lightInAngleId=[],this.lightOutAngleId=[],this.lightCookieId=[],this.lightCookieIntId=[],this.lightCookieMatrixId=[],this.lightCookieOffsetId=[],this.lightShadowSearchAreaId=[],this.lightCameraParamsId=[],this.lightSoftShadowParamsId=[],this.shadowMatrixPaletteId=[],this.shadowCascadeDistancesId=[],this.shadowCascadeCountId=[],this.shadowCascadeBlendId=[],this.screenSizeId=s.resolve("uScreenSize"),this._screenSize=new Float32Array(4),this.fogColor=new Float32Array(3),this.ambientColor=new Float32Array(3),this.pcssDiskSamples=function(){let e=[];for(let t=0;t<16;++t){let i=Math.sqrt(t+.5)/Math.sqrt(16);e.push(i);}return e}(),this.pcssSphereSamples=function(){let e=[];for(let t=0;t<16;t++){let i=t/16,s=Math.sqrt(i*i);e.push(s);}return e}();}}let hm=0,h_=[],hg=new Set,hv=[null,function(e,t){return e.drawOrder-t.drawOrder},function(e,t){let i=e._sortKeyForward,s=t._sortKeyForward;return i===s?t.mesh.id-e.mesh.id:s-i},function(e,t){return t._sortKeyDynamic-e._sortKeyDynamic},function(e,t){return e._sortKeyDynamic-t._sortKeyDynamic}];class hS{constructor(){this.opaque=[],this.transparent=[];}}class hy{set enabled(e){e!==this._enabled&&(this._dirtyComposition=true,this.gsplatPlacementsDirty=true,this._enabled=e,e?(this.incrementCounter(),this.onEnable&&this.onEnable()):(this.decrementCounter(),this.onDisable&&this.onDisable()));}get enabled(){return this._enabled}set clearColorBuffer(e){this._clearColorBuffer=e,this._dirtyComposition=true;}get clearColorBuffer(){return this._clearColorBuffer}set clearDepthBuffer(e){this._clearDepthBuffer=e,this._dirtyComposition=true;}get clearDepthBuffer(){return this._clearDepthBuffer}set clearStencilBuffer(e){this._clearStencilBuffer=e,this._dirtyComposition=true;}get clearStencilBuffer(){return this._clearStencilBuffer}get hasClusteredLights(){return this._clusteredLightsSet.size>0}get clusteredLightsSet(){return this._clusteredLightsSet}incrementCounter(){0===this._refCounter&&(this._enabled=true,this.onEnable&&this.onEnable()),this._refCounter++;}decrementCounter(){if(1===this._refCounter)this._enabled=false,this.onDisable&&this.onDisable();else if(0===this._refCounter)return;this._refCounter--;}addGSplatPlacement(e){this.gsplatPlacementsSet.has(e)||(this.gsplatPlacements.push(e),this.gsplatPlacementsSet.add(e),this.gsplatPlacementsDirty=true);}removeGSplatPlacement(e){let t=this.gsplatPlacements.indexOf(e);t>=0&&(this.gsplatPlacements.splice(t,1),this.gsplatPlacementsSet.delete(e),this.gsplatPlacementsDirty=true);}addGSplatShadowCaster(e){this.gsplatShadowCastersSet.has(e)||(this.gsplatShadowCasters.push(e),this.gsplatShadowCastersSet.add(e),this.gsplatPlacementsDirty=true);}removeGSplatShadowCaster(e){let t=this.gsplatShadowCasters.indexOf(e);t>=0&&(this.gsplatShadowCasters.splice(t,1),this.gsplatShadowCastersSet.delete(e),this.gsplatPlacementsDirty=true);}addMeshInstances(e,t){let i=this.meshInstances,s=this.meshInstancesSet;for(let t=0;t0){let e=this._shaderVersion;hg.forEach(t=>{e>=0&&t._shaderVersion!==e&&(t.getShaderVariant!==lw.prototype.getShaderVariant&&t.clearVariants(),t._shaderVersion=e);}),hg.clear();}}removeMeshInstances(e,t){let i=this.meshInstances,s=this.meshInstancesSet;for(let t=0;t=0&&i.splice(e,1);}}t||this.removeShadowCasters(e);}addShadowCasters(e){let t=this.shadowCasters,i=this.shadowCastersSet;for(let s=0;s=0&&t.splice(e,1);}}}clearMeshInstances(e=false){this.meshInstances.length=0,this.meshInstancesSet.clear(),e||(this.shadowCasters.length=0,this.shadowCastersSet.clear());}markLightsDirty(){this._lightHashDirty=true,this._lightIdHashDirty=true,this._splitLightsDirty=true;}hasLight(e){return this._lightsSet.has(e)}addLight(e){let t=e.light;this._lightsSet.has(t)||(this._lightsSet.add(t),this._lights.push(t),this.markLightsDirty()),0!==t.type&&this._clusteredLightsSet.add(t);}removeLight(e){let t=e.light;this._lightsSet.has(t)&&(this._lightsSet.delete(t),this._lights.splice(this._lights.indexOf(t),1),this.markLightsDirty()),0!==t.type&&this._clusteredLightsSet.delete(t);}clearLights(){this._lightsSet.forEach(e=>e.removeLayer(this)),this._lightsSet.clear(),this._clusteredLightsSet.clear(),this._lights.length=0,this.markLightsDirty();}get splitLights(){if(this._splitLightsDirty){this._splitLightsDirty=false;let e=this._splitLights;for(let t=0;te.key-t.key);}return this._splitLights}evaluateLightHash(e,t,i){let s=0,r=this._lights;for(let s=0;s0&&(h_.sort(),s=iM(h_),h_.length=0),s}getLightHash(e){return this._lightHashDirty&&(this._lightHashDirty=false,this._lightHash=this.evaluateLightHash(!e,true,false)),this._lightHash}getLightIdHash(){return this._lightIdHashDirty&&(this._lightIdHashDirty=false,this._lightIdHash=this.evaluateLightHash(true,false,true)),this._lightIdHash}addCamera(e){this.camerasSet.has(e.camera)||(this.camerasSet.add(e.camera),this.cameras.push(e),this._dirtyComposition=true);}removeCamera(e){if(this.camerasSet.has(e.camera)){this.camerasSet.delete(e.camera);let t=this.cameras.indexOf(e);this.cameras.splice(t,1),this._dirtyComposition=true;}}clearCameras(){this.cameras.length=0,this.camerasSet.clear(),this._dirtyComposition=true;}_calculateSortDistances(e,t,i){let s=e.length,{x:r,y:a,z:n}=t,{x:o,y:l,z:h}=i;for(let c=0;ce.priority-t.priority;class hT extends X{destroy(){this.destroyRenderActions();}destroyRenderActions(){this._renderActions.forEach(e=>e.destroy()),this._renderActions.length=0;}markDirty(){this._dirty=true;}_update(){let e=this.layerList.length;if(!this._dirty){for(let t=0;t1&&this.cameras.sort(hx);let t=0;this.destroyRenderActions();for(let i=0;i0){this.addDummyRenderAction(t,s),t++;continue}let r=true,a=t,n=null,o=false;for(let i=0;i0&&s.layers.indexOf(e.id)>=0){!o&&e.id===s.disablePostEffectsLayer&&(o=true,n&&(n.triggerPostprocess=true));let a=this.subLayerList[i];n=this.addRenderAction(t,e,a,s,r,o),t++,r=false;}}a=0;t--)if(l[t].camera===s&&l[t].renderTarget===n){o=true;break}a&&s.postEffectsEnabled&&(n=null);let h=this.getNextRenderAction(e);h.triggerPostprocess=false,h.layer=t,h.transparent=i,h.camera=s,h.renderTarget=n,h.firstCameraUse=r,h.lastCameraUse=false;let c=r||!o,d=t.clearColorBuffer||t.clearDepthBuffer||t.clearStencilBuffer;return (c||d)&&h.setupClears(c?s:void 0,t),h}propagateRenderTarget(e,t){for(let i=e;i>=0;i--){let e=this._renderActions[i],s=e.layer;if(e.renderTarget&&1!==s.id)break;if(1===s.id)continue;if(e.useCameraPasses)break;let r=e?.camera.camera;if(r&&(!t.camera.rect.equals(r.rect)||!t.camera.scissorRect.equals(r.scissorRect)))break;e.renderTarget=t.renderTarget;}}_logRenderActions(){}_isLayerAdded(e){return this.layerIdMap.get(e.id)===e}_isSublayerAdded(e,t){return void 0!==(t?this.layerTransparentIndexMap:this.layerOpaqueIndexMap).get(e)}push(e){this._isLayerAdded(e)||(this.layerList.push(e),this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(false)-1,this._transparentOrder[e.id]=this.subLayerList.push(true)-1,this.subLayerEnabled.push(true),this.subLayerEnabled.push(true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e));}insert(e,t){if(this._isLayerAdded(e))return;this.layerList.splice(t,0,e,e),this.subLayerList.splice(t,0,false,true);let i=this.layerList.length;this._updateOpaqueOrder(t,i-1),this._updateTransparentOrder(t,i-1),this.subLayerEnabled.splice(t,0,true,true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e);}remove(e){let t=this.layerList.indexOf(e);for(delete this._opaqueOrder[t],delete this._transparentOrder[t];t>=0;)this.layerList.splice(t,1),this.subLayerList.splice(t,1),this.subLayerEnabled.splice(t,1),t=this.layerList.indexOf(e),this._dirty=true,this.fire("remove",e);let i=this.layerList.length;this._updateOpaqueOrder(0,i-1),this._updateTransparentOrder(0,i-1),this._updateLayerMaps();}pushOpaque(e){this._isSublayerAdded(e,false)||(this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(false)-1,this.subLayerEnabled.push(true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e));}insertOpaque(e,t){if(this._isSublayerAdded(e,false))return;this.layerList.splice(t,0,e),this.subLayerList.splice(t,0,false);let i=this.subLayerList.length;this._updateOpaqueOrder(t,i-1),this.subLayerEnabled.splice(t,0,true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e);}removeOpaque(e){for(let t=0,i=this.layerList.length;tthis.layerList.indexOf(e)&&this.fire("remove",e);break}this._updateLayerMaps();}pushTransparent(e){this._isSublayerAdded(e,true)||(this.layerList.push(e),this._transparentOrder[e.id]=this.subLayerList.push(true)-1,this.subLayerEnabled.push(true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e));}insertTransparent(e,t){if(this._isSublayerAdded(e,true))return;this.layerList.splice(t,0,e),this.subLayerList.splice(t,0,true);let i=this.subLayerList.length;this._updateTransparentOrder(t,i-1),this.subLayerEnabled.splice(t,0,true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e);}removeTransparent(e){for(let t=0,i=this.layerList.length;tthis.layerList.indexOf(e)&&this.fire("remove",e);break}this._updateLayerMaps();}getOpaqueIndex(e){return this.layerOpaqueIndexMap.get(e)??-1}getTransparentIndex(e){return this.layerTransparentIndexMap.get(e)??-1}isEnabled(e,t){if(e.enabled){let i=t?this.getTransparentIndex(e):this.getOpaqueIndex(e);if(i>=0)return this.subLayerEnabled[i]}return false}_updateLayerMaps(){this.layerIdMap.clear(),this.layerNameMap.clear(),this.layerOpaqueIndexMap.clear(),this.layerTransparentIndexMap.clear();for(let e=0;e{e.defaultUniformBuffer.destroy(),e.destroy();}),this.viewBindGroups.length=0;}get shadowBuffer(){let e=this.shadowCamera.renderTarget;return e?this.light._isPcf?e.depthBuffer:e.colorBuffer:null}constructor(e,t,i){this.light=i,this.camera=e,this.shadowCamera=lV.createShadowCamera(i._shadowType,i._type,t),this.shadowMatrix=new ey,this.shadowViewport=new ep(0,0,1,1),this.shadowScissor=new ep(0,0,1,1),this.projectionCompensation=0,this.face=t,this.visibleCasters=[],this.viewBindGroups=[];}}class hL{destroy(){this._evtDeviceRestored?.off(),this._evtDeviceRestored=null,this._destroyShadowMap(),this.releaseRenderData(),this._renderData=null;}onDeviceRestored(){0===this.shadowUpdateMode&&(this.shadowUpdateMode=1);}releaseRenderData(){if(this._renderData){for(let e=0;e45?(e.radius=t*this._outerConeAngleSin,hE.mulScalar(-t*s)):(e.radius=t/(2*s),hE.mulScalar(-e.radius)),e.center.add2(r.getPosition(),hE);}else 1===this._type&&(e.center=this._node.getPosition(),e.radius=this.attenuationEnd);}getBoundingBox(e){if(2===this._type){let t=this.attenuationEnd,i=this._outerConeAngle,s=this._node,r=Math.abs(Math.sin(i*ei.DEG_TO_RAD)*t);e.center.set(0,-(.5*t),0),e.halfExtents.set(r,.5*t,r),e.setFromTransformedAabb(e,s.getWorldTransform(),true);}else 1===this._type&&(e.center.copy(this._node.getPosition()),e.halfExtents.set(this.attenuationEnd,this.attenuationEnd,this.attenuationEnd));}_updateShadowBias(){if(1!==this._type||this.clusteredLighting){let e=-1e3*this.shadowBias;this.shadowDepthState.depthBias=e,this.shadowDepthState.depthBiasSlope=e;}else this.shadowDepthState.depthBias=0,this.shadowDepthState.depthBiasSlope=0;}_updateLinearColor(){let e=this._intensity;this._usePhysicalUnits&&(e=this._luminance/hL.getLightUnitConversion(this._type,this._outerConeAngle*ei.DEG_TO_RAD,this._innerConeAngle*ei.DEG_TO_RAD));let t=this._color,i=this._colorLinear;e>=1?hb.linear(t).mulScalar(e):hb.copy(t).mulScalar(e).linear(),i[0]=hb.r,i[1]=hb.g,i[2]=hb.b,this.updateClusterData(true);}setColor(){1==arguments.length?this._color.set(arguments[0].r,arguments[0].g,arguments[0].b):3==arguments.length&&this._color.set(arguments[0],arguments[1],arguments[2]),this._updateLinearColor();}layersDirty(){this.layers.forEach(e=>{e.hasLight(this)&&e.markLightsDirty();});}updateKey(){let e=this._type<<29|this._shadowType<<25|this._falloffMode<<23|(0!==this._normalOffsetBias)<<22|!!this._cookie<<21|!!this._cookieFalloff<<20|hC[this._cookieChannel.charAt(0)]<<18|!!this._cookieTransform<<12|this._shape<<10|(this.numCascades>0)<<9|(this._cascadeBlend>0)<<8|!!this.affectSpecularity<<7|this.mask<<6|!!this._castShadows<<3;3===this._cookieChannel.length&&(e|=hC[this._cookieChannel.charAt(1)]<<16,e|=hC[this._cookieChannel.charAt(2)]<<14),e!==this.key&&this.layersDirty(),this.key=e;}updateClusteredFlags(){let e=!!(1&this.mask),t=!!(2&this.mask);this.clusteredFlags=(2===this.type)<<30|(3&this._shape)<<28|(1&this._falloffMode)<<27|(hI[this._cookieChannel]??0)<<23|!!e<<22|!!t<<21;}getClusteredFlags(e,t){return this.clusteredFlags|(e?Math.floor(255*this.shadowIntensity):0)&255|((t?Math.floor(255*this.cookieIntensity):0)&255)<<8}updateClusterData(e,t){let{clusteredData16:i}=this,s=eh.float2Half;if(e&&(i[0]=s(ei.clamp(this._colorLinear[0]/100,0,65504)),i[1]=s(ei.clamp(this._colorLinear[1]/100,0,65504)),i[2]=s(ei.clamp(this._colorLinear[2]/100,0,65504))),t){let e=0,t=Math.cos(.99*this._innerConeAngle*ei.DEG_TO_RAD);t>.5&&(t=1-t,e|=1);let r=Math.cos(.99*this._outerConeAngle*ei.DEG_TO_RAD);r>.5&&(r=1-r,e|=2),i[3]=e,i[4]=s(t),i[5]=s(r);}}constructor(e,t){this.layers=new Set,this.shadowDepthState=iT.DEFAULT.clone(),this.clusteredFlags=0,this.clusteredData=new Uint32Array(3),this.clusteredData16=new Uint16Array(this.clusteredData.buffer),this._evtDeviceRestored=null,this.device=e,this.clusteredLighting=t,this.id=hD++,this._evtDeviceRestored=e.on("devicerestored",this.onDeviceRestored,this),this._type=0,this._color=new es(.8,.8,.8),this._intensity=1,this._affectSpecularity=true,this._luminance=0,this._castShadows=false,this._enabled=false,this._mask=1,this.isStatic=false,this.key=0,this.bakeDir=true,this.bakeNumSamples=1,this.bakeArea=0,this.attenuationStart=10,this.attenuationEnd=10,this._falloffMode=0,this._shadowType=0,this._vsmBlurSize=11,this.vsmBlurMode=1,this.vsmBias=.0025,this._cookie=null,this.cookieIntensity=1,this._cookieFalloff=true,this._cookieChannel="rgb",this._cookieTransform=null,this._cookieTransformUniform=new Float32Array(4),this._cookieOffset=null,this._cookieOffsetUniform=new Float32Array(2),this._cookieTransformSet=false,this._cookieOffsetSet=false,this._innerConeAngle=40,this._outerConeAngle=45,this.cascades=null,this._shadowMatrixPalette=null,this._shadowCascadeDistances=null,this.numCascades=1,this._cascadeBlend=0,this.cascadeDistribution=.5,this._shape=0,this._colorLinear=new Float32Array(3),this._updateLinearColor(),this._position=new ed(0,0,0),this._direction=new ed(0,0,0),this._innerConeAngleCos=Math.cos(this._innerConeAngle*ei.DEG_TO_RAD),this._updateOuterAngle(this._outerConeAngle),this._usePhysicalUnits=void 0,this._shadowMap=null,this._shadowRenderParams=[],this._shadowCameraParams=[],this.shadowDistance=40,this._shadowResolution=1024,this._shadowBias=-5e-4,this._shadowIntensity=1,this._normalOffsetBias=0,this.shadowUpdateMode=2,this.shadowUpdateOverrides=null,this._isVsm=false,this._isPcf=true,this._softShadowParams=new Float32Array(4),this.shadowSamples=16,this.shadowBlockerSamples=16,this.penumbraSize=1,this.penumbraFalloff=1,this._cookieMatrix=null,this._atlasViewport=null,this.atlasViewportAllocated=false,this.atlasVersion=0,this.atlasSlotIndex=0,this.atlasSlotUpdated=false,this._node=null,this._renderData=[],this.visibleThisFrame=false,this.maxScreenSize=0,this._updateShadowBias();}}class hM{applySettings(e){this.shadowsEnabled=e.lightingShadowsEnabled??this.shadowsEnabled,this.cookiesEnabled=e.lightingCookiesEnabled??this.cookiesEnabled,this.areaLightsEnabled=e.lightingAreaLightsEnabled??this.areaLightsEnabled,this.shadowAtlasResolution=e.lightingShadowAtlasResolution??this.shadowAtlasResolution,this.cookieAtlasResolution=e.lightingCookieAtlasResolution??this.cookieAtlasResolution,this.maxLightsPerCell=e.lightingMaxLightsPerCell??this.maxLightsPerCell,this.shadowType=e.lightingShadowType??this.shadowType,e.lightingCells&&(this.cells=new ed(e.lightingCells));}set cells(e){this._cells.copy(e);}get cells(){return this._cells}set maxLightsPerCell(e){this._maxLightsPerCell=ei.clamp(e,1,255);}get maxLightsPerCell(){return this._maxLightsPerCell}set cookieAtlasResolution(e){this._cookieAtlasResolution=ei.clamp(e,32,this._maxTextureSize);}get cookieAtlasResolution(){return this._cookieAtlasResolution}set shadowAtlasResolution(e){this._shadowAtlasResolution=ei.clamp(e,32,this._maxTextureSize);}get shadowAtlasResolution(){return this._shadowAtlasResolution}set shadowType(e){this._shadowType!==e&&(this._shadowType=e,this._dirtyLightsFnc());}get shadowType(){return this._shadowType}set cookiesEnabled(e){this._cookiesEnabled!==e&&(this._cookiesEnabled=e,this._dirtyLightsFnc());}get cookiesEnabled(){return this._cookiesEnabled}set areaLightsEnabled(e){this._supportsAreaLights&&this._areaLightsEnabled!==e&&(this._areaLightsEnabled=e,this._dirtyLightsFnc());}get areaLightsEnabled(){return this._areaLightsEnabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this._dirtyLightsFnc());}get shadowsEnabled(){return this._shadowsEnabled}constructor(e,t,i){this._areaLightsEnabled=false,this._cells=new ed(10,3,10),this._maxLightsPerCell=255,this._shadowsEnabled=true,this._shadowType=0,this._shadowAtlasResolution=2048,this._cookiesEnabled=false,this._cookieAtlasResolution=2048,this.atlasSplit=null,this._supportsAreaLights=e,this._maxTextureSize=t,this._dirtyLightsFnc=i;}}class hO{destroy(){this.shader=null;let e=this.morph;e&&(this.morph=null,e.decRefCount(),e.refCount<1&&e.destroy()),this.rtPositions?.destroy(),this.rtPositions=null,this.texturePositions?.destroy(),this.texturePositions=null,this.rtNormals?.destroy(),this.rtNormals=null,this.textureNormals?.destroy(),this.textureNormals=null;}clone(){return new hO(this.morph)}_getWeightIndex(e){return "string"==typeof e?this._weightMap.get(e):e}getWeight(e){let t=this._getWeightIndex(e);return this._weights[t]}setWeight(e,t){let i=this._getWeightIndex(e);this._weights[i]=t,this._dirty=true;}_createShader(e){let t=new Map;t.set("{MORPH_TEXTURE_MAX_COUNT}",e),this.morph.intRenderFormat&&t.set("MORPH_INT","");let i=this.morph.intRenderFormat?"uvec4":"vec4";return nJ.createShader(this.device,{uniqueName:`TextureMorphShader_${e}-${this.morph.intRenderFormat?"int":"float"}`,attributes:{vertex_position:e8},vertexChunk:"morphVS",fragmentChunk:"morphPS",fragmentDefines:t,fragmentOutputTypes:[i]})}_updateTextureRenderTarget(e,t,i){let{morph:s,device:r}=this;this.setAabbUniforms(i),this.morphTextureId.setValue(i?s.targetsTexturePositions:s.targetsTextureNormals),r.setBlendState(iy.NOBLEND),this.countId.setValue(t),this.morphFactor.setValue(this._shaderMorphWeights),this.morphIndex.setValue(this._shaderMorphIndex),n8(r,e,this.shader);}_updateTextureMorph(e){this.device,(e>0||!this.zeroTextures)&&(this.rtPositions&&this._updateTextureRenderTarget(this.rtPositions,e,true),this.rtNormals&&this._updateTextureRenderTarget(this.rtNormals,e,false),this.zeroTextures=0===e);}setAabbUniforms(e=true){this.aabbSizeId.setValue(e?this._aabbSize:this._aabbNrmSize),this.aabbMinId.setValue(e?this._aabbMin:this._aabbNrmMin);}prepareRendering(e){this.setAabbUniforms();}update(){this._dirty=false;let e=this.morph._targets,t=this._shaderMorphWeights,i=this._shaderMorphIndex,s=0;for(let r=0;r1e-5&&(t[s]=this.getWeight(r),i[s]=r,s++);this._updateTextureMorph(s);}constructor(e){this.morph=e,e.incRefCount(),this.device=e.device;let t=e._targets.length;this.shader=this._createShader(t),this._weights=[],this._weightMap=new Map;for(let t=0;t(this[i]=e._createTexture(t,e._renderTextureFormat),new iG({colorBuffer:this[i],depth:false}));e.morphPositions&&(this.rtPositions=i("MorphRTPos","texturePositions")),e.morphNormals&&(this.rtNormals=i("MorphRTNrm","textureNormals")),this._textureParams=new Float32Array([e.morphTextureWidth,e.morphTextureHeight]);let s=e.aabb.halfExtents;this._aabbSize=new Float32Array([4*s.x,4*s.y,4*s.z]);let r=e.aabb.getMin();this._aabbMin=new Float32Array([2*r.x,2*r.y,2*r.z]),this._aabbNrmSize=new Float32Array([2,2,2]),this._aabbNrmMin=new Float32Array([-1,-1,-1]),this.aabbSizeId=this.device.scope.resolve("aabbSize"),this.aabbMinId=this.device.scope.resolve("aabbMin"),this.morphTextureId=this.device.scope.resolve("morphTexture"),this.morphFactor=this.device.scope.resolve("morphFactor[0]"),this.morphIndex=this.device.scope.resolve("morphIndex[0]"),this.countId=this.device.scope.resolve("count"),this.zeroTextures=false;}}class hF{getGraph(){return this.graph}setGraph(e){this.graph=e;}getCameras(){return this.cameras}setCameras(e){this.cameras=e;}getLights(){return this.lights}setLights(e){this.lights=e;}getMaterials(){let e=[];for(let t=0;tn)return;this.morphTextureWidth=o,this.morphTextureHeight=l;let h=false,c=eh.float2Half;12===this._textureFormat&&(h=true);let d=[],u=[],f=o*l*4;for(let i=0;i0&&(this.targetsTexturePositions=this._createTexture("MorphPositionsTexture",this._textureFormat,i.length,[d])),u.length>0&&(this.targetsTextureNormals=this._createTexture("MorphNormalsTexture",this._textureFormat,i.length,[u]));let p=[{semantic:tA,components:1,type:5,asInt:true}];return this.vertexBufferIds=new iR(this.device,new iB(this.device,p,s.length),s.length,{data:new Uint32Array(s)}),true}get targets(){return this._targets}_updateMorphFlags(){this._morphPositions=false,this._morphNormals=false;for(let e=0;e=P)&&this.calcSpawnPosition(s,r,a,n,b);let M=I>0&&I0&&(1===x.emitterShape?(hG.copy(hH).mulScalar(2).sub(ed.ONE).normalize(),hY.add(hG.mulScalar(x.initialVelocity))):hY.add(ed.FORWARD.mulScalar(x.initialVelocity))),hX.x+=(hq.x-hX.x)*hH.x,hX.y+=(hq.y-hX.y)*hH.y,hX.z+=(hq.z-hX.z)*hH.z,p+=(m-p)*hH.y,R=(R+1e4*C%1*(_-R))*hk,L=1e3*C%1*(v-g),x.meshInstance.node&&(x.localSpace?(hY.x/=t.x,hY.y/=t.y,hY.z/=t.z):hU.transformPoint(hY,hY)),x.localSpace?(hz.transformPoint(hX,hX),hY.add(hX).add(hK)):(hY.add(hX.mul(t)),hY.add(hK.mul(t))),hQ.copy(hY),h$.copy(hW).add(hY.mulScalar(o)),hZ.copy(h$),s[4*b]=hZ.x,s[4*b+1]=hZ.y,s[4*b+2]=hZ.z,s[4*b+3]+=p*o,x.wrap&&x.wrapBounds&&(x.localSpace||hZ.sub(n),hZ.x=h1(hZ.x,x.wrapBounds.x)-.5*x.wrapBounds.x,hZ.y=h1(hZ.y,x.wrapBounds.y)-.5*x.wrapBounds.y,hZ.z=h1(hZ.z,x.wrapBounds.z)-.5*x.wrapBounds.z,x.localSpace||hZ.add(n)),x.sort>0&&(1===x.sort?(hJ.copy(hZ).sub(T),x.particleDistance[b]=-(hJ.x*hJ.x+hJ.y*hJ.y+hJ.z*hJ.z)):2===x.sort?x.particleDistance[b]=I:3===x.sort&&(x.particleDistance[b]=-I))),l?I<0&&(s[4*b+3+2*x.numParticlesPot*4]=-1):(I>=P&&(I-=Math.max(P,x.numParticles*A),s[4*b+3+2*x.numParticlesPot*4]=x.loop?1:-1),I<0&&x.loop&&(s[4*b+3+2*x.numParticlesPot*4]=1)),s[4*b+3+2*x.numParticlesPot*4]<0&&(M=false),s[4*b+3+4*x.numParticlesPot]=I;for(let t=0;t0&&x.camera){let e=x.useMesh?6:4,t=x.particleDistance;for(let s=0;se[1]-t[1]);for(let t=0;t0&&i.set("SOFT",""),e.stretch>0&&i.set("STRETCH",""),e.customFace&&i.set("CUSTOM_FACE",""),e.pack8&&i.set("PACK8",""),e.localSpace&&i.set("LOCAL_SPACE",""),e.animTexLoop&&i.set("ANIMTEX_LOOP",""),e.wrap&&i.set("WRAP",""),e.alignToMotion&&i.set("ALIGN_TO_MOTION",""),i.set("NORMAL",h9[e.normal]),t.particle_vertexData=e8,e.mesh&&e.meshUv&&(t.particle_uv=tr),e.useCpu&&(t.particle_vertexData2=tf,t.particle_vertexData3=tp,t.particle_vertexData4=tm,t.particle_vertexData5=t_),i}createFragmentDefines(e){let t=new Map(e.defines);return e.soft>0&&t.set("SOFT",""),e.halflambert&&t.set("HALF_LAMBERT",""),t.set("NORMAL",h9[e.normal]),t.set("BLEND",ni[e.blend]),t}createShaderDefinition(e,t){let i=e.isWebGPU?tV:tz,s=n$.get(e,i),r={},a=this.createVertexDefines(t,r),n=this.createFragmentDefines(t),o=`PARTICLE_${t.useCpu?"CPU":"GPU"} -`;a.set(o,""),n.set(o,"");let l=new Map(s);return rp.createDefinition(e,{name:"ParticleShader",shaderLanguage:i,attributes:r,vertexCode:s.get("particle_shaderVS"),fragmentCode:s.get("particle_shaderPS"),fragmentDefines:n,fragmentIncludes:l,vertexIncludes:l,vertexDefines:a})}};class ce extends lw{getShaderVariant(e){let{device:t,scene:i,cameraShaderParams:s,objDefs:r}=e,{emitter:a}=this,n={defines:nJ.getCoreDefines(this,e),pass:0,useCpu:this.emitter.useCpu,normal:a.lighting?null!==a.normalMap?2:1:0,halflambert:this.emitter.halfLambert,stretch:this.emitter.stretch,alignToMotion:this.emitter.alignToMotion,soft:this.emitter.depthSoftening,mesh:this.emitter.useMesh,meshUv:4&r,gamma:s?.shaderOutputGamma??0,toneMap:s?.toneMapping??0,fog:i&&!this.emitter.noFog?i.fog.type:"none",wrap:this.emitter.wrap&&this.emitter.wrapBounds,localSpace:this.emitter.localSpace,screenSpace:!a.inTools&&this.emitter.screenSpace,blend:this.emitter.blendType,animTex:this.emitter._isAnimated(),animTexLoop:this.emitter.animLoop,pack8:this.emitter.pack8,customFace:0!==this.emitter.orientation},o=new nV(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),l=nH(t);return l.register("particle",h7),l.getProgram("particle",n,o,this.userId)}constructor(e){super(),this.emitter=null,this.emitter=e;}}let ct=[[-1,-1],[1,-1],[1,1],[-1,1]];function ci(e,t,i,s,r=14,a,n){let o=0;n&&(7===r||20===r)&&(o=1);let l=new ic(e,{width:t,height:i,format:r,cubemap:false,mipmaps:false,minFilter:o,magFilter:o,addressU:1,addressV:1,name:"ParticleSystemTexture"}),h=l.lock();if(7===r||20===r){let e=new Uint8Array(s.length);for(let t=0;t{let e=new Float32Array(1024);for(let t=0;t<16;t++)for(let i=0;i<16;i++){let s=i+1-8.5,r=t+1-8.5,a=cs(1-cs(Math.sqrt(s*s+r*r)/16)-.5),n=16*t+i;e[4*n]=1,e[4*n+1]=1,e[4*n+2]=1,e[4*n+3]=a;}let t=ci(this.graphicsDevice,16,16,e,20,1,true);return t.minFilter=1,t.magFilter=1,t})}onChangeCamera(){this.resetMaterial();}calculateBoundsMad(){this.worldBoundsMul.x=1/this.worldBoundsSize.x,this.worldBoundsMul.y=1/this.worldBoundsSize.y,this.worldBoundsMul.z=1/this.worldBoundsSize.z,this.worldBoundsAdd.copy(this.worldBounds.center).mul(this.worldBoundsMul).mulScalar(-1),this.worldBoundsAdd.x+=.5,this.worldBoundsAdd.y+=.5,this.worldBoundsAdd.z+=.5;}calculateWorldBounds(){if(!this.node)return;(this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),!this.useCpu)&&((0===this.emitterShape?this.emitterExtents.equals(this.prevEmitterExtents):this.emitterRadius===this.prevEmitterRadius)||this.calculateLocalBounds());let e=this.node.getWorldTransform();this.localSpace?this.worldBoundsNoTrail.copy(this.localBounds):this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,e),this.worldBoundsTrail[0].add(this.worldBoundsNoTrail),this.worldBoundsTrail[1].add(this.worldBoundsNoTrail);let t=this.simTimeTotal;t>=this.timeToSwitchBounds&&(this.worldBoundsTrail[0].copy(this.worldBoundsTrail[1]),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.timeToSwitchBounds=t+this.lifetime),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.localSpace?(this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,e),this.meshInstance.mesh.aabb.setFromTransformedAabb(this.worldBounds,e)):(this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance.mesh.aabb.copy(this.worldBounds)),this.meshInstance._aabbVer=1-this.meshInstance._aabbVer,this.pack8&&this.calculateBoundsMad();}resetWorldBounds(){this.node&&(this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,this.localSpace?ey.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBoundsNoTrail),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.simTimeTotal=0,this.timeToSwitchBounds=0);}calculateLocalBounds(){let e,t,i,s=Number.MAX_VALUE,r=Number.MAX_VALUE,a=Number.MAX_VALUE,n=-Number.MAX_VALUE,o=-Number.MAX_VALUE,l=-Number.MAX_VALUE,h=0,c=0,d=this.lifetime/this.precision,u=[this.qVelocity,this.qVelocity2],f=[this.qLocalVelocity,this.qLocalVelocity2],p=[0,0],m=[0,0],_=[0,0],g=[0,0],v=[0,0];for(let S=0;S0||e.maxVertexTextures<=1||e.fragmentUniformsCount<64||e.forceCpuParticles;let t=this._destroyResources();this.pack8=(this.pack8||!e.textureFloatRenderable)&&!this.useCpu,cl=this.useCpu||this.pack8?4:2,this.useMesh=!!this.mesh,this.numParticlesPot=ei.nextPowerOfTwo(this.numParticles),this.rebuildGraphs(),this.calculateLocalBounds(),this.resetWorldBounds(),this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?ey.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBounds),this.worldBoundsTrail[1].copy(this.worldBounds),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.pack8&&this.calculateBoundsMad()),this.vbToSort=Array(this.numParticles);for(let e=0;e=1&&(this.animTilesX>1||this.animTilesY>1)&&(this.colorMap&&this.colorMap!==this.defaultParamTexture||this.normalMap)}rebuildGraphs(){let e=this.precision,t=this.graphicsDevice;this.qLocalVelocity=this.localVelocityGraph.quantize(e),this.qVelocity=this.velocityGraph.quantize(e),this.qColor=this.colorGraph.quantizeClamped(e,0,1),this.qRotSpeed=this.rotationSpeedGraph.quantize(e),this.qScale=this.scaleGraph.quantize(e),this.qAlpha=this.alphaGraph.quantize(e),this.qRadialSpeed=this.radialSpeedGraph.quantize(e),this.qLocalVelocity2=this.localVelocityGraph2.quantize(e),this.qVelocity2=this.velocityGraph2.quantize(e),this.qColor2=this.colorGraph2.quantizeClamped(e,0,1),this.qRotSpeed2=this.rotationSpeedGraph2.quantize(e),this.qScale2=this.scaleGraph2.quantize(e),this.qAlpha2=this.alphaGraph2.quantize(e),this.qRadialSpeed2=this.radialSpeedGraph2.quantize(e);for(let t=0;t0&&e.setParameter("softening",1/(this.depthSoftening*this.depthSoftening*100)),this.stretch>0&&(e.cull=0),this._compParticleFaceParams();}_compParticleFaceParams(){let e,t;if(0===this.orientation)e=new Float32Array([1,0,0]),t=new Float32Array([0,0,1]);else {let i;i=1===this.orientation?this.particleNormal.normalize():(null===this.node?ey.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize();let s=new ed(1,0,0);1===Math.abs(s.dot(i))&&s.set(0,0,1);let r=new ed().cross(i,s).normalize();s.cross(r,i).normalize(),e=new Float32Array([s.x,s.y,s.z]),t=new Float32Array([r.x,r.y,r.z]);}this.material.setParameter("faceTangent",e),this.material.setParameter("faceBinorm",t);}getVertexInfo(){let e=[];return this.useCpu?e.push({semantic:tu,components:4,type:6},{semantic:tf,components:4,type:6},{semantic:tp,components:4,type:6},{semantic:tm,components:1,type:6},{semantic:t_,components:this.useMesh?4:2,type:6}):(e.push({semantic:tu,components:4,type:6}),this.useMesh&&e.push({semantic:tf,components:2,type:6})),e}_allocate(e){let t=e*this.numParticleVerts,i=e*this.numParticleIndices;if(void 0===this.vertexBuffer||this.vertexBuffer.getNumVertices()!==t){let s,r,a,n=this.getVertexInfo(),o=new iB(this.graphicsDevice,n);this.vertexBuffer=new iR(this.graphicsDevice,o,t,{usage:1}),this.indexBuffer=new iw(this.graphicsDevice,2,i);let l=new Float32Array(this.vertexBuffer.lock());if(this.useMesh){r=(s=new Float32Array(this.mesh.vertexBuffer.lock())).length/this.mesh.vertexBuffer.numVertices;for(let e=0;ethis.endTime&&(this.onFinished&&this.onFinished(),this.meshInstance.visible=false),this.meshInstance&&(this.meshInstance.drawOrder=this.drawOrder);}_destroyResources(){this.particleTexIN?.destroy(),this.particleTexIN=null,this.particleTexOUT?.destroy(),this.particleTexOUT=null,this.particleTexStart&&this.particleTexStart.destroy&&(this.particleTexStart.destroy(),this.particleTexStart=null),this.rtParticleTexIN?.destroy(),this.rtParticleTexIN=null,this.rtParticleTexOUT?.destroy(),this.rtParticleTexOUT=null,this.internalTex0?.destroy(),this.internalTex0=null,this.internalTex1?.destroy(),this.internalTex1=null,this.internalTex2?.destroy(),this.internalTex2=null,this.internalTex3?.destroy(),this.internalTex3=null,this.colorParam?.destroy(),this.colorParam=null,this.vertexBuffer=void 0,this.indexBuffer=void 0;let e=this.meshInstance?.visible??true;return this.meshInstance?.destroy(),this.meshInstance=null,this.material?.destroy(),this.material=null,e}destroy(){this.camera=null,this._destroyResources();}constructor(e,t){this.material=null,this.internalTex0=null,this.internalTex1=null,this.internalTex2=null,this.colorParam=null,this.graphicsDevice=e,this.precision=32,this._addTimeTime=0,i=this,s=t,cp("numParticles",1),this.numParticles>e.maxTextureSize&&(this.numParticles=e.maxTextureSize),cp("rate",1),cp("rate2",this.rate),cp("lifetime",50),cp("emitterExtents",new ed(0,0,0)),cp("emitterExtentsInner",new ed(0,0,0)),cp("emitterRadius",0),cp("emitterRadiusInner",0),cp("emitterShape",0),cp("initialVelocity",1),cp("wrap",false),cp("localSpace",false),cp("screenSpace",false),cp("wrapBounds",null),cp("colorMap",this.defaultParamTexture),cp("normalMap",null),cp("loop",true),cp("preWarm",false),cp("sort",0),cp("mode",0),cp("scene",null),cp("lighting",false),cp("halfLambert",false),cp("intensity",1),cp("stretch",0),cp("alignToMotion",false),cp("depthSoftening",0),cp("mesh",null),cp("particleNormal",new ed(0,1,0)),cp("orientation",0),cp("depthWrite",false),cp("noFog",false),cp("blendType",2),cp("node",null),cp("startAngle",0),cp("startAngle2",this.startAngle),cp("animTilesX",1),cp("animTilesY",1),cp("animStartFrame",0),cp("animNumFrames",1),cp("animNumAnimations",1),cp("animIndex",0),cp("randomizeAnimIndex",false),cp("animSpeed",1),cp("animLoop",true),this._gpuUpdater=new h8(this,e),this._cpuUpdater=new h3(this),this.emitterPosUniform=new Float32Array(3),this.wrapBoundsUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),cp("colorGraph",co),cp("colorGraph2",this.colorGraph),cp("scaleGraph",ca),cp("scaleGraph2",this.scaleGraph),cp("alphaGraph",ca),cp("alphaGraph2",this.alphaGraph),cp("localVelocityGraph",cn),cp("localVelocityGraph2",this.localVelocityGraph),cp("velocityGraph",cn),cp("velocityGraph2",this.velocityGraph),cp("rotationSpeedGraph",cr),cp("rotationSpeedGraph2",this.rotationSpeedGraph),cp("radialSpeedGraph",cr),cp("radialSpeedGraph2",this.radialSpeedGraph),this.animTilesParams=new Float32Array(2),this.animParams=new Float32Array(4),this.animIndexParams=new Float32Array(2),this.vbToSort=null,this.vbOld=null,this.particleDistance=null,this.camera=null,this.swapTex=false,this.useMesh=true,this.useCpu=!e.supportsGpuParticles,this.pack8=true,this.localBounds=new eA,this.worldBoundsNoTrail=new eA,this.worldBoundsTrail=[new eA,new eA],this.worldBounds=new eA,this.worldBoundsSize=new ed,this.prevWorldBoundsSize=new ed,this.prevWorldBoundsCenter=new ed,this.prevEmitterExtents=this.emitterExtents,this.prevEmitterRadius=this.emitterRadius,this.worldBoundsMul=new ed,this.worldBoundsAdd=new ed,this.timeToSwitchBounds=0,this.shaderParticleUpdateRespawn=null,this.shaderParticleUpdateNoRespawn=null,this.shaderParticleUpdateOnStop=null,this.numParticleVerts=0,this.numParticleIndices=0,this.material=null,this.meshInstance=null,this.drawOrder=0,this.seed=Math.random(),this.fixedTimeStep=1/60,this.maxSubSteps=10,this.simTime=0,this.simTimeTotal=0,this.beenReset=false,this._layer=null,this.rebuild();}}let cx=new class extends nW{generateKey(e){let t=e.shaderDesc,i=t.vertexGLSL?iL(t.vertexGLSL):0,s=t.fragmentGLSL?iL(t.fragmentGLSL):0,r=t.vertexWGSL?iL(t.vertexWGSL):0,a=t.fragmentWGSL?iL(t.fragmentWGSL):0,n=nW.definesHash(e.defines),o=e.shaderChunks?.key??"",l=`${t.uniqueName}_${n}_${i}_${s}_${r}_${a}_${o}`;return e.skin&&(l+="_skin"),e.useInstancing&&(l+="_inst"),e.useMorphPosition&&(l+="_morphp"),e.useMorphNormal&&(l+="_morphn"),e.useMorphTextureBasedInt&&(l+="_morphi"),l}createAttributesDefinition(e,t){let i=t.shaderDesc.attributes,s=i?{...i}:void 0;t.skin&&(s.vertex_boneWeights=te,s.vertex_boneIndices=tt),(t.useMorphPosition||t.useMorphNormal)&&(s.morph_vertex_id=tA),e.attributes=s;}createVertexDefinition(e,t,i,s){let r=t.shaderDesc,a=new Map(i);a.set("transformInstancingVS","");let n=new Map(t.defines);t.skin&&n.set("SKIN",true),t.useInstancing&&n.set("INSTANCING",true),(t.useMorphPosition||t.useMorphNormal)&&(n.set("MORPHING",true),t.useMorphTextureBasedInt&&n.set("MORPHING_INT",true),t.useMorphPosition&&n.set("MORPHING_POSITION",true),t.useMorphNormal&&n.set("MORPHING_NORMAL",true)),e.vertexCode=s?r.vertexWGSL:r.vertexGLSL,e.vertexIncludes=a,e.vertexDefines=n;}createFragmentDefinition(e,t,i,s){let r=t.shaderDesc,a=new Map(i),n=new Map(t.defines);e.fragmentCode=s?r.fragmentWGSL:r.fragmentGLSL,e.fragmentIncludes=a,e.fragmentDefines=n;}createShaderDefinition(e,t){let i=t.shaderDesc,s=e.isWebGPU&&!!i.vertexWGSL&&!!i.fragmentWGSL&&(t.shaderChunks?.useWGSL??true),r={name:`ShaderMaterial-${i.uniqueName}`,shaderLanguage:s?tV:tz,fragmentOutputTypes:i.fragmentOutputTypes,meshUniformBufferFormat:i.meshUniformBufferFormat,meshBindGroupFormat:i.meshBindGroupFormat},a=s?tV:tz,n=nZ.merge(n$.get(e,a),t.shaderChunks[a]);return this.createAttributesDefinition(r,t),this.createVertexDefinition(r,t,n,s),this.createFragmentDefinition(r,t,n,s),rp.createDefinition(e,r)}};class cT extends lw{set shaderDesc(e){if(this._shaderDesc=void 0,e&&(this._shaderDesc={uniqueName:e.uniqueName,attributes:e.attributes,fragmentOutputTypes:e.fragmentOutputTypes,vertexGLSL:e.vertexGLSL,fragmentGLSL:e.fragmentGLSL,vertexWGSL:e.vertexWGSL,fragmentWGSL:e.fragmentWGSL},e.vertexCode||e.fragmentCode||e.shaderLanguage)){let t=e.shaderLanguage??tz;t===tz?(this._shaderDesc.vertexGLSL=e.vertexCode,this._shaderDesc.fragmentGLSL=e.fragmentCode):t===tV&&(this._shaderDesc.vertexWGSL=e.vertexCode,this._shaderDesc.fragmentWGSL=e.fragmentCode);}this.clearVariants();}get shaderDesc(){return this._shaderDesc}copy(e){return super.copy(e),this.shaderDesc=e.shaderDesc,this}getShaderVariant(e){let{objDefs:t}=e,i={defines:nJ.getCoreDefines(this,e),skin:(2&t)!=0,useInstancing:(32&t)!=0,useMorphPosition:(1024&t)!=0,useMorphNormal:(2048&t)!=0,useMorphTextureBasedInt:(8192&t)!=0,pass:e.pass,gamma:e.cameraShaderParams.shaderOutputGamma,toneMapping:e.cameraShaderParams.toneMapping,fog:e.cameraShaderParams.fog,shaderDesc:this.shaderDesc,shaderChunks:this.shaderChunks},s=new nV(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),r=nH(e.device);return r.register("shader-material",cx),r.getProgram("shader-material",i,s,this.userId)}constructor(e){super(),this.shaderDesc=e;}}var cE=` + ${kL(jt,"CLUSTER_TEXTURE_")} + ${kL(vY,"")} +`,OT=class{constructor(t){n(this,"areaLightsEnabled",!1);this.device=t,ne.get(t,fe).set("lightBufferDefinesPS",zL),ne.get(t,se).set("lightBufferDefinesPS",zL),this.cookiesEnabled=!1,this.shadowsEnabled=!1,this.areaLightsEnabled=!1,this.maxLights=255;let e=jt.COUNT;this.lightsFloat=new Float32Array(4*e*this.maxLights),this.lightsUint=new Uint32Array(this.lightsFloat.buffer),this.lightsTexture=this.createTexture(this.device,e,this.maxLights,ke,"LightsTexture"),this._lightsTextureId=this.device.scope.resolve("lightsTexture"),this.invMaxColorValue=0,this.invMaxAttenuation=0,this.boundsMin=new x,this.boundsDelta=new x}destroy(){this.lightsTexture?.destroy(),this.lightsTexture=null}createTexture(t,e,s,i,r){return new Z(t,{name:r,width:e,height:s,mipmaps:!1,format:i,addressU:1,addressV:1,type:Gt,magFilter:0,minFilter:0,anisotropy:1})}setBounds(t,e){this.boundsMin.copy(t),this.boundsDelta.copy(e)}uploadTextures(){this.lightsTexture.lock().set(this.lightsFloat),this.lightsTexture.unlock()}updateUniforms(){this._lightsTextureId.setValue(this.lightsTexture)}getSpotDirection(t,e){e._node.getWorldTransform().getY(t).mulScalar(-1),t.normalize()}getLightAreaSizes(t){let e=t._node.getWorldTransform();return e.transformVector(SY,aa),jf[0]=aa.x,jf[1]=aa.y,jf[2]=aa.z,e.transformVector(xY,aa),jf[3]=aa.x,jf[4]=aa.y,jf[5]=aa.z,jf}addLightData(t,e){let s=t._type===je,i=t.atlasViewportAllocated,r=this.cookiesEnabled&&!!t._cookie&&i,a=this.areaLightsEnabled&&t.shape!==$i,o=this.shadowsEnabled&&t.castShadows&&i,l=t._node.getPosition(),h=null,f=null;s?o?h=t.getRenderData(null,0).shadowMatrix:r&&(h=Wo.evalSpotCookieMatrix(t)):(o||r)&&(f=t.atlasViewport);let u=this.lightsFloat,d=this.lightsUint,p=e*this.lightsTexture.width*4;u[p+4*jt.POSITION_RANGE+0]=l.x,u[p+4*jt.POSITION_RANGE+1]=l.y,u[p+4*jt.POSITION_RANGE+2]=l.z,u[p+4*jt.POSITION_RANGE+3]=t.attenuationEnd;let m=t.clusteredData;if(d[p+4*jt.COLOR_ANGLES_BIAS+0]=m[0],d[p+4*jt.COLOR_ANGLES_BIAS+1]=m[1],d[p+4*jt.COLOR_ANGLES_BIAS+2]=m[2],t.castShadows){let _=t.getRenderData(null,0),S=t._getUniformBiasValues(_),g=Hs.float2Half(S.bias),T=Hs.float2Half(S.normalBias);d[p+4*jt.COLOR_ANGLES_BIAS+3]=g|T<<16}if(s&&(this.getSpotDirection(aa,t),u[p+4*jt.DIRECTION_FLAGS+0]=aa.x,u[p+4*jt.DIRECTION_FLAGS+1]=aa.y,u[p+4*jt.DIRECTION_FLAGS+2]=aa.z),d[p+4*jt.DIRECTION_FLAGS+3]=t.getClusteredFlags(o,r),h){let _=h.data;for(let S=0;S<16;S++)u[p+4*jt.PROJ_MAT_0+S]=_[S]}if(f&&(u[p+4*jt.ATLAS_VIEWPORT+0]=f.x,u[p+4*jt.ATLAS_VIEWPORT+1]=f.y,u[p+4*jt.ATLAS_VIEWPORT+2]=f.z/3),a){let _=this.getLightAreaSizes(t);u[p+4*jt.AREA_DATA_WIDTH+0]=_[0],u[p+4*jt.AREA_DATA_WIDTH+1]=_[1],u[p+4*jt.AREA_DATA_WIDTH+2]=_[2],u[p+4*jt.AREA_DATA_HEIGHT+0]=_[3],u[p+4*jt.AREA_DATA_HEIGHT+1]=_[4],u[p+4*jt.AREA_DATA_HEIGHT+2]=_[5]}}};var TY=new B,FT=new x,NT=new x,BT=new x,Vw=new ge;var UT=class{constructor(){this.light=null,this.min=new x,this.max=new x}},sl=class{constructor(t){n(this,"clusterTexture");this.device=t,this.name="Untitled",this.reportCount=0,this.boundsMin=new x,this.boundsMax=new x,this.boundsDelta=new x,this._cells=new x(1,1,1),this._cellsLimit=new x,this.cells=this._cells,this.maxCellLightCount=4,this._usedLights=[],this._usedLights.push(new UT),this.lightsBuffer=new OT(t),this.registerUniforms(t)}set maxCellLightCount(t){t!==this._maxCellLightCount&&(this._maxCellLightCount=t,this._cellsDirty=!0)}get maxCellLightCount(){return this._maxCellLightCount}set cells(t){FT.copy(t).floor(),this._cells.equals(FT)||(this._cells.copy(FT),this._cellsLimit.copy(FT).sub(x.ONE),this._cellsDirty=!0)}get cells(){return this._cells}destroy(){this.lightsBuffer.destroy(),this.releaseClusterTexture()}releaseClusterTexture(){this.clusterTexture&&(this.clusterTexture.destroy(),this.clusterTexture=null)}registerUniforms(t){this._numClusteredLightsId=t.scope.resolve("numClusteredLights"),this._clusterMaxCellsId=t.scope.resolve("clusterMaxCells"),this._clusterWorldTextureId=t.scope.resolve("clusterWorldTexture"),this._clusterBoundsMinId=t.scope.resolve("clusterBoundsMin"),this._clusterBoundsMinData=new Float32Array(3),this._clusterBoundsDeltaId=t.scope.resolve("clusterBoundsDelta"),this._clusterBoundsDeltaData=new Float32Array(3),this._clusterCellsCountByBoundsSizeId=t.scope.resolve("clusterCellsCountByBoundsSize"),this._clusterCellsCountByBoundsSizeData=new Float32Array(3),this._clusterCellsDotId=t.scope.resolve("clusterCellsDot"),this._clusterCellsDotData=new Int32Array(3),this._clusterCellsMaxId=t.scope.resolve("clusterCellsMax"),this._clusterCellsMaxData=new Int32Array(3),this._clusterTextureWidthId=t.scope.resolve("clusterTextureWidth")}updateParams(t){t&&(this.cells=t.cells,this.maxCellLightCount=t.maxLightsPerCell,this.lightsBuffer.cookiesEnabled=t.cookiesEnabled,this.lightsBuffer.shadowsEnabled=t.shadowsEnabled,this.lightsBuffer.areaLightsEnabled=t.areaLightsEnabled)}updateCells(){if(this._cellsDirty){this._cellsDirty=!1;let t=this._cells.x,e=this._cells.y,s=this._cells.z,i=t*e*s,r=this.maxCellLightCount*i,{x:a,y:o}=gt.calcTextureSize(r,TY,this.maxCellLightCount);this._clusterCellsMaxData[0]=t,this._clusterCellsMaxData[1]=e,this._clusterCellsMaxData[2]=s,this._clusterCellsDotData[0]=this.maxCellLightCount,this._clusterCellsDotData[1]=t*s*this.maxCellLightCount,this._clusterCellsDotData[2]=t*this.maxCellLightCount,this.clusters=new Uint8ClampedArray(r),this.counts=new Int32Array(i),this.releaseClusterTexture(),this.clusterTexture=this.lightsBuffer.createTexture(this.device,a,o,sc,"ClusterTexture")}}uploadTextures(){this.clusterTexture.lock().set(this.clusters),this.clusterTexture.unlock(),this.lightsBuffer.uploadTextures()}updateUniforms(){this._numClusteredLightsId.setValue(this._usedLights.length),this.lightsBuffer.updateUniforms(),this._clusterWorldTextureId.setValue(this.clusterTexture),this._clusterMaxCellsId.setValue(this.maxCellLightCount);let t=this.boundsDelta;this._clusterCellsCountByBoundsSizeData[0]=this._cells.x/t.x,this._clusterCellsCountByBoundsSizeData[1]=this._cells.y/t.y,this._clusterCellsCountByBoundsSizeData[2]=this._cells.z/t.z,this._clusterCellsCountByBoundsSizeId.setValue(this._clusterCellsCountByBoundsSizeData),this._clusterBoundsMinData[0]=this.boundsMin.x,this._clusterBoundsMinData[1]=this.boundsMin.y,this._clusterBoundsMinData[2]=this.boundsMin.z,this._clusterBoundsDeltaData[0]=t.x,this._clusterBoundsDeltaData[1]=t.y,this._clusterBoundsDeltaData[2]=t.z,this._clusterBoundsMinId.setValue(this._clusterBoundsMinData),this._clusterBoundsDeltaId.setValue(this._clusterBoundsDeltaData),this._clusterCellsDotId.setValue(this._clusterCellsDotData),this._clusterCellsMaxId.setValue(this._clusterCellsMaxData),this._clusterTextureWidthId.setValue(this.clusterTexture.width)}evalLightCellMinMax(t,e,s){e.copy(t.min),e.sub(this.boundsMin),e.div(this.boundsDelta),e.mul2(e,this.cells),e.floor(),s.copy(t.max),s.sub(this.boundsMin),s.div(this.boundsDelta),s.mul2(s,this.cells),s.ceil(),e.max(x.ZERO),s.min(this._cellsLimit)}collectLights(t){let e=this.lightsBuffer.maxLights,s=this._usedLights,i=1;t.forEach(r=>{let a=!!(r.mask&(cs|xi)),o=r.type===je&&r._outerConeAngle===0;if(r.enabled&&r.type!==Ce&&r.visibleThisFrame&&r.intensity>0&&a&&!o&&i1){e.copy(t[1].min),s.copy(t[1].max);for(let i=2;i>>16)>>>0;return t=((t&1431655765)<<1|(t&2863311530)>>>1)>>>0,t=((t&858993459)<<2|(t&3435973836)>>>2)>>>0,t=((t&252645135)<<4|(t&4042322160)>>>4)>>>0,t=((t&16711935)<<8|(t&4278255360)>>>8)>>>0,t*23283064365386963e-26}};var yY={linear:"decodeLinear",srgb:"decodeGamma",rgbm:"decodeRGBM",rgbe:"decodeRGBE",rgbp:"decodeRGBP",xy:"unpackNormalXY",xyz:"unpackNormalXYZ"},EY={linear:"encodeLinear",srgb:"encodeGamma",rgbm:"encodeRGBM",rgbe:"encodeRGBE",rgbp:"encodeRGBP"},li=class{static decodeFunc(t){return yY[t]??"decodeGamma"}static encodeFunc(t){return EY[t]??"encodeGamma"}};var VL=c=>{switch(c){case Ld:return"Cubemap";case JC:return"Octahedral";default:return"Equirect"}},kT=(c,t,e)=>{if(c<=0)t[e+0]=0,t[e+1]=0,t[e+2]=0,t[e+3]=0;else if(c>=1)t[e+0]=255,t[e+1]=0,t[e+2]=0,t[e+3]=0;else{let s=1*c%1,i=255*c%1,r=65025*c%1,a=16581375*c%1;s-=i/255,i-=r/255,r-=a/255,t[e+0]=Math.min(255,Math.floor(s*256)),t[e+1]=Math.min(255,Math.floor(i*256)),t[e+2]=Math.min(255,Math.floor(r*256)),t[e+3]=Math.min(255,Math.floor(a*256))}},AY=c=>{let t=c.length,e=Math.min(t,512),s=Math.ceil(t/e),i=new Uint8Array(e*s*4),r=0;for(let a=0;a{let i=e*2*Math.PI,r=Math.pow(1-t,1/(s+1)),a=Math.sqrt(1-r*r);c.set(Math.cos(i)*a,Math.sin(i)*a,r).normalize()},PY=(c,t,e)=>{let s=e*2*Math.PI,i=Math.sqrt(1-t),r=Math.sqrt(t);c.set(Math.cos(s)*r,Math.sin(s)*r,i).normalize()},wY=(c,t,e,s)=>{let i=e*2*Math.PI,r=Math.sqrt((1-t)/(1+(s*s-1)*t)),a=Math.sqrt(1-r*r);c.set(Math.cos(i)*a,Math.sin(i)*a,r).normalize()},IY=(c,t)=>{let e=c*t,s=t/(1-c*c+e*e);return s*s*(1/Math.PI)},RY=(c,t)=>{let e=new x,s=[];for(let i=0;i{let e=t/c,s=new x,i=[];for(let r=0;r{let e=DY[c];return e&&e[t]||c},MY=(c,t,e)=>{let s=e/c,i=1-Math.log2(t)/11,r=i*i,a=new x,o=new x,l=new x(0,0,1),h=[],f=LY(c,t);for(let u=0;u0){let p=IY(Math.min(1,d),r)/4+.001,m=.5*Math.log2(s/p);h.push(o.x,o.y,o.z,m)}}for(;h.length{let s=AY(e);return new Z(c,{name:t,width:s.width,height:s.height,mipmaps:!1,minFilter:0,magFilter:0,levels:[s.data]})},zT=class{constructor(t=!0){n(this,"map",new Map);this.destroyContent=t}destroy(){this.destroyContent&&this.map.forEach((t,e)=>{t.destroy()})}get(t,e){if(!this.map.has(t)){let s=e();return this.map.set(t,s),s}return this.map.get(t)}},FY=new zT(!1),NY=new et,Hw=(c,t,e)=>NY.get(c,()=>new zT).get(t,()=>OY(c,t,FY.get(t,e))),BY=(c,t,e)=>{let s=`lambert-samples-${t}-${e}`;return Hw(c,s,()=>bY(t,e))},UY=(c,t,e)=>{let s=`phong-samples-${t}-${e}`;return Hw(c,s,()=>RY(t,e))},kY=(c,t,e,s)=>{let i=`ggx-samples-${t}-${e}-${s}`;return Hw(c,i,()=>MY(t,e,s))};function oa(c,t,e={}){let s=e.seamPixels??0,i=(e.rect?.z??t.width)-s*2,r=(e.rect?.w??t.height)-s*2;if(i<1||r<1)return!1;let a={none:"reproject",lambert:"prefilterSamplesUnweighted",phong:"prefilterSamplesUnweighted",ggx:"prefilterSamples"},o=e.hasOwnProperty("specularPower")?e.specularPower:1,l=e.hasOwnProperty("face")?e.face:null,h=e.hasOwnProperty("distribution")?e.distribution:o===1?"none":"phong",f=a[h]||"reproject",u=f.startsWith("prefilterSamples"),d=li.decodeFunc(c.encoding),p=li.encodeFunc(t.encoding),m=`sample${VL(c.projection)}`,_=`getDirection${VL(t.projection)}`,S=e.hasOwnProperty("numSamples")?e.numSamples:1024,g=`ReprojectShader:${f}_${d}_${p}_${m}_${_}_${S}`,T=c.device,C=Ji(T).getCachedShader(g);if(!C){let A=new Map;u&&A.set("USE_SAMPLES_TEX",""),c.cubemap&&A.set("CUBEMAP_SOURCE",""),A.set("{PROCESS_FUNC}",f),A.set("{DECODE_FUNC}",d),A.set("{ENCODE_FUNC}",p),A.set("{SOURCE_FUNC}",m),A.set("{TARGET_FUNC}",_),A.set("{NUM_SAMPLES}",S),A.set("{NUM_SAMPLES_SQRT}",Math.round(Math.sqrt(S)).toFixed(1)),C=Se.createShader(T,{uniqueName:g,attributes:{vertex_position:ee},vertexChunk:"reprojectVS",fragmentChunk:"reprojectPS",fragmentDefines:A})}T.setBlendState(Oe.NOBLEND),T.scope.resolve(c.cubemap?"sourceCube":"sourceTex").setValue(c);let E=T.scope.resolve("params"),y=T.scope.resolve("uvMod");s>0?y.setValue([(i+s*2)/i,(r+s*2)/r,-s/i,-s/r]):y.setValue([1,1,0,0]);let P=[0,t.width*t.height*(t.cubemap?6:1),c.width*c.height*(c.cubemap?6:1)];if(u){let A=c.width*c.height*(c.cubemap?6:1),w=h==="ggx"?kY(T,S,o,A):h==="lambert"?BY(T,S,A):UY(T,S,o);T.scope.resolve("samplesTex").setValue(w),T.scope.resolve("samplesTexInverseSize").setValue([1/w.width,1/w.height])}for(let A=0;A<(t.cubemap?6:1);A++)if(l===null||A===l){let w=new me({colorBuffer:t,face:A,depth:!1,flipY:T.isWebGPU});P[0]=A,E.setValue(P),Qt(T,w,C,e?.rect),w.destroy()}return!0}var Ww=(c,t=0)=>1+Math.floor(Math.log2(Math.max(c,t))),zY=c=>c.textureHalfFloatRenderable,GY=c=>c.textureFloatRenderable,VY=c=>zY(c)?Me:GY(c)?ke:ce,HY=c=>ce,WY=(c,t,e,s)=>new Z(c,{name:`lighting-${t}`,cubemap:!0,width:t,height:t,format:e,type:e===ce?In:Gt,addressU:1,addressV:1,mipmaps:!!s}),bc=class{static generateSkyboxCubemap(t,e){let s=t.device,i=WY(s,e||(t.cubemap?t.width:t.width/4),ce,!1);return oa(t,i,{numSamples:1024}),i}static generateLightingSource(t,e){let s=t.device,i=VY(s),r=e?.target||new Z(s,{name:"lighting-source",cubemap:!0,width:e?.size||128,height:e?.size||128,format:i,type:i===ce?In:Gt,addressU:1,addressV:1,mipmaps:!0});return oa(t,r,{numSamples:t.mipmaps?1:1024}),r}static generateAtlas(t,e){let s=t.device,i=HY(s),r=e?.target||new Z(s,{name:"envAtlas",width:e?.size||512,height:e?.size||512,format:i,type:i===ce?In:Gt,projection:Gx,addressU:1,addressV:1,mipmaps:!1}),a=r.width/512,o=new Q(0,0,512*a,256*a),l=Ww(256)-Ww(4);for(let h=0;h>h*2),rect:o,seamPixels:a}),o.y+=o.w,o.z=Math.max(1,Math.floor(o.z*.5)),o.w=Math.max(1,Math.floor(o.w*.5));return o.set(128*a,384*a,64*a,32*a),oa(t,r,{numSamples:e?.numAmbientSamples||2048,distribution:"lambert",rect:o,seamPixels:a}),r}static generatePrefilteredAtlas(t,e){let s=t[0].device,i=t[0].format,r=t[0].type,a=e?.target||new Z(s,{name:"envPrefilteredAtlas",width:e?.size||512,height:e?.size||512,format:i,type:r,projection:Gx,addressU:1,addressV:1,mipmaps:!1}),o=a.width/512,l=new Q(0,0,512*o,256*o),h=Ww(512);for(let f=0;f{for(let h in Xw)Xw.hasOwnProperty(h)&&o.indexOf(h)>=0&&(this.attributes[h]=Xw[h]);this.chunks.set(l,o)}),this.shaderPassInfo=Ns.get(this.device).getByIndex(e.pass),this.shadowPass=this.shaderPassInfo.isShadow,this.lighting=e.lights.length>0||e.dirLightMapEnabled||e.clusteredLightingEnabled,this.reflections=e.reflectionSource!==gr,this.needsNormal=this.lighting||this.reflections||e.useSpecular||e.ambientSH||e.useHeights||e.enableGGXSpecular||e.clusteredLightingEnabled&&!this.shadowPass||e.useClearCoatNormals,this.needsNormal=this.needsNormal&&!this.shadowPass,this.needsSceneColor=e.useDynamicRefraction,this.needsScreenSize=e.useDynamicRefraction,this.needsTransforms=e.useDynamicRefraction,this.vshader=null,this.fshader=null}fDefineSet(t,e,s=""){t&&this.fDefines.set(e,s)}generateVertexShader(t,e,s){let{options:i,vDefines:r,attributes:a}=this,o=new Map;if(o.set("vPositionW","vec3"),(i.nineSlicedMode===It||i.nineSlicedMode===Rt)&&r.set("NINESLICED",!0),this.options.linearDepth&&(r.set("LINEAR_DEPTH",!0),o.set("vLinearDepth","float")),this.needsNormal&&r.set("NORMALS",!0),this.options.useInstancing){let u=ne.get(this.device,this.shaderLanguage);this.chunks.get("transformInstancingVS")===u.get("transformInstancingVS")&&(a.instance_line1=Id,a.instance_line2=Rd,a.instance_line3=bd,a.instance_line4=Da)}this.needsNormal&&(a.vertex_normal=Ot,o.set("vNormalW","vec3"),i.hasTangents&&(i.useHeights||i.useNormals||i.useClearCoatNormals||i.enableGGXSpecular)?(r.set("TANGENTS",!0),a.vertex_tangent=vs,o.set("vTangentW","vec3"),o.set("vBinormalW","vec3")):i.enableGGXSpecular&&(r.set("GGX_SPECULAR",!0),o.set("vObjectSpaceUpW","vec3")));let l=2;for(let u=0;u{let{id:d,uv:p,name:m}=u,_=d+p*100;if(!f.has(_)){f.add(_),o.set(`vUV${p}_${d}`,"vec2");let S=`texture_${m}MapTransform`;r.set(`{TRANSFORM_NAME_${h}}`,S),r.set(`{TRANSFORM_UV_${h}}`,p),r.set(`{TRANSFORM_ID_${h}}`,d),h++}}),r.set("UV_TRANSFORMS_COUNT",h),i.vertexColors&&(a.vertex_color=Ct,r.set("VERTEX_COLOR",!0),o.set("vVertexColor","vec4"),i.useVertexColorGamma&&r.set("STD_VERTEX_COLOR_GAMMA","")),i.useMsdf&&i.msdfTextAttribute&&(a.vertex_outlineParameters=rc,a.vertex_shadowParameters=ac,r.set("MSDF",!0)),(i.useMorphPosition||i.useMorphNormal)&&(r.set("MORPHING",!0),i.useMorphTextureBasedInt&&r.set("MORPHING_INT",!0),i.useMorphPosition&&r.set("MORPHING_POSITION",!0),i.useMorphNormal&&r.set("MORPHING_NORMAL",!0),a.morph_vertex_id=Da),i.skin&&(a.vertex_boneIndices=$t,i.batch?r.set("BATCH",!0):(a.vertex_boneWeights=bs,r.set("SKIN",!0))),i.useInstancing&&r.set("INSTANCING",!0),i.screenSpace&&r.set("SCREENSPACE",!0),i.pixelSnap&&r.set("PIXELSNAP",!0),o.forEach((u,d)=>{this.varyingsCode+=`#define VARYING_${d.toUpperCase()} +`,this.varyingsCode+=this.shaderLanguage===se?`varying ${d}: ${Bg.get(u)}; +`:`varying ${u} ${d}; +`}),this.includes.set("varyingsVS",this.varyingsCode),this.includes.set("varyingsPS",this.varyingsCode),this.vshader=` + #include "litMainVS" + `}_setupLightingDefines(t,e){let s=this.fDefines,i=this.options;if(this.fDefines.set("LIGHT_COUNT",i.lights.length),t&&s.set("AREA_LIGHTS",!0),e&&this.lighting&&(s.set("LIT_CLUSTERED_LIGHTS",!0),i.clusteredLightingCookiesEnabled&&s.set("CLUSTER_COOKIES",!0),i.clusteredLightingAreaLightsEnabled&&s.set("CLUSTER_AREALIGHTS",!0),i.lightMaskDynamic&&s.set("CLUSTER_MESH_DYNAMIC_LIGHTS",!0),i.clusteredLightingShadowsEnabled&&!i.noShadow)){let r=Fi.get(i.clusteredLightingShadowType);s.set("CLUSTER_SHADOWS",!0),s.set(`SHADOW_KIND_${r.kind}`,!0),s.set(`CLUSTER_SHADOW_TYPE_${r.kind}`,!0)}for(let r=0;r0&&s.set(`LIGHT${r}_SHADOW_CASCADE_BLEND`,!0),a.numCascades>1&&s.set(`LIGHT${r}_SHADOW_CASCADES`,!0)),(u.pcf||u.pcss||this.device.isWebGPU)&&s.set(`LIGHT${r}_SHADOW_SAMPLE_SOURCE_ZBUFFER`,!0),o===We&&s.set(`LIGHT${r}_SHADOW_SAMPLE_POINT`,!0)),f&&(s.set(`SHADOW_KIND_${u.kind}`,!0),o===Ce&&s.set("SHADOW_DIRECTIONAL",!0))}}prepareForwardPass(t){let{options:e}=this,i=e.clusteredLightingEnabled&&e.clusteredLightingAreaLightsEnabled||e.lights.some(o=>o._shape&&o._shape!==$i),r=!e.lightMapEnabled||e.lightMapWithoutAmbient,a=this.needsNormal&&(e.useNormals||e.useClearCoatNormals||e.enableGGXSpecular&&!e.useHeights);e.useSpecular&&(this.fDefineSet(!0,"LIT_SPECULAR"),this.fDefineSet(this.reflections,"LIT_REFLECTIONS"),this.fDefineSet(e.useClearCoat,"LIT_CLEARCOAT"),this.fDefineSet(e.fresnelModel>0,"LIT_SPECULAR_FRESNEL"),this.fDefineSet(e.useSheen,"LIT_SHEEN"),this.fDefineSet(e.useIridescence,"LIT_IRIDESCENCE")),this.fDefineSet(this.lighting&&e.useSpecular||this.reflections,"LIT_SPECULAR_OR_REFLECTION"),this.fDefineSet(this.needsSceneColor,"LIT_SCENE_COLOR"),this.fDefineSet(this.needsScreenSize,"LIT_SCREEN_SIZE"),this.fDefineSet(this.needsTransforms,"LIT_TRANSFORMS"),this.fDefineSet(this.needsNormal,"LIT_NEEDS_NORMAL"),this.fDefineSet(this.lighting,"LIT_LIGHTING"),this.fDefineSet(e.useMetalness,"LIT_METALNESS"),this.fDefineSet(e.enableGGXSpecular,"LIT_GGX_SPECULAR"),this.fDefineSet(e.useAnisotropy,"LIT_ANISOTROPY"),this.fDefineSet(e.useSpecularityFactor,"LIT_SPECULARITY_FACTOR"),this.fDefineSet(e.useCubeMapRotation,"CUBEMAP_ROTATION"),this.fDefineSet(e.occludeSpecularFloat,"LIT_OCCLUDE_SPECULAR_FLOAT"),this.fDefineSet(e.separateAmbient,"LIT_SEPARATE_AMBIENT"),this.fDefineSet(e.twoSidedLighting,"LIT_TWO_SIDED_LIGHTING"),this.fDefineSet(e.lightMapEnabled,"LIT_LIGHTMAP"),this.fDefineSet(e.dirLightMapEnabled,"LIT_DIR_LIGHTMAP"),this.fDefineSet(e.skyboxIntensity>0,"LIT_SKYBOX_INTENSITY"),this.fDefineSet(e.clusteredLightingShadowsEnabled,"LIT_CLUSTERED_SHADOWS"),this.fDefineSet(e.clusteredLightingAreaLightsEnabled,"LIT_CLUSTERED_AREA_LIGHTS"),this.fDefineSet(a,"LIT_TBN"),this.fDefineSet(r,"LIT_ADD_AMBIENT"),this.fDefineSet(e.hasTangents,"LIT_TANGENTS"),this.fDefineSet(e.useNormals,"LIT_USE_NORMALS"),this.fDefineSet(e.useClearCoatNormals,"LIT_USE_CLEARCOAT_NORMALS"),this.fDefineSet(e.useRefraction,"LIT_REFRACTION"),this.fDefineSet(e.useDynamicRefraction,"LIT_DYNAMIC_REFRACTION"),this.fDefineSet(e.dispersion,"LIT_DISPERSION"),this.fDefineSet(e.useHeights,"LIT_HEIGHTS"),this.fDefineSet(e.opacityFadesSpecular,"LIT_OPACITY_FADES_SPECULAR"),this.fDefineSet(e.alphaToCoverage,"LIT_ALPHA_TO_COVERAGE"),this.fDefineSet(e.alphaTest,"LIT_ALPHA_TEST"),this.fDefineSet(e.useMsdf,"LIT_MSDF"),this.fDefineSet(e.ssao,"LIT_SSAO"),this.fDefineSet(e.useAo,"LIT_AO"),this.fDefineSet(e.occludeDirect,"LIT_OCCLUDE_DIRECT"),this.fDefineSet(e.msdfTextAttribute,"LIT_MSDF_TEXT_ATTRIBUTE"),this.fDefineSet(e.diffuseMapEnabled,"LIT_DIFFUSE_MAP"),this.fDefineSet(e.shadowCatcher,"LIT_SHADOW_CATCHER"),this.fDefineSet(!0,"LIT_FRESNEL_MODEL",aw[e.fresnelModel]),this.fDefineSet(!0,"LIT_NONE_SLICE_MODE",_w[e.nineSlicedMode]),this.fDefineSet(!0,"LIT_BLEND_TYPE",Wg[e.blendType]),this.fDefineSet(!0,"LIT_CUBEMAP_PROJECTION",uw[e.cubeMapProjection]),this.fDefineSet(!0,"LIT_OCCLUDE_SPECULAR",dw[e.occludeSpecular]),this.fDefineSet(!0,"LIT_REFLECTION_SOURCE",pw[e.reflectionSource]),this.fDefineSet(!0,"LIT_AMBIENT_SOURCE",mw[e.ambientSource]),this.fDefineSet(!0,"{lightingUv}",t??""),this.fDefineSet(!0,"{reflectionDecode}",li.decodeFunc(e.reflectionEncoding)),this.fDefineSet(!0,"{reflectionCubemapDecode}",li.decodeFunc(e.reflectionCubemapEncoding)),this.fDefineSet(!0,"{ambientDecode}",li.decodeFunc(e.ambientEncoding)),this._setupLightingDefines(i,e.clusteredLightingEnabled)}preparePrepassPass(){let{options:t}=this;this.fDefineSet(t.alphaTest,"LIT_ALPHA_TEST"),this.fDefineSet(!0,"STD_OPACITY_DITHER",eS[t.opacityShadowDither])}prepareShadowPass(){let{options:t}=this,e=this.shaderPassInfo.lightType,s=this.shaderPassInfo.shadowType,i=Fi.get(s),r=e===Ce||!i.vsm&&e===je;this.fDefineSet(r,"PERSPECTIVE_DEPTH"),this.fDefineSet(!0,"LIGHT_TYPE",`${lT[e]}`),this.fDefineSet(!0,"SHADOW_TYPE",`${i.name}`),this.fDefineSet(t.alphaTest,"LIT_ALPHA_TEST")}generateFragmentShader(t,e,s){let i=this.options;this.includes.set("frontendDeclPS",t??""),this.includes.set("frontendCodePS",e??""),i.pass===ta||(i.pass===xr?this.preparePrepassPass():this.shadowPass?this.prepareShadowPass():this.prepareForwardPass(s)),this.fshader=` + #include "litMainPS" + `}};var Xa=class{constructor(){n(this,"hasTangents",!1);n(this,"shaderChunks",null);n(this,"pass",0);n(this,"alphaTest",!1);n(this,"blendType",wt);n(this,"separateAmbient",!1);n(this,"screenSpace",!1);n(this,"skin",!1);n(this,"batch",!1);n(this,"useInstancing",!1);n(this,"useMorphPosition",!1);n(this,"useMorphNormal",!1);n(this,"useMorphTextureBasedInt",!1);n(this,"nineSlicedMode",0);n(this,"clusteredLightingEnabled",!0);n(this,"clusteredLightingCookiesEnabled",!1);n(this,"clusteredLightingShadowsEnabled",!1);n(this,"clusteredLightingShadowType",0);n(this,"clusteredLightingAreaLightsEnabled",!1);n(this,"vertexColors",!1);n(this,"useVertexColorGamma",!1);n(this,"lightMapEnabled",!1);n(this,"dirLightMapEnabled",!1);n(this,"useHeights",!1);n(this,"useNormals",!1);n(this,"useClearCoatNormals",!1);n(this,"useAo",!1);n(this,"diffuseMapEnabled",!1);n(this,"pixelSnap",!1);n(this,"ambientSH",!1);n(this,"ssao",!1);n(this,"twoSidedLighting",!1);n(this,"occludeDirect",!1);n(this,"occludeSpecular",0);n(this,"occludeSpecularFloat",!1);n(this,"useMsdf",!1);n(this,"msdfTextAttribute",!1);n(this,"alphaToCoverage",!1);n(this,"opacityFadesSpecular",!1);n(this,"opacityDither",Bi);n(this,"opacityShadowDither",Bi);n(this,"cubeMapProjection",0);n(this,"useSpecular",!1);n(this,"useSpecularityFactor",!1);n(this,"enableGGXSpecular",!1);n(this,"fresnelModel",0);n(this,"useRefraction",!1);n(this,"useClearCoat",!1);n(this,"useSheen",!1);n(this,"useIridescence",!1);n(this,"useMetalness",!1);n(this,"useDynamicRefraction",!1);n(this,"dispersion",!1);n(this,"fog",Mi);n(this,"gamma",Zi);n(this,"toneMap",-1);n(this,"reflectionSource",gr);n(this,"reflectionEncoding",null);n(this,"reflectionCubemapEncoding",null);n(this,"ambientSource","constant");n(this,"ambientEncoding",null);n(this,"skyboxIntensity",1);n(this,"useCubeMapRotation",!1);n(this,"lightMapWithoutAmbient",!1);n(this,"lights",[]);n(this,"noShadow",!1);n(this,"lightMaskDynamic",0);n(this,"userAttributes",{});n(this,"linearDepth",!1);n(this,"shadowCatcher",!1)}};var tr=class{constructor(){n(this,"defines",new Map);n(this,"forceUv1",!1);n(this,"specularTint",!1);n(this,"metalnessTint",!1);n(this,"glossTint",!1);n(this,"emissiveEncoding","linear");n(this,"lightMapEncoding","linear");n(this,"vertexColorGamma",!1);n(this,"packedNormal",!1);n(this,"normalDetailPackedNormal",!1);n(this,"clearCoatPackedNormal",!1);n(this,"glossInvert",!1);n(this,"sheenGlossInvert",!1);n(this,"clearCoatGlossInvert",!1);n(this,"useAO",!1);n(this,"litOptions",new Xa)}get pass(){return this.litOptions.pass}};var cS={generateKey(c){return`lit${Object.keys(c).sort().map(t=>t==="shaderChunks"?c.shaderChunks?.key??"":t==="lights"?cS.generateLightsKey(c):t+c[t]).join(` +`)}`},generateLightsKey(c){return`lights:${c.lights.map(t=>!c.clusteredLightingEnabled||t._type===Ce?`${t.key},`:"").join("")}`}};var Dc=[],Yw=c=>Object.keys(c).filter(t=>t!=="litOptions").sort(),Kw=class extends yi{constructor(){super(...arguments);n(this,"optionsContext",new tr);n(this,"optionsContextMin",new tr)}generateKey(e){let s;return e===this.optionsContextMin?(this.propsMin||(this.propsMin=Yw(e)),s=this.propsMin):e===this.optionsContext?(this.props||(this.props=Yw(e)),s=this.props):s=Yw(e),`standard: +${yi.definesHash(e.defines)} +${s.map(a=>a+e[a]).join(` +`)}${cS.generateKey(e.litOptions)}`}_getUvSourceExpression(e,s,i){let r=i[e],a=i[s],o=i.litOptions.pass===Sr,l;return o&&i.litOptions.nineSlicedMode===It||o&&i.litOptions.nineSlicedMode===Rt?l="nineSlicedUv":(r===0?l=`vUv${a}`:l=`vUV${a}_${r}`,i.heightMap&&e!=="heightMapTransform"&&(l+=" + dUvOffset")),l}_validateMapChunk(e,s,i,r){}_addMapDefines(e,s,i,r,a,o,l=null){let h=`${s}Map`,f=s.toUpperCase(),u=`${h}Uv`,d=`${h}Identifier`,p=`${h}Transform`,m=`${h}Channel`,_=`${s}VertexColorChannel`,S=`${s}Tint`,g=`${s}VertexColor`,T=`${s}Mode`,C=`${s}Invert`,v=r[S],E=r[g],y=r[h],P=r[d],A=r[T],w=a.get(i);if(y){e.set(`STD_${f}_TEXTURE`,"");let I=this._getUvSourceExpression(p,u,r);e.set(`{STD_${f}_TEXTURE_UV}`,I),e.set(`{STD_${f}_TEXTURE_CHANNEL}`,r[m]);let D=`{STD_${f}_TEXTURE_NAME}`;if(w.includes(D)){let O=`texture_${h}`,G=o[P];G?O=G:(o[P]=O,e.set(`STD_${f}_TEXTURE_ALLOCATE`,"")),e.set(D,O)}if(l){let O=r[m]==="aaa"?"passThrough":li.decodeFunc(l);e.set(`{STD_${f}_TEXTURE_DECODE}`,O)}}E&&(e.set(`STD_${f}_VERTEX`,""),e.set(`{STD_${f}_VERTEX_CHANNEL}`,r[_])),A&&e.set(`{STD_${f}_DETAILMODE}`,A),v&&e.set(`STD_${f}_CONSTANT`,""),r[C]&&e.set(`STD_${f}_INVERT`,"")}_correctChannel(e,s,i){if(i[e]>0){if(i[e]s.length){let r=s,a=r.charAt(r.length-1),o=i[e]-r.length;for(let l=0;l{a&&s.set(o,l)};r(e.lightMap,"STD_LIGHTMAP",""),r(e.lightVertexColor,"STD_LIGHT_VERTEX_COLOR",""),r(e.dirLightMap&&e.litOptions.useSpecular,"STD_LIGHTMAP_DIR",""),r(e.heightMap,"STD_HEIGHT_MAP",""),r(e.useSpecularColor,"STD_SPECULAR_COLOR",""),r(e.aoMap||e.aoVertexColor||e.useAO,"STD_AO",""),r(!0,"STD_OPACITY_DITHER",eS[i.isForward?e.litOptions.opacityDither:e.litOptions.opacityShadowDither])}createShaderDefinition(e,s){let i=Ns.get(e).getByIndex(s.litOptions.pass),r=i.isForward,a=new Lp(e,s.litOptions);this.createVertexShader(a,s);let o={};s.litOptions.fresnelModel=s.litOptions.fresnelModel===0?Sc:s.litOptions.fresnelModel;let l=a.fDefines;this.prepareFragmentDefines(s,l,i);let h="";if(r){if(s.heightMap&&this._addMapDefines(l,"height","parallaxPS",s,a.chunks,o),(s.litOptions.blendType!==wt||s.litOptions.alphaTest||s.litOptions.alphaToCoverage||s.litOptions.opacityDither!==Bi)&&this._addMapDefines(l,"opacity","opacityPS",s,a.chunks,o),a.needsNormal){if((s.normalMap||s.clearCoatNormalMap)&&!s.litOptions.hasTangents){let p=s.normalMap?"normalMap":"clearCoatNormalMap";h=this._getUvSourceExpression(`${p}Transform`,`${p}Uv`,s)}this._addMapDefines(l,"normalDetail","normalMapPS",s,a.chunks,o,s.normalDetailPackedNormal?"xy":"xyz"),this._addMapDefines(l,"normal","normalMapPS",s,a.chunks,o,s.packedNormal?"xy":"xyz")}s.diffuseDetail&&this._addMapDefines(l,"diffuseDetail","diffusePS",s,a.chunks,o,s.diffuseDetailEncoding),this._addMapDefines(l,"diffuse","diffusePS",s,a.chunks,o,s.diffuseEncoding),s.litOptions.useRefraction&&(this._addMapDefines(l,"refraction","transmissionPS",s,a.chunks,o),this._addMapDefines(l,"thickness","thicknessPS",s,a.chunks,o)),s.litOptions.useIridescence&&(this._addMapDefines(l,"iridescence","iridescencePS",s,a.chunks,o),this._addMapDefines(l,"iridescenceThickness","iridescenceThicknessPS",s,a.chunks,o)),(a.lighting&&s.litOptions.useSpecular||a.reflections)&&(s.litOptions.useSheen&&(this._addMapDefines(l,"sheen","sheenPS",s,a.chunks,o,s.sheenEncoding),this._addMapDefines(l,"sheenGloss","sheenGlossPS",s,a.chunks,o)),s.litOptions.useMetalness&&(this._addMapDefines(l,"metalness","metalnessPS",s,a.chunks,o),this._addMapDefines(l,"ior","iorPS",s,a.chunks,o)),s.litOptions.useSpecularityFactor&&this._addMapDefines(l,"specularityFactor","specularityFactorPS",s,a.chunks,o),s.useSpecularColor&&this._addMapDefines(l,"specular","specularPS",s,a.chunks,o,s.specularEncoding),this._addMapDefines(l,"gloss","glossPS",s,a.chunks,o)),s.aoDetail&&this._addMapDefines(l,"aoDetail","aoPS",s,a.chunks,o),(s.aoMap||s.aoVertexColor||s.useAO)&&this._addMapDefines(l,"ao","aoPS",s,a.chunks,o),this._addMapDefines(l,"emissive","emissivePS",s,a.chunks,o,s.emissiveEncoding),s.litOptions.useClearCoat&&(this._addMapDefines(l,"clearCoat","clearCoatPS",s,a.chunks,o),this._addMapDefines(l,"clearCoatGloss","clearCoatGlossPS",s,a.chunks,o),this._addMapDefines(l,"clearCoatNormal","clearCoatNormalPS",s,a.chunks,o,s.clearCoatPackedNormal?"xy":"xyz")),s.litOptions.enableGGXSpecular&&this._addMapDefines(l,"anisotropy","anisotropyPS",s,a.chunks,o),(s.lightMap||s.lightVertexColor)&&this._addMapDefines(l,"light","lightmapPS",s,a.chunks,o,s.lightMapEncoding)}else{let p=s.litOptions.opacityShadowDither;(s.litOptions.alphaTest||p)&&this._addMapDefines(l,"opacity","opacityPS",s,a.chunks,o)}a.generateFragmentShader(a.chunks.get("stdDeclarationPS"),a.chunks.get("stdFrontEndPS"),h);let f=Ha.merge(a.chunks,a.includes),u=a.vDefines;s.defines.forEach((p,m)=>u.set(m,p)),s.defines.forEach((p,m)=>l.set(m,p));let d=ns.createDefinition(e,{name:"StandardShader",attributes:a.attributes,shaderLanguage:a.shaderLanguage,vertexCode:a.vshader,fragmentCode:a.fshader,vertexIncludes:f,fragmentIncludes:f,fragmentDefines:l,vertexDefines:u});return a.shaderPassInfo.isForward&&(d.tag=Cg),d}},GT=new Kw;var sr=[];sr[rp]={src:1,dst:1,op:2};sr[wt]={src:1,dst:0,op:0};sr[ls]={src:6,dst:8,op:0,alphaSrc:1};sr[Ms]={src:1,dst:8,op:0};sr[ea]={src:1,dst:1,op:0};sr[op]={src:6,dst:1,op:0};sr[np]={src:4,dst:2,op:0};sr[lp]={src:5,dst:1,op:0};sr[ap]={src:4,dst:0,op:0};sr[cp]={src:1,dst:1,op:3};sr[hp]={src:1,dst:1,op:4};var XY=0,Us=class c{constructor(){n(this,"meshInstances",new Set);n(this,"name","Untitled");n(this,"userId","");n(this,"id",XY++);n(this,"variants",new Map);n(this,"defines",new Map);n(this,"_definesDirty",!1);n(this,"parameters",{});n(this,"alphaTest",0);n(this,"alphaToCoverage",!1);n(this,"_blendState",new Oe);n(this,"_depthState",new Pt);n(this,"cull",1);n(this,"frontFace",0);n(this,"stencilFront",null);n(this,"stencilBack",null);n(this,"_shaderChunks",null);n(this,"_oldChunks",{});n(this,"_dirtyShader",!0);n(this,"_shaderVersion",0);n(this,"_scene",null);n(this,"dirty",!0);new.target}get hasShaderChunks(){return this._shaderChunks!=null}get shaderChunks(){return this._shaderChunks||(this._shaderChunks=new ne),this._shaderChunks}getShaderChunks(t=fe){let e=this.shaderChunks;return t===fe?e.glsl:e.wgsl}set shaderChunksVersion(t){this.shaderChunks.version=t}get shaderChunksVersion(){return this.shaderChunks.version}set chunks(t){this._oldChunks=t}get chunks(){return Object.assign(this._oldChunks,Object.fromEntries(this.shaderChunks.glsl)),this._oldChunks}set depthBias(t){this._depthState.depthBias=t}get depthBias(){return this._depthState.depthBias}set slopeDepthBias(t){this._depthState.depthBiasSlope=t}get slopeDepthBias(){return this._depthState.depthBiasSlope}set redWrite(t){this._blendState.redWrite=t}get redWrite(){return this._blendState.redWrite}set greenWrite(t){this._blendState.greenWrite=t}get greenWrite(){return this._blendState.greenWrite}set blueWrite(t){this._blendState.blueWrite=t}get blueWrite(){return this._blendState.blueWrite}set alphaWrite(t){this._blendState.alphaWrite=t}get alphaWrite(){return this._blendState.alphaWrite}get transparent(){return this._blendState.blend}_updateTransparency(){for(let t of this.meshInstances)t.transparent=this.transparent}set blendState(t){this._blendState.copy(t),this._updateTransparency()}get blendState(){return this._blendState}set blendType(t){let e=sr[t];this._blendState.setColorBlend(e.op,e.src,e.dst),this._blendState.setAlphaBlend(e.alphaOp??e.op,e.alphaSrc??e.src,e.alphaDst??e.dst);let s=t!==wt;this._blendState.blend!==s&&(this._blendState.blend=s,this._updateTransparency()),this._updateMeshInstanceKeys()}get blendType(){if(!this.transparent)return wt;let{colorOp:t,colorSrcFactor:e,colorDstFactor:s,alphaOp:i,alphaSrcFactor:r,alphaDstFactor:a}=this._blendState;for(let o=0;othis.defines.set(s,e)),this._shaderChunks=t.hasShaderChunks?new ne:null,this._shaderChunks?.copy(t._shaderChunks),this}clone(){return new this.constructor().copy(this)}_updateMeshInstanceKeys(){for(let t of this.meshInstances)t.updateKey()}updateUniforms(t,e){this._dirtyShader&&(this.clearVariants(),this._dirtyShader=!1)}getShaderVariant(t){}update(){if(Object.keys(this._oldChunks).length>0)for(let[t,e]of Object.entries(this._oldChunks))this.shaderChunks.glsl.set(t,e),delete this._oldChunks[t];(this._definesDirty||this._shaderChunks?.isDirty())&&(this._definesDirty=!1,this._shaderChunks?.resetDirty(),this.clearVariants()),this.dirty=!0}clearParameters(){this.parameters={}}getParameters(){return this.parameters}clearVariants(){this.variants.clear();for(let t of this.meshInstances)t.clearShaders()}getParameter(t){return this.parameters[t]}_setParameterSimple(t,e){let s=this.parameters[t];s?s.data=e:this.parameters[t]={scopeId:null,data:e}}setParameter(t,e){if(e===void 0&&typeof t=="object"){let s=t;if(s.length){for(let i=0;i0,t.blendType=e.blendType,t.screenSpace=i&&(i&Ec)!==0,t.skin=i&&(i&Uo)!==0,t.useInstancing=i&&(i&ko)!==0,t.useMorphPosition=i&&(i&zo)!==0,t.useMorphNormal=i&&(i&Go)!==0,t.useMorphTextureBasedInt=i&&(i&Vo)!==0,t.hasTangents=i&&(i&Nf)!==0,t.nineSlicedMode=e.nineSlicedMode||Ti,e.useLighting&&s.clusteredLightingEnabled?(t.clusteredLightingEnabled=!0,t.clusteredLightingCookiesEnabled=s.lighting.cookiesEnabled,t.clusteredLightingShadowsEnabled=s.lighting.shadowsEnabled,t.clusteredLightingShadowType=s.lighting.shadowType,t.clusteredLightingAreaLightsEnabled=s.lighting.areaLightsEnabled):(t.clusteredLightingEnabled=!1,t.clusteredLightingCookiesEnabled=!1,t.clusteredLightingShadowsEnabled=!1,t.clusteredLightingAreaLightsEnabled=!1)}static updateMaterialOptions(t,e){t.separateAmbient=!1,t.pixelSnap=e.pixelSnap,t.ambientSH=e.ambientSH,t.twoSidedLighting=e.twoSidedLighting,t.occludeDirect=e.occludeDirect,t.occludeSpecular=e.occludeSpecular,t.occludeSpecularFloat=e.occludeSpecularIntensity!==1,t.useMsdf=!1,t.msdfTextAttribute=!1,t.alphaToCoverage=e.alphaToCoverage,t.opacityFadesSpecular=e.opacityFadesSpecular,t.opacityDither=e.opacityDither,t.cubeMapProjection=pp,t.useSpecular=e.hasSpecular,t.useSpecularityFactor=e.hasSpecularityFactor,t.enableGGXSpecular=e.ggxSpecular,t.useAnisotropy=!1,t.fresnelModel=e.fresnelModel,t.useRefraction=e.hasRefraction,t.useClearCoat=e.hasClearCoat,t.useSheen=e.hasSheen,t.useIridescence=e.hasIrridescence,t.useMetalness=e.hasMetalness,t.useDynamicRefraction=e.dynamicRefraction,t.dispersion=e.dispersion>0,t.vertexColors=!1,t.lightMapEnabled=e.hasLighting,t.dirLightMapEnabled=e.dirLightMap,t.useHeights=e.hasHeights,t.useNormals=e.hasNormals,t.useClearCoatNormals=e.hasClearCoatNormals,t.useAo=e.hasAo,t.diffuseMapEnabled=e.hasDiffuseMap}static updateEnvOptions(t,e,s,i){t.fog=e.useFog?i.fog:Mi,t.gamma=i.shaderOutputGamma,t.toneMap=e.useTonemap?i.toneMapping:Rf,e.useSkybox&&s.envAtlas&&s.skybox?(t.reflectionSource=Lf,t.reflectionEncoding=s.envAtlas.encoding,t.reflectionCubemapEncoding=s.skybox.encoding):e.useSkybox&&s.envAtlas?(t.reflectionSource=Df,t.reflectionEncoding=s.envAtlas.encoding):e.useSkybox&&s.skybox?(t.reflectionSource=Mf,t.reflectionEncoding=s.skybox.encoding):(t.reflectionSource=gr,t.reflectionEncoding=null),e.ambientSH?(t.ambientSource=mp,t.ambientEncoding=null):t.reflectionSource!==gr&&s.envAtlas?(t.ambientSource=_p,t.ambientEncoding=s.envAtlas.encoding):(t.ambientSource=gp,t.ambientEncoding=null);let r=t.reflectionSource!==gr;t.skyboxIntensity=r,t.useCubeMapRotation=r&&s._skyboxRotationShaderInclude}static updateLightingOptions(t,e,s,i,r){if(t.lightMapWithoutAmbient=!1,e.useLighting){let a=[],o=i?i>>16:cs;t.lightMaskDynamic=!!(o&cs),t.lightMapWithoutAmbient=!1,r&&(c.collectLights(Ce,r[Ce],a,o),s.clusteredLightingEnabled||(c.collectLights(We,r[We],a,o),c.collectLights(je,r[je],a,o))),t.lights=a}else t.lights=[];(t.lights.length===0&&!s.clusteredLightingEnabled||(i&Tc)!==0)&&(t.noShadow=!0)}static collectLights(t,e,s,i){for(let r=0;r{if(c.length!==t.length)return!1;for(let e=0;ec.r!==1||c.g!==1||c.b!==1,KY=c=>c.r!==0||c.g!==0||c.b!==0,VT=class{constructor(){this._mapXForms=null}updateMinRef(t,e,s,i,r,a){this._updateSharedOptions(t,e,s,i,r),this._updateMinOptions(t,s,r),this._updateUVOptions(t,s,i,!0)}updateRef(t,e,s,i,r,a,o){this._updateSharedOptions(t,e,i,r,a),this._updateEnvOptions(t,i,e,s),this._updateMaterialOptions(t,i,e),t.litOptions.hasTangents=r&&(r&Nf)!==0,this._updateLightOptions(t,e,i,r,o),this._updateUVOptions(t,i,r,!1,s)}_updateSharedOptions(t,e,s,i,r){t.forceUv1=s.forceUv1,s.userAttributes&&(t.litOptions.userAttributes=Object.fromEntries(s.userAttributes.entries())),t.litOptions.shaderChunks=s.shaderChunks,t.litOptions.pass=r,t.litOptions.alphaTest=s.alphaTest>0,t.litOptions.blendType=s.blendType,t.litOptions.screenSpace=i&&(i&Ec)!==0,t.litOptions.skin=i&&(i&Uo)!==0,t.litOptions.batch=i&&(i&Uf)!==0,t.litOptions.useInstancing=i&&(i&ko)!==0,t.litOptions.useMorphPosition=i&&(i&zo)!==0,t.litOptions.useMorphNormal=i&&(i&Go)!==0,t.litOptions.useMorphTextureBasedInt=i&&(i&Vo)!==0,t.litOptions.nineSlicedMode=s.nineSlicedMode||0,e.clusteredLightingEnabled&&s.useLighting?(t.litOptions.clusteredLightingEnabled=!0,t.litOptions.clusteredLightingCookiesEnabled=e.lighting.cookiesEnabled,t.litOptions.clusteredLightingShadowsEnabled=e.lighting.shadowsEnabled,t.litOptions.clusteredLightingShadowType=e.lighting.shadowType,t.litOptions.clusteredLightingAreaLightsEnabled=e.lighting.areaLightsEnabled):(t.litOptions.clusteredLightingEnabled=!1,t.litOptions.clusteredLightingCookiesEnabled=!1,t.litOptions.clusteredLightingShadowsEnabled=!1,t.litOptions.clusteredLightingAreaLightsEnabled=!1)}_updateUVOptions(t,e,s,i,r){let a=!1,o=!1,l=!1;s&&(a=(s&Of)!==0,o=(s&$g)!==0,l=(s&Zg)!==0),t.litOptions.vertexColors=!1,this._mapXForms=[];let h={};for(let f in Dc)this._updateTexOptions(t,e,f,a,o,l,i,h);this._mapXForms=null,t.litOptions.ssao=r?.ssaoEnabled,t.useAO=t.litOptions.ssao,t.litOptions.lightMapEnabled=t.lightMap,t.litOptions.dirLightMapEnabled=t.dirLightMap,t.litOptions.useHeights=t.heightMap,t.litOptions.useNormals=t.normalMap,t.litOptions.useClearCoatNormals=t.clearCoatNormalMap,t.litOptions.useAo=t.aoMap||t.aoVertexColor||t.litOptions.ssao,t.litOptions.diffuseMapEnabled=t.diffuseMap}_updateTexOptions(t,e,s,i,r,a,o,l){let h=s==="opacity";if(!o||h){let f=`${s}Map`,u=`${s}VertexColor`,d=`${s}VertexColorChannel`,p=`${f}Channel`,m=`${f}Transform`,_=`${f}Uv`,S=`${f}Identifier`;if(s!=="light"&&(t[f]=!1,t[S]=void 0,t[p]="",t[m]=0,t[_]=0),t[u]=!1,t[d]="",h&&e.blendType===wt&&e.alphaTest===0&&!e.alphaToCoverage&&e.opacityDither===Bi)return;if(s!=="height"&&e[u]&&a&&(t[u]=e[u],t[d]=e[d],t.litOptions.vertexColors=!0),e[f]){let g=!0;if(e[_]===0&&!i&&(g=!1),e[_]===1&&!r&&(g=!1),g){let T=e[f].id,C=l[T];C===void 0&&(l[T]=s,C=s),t[f]=!!e[f],t[S]=C,t[m]=this._getMapTransformID(e.getUniform(m),e[_]),t[p]=e[p],t[_]=e[_]}}}}_updateMinOptions(t,e,s){let i=s===xr;t.litOptions.opacityShadowDither=i?e.opacityDither:e.opacityShadowDither,t.litOptions.linearDepth=i,t.litOptions.lights=[]}_updateMaterialOptions(t,e,s){let i=!!(e.useMetalness||e.specularMap||e.sphereMap||e.cubeMap||KY(e.specular)||e.specularityFactor>0&&e.useMetalness||e.enableGGXSpecular||e.clearCoat>0),r=!e.useMetalness||e.useMetalnessSpecularColor,a=i&&(e.specularTint||YY(e.specular)),o=i&&e.useMetalnessSpecularColor&&(e.specularityFactorTint||e.specularityFactor!==1),l=f=>f?f.format===Gr||f.type===Rn:!1,h=(f,u)=>Math.abs(f-u)<1e-4;t.specularTint=a,t.specularityFactorTint=o,t.metalnessTint=e.useMetalness&&e.metalness<1,t.glossTint=!0,t.diffuseEncoding=e.diffuseMap?.encoding,t.diffuseDetailEncoding=e.diffuseDetailMap?.encoding,t.emissiveEncoding=e.emissiveMap?.encoding,t.lightMapEncoding=e.lightMap?.encoding,t.packedNormal=l(e.normalMap),t.refractionTint=!h(e.refraction,1),t.refractionIndexTint=!h(e.refractionIndex,1/1.5),t.thicknessTint=e.useDynamicRefraction&&e.thickness!==1,t.specularEncoding=e.specularMap?.encoding,t.sheenEncoding=e.sheenMap?.encoding,t.aoMapUv=e.aoUvSet,t.aoDetail=!!e.aoDetailMap,t.diffuseDetail=!!e.diffuseDetailMap,t.normalDetail=!!e.normalMap,t.normalDetailPackedNormal=l(e.normalDetailMap),t.diffuseDetailMode=e.diffuseDetailMode,t.aoDetailMode=e.aoDetailMode,t.clearCoatGloss=!!e.clearCoatGloss,t.clearCoatPackedNormal=l(e.clearCoatNormalMap),t.iorTint=!h(e.refractionIndex,1/1.5),s.forcePassThroughSpecular&&(t.specularEncoding="linear",t.sheenEncoding="linear"),t.iridescenceTint=e.iridescence!==1,t.glossInvert=e.glossInvert,t.sheenGlossInvert=e.sheenGlossInvert,t.clearCoatGlossInvert=e.clearCoatGlossInvert,t.useSpecularColor=r,t.litOptions.separateAmbient=!1,t.litOptions.pixelSnap=e.pixelSnap,t.litOptions.ambientSH=!!e.ambientSH,t.litOptions.twoSidedLighting=e.twoSidedLighting,t.litOptions.occludeSpecular=e.occludeSpecular,t.litOptions.occludeSpecularFloat=e.occludeSpecularIntensity!==1,t.litOptions.useMsdf=!!e.msdfMap,t.litOptions.msdfTextAttribute=!!e.msdfTextAttribute,t.litOptions.alphaToCoverage=e.alphaToCoverage,t.litOptions.opacityFadesSpecular=e.opacityFadesSpecular,t.litOptions.opacityDither=e.opacityDither,t.litOptions.cubeMapProjection=e.cubeMapProjection,t.litOptions.occludeDirect=e.occludeDirect,t.litOptions.useSpecular=i,t.litOptions.useSpecularityFactor=(o||!!e.specularityFactorMap)&&e.useMetalnessSpecularColor,t.litOptions.enableGGXSpecular=e.enableGGXSpecular,t.litOptions.useAnisotropy=e.enableGGXSpecular&&(e.anisotropyIntensity>0||!!e.anisotropyMap),t.litOptions.fresnelModel=e.fresnelModel,t.litOptions.useRefraction=(e.refraction||!!e.refractionMap)&&(e.useDynamicRefraction||t.litOptions.reflectionSource!==gr),t.litOptions.useClearCoat=!!e.clearCoat,t.litOptions.useSheen=e.useSheen,t.litOptions.useIridescence=e.useIridescence&&e.iridescence!==0,t.litOptions.useMetalness=e.useMetalness,t.litOptions.useDynamicRefraction=e.useDynamicRefraction,t.litOptions.dispersion=e.dispersion>0,t.litOptions.shadowCatcher=e.shadowCatcher,t.litOptions.useVertexColorGamma=e.vertexColorGamma}_updateEnvOptions(t,e,s,i){t.litOptions.fog=e.useFog?i.fog:Mi,t.litOptions.gamma=i.shaderOutputGamma,t.litOptions.toneMap=e.useTonemap?i.toneMapping:Rf;let r=!1;if(e.envAtlas&&e.cubeMap?(t.litOptions.reflectionSource=Lf,t.litOptions.reflectionEncoding=e.envAtlas.encoding,t.litOptions.reflectionCubemapEncoding=e.cubeMap.encoding):e.envAtlas?(t.litOptions.reflectionSource=Df,t.litOptions.reflectionEncoding=e.envAtlas.encoding):e.cubeMap?(t.litOptions.reflectionSource=Mf,t.litOptions.reflectionEncoding=e.cubeMap.encoding):e.sphereMap?(t.litOptions.reflectionSource=TT,t.litOptions.reflectionEncoding=e.sphereMap.encoding):e.useSkybox&&s.envAtlas&&s.skybox?(t.litOptions.reflectionSource=Lf,t.litOptions.reflectionEncoding=s.envAtlas.encoding,t.litOptions.reflectionCubemapEncoding=s.skybox.encoding,r=!0):e.useSkybox&&s.envAtlas?(t.litOptions.reflectionSource=Df,t.litOptions.reflectionEncoding=s.envAtlas.encoding,r=!0):e.useSkybox&&s.skybox?(t.litOptions.reflectionSource=Mf,t.litOptions.reflectionEncoding=s.skybox.encoding,r=!0):(t.litOptions.reflectionSource=gr,t.litOptions.reflectionEncoding=null),e.ambientSH)t.litOptions.ambientSource=mp,t.litOptions.ambientEncoding=null;else{let a=e.envAtlas||(e.useSkybox&&s.envAtlas?s.envAtlas:null);a&&!e.sphereMap?(t.litOptions.ambientSource=_p,t.litOptions.ambientEncoding=a.encoding):(t.litOptions.ambientSource=gp,t.litOptions.ambientEncoding=null)}t.litOptions.skyboxIntensity=r,t.litOptions.useCubeMapRotation=r&&s._skyboxRotationShaderInclude}_updateLightOptions(t,e,s,i,r){if(t.lightMap=!1,t.lightMapChannel="",t.lightMapUv=0,t.lightMapTransform=0,t.litOptions.lightMapWithoutAmbient=!1,t.dirLightMap=!1,i&&(t.litOptions.noShadow=(i&Tc)!==0,(i&yc)!==0&&(t.lightMapEncoding=e.lightmapPixelFormat===ce?"rgbm":"linear",t.lightMap=!0,t.lightMapChannel="rgb",t.lightMapUv=1,t.lightMapTransform=0,t.litOptions.lightMapWithoutAmbient=!s.lightMap,(i&Ff)!==0&&(t.dirLightMap=!0),(i&Bf)!==0&&(t.litOptions.lightMapWithoutAmbient=!1))),s.useLighting){let a=[],o=i?i>>16:cs;t.litOptions.lightMaskDynamic=!!(o&cs),r&&(Lc.collectLights(Ce,r[Ce],a,o),e.clusteredLightingEnabled||(Lc.collectLights(We,r[We],a,o),Lc.collectLights(je,r[je],a,o))),t.litOptions.lights=a}else t.litOptions.lights=[];t.litOptions.lights.length===0&&!e.clusteredLightingEnabled&&(t.litOptions.noShadow=!0)}_getMapTransformID(t,e){if(!t)return 0;let s=this._mapXForms[e];s||(s=[],this._mapXForms[e]=s);for(let i=0;i{this[`_${e}`]=WT[e].value()}),this._uniformCache={}}copy(e){return super.copy(e),Object.keys(WT).forEach(s=>{this[s]=e[s]}),this._alphaDither=e._alphaDither,this.userAttributes=new Map(e.userAttributes),this}setAttribute(e,s){this.userAttributes.set(s,e)}_setParameter(e,s){fS.add(e),this.setParameter(e,s)}_setParameters(e){e.forEach(s=>{this._setParameter(s.name,s.value)})}_processParameters(e){let s=this[e];s.forEach(i=>{fS.has(i)||delete this.parameters[i]}),this[e]=fS,fS=s,fS.clear()}_updateMap(e){let s=`${e}Map`,i=this[s];if(i){this._setParameter(`texture_${s}`,i);let r=`${s}Transform`,a=this.getUniform(r);a&&this._setParameters(a)}}_allocUniform(e,s){let i=this._uniformCache[e];return i||(i=s(),this._uniformCache[e]=i),i}getUniform(e,s,i){return XL[e](this,s,i)}updateUniforms(e,s){let i=l=>this.getUniform(l,e,s);this._setParameter("material_ambient",i("ambient")),this._setParameter("material_diffuse",i("diffuse")),this._setParameter("material_aoIntensity",this.aoIntensity);let r=this.specular.r!==1||this.specular.g!==1||this.specular.b!==1,a=!this.specularMap||this.specularTint||r;this.useMetalness?((!this.metalnessMap||this.metalness<1)&&this._setParameter("material_metalness",this.metalness),a&&this._setParameter("material_specular",i("specular")),(!this.specularityFactorMap||this.specularityFactorTint||this.specularityFactor!==1)&&this._setParameter("material_specularityFactor",this.specularityFactor),this._setParameter("material_sheen",i("sheen")),this._setParameter("material_sheenGloss",this.sheenGloss),this._setParameter("material_refractionIndex",this.refractionIndex)):a&&this._setParameter("material_specular",i("specular")),this.enableGGXSpecular&&(this._setParameter("material_anisotropyIntensity",this.anisotropyIntensity),this._setParameter("material_anisotropyRotation",[Math.cos(this.anisotropyRotation*R.DEG_TO_RAD),Math.sin(this.anisotropyRotation*R.DEG_TO_RAD)])),this.clearCoat>0&&(this._setParameter("material_clearCoat",this.clearCoat),this._setParameter("material_clearCoatGloss",this.clearCoatGloss),this._setParameter("material_clearCoatBumpiness",this.clearCoatBumpiness)),this._setParameter("material_gloss",this.gloss),this._setParameter("material_emissive",i("emissive")),this._setParameter("material_emissiveIntensity",this.emissiveIntensity),this.refraction>0&&this._setParameter("material_refraction",this.refraction),this.dispersion>0&&this._setParameter("material_dispersion",this.dispersion),this.useDynamicRefraction&&(this._setParameter("material_thickness",this.thickness),this._setParameter("material_attenuation",i("attenuation")),this._setParameter("material_invAttenuationDistance",this.attenuationDistance===0?0:1/this.attenuationDistance)),this.useIridescence&&(this._setParameter("material_iridescence",this.iridescence),this._setParameter("material_iridescenceRefractionIndex",this.iridescenceRefractionIndex),this._setParameter("material_iridescenceThicknessMin",this.iridescenceThicknessMin),this._setParameter("material_iridescenceThicknessMax",this.iridescenceThicknessMax)),this._setParameter("material_opacity",this.opacity);let o=this._opacity>0?this.alphaDither/this._opacity:1;this._setParameter("material_alphaDitherScale",o),this.opacityFadesSpecular===!1&&this._setParameter("material_alphaFade",this.alphaFade),this.occludeSpecular&&this._setParameter("material_occludeSpecularIntensity",this.occludeSpecularIntensity),this.cubeMapProjection===gT&&this._setParameter(i("cubeMapProjectionBox"));for(let l in Dc)this._updateMap(l);this.ambientSH&&this._setParameter("ambientSH[0]",this.ambientSH),this.normalMap&&this._setParameter("material_bumpiness",this.bumpiness),this.normalMap&&this.normalDetailMap&&this._setParameter("material_normalDetailMapBumpiness",this.normalDetailMapBumpiness),this.heightMap&&this._setParameter("material_heightMapFactor",i("heightMapFactor")),this.envAtlas&&this.cubeMap?(this._setParameter("texture_envAtlas",this.envAtlas),this._setParameter("texture_cubeMap",this.cubeMap)):this.envAtlas?this._setParameter("texture_envAtlas",this.envAtlas):this.cubeMap?this._setParameter("texture_cubeMap",this.cubeMap):this.sphereMap&&this._setParameter("texture_sphereMap",this.sphereMap),this._setParameter("material_reflectivity",this.reflectivity),this._processParameters("_activeParams"),super.updateUniforms(e,s)}updateEnvUniforms(e,s){!(this.envAtlas||this.cubeMap||this.sphereMap)&&this.useSkybox&&(s.envAtlas&&s.skybox?(this._setParameter("texture_envAtlas",s.envAtlas),this._setParameter("texture_cubeMap",s.skybox)):s.envAtlas?this._setParameter("texture_envAtlas",s.envAtlas):s.skybox&&this._setParameter("texture_cubeMap",s.skybox)),this._processParameters("_activeLightingParams")}getShaderVariant(e){let{device:s,scene:i,pass:r,objDefs:a,sortedLights:o,cameraShaderParams:l}=e;this.updateEnvUniforms(s,i);let h=Ns.get(s).getByIndex(r),f=r===ta||r===xr||h.isShadow,u=f?GT.optionsContextMin:GT.optionsContext;u.defines=Se.getCoreDefines(this,e),f?this.shaderOptBuilder.updateMinRef(u,i,this,a,r,o):this.shaderOptBuilder.updateRef(u,i,l,this,a,r,o),this.useFog||u.defines.set("FOG","NONE"),u.defines.set("TONEMAP",bf[u.litOptions.toneMap]),this.onUpdateShader&&(u=this.onUpdateShader(u));let d=new sa(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),p=Ji(s);return p.register("standard",GT),p.getProgram("standard",u,d,this.userId)}destroy(){for(let e in this._assetReferences)this._assetReferences[e]._unbind();this._assetReferences=null,super.destroy()}};n(it,"TEXTURE_PARAMETERS",qf),n(it,"CUBEMAP_PARAMETERS",hS);var XT=(c,t)=>{XL[c]=t},jw=(c,t,e,s)=>{Object.defineProperty(it.prototype,c,{get:s||function(){return this[`_${c}`]},set:e}),WT[c]={value:t}},jY=c=>{let t=`_${c.name}`,e=c.dirtyShaderFunc||(()=>!0),s=function(i){let r=this[t];r!==i&&(this._dirtyShader=this._dirtyShader||e(r,i),this[t]=i)};jw(c.name,()=>c.defaultValue,s,c.getterFunc)},qY=c=>{let t=`_${c.name}`,e=c.dirtyShaderFunc||(()=>!0),s=function(i){let r=this[t];r.equals(i)||(this._dirtyShader=this._dirtyShader||e(r,i),this[t]=r.copy(i))};jw(c.name,()=>c.defaultValue.clone(),s,c.getterFunc)},Er=c=>c.defaultValue&&c.defaultValue.clone?qY(c):jY(c);function Ht(c,t="rgb",e=!0,s=0){Dc[c]=t.length||-1,Er({name:`${c}Map`,defaultValue:null,dirtyShaderFunc:(l,h)=>!!l!=!!h||l&&(l.type!==h.type||l.format!==h.format)}),Er({name:`${c}MapTiling`,defaultValue:new B(1,1)}),Er({name:`${c}MapOffset`,defaultValue:new B(0,0)}),Er({name:`${c}MapRotation`,defaultValue:0}),Er({name:`${c}MapUv`,defaultValue:s}),t&&(Er({name:`${c}MapChannel`,defaultValue:t}),e&&(Er({name:`${c}VertexColor`,defaultValue:!1}),Er({name:`${c}VertexColorChannel`,defaultValue:t})));let i=`${c}MapTiling`,r=`${c}MapOffset`,a=`${c}MapRotation`,o=`${c}MapTransform`;XT(o,(l,h,f)=>{let u=l[i],d=l[r],p=l[a];if(u.x===1&&u.y===1&&d.x===0&&d.y===0&&p===0)return null;let m=l._allocUniform(o,()=>[{name:`texture_${o}0`,value:new Float32Array(3)},{name:`texture_${o}1`,value:new Float32Array(3)}]),_=Math.cos(p*R.DEG_TO_RAD),S=Math.sin(p*R.DEG_TO_RAD),g=m[0].value;g[0]=_*u.x,g[1]=-S*u.y,g[2]=d.x;let T=m[1].value;return T[0]=S*u.x,T[1]=_*u.y,T[2]=1-u.y-d.y,m})}function Mp(c,t){Er({name:c,defaultValue:t,getterFunc:function(){return this._dirtyShader=!0,this[`_${c}`]}}),XT(c,(e,s,i)=>{let r=e._allocUniform(c,()=>new Float32Array(3)),a=e[c];return HT.linear(a),r[0]=HT.r,r[1]=HT.g,r[2]=HT.b,r})}function vt(c,t,e){Er({name:c,defaultValue:t,dirtyShaderFunc:(s,i)=>(s===0||s===1)!=(i===0||i===1)}),XT(c,e)}function uS(c,t){Er({name:c,defaultValue:null,dirtyShaderFunc:(e,s)=>!!e==!!s}),XT(c,t)}function lt(c,t){Er({name:c,defaultValue:t})}function $Y(){Mp("ambient",new F(1,1,1)),Mp("diffuse",new F(1,1,1)),Mp("specular",new F(0,0,0)),Mp("emissive",new F(0,0,0)),Mp("sheen",new F(1,1,1)),Mp("attenuation",new F(1,1,1)),vt("emissiveIntensity",1),vt("specularityFactor",1),vt("sheenGloss",0),vt("gloss",.25),vt("aoIntensity",1),vt("heightMapFactor",1,(s,i,r)=>s.heightMapFactor*.025),vt("opacity",1),vt("alphaFade",1),Er({name:"alphaDither",defaultValue:null,dirtyShaderFunc:()=>!1,getterFunc:function(){return this._alphaDither??this._opacity}}),vt("alphaTest",0),vt("bumpiness",1),vt("normalDetailMapBumpiness",1),vt("reflectivity",1),vt("occludeSpecularIntensity",1),vt("refraction",0),vt("refractionIndex",1/1.5,(s,i,r)=>Math.max(.001,s.refractionIndex)),vt("dispersion",0),vt("thickness",0),vt("attenuationDistance",0),vt("metalness",1),vt("anisotropyIntensity",0),vt("anisotropyRotation",0),vt("clearCoat",0),vt("clearCoatGloss",1),vt("clearCoatBumpiness",1),vt("aoUvSet",0,null),vt("iridescence",0),vt("iridescenceRefractionIndex",1/1.5),vt("iridescenceThicknessMin",0),vt("iridescenceThicknessMax",0),uS("ambientSH"),uS("cubeMapProjectionBox",(s,i,r)=>{let a=s._allocUniform("cubeMapProjectionBox",()=>[{name:"envBoxMin",value:new Float32Array(3)},{name:"envBoxMax",value:new Float32Array(3)}]),o=s.cubeMapProjectionBox.getMin(),l=a[0].value;l[0]=o.x,l[1]=o.y,l[2]=o.z;let h=s.cubeMapProjectionBox.getMax(),f=a[1].value;return f[0]=h.x,f[1]=h.y,f[2]=h.z,a}),lt("specularTint",!1),lt("specularityFactorTint",!1),lt("useMetalness",!1),lt("useMetalnessSpecularColor",!1),lt("useSheen",!1),lt("enableGGXSpecular",!1),lt("occludeDirect",!1),lt("opacityFadesSpecular",!0),lt("occludeSpecular",Bo),lt("fresnelModel",Sc),lt("useDynamicRefraction",!1),lt("cubeMapProjection",pp),lt("useFog",!0),lt("useLighting",!0),lt("useTonemap",!0),lt("useSkybox",!0),lt("forceUv1",!1),lt("pixelSnap",!1),lt("twoSidedLighting",!1),lt("nineSlicedMode",void 0),lt("msdfTextAttribute",!1),lt("useIridescence",!1),lt("glossInvert",!1),lt("sheenGlossInvert",!1),lt("clearCoatGlossInvert",!1),lt("opacityDither",Bi),lt("opacityShadowDither",Bi),lt("shadowCatcher",!1),lt("vertexColorGamma",!1),Ht("diffuse"),Ht("specular"),Ht("emissive"),Ht("thickness","g"),Ht("specularityFactor","g"),Ht("normal",""),Ht("metalness","g"),Ht("gloss","g"),Ht("opacity","a"),Ht("refraction","g"),Ht("height","g",!1),Ht("ao","g"),Ht("light","rgb",!0,1),Ht("msdf",""),Ht("diffuseDetail","rgb",!1),Ht("normalDetail",""),Ht("aoDetail","g",!1),Ht("clearCoat","g"),Ht("clearCoatGloss","g"),Ht("clearCoatNormal",""),Ht("sheen","rgb"),Ht("sheenGloss","g"),Ht("iridescence","g"),Ht("iridescenceThickness","g"),Ht("anisotropy",""),lt("diffuseDetailMode",ST),lt("aoDetailMode",ST),uS("cubeMap"),uS("sphereMap"),uS("envAtlas");let c=function(){return this._prefilteredCubemaps},t=function(s){let i=this._prefilteredCubemaps;s=s||[];let r=!1,a=!0;for(let o=0;o<6;++o){let l=s[o]||null;i[o]!==l&&(i[o]=l,r=!0),a=a&&!!i[o]}r&&(a?this.envAtlas=bc.generatePrefilteredAtlas(i,{target:this.envAtlas}):this.envAtlas&&(this.envAtlas.destroy(),this.envAtlas=null),this._dirtyShader=!0)},e=[null,null,null,null,null,null];jw("prefilteredCubemaps",()=>e.slice(),t,c)}$Y();var ZY="muPIHORMLNDCz4DxVR/ZvYfAUVEFR47KRIC4nwAAAAAP7WxlhD6Ci+2HCe7BF8jRAPZwdH2UPpI5PdLCJdkvG4UTaNDJ/0crAzne71GCrb4kbdMjjCEGzdX6fNxDMLJq5xkeoIVTdfiZkodEeArmZmp/FQzFjD4x8iOW7Dg64n+3mWqyEwLxXT8zoJXfbw8QJKDCaarUYyTlMzNFHbgUe9IQV7g4YOgtSKpIFZJ0qERm7u4PpmiF89ktHWCywaGmD6h+hfh2/Zd8KYlKqqo4Cem4T42bT/Z9FpCQF1hhSjfBzZ5XFn/y3jegWC6u86KuELRundQS/1Rp+XuKKGIgRv3CvP5y749yqLlFO495JOT3+f2CXgd71npU0/KjjpkZucbJ5m78IVyuSrSozc9jgBUhDrz0hFsyb7LFUH9//wJbBgLdNWJZObfKxrNt8TliLA9w9sXFv6g26iXpf6r/BqcAusj/QzGBZuoUGeEtw8BCXCZ3jUiw4hvM18ZVqlUD3C40LAFXW6FRjuAZGRNstb0/qVk4skwyT+MHrvRorI4rKHVMWZmKyAkzL/78u/9pMQuX14pZN50b2PHn6fRxeaCQLsfT4dpvIkWWFuFVENZIh+8xgR6lU+85W0PPdAu1j99kcCG40JBQa4JMyRzq6qriOBLtqF87vpCJan0WEduVr/mOYkS00urVA0mA6M3031+GmGmW48PaJDYOEIb3bIXWPaLoAOEinX1TN3+/vwhG6nqJu0TdHpedS7QsGZIoxH3nQYYjQP1jmbahlbNngw5ogsGk1y50XZyUmQBY+/JBJ3Unu4dApm+WmPwHPU9gLb+4mHh4BiY6M86pq+WeTyWdI3s0CXPEtHGXZ8zMZgUoyRomBi1VdazzuN+WOmQ9Pa0Z0tlNopUi8AJ4x2Xn4mmOKEbXLxlbVsWu8XhuDGYFOGCRVdSqDPXrHU5SDdUlti3k5///SBwzTMwK3L4a1H7w4lnpEas6////AfX8asyIBfeFXVJ3tgvxQ/blZuUKyIODIfr/UzdWNu7pciLBpdZRZ4pIfZ1R6szq+XNxkGG///8EZFpu7VHAhFWqHEOrB9unw+YQa5o8/9IR/V5/zq+986rJSyfgJKt2u9hxU1wzyQWPjJGvzG9+eWWxGFOHVKqI4jBQALwZZswesnvZ2UmmkEXdiRpz8B+oWE7PY70ZTMndisYSXg2TqoI+3y9BxbnY2Y4EfbdcRhAvG59NqDENNYbxKvK5HJfPG5M+Wi2AcpLVJrD6caiEOzgSoVNSgQK8fm2M3zGcF4xtClv/8Hs9oD7C3jitTATYNQxmKqKf1LhIxzf1bmfiNn7UKFmcJu4sLqVLwxGSue3taBEyknkw5hXTsUCvqmmL/f8n/w0giR7Hu/9EHvpkz3yuu64TioMkzdTJ30i0+hFnQqW1+v9mMwq+z9qGX0UFu9MomvVG2xod6vc12AAAAACq7sGa5qptFR0jF3nQt/D+7PibKYahaxP3hEixPbGi9nwNf2LAa7LkEZRKxzXeCD64Xpii5n+8Kpg8eHIv7AWXZltgMoGltmoJ0XGdOCL8WkzphvR9N2o3ARSZ42l5e5Pe4B58MCRlP3EKv+mcloknH+fto5BWsmEutW6KvjOVsznFCktkSczVk4aGvj9VXlRcLeDoKG8RkBgdcNG2bf8HUL4MT2DM+ar7NImJhKpxakX4Vk0CnP+/XNhl5UsP0lXgeZXPoDBMSW5An+DXlTCO5FQGwSPYwHLKYVIimEdAoVe49rQLaaNcye5LxU2/c5TijTgJtD5eQQIe1snxauj5jZsxJBUJdoP/zqpjqv8qBruoPsVsP8N44PCUW5Dd0DzqjSS/Dl5mI9cn1w2ndN/0KAEm1QAAAACwu6KM/083IBbH5bPa/9oHUwcU8I9v3j6/v18QYammrf+P6VL///8BrpuM3fOLCxaLNOFNF1zPbPYTP65ni6njft4eVcyrVXRQFrs52tr35StiSp55edVDCBC0H5rIfac6nzUwxQSt7y15QoKb+5zebEQUmVbrPjXuUa19Ey7sqXMiSUKHaw72PJKDdrutJoQr3u6lEYJ8K0MakWKj9zjTFi4X94TsKYco0GrLeB60M6D8M/80rhXUW8iMequg8y5F838WI0+gp3GBN5Kj/xIOxTWQuUaPV/LwvARr1VH93BFgGZR1MFW0Ua30GbYmdnAgo9VWy8SQtpDUgGE2r2zq2eTEMCL7sMKmE1hchVhuF/TCq9iXKEm86kzOf3Rp9ZnCxbpDUj+FKNxVyXe6pVZkRXv/m95SnB/EB8aME29N85MtAcDoXWlor8De2Q5Dg1tar+8wgiZufbMam81j//ASUohoR/zSh2KG4bvT6mkIPz6C5/98DC3LaWlaEZ1zA5JORZRu6J/a0GY285sEYzw71YqOT1ihAG0z5SDt1xNiDQWZdFpndArp6xWhqSDkRb4kSJEHb9liPvw7uLV/6i5MVf//A9Qjr8xkAEUh+KDI+zdtJ68d6MBOktg1iyp/SCq8O9f5pbamn1VVVQPRTWqNBvhQKa07s6P0lc9Luu/3gw4HeyOUfz8MxMwV4UQhua+t9cr4bz/nIB2wnDSK1K7I94M+s6C84htaX/CNlMQUSs2KJO+yaebfTbkNX5yWcqEJevo0vbKUiETuFXiL019A3E+lmsyZMwXrXLLiQAZ5t9+jI3JobhJTMiDH5ZOQ+8Jau5555NMjHSscP9qCVaa40doh+1a3Ukf6jqBmLddgh79/fwTfCyqiuldNkUoy+nUp+4nerwg0OjtGv2x485PJOJvUEokNhYIdWjpx7BWk0VZGWOp3jSFTJ2bnu6KCduZtG/UcBC9RZ3W/jMSfSMw4Etr/DoD/XYP2V5Ovw+YoM3F5g2dGLdvuG6ZkVGLE6Dk5Zr+sdSyGliJP1y2OFf/KFO0RWO+3gsGhesTnfZVpTd8/HwgO216gwaqo+vY3TljfJWowY+i0p0Os4SLn/1wLqDHMlszggmT/D8MRFzs+pLv6LNJSsNZ/r41mWi/rF6ZcKp/yzJdK0VU44hskq3RGpgO6mIpJDsf/mZkFrz0yYOMLbuaj/wp1v7JMFM5eqvBhmTd7U8frQAtHtys4zgpjZmzUhOVTfNNLifElGXADlqHGKrkBT/nYwX8ZRm3RjvyPvjKyEqEGKUpVnvOGx+NKPHiWM//ZDpDVGvvrjmk8RPF/wiYZD3+Us8YCXjrVOfjdd1UPAfjLp8jgSn4me7DPTpz1Ggy9XL80guFO7ECT10AvILKfD18Qx+KY/f8aRqu0oOO8hfKRFZa9PUJwCsp6VdZz6LFkm2b9Pl2LIifCwzRy7TpdG2uAtOxP2OemY26bJMa9ZGSLIRlMsgpDpnDJwd0oa5pQ13x1hrHf52HpulUWonGWsfXZbSQYKu9bnEN76ciQih0opN3deDVrbrxorfVlnCmL1R9zq3ePGWIv21c7pW8kEiFTM5JX8dAw867s/60cf79/BH+MDFCZBHlz1L+qGOJf/1txhhmrf3//As+RIJwevDb+fgNXVeHw67QptZegayhrEwr5Gy+EPo1RLaMtPbqOZYoVzXzwzjMFWZxyUG9YUIf6////AQWy84iAygLk9COtXt92+0mT/xg0zMzMBeLkb8y9SL2TDXgSX422hDgpGNLJyuPioA+YJ91G8znrpNqHkwYyscaJDEc9Vc+j4cXle3hvcd2JqDQH2lBZxDn6mUTs0b75raMvbs727codX01Anj8f3wir9P2xQaQ22v/TxCMglKDFoTjaP01XTLgxnTvPv02JgEUrW6UDgOnobFpLdvKdlypgIzPcq14fgXU5tvVW0FEs7VRlsG1IyA69fN4n+awHhT34cE+xUvdj86C8LgAsFheTjI9Ht9EyYAAAAAAVBVKRx2wLgUTI0/2QfyJo2riRw3JDqzEShmx/Lifo6mRkQVbS7X53t+EvKxcXogtdts31e9MRHdcHgsA8rt4/mt2unlzQ/wsU8Gu7+W6Oj7eD8EQdDp5XlCsVaS/AV/t5ZpPOHR3rGpyAJe9IPV+xMrBL1Oz/8MQhFs31h0N1cVnq371uqIJYHyafKH1jteAK3VpMXBcuC+yt0ZeKyRUY4QhdrJJ4tJ1wg3Hu6kDsbovxupTMkGdRrm8oZSoYPbJ+PwH/xotgTdkA1205vUEfnqkI04T/fnnd1fiZW5AwNcggd7fi4j5zasmcntZexIxqFZQMzMJpfndmI5jn17cgn5EV5t9XN0C///8Q9wlJpMGXdoiaMTG2sVyHQsn8mWRISCLNG777S0OuDRP2GlLcJ2UeOg7Fo8hTNPeJ//iTJhyqxhKRUntdXOihq2wfKfH///8B0GGrwT+fSOQRdctKxjjGCSS11d6BlQ9BDfE0J6Z25FaNTKGpFKNCMr2G/041KpWwBLVe1k08vncseQbKZdXi8x1t9XA45U/Wd43D9wAh3Tal0aiLVzGPusOZ1F+W3TWoqlX/A95+dNef11TsuGful+ctGssldk3fqpfqh+43XTxL42+leSHoF/dWHYGX6maqUEuLX7UB+r/6Llr4LKocbVIeu+hB9QTPfz9fCP8RyWmX4SmbhMFsNtCijV7lVcwejLKlvl0GfCndnWV7/39VBrtTRuUx92oke3GBgKkC5fdGK0YvNK+xenKaDmsHDjNFUM3NMz3ZiXXFuLgojosPVCDEl2W5BjX3Ms+j0GSqACHmh0+RPWyuNm/Qe8vFf9AW7N1uRaxWirrUytqEJnJ4/Flm8hSoiZ2NQBsS6w/yQlC4gCaFo8q4nyY6AFdo4hiwhBXzbNKKvZvktCjSCukRR/BbYVbNwZi2Yh3hGodEacLW8qijiWJODf0P2bhfaiPspPT4lYJBgi/KfcFwCfvyUIgkJOv///8CG/JEepRBLaMFE+2TgrqsJXOVOWHt6g/bFwVLLMVBsMR50dis/39/AlBX+/rMTJkUQrnlxpR2iu0Tp8tATkRYGmDIrcAiRP8PjoWIlb7/0ecTdSCE9Y58+a+n/FovJQTVF4F2jAxMZhTgrM/KVS5BQu6bVbkWY5HXnxRshks3urDdW4RkWp4M4TeLmFK5KF/uHkkiO5Kv96RioH984v/CSDBnG+BwlnU9B+o7Y+0X0Nob+0pLsStxjvPXMy2eCpzhOWV4XbObBHN4UE2sLQ/DIqXhOzxVf38GlTi6aG7EnePO7TRJm9yOfUUcqq1I2iQHrVDqn3TUNRi/lMw8KbMW/3/nqCz/Ef8PoW5Qxcz2yHR/f78EPB2Stbd+ZFmfNTUYILzsb9YNhpaHcaymYrBiNHmFE3Y4ccYJ25Prqm7zHobGHED8/93ZNlWro9vcKivGZs31UiK1k5zjUhexUgbqJb+fUTjxce/7Zly8a5KMC1fX5nfjPgibdvzbXV1jRT2asXvmSAusaLdq1TSIJ8fXINk5AtT34EWPAsfP9IFQqM5K11O6saoHJA==",il=null,YL=()=>{if(!il){let c=atob(ZY);il=Uint8Array.from(c,t=>t.charCodeAt(0))}},KL=()=>(YL(),il),Op=class{constructor(t=0){n(this,"seed",0);this.seed=t*4,YL()}_next(){this.seed=(this.seed+4)%il.length}value(){return this._next(),il[this.seed]/255}vec4(t=new Q){return this._next(),t.set(il[this.seed],il[this.seed+1],il[this.seed+2],il[this.seed+3]).mulScalar(1/255)}};var QY=[new x(-1,0,0),new x(1,0,0),new x(0,-1,0),new x(0,1,0),new x(0,0,-1),new x(0,0,1)],YT=class{constructor(){n(this,"colors",new Float32Array(18))}update(t,e){let s=this.colors,{r:i,g:r,b:a}=t;for(let o=0;o<6;o++)s[o*3]=i,s[o*3+1]=r,s[o*3+2]=a;for(let o=0;o{let i=new Z(c,{name:`${t}${e}`,width:e,height:e,format:ce,addressU:0,addressV:0,type:Gt,magFilter:0,minFilter:0,anisotropy:1,mipmaps:!1});return i.lock().set(s),i.unlock(),i},e6=new et,jL=c=>e6.get(c,()=>{let t=KL(),e=Math.sqrt(t.length/4);return JY(c,"BlueNoise",e,t)});var Xo=class c{constructor(t,e){this.texture=t,this.cached=!1,this.renderTargets=e}destroy(){this.texture&&(this.texture.destroy(),this.texture=null);let t=this.renderTargets;for(let e=0;er.length===a.length&&r.every((o,l)=>o===a[l]))(s,this.atlasSplit)){this.version++,this.slots.length=0,this.atlasSplit.length=0,this.atlasSplit.push(...s);let r=this.atlasSplit[0];if(r>1){let a=1/r;for(let o=0;o1)for(let u=0;uo.size-a.size)}}collectLights(t,e){let s=e.cookiesEnabled,i=e.shadowsEnabled,r=!1,a=!1,o=t6;return o.length=0,(s||i)&&(h=>{for(let f=0;ff.maxScreenSize-h.maxScreenSize),r&&this.allocateShadowAtlas(this.shadowAtlasResolution,e.shadowType),a&&this.allocateCookieAtlas(this.cookieAtlasResolution),(r||a)&&this.subdivide(o.length,e),o}setupSlot(t,e){t.atlasViewport.copy(e);let s=t.numShadowFaces;for(let i=0;i0){let i=this.slots;for(let o=0;o{t.forEach(e=>{e.destroy()})}),this.cache.clear()}getKey(t){let e=t._type===We,s=t._shadowType,i=t._shadowResolution;return`${e}-${s}-${i}`}get(t,e){let s=this.getKey(e),i=this.cache.get(s);if(i&&i.length)return i.pop();let r=Xo.create(t,e);return r.cached=!0,r}add(t,e){let s=this.getKey(t),i=this.cache.get(s);i?i.push(e):this.cache.set(s,[e])}};var Fp=class extends yt{constructor(t,e,s,i,r){super(t),this.requiresCubemaps=!1,this.shadowRenderer=e,this.light=s,this.face=i,this.applyVsm=r,this.shadowCamera=e.prepareFace(s,null,i),e.setupRenderPass(this,this.shadowCamera,!0)}execute(){this.shadowRenderer.renderFace(this.light,null,this.face,!1)}after(){this.applyVsm&&this.shadowRenderer.renderVsm(this.light,this.shadowCamera)}};var qT=class{constructor(t,e){n(this,"shadowLights",[]);n(this,"renderer");n(this,"shadowRenderer");n(this,"device");this.renderer=t,this.shadowRenderer=e,this.device=t.device}cull(t,e,s=null){let i=this.renderer.scene.clusteredLightingEnabled;t.visibleThisFrame=!0,i||t._shadowMap||(t._shadowMap=Xo.create(this.device,t));let r=t._type,a=r===je?1:6;for(let o=0;oi&&(i=a)}return $w.min=s,$w.max=i,$w}var QT=class{constructor(t,e){n(this,"renderer");n(this,"shadowRenderer");n(this,"device");this.renderer=t,this.shadowRenderer=e,this.device=t.device}cull(t,e,s,i=null){t.visibleThisFrame=!0,t._shadowMap||(t._shadowMap=Xo.create(this.device,t));let r=s._nearClip;this.generateSplitDistances(t,r,Math.min(s._farClip,t.shadowDistance));let a=t.shadowUpdateOverrides;for(let o=0;oS&&(S=L)}let g=f.right,T=f.up,C=f.forward,v=.25*t._shadowResolution/S,E=Math.ceil(al.dot(T)*v)/v,y=Math.ceil(al.dot(g)*v)/v,P=T.mulScalar(E),A=g.mulScalar(y),w=al.dot(C),I=C.mulScalar(w);al.add2(P,A).add(I),f.setPosition(al),f.translateLocal(0,0,1e6),h.nearClip=.01,h.farClip=2e6,h.orthoHeight=S,this.renderer.updateCameraFrustum(h),this.shadowRenderer.cullShadowCasters(e,t,l.visibleCasters,h,i);let D=1<1&&(!this.renderer.scene.clusteredLightingEnabled||t._type===Ce)&&this.applyVsmBlur(t,e)}getVsmBlurShader(t,e){let s=this.blurVsmShader,i=s[t][e];if(!i){this.blurVsmWeights[e]=a6(e);let r=new Map;r.set("{SAMPLES}",e),t===1&&r.set("GAUSS",""),i=Se.createShader(this.device,{uniqueName:`blurVsm${t}${e}`,attributes:{vertex_position:ee},vertexChunk:"fullscreenQuadVS",fragmentChunk:"blurVSMPS",fragmentDefines:r}),s[t][e]=i}return i}applyVsmBlur(t,e){let s=this.device;s.setBlendState(Oe.NOBLEND);let a=t.getRenderData(t._type===Ce?e:null,0).shadowCamera.renderTarget,o=this.renderer.shadowMapCache.get(s,t),l=o.renderTargets[0],h=t.vsmBlurMode,f=t._vsmBlurSize,u=this.getVsmBlurShader(h,f);pS.z=t._shadowResolution-2,pS.w=pS.z,this.sourceId.setValue(a.colorBuffer),$f[0]=1/t._shadowResolution,$f[1]=0,this.pixelOffsetId.setValue($f),h===Kg&&this.weightId.setValue(this.blurVsmWeights[f]),Qt(s,l,u,null,pS),this.sourceId.setValue(l.colorBuffer),$f[1]=$f[0],$f[0]=0,this.pixelOffsetId.setValue($f),Qt(s,a,u,null,pS),this.renderer.shadowMapCache.add(t,o)}initViewBindGroupFormat(){this.device.supportsUniformBuffers&&!this.viewUniformFormat&&(this.viewUniformFormat=new Xe(this.device,[new Y("matrix_viewProjection",as)]),this.viewBindGroupFormat=new Ue(this.device,[new Qe(Hn,Xi|Yi)]))}frameUpdate(){this.initViewBindGroupFormat()}};var Zf=class extends Nt{constructor(e){super(e);n(this,"children",[]);this.name="FramePassMultiView"}addChild(e){this.children.push(e)}render(){if(!this.enabled)return;let e=this.device,s=e.xrSubImages,i=s?.length??0,r=this.children,a=r.length;if(i===0){for(let u=0;u{t.destroy()}),this._allocated.length=0}get count(){return this._allocated.length}get empty(){if(!this._empty){let t=new sl(this.device);t.name="ClusterEmpty",t.update([]),this._empty=t}return this._empty}_assignClustersForPass(t){let e=t.renderActions;if(!e)return;let s=e.length;for(let i=0;is.destroy()),JT.length=0}update(t,e){this.assign(t),this._clusters.forEach(s=>{let i=s.layer;s.lightClusters.update(i.clusteredLightsSet,e)})}};var Oc=new Q,Qw=[],ty=class c extends yt{constructor(e,s){super(e);n(this,"_quadRenderer2D",null);n(this,"_quadRendererCube",null);n(this,"_filteredLights",[]);n(this,"_forceCopy",!1);n(this,"_evtDeviceRestored",null);this._cubeSlotsOffsets=s,this.requiresCubemaps=!1,this.blitTextureId=e.scope.resolve("blitTexture"),this.invViewProjId=e.scope.resolve("invViewProj"),this._evtDeviceRestored=e.on("devicerestored",this.onDeviceRestored,this)}destroy(){this._quadRenderer2D?.destroy(),this._quadRenderer2D=null,this._quadRendererCube?.destroy(),this._quadRendererCube=null,this._evtDeviceRestored?.off(),this._evtDeviceRestored=null}static create(e,s){let i=new c(e.device,s);return i.init(e),i.colorOps.clear=!1,i.depthStencilOps.clearDepth=!1,i}onDeviceRestored(){this._forceCopy=!0}update(e){let s=this._filteredLights;this.filter(e,s),this.executeEnabled=s.length>0}filter(e,s){for(let i=0;i1?this.quadRendererCube:this.quadRenderer2D;l>1&&this.initInvViewProjMatrices(),this.blitTextureId.setValue(o.cookie);for(let f=0;f1){let u=Oc.z/3,d=i[f];Oc.x+=u*d.x,Oc.y+=u*d.y,Oc.z=u,Oc.w=u,this.invViewProjId.setValue(Qw[f].data)}Oc.mulScalar(s),h.render(Oc)}}r.length=0}};var Bp=class extends yt{constructor(t,e,s){super(t),this.requiresCubemaps=!1,this.shadowRenderer=e,this.shadowRendererLocal=s}update(t){let e=this.shadowRendererLocal.shadowLights,s=this.shadowRendererLocal.prepareLights(e,t),i=e.length;this.enabled=i>0,i&&this.shadowRenderer.setupRenderPass(this,s,!1)}execute(){let t=this.shadowRendererLocal.shadowLights,e=t.length;for(let s=0;s0){let _=e?e.width:this.device.width,S=e?e.height:this.device.height,g=tM[this.device.renderVersion%tM.length];d=u*(g.x*2-1)/_,p=u*(g.y*2-1)/S,l=l6.copy(l),l.data[8]=d,l.data[9]=p,h=c6.copy(h),h.data[8]=d,h.data[9]=p,this.blueNoiseJitterVersion!==this.device.renderVersion&&(this.blueNoiseJitterVersion=this.device.renderVersion,this.blueNoise.vec4(this.blueNoiseJitterVec))}let m=u>0?this.blueNoiseJitterVec:Q.ZERO;if(this.blueNoiseJitterData[0]=m.x,this.blueNoiseJitterData[1]=m.y,this.blueNoiseJitterData[2]=m.z,this.blueNoiseJitterData[3]=m.w,this.blueNoiseJitterId.setValue(this.blueNoiseJitterData),this.projId.setValue(l.data),this.projSkyboxId.setValue(h.data),t.calculateTransform)t.calculateTransform(Fc,xp);else{let _=t._node.getPosition(),S=t._node.getRotation();Fc.setTRS(_,S,x.ONE)}this.viewInvId.setValue(Fc.data),Up.copy(Fc).invert(),this.viewId.setValue(Up.data),JL.setFromMat4(Up),this.viewId3.setValue(JL.data),Yo.mul2(l,Up),this.viewProjId.setValue(Yo.data),t._storeShaderMatrices(Yo,d,p,this.device.renderVersion),this.flipYId.setValue(s?-1:1),this.dispatchViewPos(t._node.getPosition()),t.frustum.setFromMat4(Yo)}this.tbnBasis.setValue(s?-1:1),this.cameraParamsId.setValue(t.fillShaderParams(this.cameraParams));let r=t.xr?.session?t.xr.views.list[0]:null,a=r?r.viewport.z:e?e.width:this.device.width,o=r?r.viewport.w:e?e.height:this.device.height;return a*=t.rect.z,o*=t.rect.w,this.viewportSize[0]=a,this.viewportSize[1]=o,this.viewportSize[2]=1/a,this.viewportSize[3]=1/o,this.viewportSizeId.setValue(this.viewportSize),this.exposureId.setValue(this.scene.physicalUnits?t.getExposure():this.scene.exposure),i}clear(t,e,s,i){let r=(e??t._clearColorBuffer?1:0)|(s??t._clearDepthBuffer?2:0)|(i??t._clearStencilBuffer?4:0);if(r){let a=this.device,o=t._clearColor;mS[0]=o.r,mS[1]=o.g,mS[2]=o.b,mS[3]=o.a,iy.depth=t._clearDepth,iy.stencil=t._clearStencil,iy.flags=r,a.clear(iy)}}setupCullModeAndFrontFace(t,e,s){let i=s.material,r=e*s.flipFacesFactor*s.node.worldScaleSign,a=i.frontFace;r<0&&(a=a===0?1:0),this.device.setCullMode(t?i.cull:0),this.device.setFrontFace(a)}setupCullMode(t,e,s){this.setupCullModeAndFrontFace(t,e,s)}updateCameraFrustum(t){if(t.xr&&t.xr.views.list.length){let s=t.xr.views.list;Yo.mul2(s[0].projMat,s[0].viewOffMat),t.frustum.setFromMat4(Yo);for(let i=1;i0)&&this.alphaTestId.setValue(e.alphaTest)}updateCpuSkinMatrices(t){Jw++;let e=t.length;if(e!==0)for(let s=0;s{t.defaultUniformBuffer.destroy(),t.destroy()}),this.viewBindGroups.length=0}setupClears(t,e){this.clearColor=t?.clearColorBuffer||e.clearColorBuffer,this.clearDepth=t?.clearDepthBuffer||e.clearDepthBuffer,this.clearStencil=t?.clearStencilBuffer||e.clearStencilBuffer}};var Ya=class extends yt{constructor(e,s,i,r){super(e);n(this,"layerComposition");n(this,"scene");n(this,"renderer");n(this,"renderActions",[]);n(this,"gammaCorrection");n(this,"toneMapping");n(this,"noDepthClear",!1);this.layerComposition=s,this.scene=i,this.renderer=r}get rendersAnything(){return this.renderActions.length>0}addRenderAction(e){this.renderActions.push(e)}addLayer(e,s,i,r=!0){let a=new zp;if(a.renderTarget=this.renderTarget,a.camera=e,a.layer=s,a.transparent=i,r){let o=this.renderActions.length===0;a.setupClears(o?e:void 0,s)}this.addRenderAction(a)}addLayers(e,s,i,r,a,o=!0){let{layerList:l,subLayerList:h}=e,f=r,u=i;for(;u{Qf.drawCalls.push(T),Qf.shaderInstances.push(C),Qf.isNewMaterial.push(v),Qf.lightMaskChanged.push(E)};Qf.clear();let f=this.device,u=this.scene,d=u.clusteredLightingEnabled,p=r?.getLightHash(d)??0,m=null,_,S,g=s.length;for(let T=0;T=0?m:0,S=p&&m>=0?m+1:p?p.length:0,g=e.drawCalls.length;for(let T=0;T{t.addRenderPass(p)}),d&&t.endMultiView();else{let p=f.id===Zt,m=p&&(u.renderSceneColorMap||u.renderSceneDepthMap);r&&(r=!1,i=l,a=h.renderTarget);let _=o[l+1],g=(_?!_.useCameraPasses&&_.layer.id===Zt:!1)&&(u.renderSceneColorMap||u.renderSceneDepthMap),T=_?_.firstCameraUse&&this.cameraDirShadowLights.has(_.camera.camera):!1;if(!_||_.renderTarget!==a||_.camera!==u||T||g||m){let C=p&&i===l;if(d&&(u.renderSceneColorMap||u.renderSceneDepthMap||h.triggerPostprocess&&u?.onPostprocessing),d&&t.beginMultiView(this.device),C||this.addMainRenderPass(t,e,a,i,l),p){if(u.renderSceneColorMap){let v=u.camera.renderPassColorGrab;v.source=u.renderTarget,t.addRenderPass(v)}u.renderSceneDepthMap&&t.addRenderPass(u.camera.renderPassDepthGrab)}if(h.triggerPostprocess&&u?.onPostprocessing){let v=new ay(this.device,this,h);t.addRenderPass(v)}d&&t.endMultiView(),r=!0}}}}_isMultiview(t){let e=t.camera?.xr;return this.device.isWebGPU&&!!e?.session&&e.views.list.length>=2}addMainRenderPass(t,e,s,i,r){let a=new Ya(this.device,e,this.scene,this);a.init(s);let o=e._renderActions;for(let l=i;l<=r;l++)a.addRenderAction(o[l]);t.addRenderPass(a)}update(t){this.frameUpdate(),this.shadowRenderer.frameUpdate(),this.scene._updateSkyMesh(),this.updateLayerComposition(t),this.collectLights(t),this.beginFrame(t),this.setSceneConstants(),this.gsplatDirector?.update(t),this.cullComposition(t),this.gpuUpdate(this.processingMeshInstances)}};var oI=0,_S=[],oy=new Set;function d6(c,t){return c.drawOrder-t.drawOrder}function p6(c,t){let e=c._sortKeyForward,s=t._sortKeyForward;return e===s?t.mesh.id-c.mesh.id:s-e}function m6(c,t){return t._sortKeyDynamic-c._sortKeyDynamic}function _6(c,t){return c._sortKeyDynamic-t._sortKeyDynamic}var g6=[null,d6,p6,m6,_6],nI=class{constructor(){n(this,"opaque",[]);n(this,"transparent",[])}},Dt=class{constructor(t={}){n(this,"id");n(this,"name");n(this,"_enabled",!0);n(this,"_refCounter",1);n(this,"opaqueSortMode",yT);n(this,"transparentSortMode",Jg);n(this,"customSortCallback",null);n(this,"customCalculateSortValues",null);n(this,"_clearColorBuffer",!1);n(this,"_clearDepthBuffer",!1);n(this,"_clearStencilBuffer",!1);n(this,"onEnable");n(this,"onDisable");n(this,"meshInstances",[]);n(this,"meshInstancesSet",new Set);n(this,"shadowCasters",[]);n(this,"shadowCastersSet",new Set);n(this,"_visibleInstances",new WeakMap);n(this,"_lights",[]);n(this,"_lightsSet",new Set);n(this,"_clusteredLightsSet",new Set);n(this,"_splitLights",[[],[],[]]);n(this,"_splitLightsDirty",!0);n(this,"_lightHash",0);n(this,"_lightHashDirty",!1);n(this,"_lightIdHash",0);n(this,"_lightIdHashDirty",!1);n(this,"requiresLightCube",!1);n(this,"cameras",[]);n(this,"camerasSet",new Set);n(this,"gsplatPlacements",[]);n(this,"gsplatPlacementsSet",new Set);n(this,"gsplatShadowCasters",[]);n(this,"gsplatShadowCastersSet",new Set);n(this,"gsplatPlacementsDirty",!0);n(this,"_dirtyComposition",!1);n(this,"_shaderVersion",-1);t.id!==void 0?(this.id=t.id,oI=Math.max(this.id+1,oI)):this.id=oI++,this.name=t.name,this._enabled=t.enabled??!0,this._refCounter=this._enabled?1:0,this.opaqueSortMode=t.opaqueSortMode??yT,this.transparentSortMode=t.transparentSortMode??Jg,this._clearColorBuffer=!!t.clearColorBuffer,this._clearDepthBuffer=!!t.clearDepthBuffer,this._clearStencilBuffer=!!t.clearStencilBuffer,this.onEnable=t.onEnable,this.onDisable=t.onDisable,this._enabled&&this.onEnable&&this.onEnable()}set enabled(t){t!==this._enabled&&(this._dirtyComposition=!0,this.gsplatPlacementsDirty=!0,this._enabled=t,t?(this.incrementCounter(),this.onEnable&&this.onEnable()):(this.decrementCounter(),this.onDisable&&this.onDisable()))}get enabled(){return this._enabled}set clearColorBuffer(t){this._clearColorBuffer=t,this._dirtyComposition=!0}get clearColorBuffer(){return this._clearColorBuffer}set clearDepthBuffer(t){this._clearDepthBuffer=t,this._dirtyComposition=!0}get clearDepthBuffer(){return this._clearDepthBuffer}set clearStencilBuffer(t){this._clearStencilBuffer=t,this._dirtyComposition=!0}get clearStencilBuffer(){return this._clearStencilBuffer}get hasClusteredLights(){return this._clusteredLightsSet.size>0}get clusteredLightsSet(){return this._clusteredLightsSet}incrementCounter(){this._refCounter===0&&(this._enabled=!0,this.onEnable&&this.onEnable()),this._refCounter++}decrementCounter(){if(this._refCounter===1)this._enabled=!1,this.onDisable&&this.onDisable();else if(this._refCounter===0)return;this._refCounter--}addGSplatPlacement(t){this.gsplatPlacementsSet.has(t)||(this.gsplatPlacements.push(t),this.gsplatPlacementsSet.add(t),this.gsplatPlacementsDirty=!0)}removeGSplatPlacement(t){let e=this.gsplatPlacements.indexOf(t);e>=0&&(this.gsplatPlacements.splice(e,1),this.gsplatPlacementsSet.delete(t),this.gsplatPlacementsDirty=!0)}addGSplatShadowCaster(t){this.gsplatShadowCastersSet.has(t)||(this.gsplatShadowCasters.push(t),this.gsplatShadowCastersSet.add(t),this.gsplatPlacementsDirty=!0)}removeGSplatShadowCaster(t){let e=this.gsplatShadowCasters.indexOf(t);e>=0&&(this.gsplatShadowCasters.splice(e,1),this.gsplatShadowCastersSet.delete(t),this.gsplatPlacementsDirty=!0)}addMeshInstances(t,e){let s=this.meshInstances,i=this.meshInstancesSet;for(let r=0;r0){let r=this._shaderVersion;oy.forEach(a=>{r>=0&&a._shaderVersion!==r&&(a.getShaderVariant!==Us.prototype.getShaderVariant&&a.clearVariants(),a._shaderVersion=r)}),oy.clear()}}removeMeshInstances(t,e){let s=this.meshInstances,i=this.meshInstancesSet;for(let r=0;r=0&&s.splice(o,1)}}e||this.removeShadowCasters(t)}addShadowCasters(t){let e=this.shadowCasters,s=this.shadowCastersSet;for(let i=0;i=0&&e.splice(a,1)}}}clearMeshInstances(t=!1){this.meshInstances.length=0,this.meshInstancesSet.clear(),t||(this.shadowCasters.length=0,this.shadowCastersSet.clear())}markLightsDirty(){this._lightHashDirty=!0,this._lightIdHashDirty=!0,this._splitLightsDirty=!0}hasLight(t){return this._lightsSet.has(t)}addLight(t){let e=t.light;this._lightsSet.has(e)||(this._lightsSet.add(e),this._lights.push(e),this.markLightsDirty()),e.type!==Ce&&this._clusteredLightsSet.add(e)}removeLight(t){let e=t.light;this._lightsSet.has(e)&&(this._lightsSet.delete(e),this._lights.splice(this._lights.indexOf(e),1),this.markLightsDirty()),e.type!==Ce&&this._clusteredLightsSet.delete(e)}clearLights(){this._lightsSet.forEach(t=>t.removeLayer(this)),this._lightsSet.clear(),this._clusteredLightsSet.clear(),this._lights.length=0,this.markLightsDirty()}get splitLights(){if(this._splitLightsDirty){this._splitLightsDirty=!1;let t=this._splitLights;for(let s=0;si.key-r.key)}return this._splitLights}evaluateLightHash(t,e,s){let i=0,r=this._lights;for(let a=0;a0&&(_S.sort(),i=dc(_S),_S.length=0),i}getLightHash(t){return this._lightHashDirty&&(this._lightHashDirty=!1,this._lightHash=this.evaluateLightHash(!t,!0,!1)),this._lightHash}getLightIdHash(){return this._lightIdHashDirty&&(this._lightIdHashDirty=!1,this._lightIdHash=this.evaluateLightHash(!0,!1,!0)),this._lightIdHash}addCamera(t){this.camerasSet.has(t.camera)||(this.camerasSet.add(t.camera),this.cameras.push(t),this._dirtyComposition=!0)}removeCamera(t){if(this.camerasSet.has(t.camera)){this.camerasSet.delete(t.camera);let e=this.cameras.indexOf(t);this.cameras.splice(e,1),this._dirtyComposition=!0}}clearCameras(){this.cameras.length=0,this.camerasSet.clear(),this._dirtyComposition=!0}_calculateSortDistances(t,e,s){let i=t.length,{x:r,y:a,z:o}=e,{x:l,y:h,z:f}=s;for(let u=0;uc.priority-t.priority,Uc=c=>c.sort(S6);var ol=class extends J{constructor(e="Untitled"){super();n(this,"layerList",[]);n(this,"layerIdMap",new Map);n(this,"layerNameMap",new Map);n(this,"layerOpaqueIndexMap",new Map);n(this,"layerTransparentIndexMap",new Map);n(this,"subLayerList",[]);n(this,"subLayerEnabled",[]);n(this,"cameras",[]);n(this,"camerasSet",new Set);n(this,"_renderActions",[]);n(this,"_dirty",!1);this.name=e,this._opaqueOrder={},this._transparentOrder={}}destroy(){this.destroyRenderActions()}destroyRenderActions(){this._renderActions.forEach(e=>e.destroy()),this._renderActions.length=0}markDirty(){this._dirty=!0}_update(){let e=this.layerList.length;if(!this._dirty){for(let s=0;s1&&Uc(this.cameras);let s=[],i=0;this.destroyRenderActions();for(let r=0;r0){this.addDummyRenderAction(i,a),i++;continue}let o=!0,l=i,h=null,f=!1;for(let u=0;u0&&a.layers.indexOf(d.id)>=0){s.push(d),!f&&d.id===a.disablePostEffectsLayer&&(f=!0,h&&(h.triggerPostprocess=!0));let m=this.subLayerList[u];h=this.addRenderAction(i,d,m,a,o,f),i++,o=!1}}l=0;m--)if(f[m].camera===r&&f[m].renderTarget===l){h=!0;break}o&&r.postEffectsEnabled&&(l=null);let u=this.getNextRenderAction(e);u.triggerPostprocess=!1,u.layer=s,u.transparent=i,u.camera=r,u.renderTarget=l,u.firstCameraUse=a,u.lastCameraUse=!1;let d=a||!h,p=s.clearColorBuffer||s.clearDepthBuffer||s.clearStencilBuffer;return(d||p)&&u.setupClears(d?r:void 0,s),u}propagateRenderTarget(e,s){for(let i=e;i>=0;i--){let r=this._renderActions[i],a=r.layer;if(r.renderTarget&&a.id!==Zt)break;if(a.id===Zt)continue;if(r.useCameraPasses)break;let o=r?.camera.camera;if(o&&(!s.camera.rect.equals(o.rect)||!s.camera.scissorRect.equals(o.scissorRect)))break;r.renderTarget=s.renderTarget}}_logRenderActions(){}_isLayerAdded(e){return this.layerIdMap.get(e.id)===e}_isSublayerAdded(e,s){return(s?this.layerTransparentIndexMap:this.layerOpaqueIndexMap).get(e)!==void 0}push(e){this._isLayerAdded(e)||(this.layerList.push(e),this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(!1)-1,this._transparentOrder[e.id]=this.subLayerList.push(!0)-1,this.subLayerEnabled.push(!0),this.subLayerEnabled.push(!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e))}insert(e,s){if(this._isLayerAdded(e))return;this.layerList.splice(s,0,e,e),this.subLayerList.splice(s,0,!1,!0);let i=this.layerList.length;this._updateOpaqueOrder(s,i-1),this._updateTransparentOrder(s,i-1),this.subLayerEnabled.splice(s,0,!0,!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e)}remove(e){let s=this.layerList.indexOf(e);for(delete this._opaqueOrder[s],delete this._transparentOrder[s];s>=0;)this.layerList.splice(s,1),this.subLayerList.splice(s,1),this.subLayerEnabled.splice(s,1),s=this.layerList.indexOf(e),this._dirty=!0,this.fire("remove",e);let i=this.layerList.length;this._updateOpaqueOrder(0,i-1),this._updateTransparentOrder(0,i-1),this._updateLayerMaps()}pushOpaque(e){this._isSublayerAdded(e,!1)||(this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(!1)-1,this.subLayerEnabled.push(!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e))}insertOpaque(e,s){if(this._isSublayerAdded(e,!1))return;this.layerList.splice(s,0,e),this.subLayerList.splice(s,0,!1);let i=this.subLayerList.length;this._updateOpaqueOrder(s,i-1),this.subLayerEnabled.splice(s,0,!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e)}removeOpaque(e){for(let s=0,i=this.layerList.length;s=0)return this.subLayerEnabled[i]}return!1}_updateLayerMaps(){this.layerIdMap.clear(),this.layerNameMap.clear(),this.layerOpaqueIndexMap.clear(),this.layerTransparentIndexMap.clear();for(let e=0;e{t.defaultUniformBuffer.destroy(),t.destroy()}),this.viewBindGroups.length=0}get shadowBuffer(){let t=this.shadowCamera.renderTarget;return t?this.light._isPcf?t.depthBuffer:t.colorBuffer:null}},kc=class c{constructor(t,e){n(this,"layers",new Set);n(this,"clusteredLighting");n(this,"shadowDepthState",Pt.DEFAULT.clone());n(this,"clusteredFlags",0);n(this,"clusteredData",new Uint32Array(3));n(this,"clusteredData16",new Uint16Array(this.clusteredData.buffer));n(this,"_evtDeviceRestored",null);this.device=t,this.clusteredLighting=e,this.id=T6++,this._evtDeviceRestored=t.on("devicerestored",this.onDeviceRestored,this),this._type=Ce,this._color=new F(.8,.8,.8),this._intensity=1,this._affectSpecularity=!0,this._luminance=0,this._castShadows=!1,this._enabled=!1,this._mask=cs,this.isStatic=!1,this.key=0,this.bakeDir=!0,this.bakeNumSamples=1,this.bakeArea=0,this.attenuationStart=10,this.attenuationEnd=10,this._falloffMode=uT,this._shadowType=Oi,this._vsmBlurSize=11,this.vsmBlurMode=Kg,this.vsmBias=.01*.25,this._cookie=null,this.cookieIntensity=1,this._cookieFalloff=!0,this._cookieChannel="rgb",this._cookieTransform=null,this._cookieTransformUniform=new Float32Array(4),this._cookieOffset=null,this._cookieOffsetUniform=new Float32Array(2),this._cookieTransformSet=!1,this._cookieOffsetSet=!1,this._innerConeAngle=40,this._outerConeAngle=45,this.cascades=null,this._shadowMatrixPalette=null,this._shadowCascadeDistances=null,this.numCascades=1,this._cascadeBlend=0,this.cascadeDistribution=.5,this._shape=$i,this._colorLinear=new Float32Array(3),this._updateLinearColor(),this._position=new x(0,0,0),this._direction=new x(0,0,0),this._innerConeAngleCos=Math.cos(this._innerConeAngle*R.DEG_TO_RAD),this._updateOuterAngle(this._outerConeAngle),this._usePhysicalUnits=void 0,this._shadowMap=null,this._shadowRenderParams=[],this._shadowCameraParams=[],this.shadowDistance=40,this._shadowResolution=1024,this._shadowBias=-5e-4,this._shadowIntensity=1,this._normalOffsetBias=0,this.shadowUpdateMode=Qg,this.shadowUpdateOverrides=null,this._isVsm=!1,this._isPcf=!0,this._softShadowParams=new Float32Array(4),this.shadowSamples=16,this.shadowBlockerSamples=16,this.penumbraSize=1,this.penumbraFalloff=1,this._cookieMatrix=null,this._atlasViewport=null,this.atlasViewportAllocated=!1,this.atlasVersion=0,this.atlasSlotIndex=0,this.atlasSlotUpdated=!1,this._node=null,this._renderData=[],this.visibleThisFrame=!1,this.maxScreenSize=0,this._updateShadowBias()}destroy(){this._evtDeviceRestored?.off(),this._evtDeviceRestored=null,this._destroyShadowMap(),this.releaseRenderData(),this._renderData=null}onDeviceRestored(){this.shadowUpdateMode===$s&&(this.shadowUpdateMode=Qi)}releaseRenderData(){if(this._renderData){for(let t=0;t45?(t.radius=e*this._outerConeAngleSin,ny.mulScalar(-e*i)):(t.radius=e/(2*i),ny.mulScalar(-t.radius)),t.center.add2(r.getPosition(),ny)}else this._type===We&&(t.center=this._node.getPosition(),t.radius=this.attenuationEnd)}getBoundingBox(t){if(this._type===je){let e=this.attenuationEnd,s=this._outerConeAngle,i=this._node,r=Math.abs(Math.sin(s*R.DEG_TO_RAD)*e);t.center.set(0,-e*.5,0),t.halfExtents.set(r,e*.5,r),t.setFromTransformedAabb(t,i.getWorldTransform(),!0)}else this._type===We&&(t.center.copy(this._node.getPosition()),t.halfExtents.set(this.attenuationEnd,this.attenuationEnd,this.attenuationEnd))}_updateShadowBias(){if(this._type===We&&!this.clusteredLighting)this.shadowDepthState.depthBias=0,this.shadowDepthState.depthBiasSlope=0;else{let t=this.shadowBias*-1e3;this.shadowDepthState.depthBias=t,this.shadowDepthState.depthBiasSlope=t}}_updateLinearColor(){let t=this._intensity;this._usePhysicalUnits&&(t=this._luminance/c.getLightUnitConversion(this._type,this._outerConeAngle*R.DEG_TO_RAD,this._innerConeAngle*R.DEG_TO_RAD));let e=this._color,s=this._colorLinear;t>=1?gS.linear(e).mulScalar(t):gS.copy(e).mulScalar(t).linear(),s[0]=gS.r,s[1]=gS.g,s[2]=gS.b,this.updateClusterData(!0)}setColor(){arguments.length===1?this._color.set(arguments[0].r,arguments[0].g,arguments[0].b):arguments.length===3&&this._color.set(arguments[0],arguments[1],arguments[2]),this._updateLinearColor()}layersDirty(){this.layers.forEach(t=>{t.hasLight(this)&&t.markLightsDirty()})}updateKey(){let t=this._type<<29|this._shadowType<<25|this._falloffMode<<23|(this._normalOffsetBias!==0?1:0)<<22|(this._cookie?1:0)<<21|(this._cookieFalloff?1:0)<<20|lI[this._cookieChannel.charAt(0)]<<18|(this._cookieTransform?1:0)<<12|this._shape<<10|(this.numCascades>0?1:0)<<9|(this._cascadeBlend>0?1:0)<<8|(this.affectSpecularity?1:0)<<7|this.mask<<6|(this._castShadows?1:0)<<3;this._cookieChannel.length===3&&(t|=lI[this._cookieChannel.charAt(1)]<<16,t|=lI[this._cookieChannel.charAt(2)]<<14),t!==this.key&&this.layersDirty(),this.key=t}updateClusteredFlags(){let t=!!(this.mask&cs),e=!!(this.mask&xi);this.clusteredFlags=(this.type===je?1:0)<<30|(this._shape&3)<<28|(this._falloffMode&1)<<27|(v6[this._cookieChannel]??0)<<23|(t?1:0)<<22|(e?1:0)<<21}getClusteredFlags(t,e){return this.clusteredFlags|((t?Math.floor(this.shadowIntensity*255):0)&255)<<0|((e?Math.floor(this.cookieIntensity*255):0)&255)<<8}updateClusterData(t,e){let{clusteredData16:s}=this,i=Hs.float2Half;if(t&&(s[0]=i(R.clamp(this._colorLinear[0]/If,0,65504)),s[1]=i(R.clamp(this._colorLinear[1]/If,0,65504)),s[2]=i(R.clamp(this._colorLinear[2]/If,0,65504))),e){let a=0,o=.99,l=Math.cos(this._innerConeAngle*o*R.DEG_TO_RAD);l>.5&&(l=1-l,a|=1);let h=Math.cos(this._outerConeAngle*o*R.DEG_TO_RAD);h>.5&&(h=1-h,a|=2),s[3]=a,s[4]=i(l),s[5]=i(h)}}};var zc=class{constructor(t,e,s){n(this,"_areaLightsEnabled",!1);n(this,"_cells",new x(10,3,10));n(this,"_maxLightsPerCell",255);n(this,"_shadowsEnabled",!0);n(this,"_shadowType",Oi);n(this,"_shadowAtlasResolution",2048);n(this,"_cookiesEnabled",!1);n(this,"_cookieAtlasResolution",2048);n(this,"debugLayer");n(this,"atlasSplit",null);this._supportsAreaLights=t,this._maxTextureSize=e,this._dirtyLightsFnc=s}applySettings(t){this.shadowsEnabled=t.lightingShadowsEnabled??this.shadowsEnabled,this.cookiesEnabled=t.lightingCookiesEnabled??this.cookiesEnabled,this.areaLightsEnabled=t.lightingAreaLightsEnabled??this.areaLightsEnabled,this.shadowAtlasResolution=t.lightingShadowAtlasResolution??this.shadowAtlasResolution,this.cookieAtlasResolution=t.lightingCookieAtlasResolution??this.cookieAtlasResolution,this.maxLightsPerCell=t.lightingMaxLightsPerCell??this.maxLightsPerCell,this.shadowType=t.lightingShadowType??this.shadowType,t.lightingCells&&(this.cells=new x(t.lightingCells))}set cells(t){this._cells.copy(t)}get cells(){return this._cells}set maxLightsPerCell(t){this._maxLightsPerCell=R.clamp(t,1,255)}get maxLightsPerCell(){return this._maxLightsPerCell}set cookieAtlasResolution(t){this._cookieAtlasResolution=R.clamp(t,32,this._maxTextureSize)}get cookieAtlasResolution(){return this._cookieAtlasResolution}set shadowAtlasResolution(t){this._shadowAtlasResolution=R.clamp(t,32,this._maxTextureSize)}get shadowAtlasResolution(){return this._shadowAtlasResolution}set shadowType(t){this._shadowType!==t&&(this._shadowType=t,this._dirtyLightsFnc())}get shadowType(){return this._shadowType}set cookiesEnabled(t){this._cookiesEnabled!==t&&(this._cookiesEnabled=t,this._dirtyLightsFnc())}get cookiesEnabled(){return this._cookiesEnabled}set areaLightsEnabled(t){this._supportsAreaLights&&this._areaLightsEnabled!==t&&(this._areaLightsEnabled=t,this._dirtyLightsFnc())}get areaLightsEnabled(){return this._areaLightsEnabled}set shadowsEnabled(t){this._shadowsEnabled!==t&&(this._shadowsEnabled=t,this._dirtyLightsFnc())}get shadowsEnabled(){return this._shadowsEnabled}};var Ar=class c{constructor(t){this.morph=t,t.incRefCount(),this.device=t.device;let e=t._targets.length;this.shader=this._createShader(e),this._weights=[],this._weightMap=new Map;for(let a=0;a(this[o]=t._createTexture(a,t._renderTextureFormat),new me({colorBuffer:this[o],depth:!1}));t.morphPositions&&(this.rtPositions=s("MorphRTPos","texturePositions")),t.morphNormals&&(this.rtNormals=s("MorphRTNrm","textureNormals")),this._textureParams=new Float32Array([t.morphTextureWidth,t.morphTextureHeight]);let i=t.aabb.halfExtents;this._aabbSize=new Float32Array([i.x*4,i.y*4,i.z*4]);let r=t.aabb.getMin();this._aabbMin=new Float32Array([r.x*2,r.y*2,r.z*2]),this._aabbNrmSize=new Float32Array([2,2,2]),this._aabbNrmMin=new Float32Array([-1,-1,-1]),this.aabbSizeId=this.device.scope.resolve("aabbSize"),this.aabbMinId=this.device.scope.resolve("aabbMin"),this.morphTextureId=this.device.scope.resolve("morphTexture"),this.morphFactor=this.device.scope.resolve("morphFactor[0]"),this.morphIndex=this.device.scope.resolve("morphIndex[0]"),this.countId=this.device.scope.resolve("count"),this.zeroTextures=!1}destroy(){this.shader=null;let t=this.morph;t&&(this.morph=null,t.decRefCount(),t.refCount<1&&t.destroy()),this.rtPositions?.destroy(),this.rtPositions=null,this.texturePositions?.destroy(),this.texturePositions=null,this.rtNormals?.destroy(),this.rtNormals=null,this.textureNormals?.destroy(),this.textureNormals=null}clone(){return new c(this.morph)}_getWeightIndex(t){if(typeof t=="string"){let e=this._weightMap.get(t);return e}return t}getWeight(t){let e=this._getWeightIndex(t);return this._weights[e]}setWeight(t,e){let s=this._getWeightIndex(t);this._weights[s]=e,this._dirty=!0}_createShader(t){let e=new Map;e.set("{MORPH_TEXTURE_MAX_COUNT}",t),this.morph.intRenderFormat&&e.set("MORPH_INT","");let s=this.morph.intRenderFormat?"uvec4":"vec4";return Se.createShader(this.device,{uniqueName:`TextureMorphShader_${t}-${this.morph.intRenderFormat?"int":"float"}`,attributes:{vertex_position:ee},vertexChunk:"morphVS",fragmentChunk:"morphPS",fragmentDefines:e,fragmentOutputTypes:[s]})}_updateTextureRenderTarget(t,e,s){let{morph:i,device:r}=this;this.setAabbUniforms(s),this.morphTextureId.setValue(s?i.targetsTexturePositions:i.targetsTextureNormals),r.setBlendState(Oe.NOBLEND),this.countId.setValue(e),this.morphFactor.setValue(this._shaderMorphWeights),this.morphIndex.setValue(this._shaderMorphIndex),Qt(r,t,this.shader)}_updateTextureMorph(t){let e=this.device;(t>0||!this.zeroTextures)&&(this.rtPositions&&this._updateTextureRenderTarget(this.rtPositions,t,!0),this.rtNormals&&this._updateTextureRenderTarget(this.rtNormals,t,!1),this.zeroTextures=t===0)}setAabbUniforms(t=!0){this.aabbSizeId.setValue(t?this._aabbSize:this._aabbNrmSize),this.aabbMinId.setValue(t?this._aabbMin:this._aabbNrmMin)}prepareRendering(t){this.setAabbUniforms()}update(){this._dirty=!1;let t=this.morph._targets,e=1e-5,s=this._shaderMorphWeights,i=this._shaderMorphIndex,r=0;for(let a=0;ae&&(s[r]=this.getWeight(a),i[r]=a,r++);this._updateTextureMorph(r)}};var Ei=class c{constructor(){n(this,"graph",null);n(this,"meshInstances",[]);n(this,"skinInstances",[]);n(this,"morphInstances",[]);this.cameras=[],this.lights=[],this._shadersVersion=0,this._immutable=!1}getGraph(){return this.graph}setGraph(t){this.graph=t}getCameras(){return this.cameras}setCameras(t){this.cameras=t}getLights(){return this.lights}setLights(t){this.lights=t}getMaterials(){let t=[];for(let e=0;el)return;this.morphTextureWidth=h,this.morphTextureHeight=f;let u=!1,d=Hs.float2Half;this._textureFormat===Me&&(u=!0);let p=[],m=[],_=h*f*4;for(let g=0;g0&&(this.targetsTexturePositions=this._createTexture("MorphPositionsTexture",this._textureFormat,i.length,[p])),m.length>0&&(this.targetsTextureNormals=this._createTexture("MorphNormalsTexture",this._textureFormat,i.length,[m]));let S=[{semantic:Da,components:1,type:kt,asInt:!0}];return this.vertexBufferIds=new ft(this.device,new Ft(this.device,S,r.length),r.length,{data:new Uint32Array(r)}),!0}get targets(){return this._targets}_updateMorphFlags(){this._morphPositions=!1,this._morphNormals=!1;for(let e=0;e=G)&&this.calcSpawnPosition(s,i,r,a,I);let k=M>0&&M0&&(d.emitterShape===hw?(Wt.copy(Ka).mulScalar(2).sub(x.ONE).normalize(),fs.add(Wt.mulScalar(d.initialVelocity))):fs.add(x.FORWARD.mulScalar(d.initialVelocity))),Cr.x+=(Vp.x-Cr.x)*Ka.x,Cr.y+=(Vp.y-Cr.y)*Ka.y,Cr.z+=(Vp.z-Cr.z)*Ka.z,g+=(T-g)*Ka.y,U=(U+(C-U)*(D*1e4%1))*sM,L=(E-v)*(D*1e3%1),d.meshInstance.node&&(d.localSpace?(fs.x/=ll.x,fs.y/=ll.y,fs.z/=ll.z):hI.transformPoint(fs,fs)),d.localSpace?(fI.transformPoint(Cr,Cr),fs.add(Cr).add(SS)):(fs.add(Cr.mul(ll)),fs.add(SS.mul(ll))),cy.copy(fs),iM.copy(Gp).add(fs.mulScalar(o)),Ai.copy(iM),s[I*Ae]=Ai.x,s[I*Ae+1]=Ai.y,s[I*Ae+2]=Ai.z,s[I*Ae+3]+=g*o,d.wrap&&d.wrapBounds&&(d.localSpace||Ai.sub(a),Ai.x=uI(Ai.x,d.wrapBounds.x)-d.wrapBounds.x*.5,Ai.y=uI(Ai.y,d.wrapBounds.y)-d.wrapBounds.y*.5,Ai.z=uI(Ai.z,d.wrapBounds.z)-d.wrapBounds.z*.5,d.localSpace||Ai.add(a)),d.sort>0&&(d.sort===1?(Jf.copy(Ai).sub(p),d.particleDistance[I]=-(Jf.x*Jf.x+Jf.y*Jf.y+Jf.z*Jf.z)):d.sort===2?d.particleDistance[I]=M:d.sort===3&&(d.particleDistance[I]=-M))),l?M<0&&(s[I*Ae+3+d.numParticlesPot*2*Ae]=-1):(M>=G&&(M-=Math.max(G,d.numParticles*O),s[I*Ae+3+d.numParticlesPot*2*Ae]=d.loop?1:-1),M<0&&d.loop&&(s[I*Ae+3+d.numParticlesPot*2*Ae]=1)),s[I*Ae+3+d.numParticlesPot*2*Ae]<0&&(k=!1),s[I*Ae+3+d.numParticlesPot*Ae]=M;for(let z=0;zup&&d.camera){let w=d.useMesh?6:4,I=d.particleDistance;for(let D=0;DD[1]-O[1]);for(let D=0;D0&&s.set("SOFT",""),t.stretch>0&&s.set("STRETCH",""),t.customFace&&s.set("CUSTOM_FACE",""),t.pack8&&s.set("PACK8",""),t.localSpace&&s.set("LOCAL_SPACE",""),t.animTexLoop&&s.set("ANIMTEX_LOOP",""),t.wrap&&s.set("WRAP",""),t.alignToMotion&&s.set("ALIGN_TO_MOTION",""),s.set("NORMAL",nM[t.normal]),e.particle_vertexData=ee,t.mesh&&t.meshUv&&(e.particle_uv=_t),t.useCpu&&(e.particle_vertexData2=_f,e.particle_vertexData3=Cd,e.particle_vertexData4=Pd,e.particle_vertexData5=wd),s}createFragmentDefines(t){let e=new Map(t.defines);return t.soft>0&&e.set("SOFT",""),t.halflambert&&e.set("HALF_LAMBERT",""),e.set("NORMAL",nM[t.normal]),e.set("BLEND",Wg[t.blend]),e}createShaderDefinition(t,e){let s=t.isWebGPU?se:fe,i=ne.get(t,s),r={},a=this.createVertexDefines(e,r),o=this.createFragmentDefines(e),l=`PARTICLE_${e.useCpu?"CPU":"GPU"} +`;a.set(l,""),o.set(l,"");let h=new Map(i);return ns.createDefinition(t,{name:"ParticleShader",shaderLanguage:s,attributes:r,vertexCode:i.get("particle_shaderVS"),fragmentCode:i.get("particle_shaderPS"),fragmentDefines:o,fragmentIncludes:h,vertexIncludes:h,vertexDefines:a})}},lM=new dI;var dy=class extends Us{constructor(e){super();n(this,"emitter",null);this.emitter=e}getShaderVariant(e){let{device:s,scene:i,cameraShaderParams:r,objDefs:a}=e,{emitter:o}=this,l={defines:Se.getCoreDefines(this,e),pass:Sr,useCpu:this.emitter.useCpu,normal:o.lighting?o.normalMap!==null?2:1:0,halflambert:this.emitter.halfLambert,stretch:this.emitter.stretch,alignToMotion:this.emitter.alignToMotion,soft:this.emitter.depthSoftening,mesh:this.emitter.useMesh,meshUv:a&Of,gamma:r?.shaderOutputGamma??Zi,toneMap:r?.toneMapping??Qn,fog:i&&!this.emitter.noFog?i.fog.type:"none",wrap:this.emitter.wrap&&this.emitter.wrapBounds,localSpace:this.emitter.localSpace,screenSpace:o.inTools?!1:this.emitter.screenSpace,blend:this.emitter.blendType,animTex:this.emitter._isAnimated(),animTexLoop:this.emitter.animLoop,pack8:this.emitter.pack8,customFace:this.emitter.orientation!==vc},h=new sa(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),f=Ji(s);return f.register("particle",lM),f.getProgram("particle",l,h,this.userId)}};var cM=[[-1,-1],[1,-1],[1,1],[-1,1]];function na(c,t,e,s,i=ke,r,a){let o=0;a&&(i===ce||i===st)&&(o=1);let l=new Z(c,{width:t,height:e,format:i,cubemap:!1,mipmaps:!1,minFilter:o,magFilter:o,addressU:1,addressV:1,name:"ParticleSystemTexture"}),h=l.lock();if(i===ce||i===st){let f=new Uint8Array(s.length);for(let u=0;ut.maxTextureSize&&(this.numParticles=t.maxTextureSize),Ie("rate",1),Ie("rate2",this.rate),Ie("lifetime",50),Ie("emitterExtents",new x(0,0,0)),Ie("emitterExtentsInner",new x(0,0,0)),Ie("emitterRadius",0),Ie("emitterRadiusInner",0),Ie("emitterShape",Ni),Ie("initialVelocity",1),Ie("wrap",!1),Ie("localSpace",!1),Ie("screenSpace",!1),Ie("wrapBounds",null),Ie("colorMap",this.defaultParamTexture),Ie("normalMap",null),Ie("loop",!0),Ie("preWarm",!1),Ie("sort",up),Ie("mode",jg),Ie("scene",null),Ie("lighting",!1),Ie("halfLambert",!1),Ie("intensity",1),Ie("stretch",0),Ie("alignToMotion",!1),Ie("depthSoftening",0),Ie("mesh",null),Ie("particleNormal",new x(0,1,0)),Ie("orientation",vc),Ie("depthWrite",!1),Ie("noFog",!1),Ie("blendType",ls),Ie("node",null),Ie("startAngle",0),Ie("startAngle2",this.startAngle),Ie("animTilesX",1),Ie("animTilesY",1),Ie("animStartFrame",0),Ie("animNumFrames",1),Ie("animNumAnimations",1),Ie("animIndex",0),Ie("randomizeAnimIndex",!1),Ie("animSpeed",1),Ie("animLoop",!0),this._gpuUpdater=new uy(this,s),this._cpuUpdater=new fy(this),this.emitterPosUniform=new Float32Array(3),this.wrapBoundsUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),Ie("colorGraph",A6),Ie("colorGraph2",this.colorGraph),Ie("scaleGraph",uM),Ie("scaleGraph2",this.scaleGraph),Ie("alphaGraph",uM),Ie("alphaGraph2",this.alphaGraph),Ie("localVelocityGraph",dM),Ie("localVelocityGraph2",this.localVelocityGraph),Ie("velocityGraph",dM),Ie("velocityGraph2",this.velocityGraph),Ie("rotationSpeedGraph",fM),Ie("rotationSpeedGraph2",this.rotationSpeedGraph),Ie("radialSpeedGraph",fM),Ie("radialSpeedGraph2",this.radialSpeedGraph),gy=null,xS=null,this.animTilesParams=new Float32Array(2),this.animParams=new Float32Array(4),this.animIndexParams=new Float32Array(2),this.vbToSort=null,this.vbOld=null,this.particleDistance=null,this.camera=null,this.swapTex=!1,this.useMesh=!0,this.useCpu=!t.supportsGpuParticles,this.pack8=!0,this.localBounds=new ge,this.worldBoundsNoTrail=new ge,this.worldBoundsTrail=[new ge,new ge],this.worldBounds=new ge,this.worldBoundsSize=new x,this.prevWorldBoundsSize=new x,this.prevWorldBoundsCenter=new x,this.prevEmitterExtents=this.emitterExtents,this.prevEmitterRadius=this.emitterRadius,this.worldBoundsMul=new x,this.worldBoundsAdd=new x,this.timeToSwitchBounds=0,this.shaderParticleUpdateRespawn=null,this.shaderParticleUpdateNoRespawn=null,this.shaderParticleUpdateOnStop=null,this.numParticleVerts=0,this.numParticleIndices=0,this.material=null,this.meshInstance=null,this.drawOrder=0,this.seed=Math.random(),this.fixedTimeStep=1/60,this.maxSubSteps=10,this.simTime=0,this.simTimeTotal=0,this.beenReset=!1,this._layer=null,this.rebuild()}get defaultParamTexture(){return D6.get(this.graphicsDevice,()=>{let s=new Float32Array(1024);for(let r=0;r<16;r++)for(let a=0;a<16;a++){let o=a+1-8.5,l=r+1-8.5,h=hM(1-hM(Math.sqrt(o*o+l*l)/16)-.5),f=r*16+a;s[f*4]=1,s[f*4+1]=1,s[f*4+2]=1,s[f*4+3]=h}let i=na(this.graphicsDevice,16,16,s,st,1,!0);return i.minFilter=1,i.magFilter=1,i})}onChangeCamera(){this.resetMaterial()}calculateBoundsMad(){this.worldBoundsMul.x=1/this.worldBoundsSize.x,this.worldBoundsMul.y=1/this.worldBoundsSize.y,this.worldBoundsMul.z=1/this.worldBoundsSize.z,this.worldBoundsAdd.copy(this.worldBounds.center).mul(this.worldBoundsMul).mulScalar(-1),this.worldBoundsAdd.x+=.5,this.worldBoundsAdd.y+=.5,this.worldBoundsAdd.z+=.5}calculateWorldBounds(){if(!this.node)return;if(this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),!this.useCpu){let s=!1;this.emitterShape===Ni?s=!this.emitterExtents.equals(this.prevEmitterExtents):s=this.emitterRadius!==this.prevEmitterRadius,s&&this.calculateLocalBounds()}let t=this.node.getWorldTransform();this.localSpace?this.worldBoundsNoTrail.copy(this.localBounds):this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,t),this.worldBoundsTrail[0].add(this.worldBoundsNoTrail),this.worldBoundsTrail[1].add(this.worldBoundsNoTrail);let e=this.simTimeTotal;e>=this.timeToSwitchBounds&&(this.worldBoundsTrail[0].copy(this.worldBoundsTrail[1]),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.timeToSwitchBounds=e+this.lifetime),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.localSpace?(this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,t),this.meshInstance.mesh.aabb.setFromTransformedAabb(this.worldBounds,t)):(this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance.mesh.aabb.copy(this.worldBounds)),this.meshInstance._aabbVer=1-this.meshInstance._aabbVer,this.pack8&&this.calculateBoundsMad()}resetWorldBounds(){this.node&&(this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,this.localSpace?W.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBoundsNoTrail),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.simTimeTotal=0,this.timeToSwitchBounds=0)}calculateLocalBounds(){let t=Number.MAX_VALUE,e=Number.MAX_VALUE,s=Number.MAX_VALUE,i=-Number.MAX_VALUE,r=-Number.MAX_VALUE,a=-Number.MAX_VALUE,o=0,l=0,h=this.lifetime/this.precision,f=[this.qVelocity,this.qVelocity2],u=[this.qLocalVelocity,this.qLocalVelocity2],d=[0,0],p=[0,0],m=[0,0],_=[0,0],S=[0,0],g,T,C;for(let E=0;Eup||t.maxVertexTextures<=1||t.fragmentUniformsCount<64||t.forceCpuParticles;let e=this._destroyResources();this.pack8=(this.pack8||!t.textureFloatRenderable)&&!this.useCpu,cl=this.useCpu||this.pack8?4:2,this.useMesh=!!this.mesh,this.numParticlesPot=R.nextPowerOfTwo(this.numParticles),this.rebuildGraphs(),this.calculateLocalBounds(),this.resetWorldBounds(),this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?W.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBounds),this.worldBoundsTrail[1].copy(this.worldBounds),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.pack8&&this.calculateBoundsMad()),this.vbToSort=new Array(this.numParticles);for(let l=0;l=1&&(this.animTilesX>1||this.animTilesY>1)&&(this.colorMap&&this.colorMap!==this.defaultParamTexture||this.normalMap)}rebuildGraphs(){let t=this.precision,e=this.graphicsDevice;this.qLocalVelocity=this.localVelocityGraph.quantize(t),this.qVelocity=this.velocityGraph.quantize(t),this.qColor=this.colorGraph.quantizeClamped(t,0,1),this.qRotSpeed=this.rotationSpeedGraph.quantize(t),this.qScale=this.scaleGraph.quantize(t),this.qAlpha=this.alphaGraph.quantize(t),this.qRadialSpeed=this.radialSpeedGraph.quantize(t),this.qLocalVelocity2=this.localVelocityGraph2.quantize(t),this.qVelocity2=this.velocityGraph2.quantize(t),this.qColor2=this.colorGraph2.quantizeClamped(t,0,1),this.qRotSpeed2=this.rotationSpeedGraph2.quantize(t),this.qScale2=this.scaleGraph2.quantize(t),this.qAlpha2=this.alphaGraph2.quantize(t),this.qRadialSpeed2=this.radialSpeedGraph2.quantize(t);for(let s=0;s0&&t.setParameter("softening",1/(this.depthSoftening*this.depthSoftening*100)),this.stretch>0&&(t.cull=0),this._compParticleFaceParams()}_compParticleFaceParams(){let t,e;if(this.orientation===vc)t=new Float32Array([1,0,0]),e=new Float32Array([0,0,1]);else{let s;this.orientation===fw?s=this.particleNormal.normalize():s=(this.node===null?W.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize();let i=new x(1,0,0);Math.abs(i.dot(s))===1&&i.set(0,0,1);let r=new x().cross(s,i).normalize();i.cross(r,s).normalize(),t=new Float32Array([i.x,i.y,i.z]),e=new Float32Array([r.x,r.y,r.z])}this.material.setParameter("faceTangent",t),this.material.setParameter("faceBinorm",e)}getVertexInfo(){let t=[];return this.useCpu?t.push({semantic:Ag,components:4,type:ye},{semantic:_f,components:4,type:ye},{semantic:Cd,components:4,type:ye},{semantic:Pd,components:1,type:ye},{semantic:wd,components:this.useMesh?4:2,type:ye}):(t.push({semantic:Ag,components:4,type:ye}),this.useMesh&&t.push({semantic:_f,components:2,type:ye})),t}_allocate(t){let e=t*this.numParticleVerts,s=t*this.numParticleIndices;if(this.vertexBuffer===void 0||this.vertexBuffer.getNumVertices()!==e){let i=this.getVertexInfo(),r=new Ft(this.graphicsDevice,i);this.vertexBuffer=new ft(this.graphicsDevice,r,e,{usage:1}),this.indexBuffer=new os(this.graphicsDevice,2,s);let a=new Float32Array(this.vertexBuffer.lock()),o,l,h;if(this.useMesh){o=new Float32Array(this.mesh.vertexBuffer.lock()),l=o.length/this.mesh.vertexBuffer.numVertices;for(let d=0;dthis.endTime&&(this.onFinished&&this.onFinished(),this.meshInstance.visible=!1),this.meshInstance&&(this.meshInstance.drawOrder=this.drawOrder)}_destroyResources(){this.particleTexIN?.destroy(),this.particleTexIN=null,this.particleTexOUT?.destroy(),this.particleTexOUT=null,this.particleTexStart&&this.particleTexStart.destroy&&(this.particleTexStart.destroy(),this.particleTexStart=null),this.rtParticleTexIN?.destroy(),this.rtParticleTexIN=null,this.rtParticleTexOUT?.destroy(),this.rtParticleTexOUT=null,this.internalTex0?.destroy(),this.internalTex0=null,this.internalTex1?.destroy(),this.internalTex1=null,this.internalTex2?.destroy(),this.internalTex2=null,this.internalTex3?.destroy(),this.internalTex3=null,this.colorParam?.destroy(),this.colorParam=null,this.vertexBuffer=void 0,this.indexBuffer=void 0;let t=this.meshInstance?.visible??!0;return this.meshInstance?.destroy(),this.meshInstance=null,this.material?.destroy(),this.material=null,t}destroy(){this.camera=null,this._destroyResources()}};var pI=class extends yi{generateKey(t){let e=t.shaderDesc,s=e.vertexGLSL?xt(e.vertexGLSL):0,i=e.fragmentGLSL?xt(e.fragmentGLSL):0,r=e.vertexWGSL?xt(e.vertexWGSL):0,a=e.fragmentWGSL?xt(e.fragmentWGSL):0,o=yi.definesHash(t.defines),l=t.shaderChunks?.key??"",h=`${e.uniqueName}_${o}_${s}_${i}_${r}_${a}_${l}`;return t.skin&&(h+="_skin"),t.useInstancing&&(h+="_inst"),t.useMorphPosition&&(h+="_morphp"),t.useMorphNormal&&(h+="_morphn"),t.useMorphTextureBasedInt&&(h+="_morphi"),h}createAttributesDefinition(t,e){let s=e.shaderDesc.attributes,i=s?{...s}:void 0;e.skin&&(i.vertex_boneWeights=bs,i.vertex_boneIndices=$t),(e.useMorphPosition||e.useMorphNormal)&&(i.morph_vertex_id=Da),t.attributes=i}createVertexDefinition(t,e,s,i){let r=e.shaderDesc,a=new Map(s);a.set("transformInstancingVS","");let o=new Map(e.defines);e.skin&&o.set("SKIN",!0),e.useInstancing&&o.set("INSTANCING",!0),(e.useMorphPosition||e.useMorphNormal)&&(o.set("MORPHING",!0),e.useMorphTextureBasedInt&&o.set("MORPHING_INT",!0),e.useMorphPosition&&o.set("MORPHING_POSITION",!0),e.useMorphNormal&&o.set("MORPHING_NORMAL",!0)),t.vertexCode=i?r.vertexWGSL:r.vertexGLSL,t.vertexIncludes=a,t.vertexDefines=o}createFragmentDefinition(t,e,s,i){let r=e.shaderDesc,a=new Map(s),o=new Map(e.defines);t.fragmentCode=i?r.fragmentWGSL:r.fragmentGLSL,t.fragmentIncludes=a,t.fragmentDefines=o}createShaderDefinition(t,e){let s=e.shaderDesc,i=t.isWebGPU&&!!s.vertexWGSL&&!!s.fragmentWGSL&&(e.shaderChunks?.useWGSL??!0),r={name:`ShaderMaterial-${s.uniqueName}`,shaderLanguage:i?se:fe,fragmentOutputTypes:s.fragmentOutputTypes,meshUniformBufferFormat:s.meshUniformBufferFormat,meshBindGroupFormat:s.meshBindGroupFormat},a=i?se:fe,o=Ha.merge(ne.get(t,a),e.shaderChunks[a]);return this.createAttributesDefinition(r,e),this.createVertexDefinition(r,e,o,i),this.createFragmentDefinition(r,e,o,i),ns.createDefinition(t,r)}},gM=new pI;var ct=class extends Us{constructor(e){super();n(this,"_shaderDesc");this.shaderDesc=e}set shaderDesc(e){if(this._shaderDesc=void 0,e&&(this._shaderDesc={uniqueName:e.uniqueName,attributes:e.attributes,fragmentOutputTypes:e.fragmentOutputTypes,vertexGLSL:e.vertexGLSL,fragmentGLSL:e.fragmentGLSL,vertexWGSL:e.vertexWGSL,fragmentWGSL:e.fragmentWGSL},e.vertexCode||e.fragmentCode||e.shaderLanguage)){let s=e.shaderLanguage??fe;s===fe?(this._shaderDesc.vertexGLSL=e.vertexCode,this._shaderDesc.fragmentGLSL=e.fragmentCode):s===se&&(this._shaderDesc.vertexWGSL=e.vertexCode,this._shaderDesc.fragmentWGSL=e.fragmentCode)}this.clearVariants()}get shaderDesc(){return this._shaderDesc}copy(e){return super.copy(e),this.shaderDesc=e.shaderDesc,this}getShaderVariant(e){let{objDefs:s}=e,i={defines:Se.getCoreDefines(this,e),skin:(s&Uo)!==0,useInstancing:(s&ko)!==0,useMorphPosition:(s&zo)!==0,useMorphNormal:(s&Go)!==0,useMorphTextureBasedInt:(s&Vo)!==0,pass:e.pass,gamma:e.cameraShaderParams.shaderOutputGamma,toneMapping:e.cameraShaderParams.toneMapping,fog:e.cameraShaderParams.fog,shaderDesc:this.shaderDesc,shaderChunks:this.shaderChunks},r=new sa(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),a=Ji(e.device);return a.register("shader-material",gM),a.getProgram("shader-material",i,r,this.userId)}};var SM=` uniform highp {sampler} {name}; {returnType} load{funcName}() { return texelFetch({name}, splat.uv, 0); } {returnType} load{funcName}WithIndex(uint index) { return texelFetch({name}, ivec2(index % splatTextureSize, index / splatTextureSize), 0); } -`,cw=` +`;var xM=` var {name}: {textureType}; fn load{funcName}() -> {returnType} { return textureLoad({name}, splat.uv, 0); } fn load{funcName}WithIndex(index: u32) -> {returnType} { return textureLoad({name}, vec2i(i32(index % uniform.splatTextureSize), i32(index / uniform.splatTextureSize)), 0); } -`,cb=` +`;var vM=` @group(0) @binding({binding}) var {name}: {textureType}; fn load{funcName}() -> {returnType} { return textureLoad({name}, splat.uv, 0); } fn load{funcName}WithIndex(index: u32) -> {returnType} { return textureLoad({name}, vec2i(i32(index % uniforms.splatTextureSize), i32(index / uniforms.splatTextureSize)), 0); } -`,cC=` +`;var mI=` void write{funcName}({returnType} value) { #if {defineGuard} pcFragColor{index} = value; #endif } -`,cA=` +`;var _I=` fn write{funcName}(value: {returnType}) { #if {defineGuard} processOutput.{colorSlot} = value; #endif } -`,cP=` +`;var Sy=` vec3 getCenter() { return loadDataCenter().xyz; } vec4 getColor() { return loadDataColor(); } vec3 getScale() { return loadDataScale().xyz; } vec4 getRotation() { return loadDataRotation(); } -`,cI=` +`;var xy=` fn getCenter() -> vec3f { return loadDataCenter().xyz; } fn getColor() -> vec4f { return loadDataColor(); } fn getScale() -> vec3f { return loadDataScale().xyz; } fn getRotation() -> vec4f { return loadDataRotation(); } -`,cD=` +`;var TM=` vec3 getCenter() { return loadDataCenter().xyz; } vec4 getColor() { return loadDataColor(); } vec3 getScale() { return vec3(loadDataCenter().w); } vec4 getRotation() { return vec4(0.0, 0.0, 0.0, 1.0); } -`,cR=` +`;var yM=` fn getCenter() -> vec3f { return loadDataCenter().xyz; } fn getColor() -> vec4f { return loadDataColor(); } fn getScale() -> vec3f { return vec3f(loadDataCenter().w); } fn getRotation() -> vec4f { return vec4f(0.0, 0.0, 0.0, 1.0); } -`;let cL=e=>e.map(e=>`${e.name}:${e.format}:${e.storage}`).join(","),cM=/\{name\}/g,cO=/\{sampler\}/g,cF=/\{textureType\}/g,cN=/\{returnType\}/g,cB=/\{funcName\}/g,ck=/\{binding\}/g,cU=/\{index\}/g,cz=/\{colorSlot\}/g,cV=/\{defineGuard\}/g;class cG{get hash(){if(void 0===this._hash){let e=cL(this.streams),t=cL(this._extraStreams);this._hash=iL(e+t+this._read);}return this._hash}get extraStreamsVersion(){return this._extraStreamsVersion}get extraStreams(){return this._extraStreams}get resourceStreams(){return null===this._resourceStreams&&(this._resourceStreams=[...this.streams.filter(e=>1!==e.storage),...this._extraStreams.filter(e=>1!==e.storage)]),this._resourceStreams}get instanceStreams(){return null===this._instanceStreams&&(this._instanceStreams=this._extraStreams.filter(e=>1===e.storage)),this._instanceStreams}addExtraStreams(e){if(!e||0===e.length)return;let t=false;for(let i of e)this._streamNames.has(i.name)||(this._extraStreams.push({name:i.name,format:i.format,storage:i.storage??0}),this._streamNames.add(i.name),t=true);t&&(this._extraStreamsVersion++,this._invalidateCaches());}removeExtraStreams(e){if(!this.allowStreamRemoval)return;let t=false;for(let i of e){let e=this._extraStreams.findIndex(e=>e.name===i);-1!==e&&(this._extraStreams.splice(e,1),this._streamNames.delete(i),t=true);}t&&(this._extraStreamsVersion++,this._invalidateCaches());}getInputDeclarations(e){let t=this._device.isWebGPU,i=t?cw:cE,s=t?e2:e1,r=[],a=[...this.streams,...this._extraStreams];for(let n of(e&&(a=a.filter(t=>e.includes(t.name))),a)){let e=s(n.format),a=n.name.charAt(0).toUpperCase()+n.name.slice(1),o=e.textureType??"";t&&14===n.format&&(o="texture_2d");let l=i.replace(cM,n.name).replace(cO,e.sampler??"").replace(cF,o).replace(cN,e.returnType).replace(cB,a);r.push(l);}return r.join("\n")}getReadCode(){return this._read}getComputeInputDeclarations(e,t){let i=[],s=[...this.streams,...this._extraStreams];t&&(s=s.filter(e=>t.includes(e.name)));for(let t=0;t");let l=cb.replace(ck,String(e+t)).replace(cM,r.name).replace(cF,o).replace(cN,a.returnType).replace(cB,n);i.push(l);}return i.join("\n")}getComputeBindFormats(e){let t=[...this.streams,...this._extraStreams];return e&&(t=t.filter(t=>e.includes(t.name))),t.map(e=>{let t=eX.get(e.format),i=0;return t?.isUint?i=4:t?.isInt&&(i=3),new ie(e.name,4,void 0,i,false)})}setWriteCode(e,t){this._write=this._device.isWebGPU?t:e;}getWriteCode(){return this._write}getOutputDeclarations(e){let t=this._device.isWebGPU,i=[],s=t?cA:cC,r=t?e2:e1;for(let t=0;tt.name===e);return t||(t=this._extraStreams.find(t=>t.name===e)),t}_invalidateCaches(){this._hash=void 0,this._resourceStreams=null,this._instanceStreams=null;}static createDefaultFormat(e){return new cG(e,[{name:"dataColor",format:12},{name:"dataCenter",format:14},{name:"dataScale",format:12},{name:"dataRotation",format:12}],{readGLSL:cP,readWGSL:cI})}static createSimpleFormat(e){return new cG(e,[{name:"dataCenter",format:14},{name:"dataColor",format:12}],{readGLSL:cD,readWGSL:cR})}constructor(e,t,i){this.allowStreamRemoval=false,this._extraStreams=[],this._streamNames=new Set,this._extraStreamsVersion=0,this._resourceStreams=null,this._instanceStreams=null,this._device=e,this.streams=[...t],this._streamNames=new Set(this.streams.map(e=>e.name));let s=e.isWebGPU;this._read=s?i.readWGSL:i.readGLSL;}}var cH=` +`;var EM=c=>c.map(t=>`${t.name}:${t.format}:${t.storage}`).join(","),AM=/\{name\}/g,L6=/\{sampler\}/g,CM=/\{textureType\}/g,vy=/\{returnType\}/g,Ty=/\{funcName\}/g,M6=/\{binding\}/g,O6=/\{index\}/g,F6=/\{colorSlot\}/g,PM=/\{defineGuard\}/g,Pr=class c{constructor(t,e,s){n(this,"_device");n(this,"streams");n(this,"_read");n(this,"allowStreamRemoval",!1);n(this,"_extraStreams",[]);n(this,"_streamNames",new Set);n(this,"_extraStreamsVersion",0);n(this,"_hash");n(this,"_resourceStreams",null);n(this,"_instanceStreams",null);this._device=t,this.streams=[...e],this._streamNames=new Set(this.streams.map(r=>r.name));let i=t.isWebGPU;this._read=i?s.readWGSL:s.readGLSL}get hash(){if(this._hash===void 0){let t=EM(this.streams),e=EM(this._extraStreams);this._hash=xt(t+e+this._read)}return this._hash}get extraStreamsVersion(){return this._extraStreamsVersion}get extraStreams(){return this._extraStreams}get resourceStreams(){return this._resourceStreams===null&&(this._resourceStreams=[...this.streams.filter(t=>t.storage!==Vf),...this._extraStreams.filter(t=>t.storage!==Vf)]),this._resourceStreams}get instanceStreams(){return this._instanceStreams===null&&(this._instanceStreams=this._extraStreams.filter(t=>t.storage===Vf)),this._instanceStreams}addExtraStreams(t){if(!t||t.length===0)return;let e=!1;for(let s of t)this._streamNames.has(s.name)||(this._extraStreams.push({name:s.name,format:s.format,storage:s.storage??Rw}),this._streamNames.add(s.name),e=!0);e&&(this._extraStreamsVersion++,this._invalidateCaches())}removeExtraStreams(t){if(!this.allowStreamRemoval)return;let e=!1;for(let s of t){let i=this._extraStreams.findIndex(r=>r.name===s);i!==-1&&(this._extraStreams.splice(i,1),this._streamNames.delete(s),e=!0)}e&&(this._extraStreamsVersion++,this._invalidateCaches())}getInputDeclarations(t){let e=this._device.isWebGPU,s=e?xM:SM,i=e?Ad:An,r=[],a=[...this.streams,...this._extraStreams];t&&(a=a.filter(o=>t.includes(o.name)));for(let o of a){let l=i(o.format),h=o.name.charAt(0).toUpperCase()+o.name.slice(1),f=l.textureType??"";e&&o.format===ke&&(f="texture_2d");let u=s.replace(AM,o.name).replace(L6,l.sampler??"").replace(CM,f).replace(vy,l.returnType).replace(Ty,h);r.push(u)}return r.join(` +`)}getReadCode(){return this._read}getComputeInputDeclarations(t,e){let s=[],i=[...this.streams,...this._extraStreams];e&&(i=i.filter(r=>e.includes(r.name)));for(let r=0;r");let f=vM.replace(M6,String(t+r)).replace(AM,a.name).replace(CM,h).replace(vy,o.returnType).replace(Ty,l);s.push(f)}return s.join(` +`)}getComputeBindFormats(t){let e=[...this.streams,...this._extraStreams];return t&&(e=e.filter(s=>t.includes(s.name))),e.map(s=>{let i=xs.get(s.format),r=rs;return i?.isUint?r=Wi:i?.isInt&&(r=Hi),new Ki(s.name,X,void 0,r,!1)})}setWriteCode(t,e){this._write=this._device.isWebGPU?e:t}getWriteCode(){return this._write}getOutputDeclarations(t){let e=this._device.isWebGPU,s=[],i=e?_I:mI,r=e?Ad:An;for(let a=0;as.name===t);return e||(e=this._extraStreams.find(s=>s.name===t)),e}_invalidateCaches(){this._hash=void 0,this._resourceStreams=null,this._instanceStreams=null}static createDefaultFormat(t){return new c(t,[{name:"dataColor",format:Me},{name:"dataCenter",format:ke},{name:"dataScale",format:Me},{name:"dataRotation",format:Me}],{readGLSL:Sy,readWGSL:xy})}static createSimpleFormat(t){return new c(t,[{name:"dataCenter",format:ke},{name:"dataColor",format:Me}],{readGLSL:TM,readWGSL:yM})}};var wM=` uvec4 cachedTransformA; vec3 getCenter() { cachedTransformA = loadDataTransformA(); @@ -468,27 +508,27 @@ float getOpacity() { return float(cachedTransformA.a >> 24u) / 255.0; } vec3 getColor() { - uint packed = loadDataColor().x; - float r = float(packed & 0x7FFu) * (4.0 / 2047.0); - float g = float((packed >> 11u) & 0x7FFu) * (4.0 / 2047.0); - float b = float((packed >> 22u) & 0x3FFu) * (4.0 / 1023.0); + uint data = loadDataColor().x; + float r = float(data & 0x7FFu) * (4.0 / 2047.0); + float g = float((data >> 11u) & 0x7FFu) * (4.0 / 2047.0); + float b = float((data >> 22u) & 0x3FFu) * (4.0 / 1023.0); return vec3(r, g, b); } vec4 getRotation() { - uint packed = loadDataTransformB().x; + uint data = loadDataTransformB().x; vec3 p = vec3( - float(packed & 0x7FFu) / 2047.0 * 2.0 - 1.0, - float((packed >> 11u) & 0x7FFu) / 2047.0 * 2.0 - 1.0, - float((packed >> 22u) & 0x3FFu) / 1023.0 * 2.0 - 1.0 + float(data & 0x7FFu) / 2047.0 * 2.0 - 1.0, + float((data >> 11u) & 0x7FFu) / 2047.0 * 2.0 - 1.0, + float((data >> 22u) & 0x3FFu) / 1023.0 * 2.0 - 1.0 ); float d = dot(p, p); return vec4(1.0 - d, sqrt(max(0.0, 2.0 - d)) * p); } vec3 getScale() { - uint packed = cachedTransformA.a; - float sx = float(packed & 0xFFu); - float sy = float((packed >> 8u) & 0xFFu); - float sz = float((packed >> 16u) & 0xFFu); + uint data = cachedTransformA.a; + float sx = float(data & 0xFFu); + float sy = float((data >> 8u) & 0xFFu); + float sz = float((data >> 16u) & 0xFFu); const float logRange = 21.0 / 255.0; const float logMin = -12.0; return vec3( @@ -497,7 +537,7 @@ vec3 getScale() { sz == 0.0 ? 0.0 : exp(sz * logRange + logMin) ); } -`,cW=` +`;var IM=` void writeSplat(vec3 center, vec4 rotation, vec3 scale, vec4 color) { vec3 rgb = clamp(color.rgb, 0.0, 4.0); uint rBits = uint(rgb.r * (2047.0 / 4.0) + 0.5); @@ -523,7 +563,7 @@ void writeSplat(vec3 center, vec4 rotation, vec3 scale, vec4 color) { writeDataTransformB(uvec4(packedQuat, 0u, 0u, 0u)); #endif } -`,cX=` +`;var RM=` uvec4 cachedTransformA; uvec2 cachedTransformB; vec4 cachedColor; @@ -557,7 +597,7 @@ vec3 getScale() { vec2 scaleYZ = unpackHalf2x16(cachedTransformB.y); return vec3(rotZscaleX.y, scaleYZ); } -`,cY=` +`;var bM=` void writeSplat(vec3 center, vec4 rotation, vec3 scale, vec4 color) { #ifdef GSPLAT_COLOR_UINT uint packed_rg = packHalf2x16(color.rg); @@ -576,7 +616,7 @@ void writeSplat(vec3 center, vec4 rotation, vec3 scale, vec4 color) { writeDataTransformB(uvec4(packHalf2x16(vec2(rotation.z, scale.x)), packHalf2x16(scale.yz), 0u, 0u)); #endif } -`,cq=` +`;var DM=` var cachedTransformA: vec4u; fn getCenter() -> vec3f { cachedTransformA = loadDataTransformA(); @@ -586,27 +626,27 @@ fn getOpacity() -> f32 { return f32(cachedTransformA.a >> 24u) / 255.0; } fn getColor() -> vec3f { - let packed = loadDataColor().x; - let r = f32(packed & 0x7FFu) * (4.0 / 2047.0); - let g = f32((packed >> 11u) & 0x7FFu) * (4.0 / 2047.0); - let b = f32((packed >> 22u) & 0x3FFu) * (4.0 / 1023.0); + let data = loadDataColor().x; + let r = f32(data & 0x7FFu) * (4.0 / 2047.0); + let g = f32((data >> 11u) & 0x7FFu) * (4.0 / 2047.0); + let b = f32((data >> 22u) & 0x3FFu) * (4.0 / 1023.0); return vec3f(r, g, b); } fn getRotation() -> vec4f { - let packed = loadDataTransformB().x; + let data = loadDataTransformB().x; let p = vec3f( - f32(packed & 0x7FFu) / 2047.0 * 2.0 - 1.0, - f32((packed >> 11u) & 0x7FFu) / 2047.0 * 2.0 - 1.0, - f32((packed >> 22u) & 0x3FFu) / 1023.0 * 2.0 - 1.0 + f32(data & 0x7FFu) / 2047.0 * 2.0 - 1.0, + f32((data >> 11u) & 0x7FFu) / 2047.0 * 2.0 - 1.0, + f32((data >> 22u) & 0x3FFu) / 1023.0 * 2.0 - 1.0 ); let d = dot(p, p); return vec4f(1.0 - d, sqrt(max(0.0, 2.0 - d)) * p); } fn getScale() -> vec3f { - let packed = cachedTransformA.a; - let sx = f32(packed & 0xFFu); - let sy = f32((packed >> 8u) & 0xFFu); - let sz = f32((packed >> 16u) & 0xFFu); + let data = cachedTransformA.a; + let sx = f32(data & 0xFFu); + let sy = f32((data >> 8u) & 0xFFu); + let sz = f32((data >> 16u) & 0xFFu); let logRange = 21.0 / 255.0; let logMin = -12.0; return vec3f( @@ -615,7 +655,7 @@ fn getScale() -> vec3f { select(exp(sz * logRange + logMin), 0.0, sz == 0.0) ); } -`,cj=` +`;var LM=` fn writeSplat(center: vec3f, rotation: vec4f, scale: vec3f, color: vec4f) { let rgb = clamp(color.rgb, vec3f(0.0), vec3f(4.0)); let rBits = u32(rgb.r * (2047.0 / 4.0) + 0.5); @@ -641,7 +681,7 @@ fn writeSplat(center: vec3f, rotation: vec4f, scale: vec3f, color: vec4f) { writeDataTransformB(vec4u(packedQuat, 0u, 0u, 0u)); #endif } -`,cK=` +`;var MM=` var cachedTransformA: vec4u; var cachedTransformB: vec2u; var cachedColor: vec4f; @@ -675,7 +715,7 @@ fn getScale() -> vec3f { let scaleYZ = unpack2x16float(cachedTransformB.y); return vec3f(rotZscaleX.y, scaleYZ); } -`,c$=` +`;var OM=` fn writeSplat(center: vec3f, rotation: vec4f, scale: vec3f, color: vec4f) { writeDataColor(color); #ifndef GSPLAT_COLOR_ONLY @@ -683,7 +723,7 @@ fn writeSplat(center: vec3f, rotation: vec4f, scale: vec3f, color: vec4f) { writeDataTransformB(vec4u(pack2x16float(vec2f(rotation.z, scale.x)), pack2x16float(scale.yz), 0u, 0u)); #endif } -`;class cZ{_createFormat(e){let t;if(e===nz)(t=new cG(this._device,[{name:"dataColor",format:37},{name:"dataTransformA",format:49},{name:"dataTransformB",format:37}],{readGLSL:cH,readWGSL:cq})).setWriteCode(cW,cj);else {let e=this._device.getRenderableHdrFormat([12])||47;(t=new cG(this._device,[{name:"dataColor",format:e},{name:"dataTransformA",format:49},{name:"dataTransformB",format:43}],{readGLSL:cX,readWGSL:cK})).setWriteCode(cY,c$);}return t.allowStreamRemoval=true,t}set renderer(e){this._renderer!==e&&(this._renderer=e,0===e?this._currentRenderer=1:2!==e&&3!==e||this._device.isWebGPU?this._currentRenderer=e:this._currentRenderer=1);}get renderer(){return this._renderer}get currentRenderer(){return this._currentRenderer}set debug(e){if(this._debug!==e){let t=this._debug;this._debug=e,(1===e||1===t||3===e||3===t)&&(this.dirty=true);}}get debug(){return this._debug}set colorizeLod(e){this.debug=+!!e;}get colorizeLod(){return 1===this._debug}set enableIds(e){e&&!this._enableIds?(this._enableIds=true,this._format.getStream("pcId")||this._format.addExtraStreams([{name:"pcId",format:37}])):!e&&this._enableIds&&(this._enableIds=false,this._format.removeExtraStreams(["pcId"]));}get enableIds(){return this._enableIds}set lodBehindPenalty(e){this._lodBehindPenalty!==e&&(this._lodBehindPenalty=e,this.dirty=true);}get lodBehindPenalty(){return this._lodBehindPenalty}set lodRangeMin(e){this._lodRangeMin!==e&&(this._lodRangeMin=e,this.dirty=true);}get lodRangeMin(){return this._lodRangeMin}set lodRangeMax(e){this._lodRangeMax!==e&&(this._lodRangeMax=e,this.dirty=true);}get lodRangeMax(){return this._lodRangeMax}set lodUnderfillLimit(e){this._lodUnderfillLimit!==e&&(this._lodUnderfillLimit=e,this.dirty=true);}get lodUnderfillLimit(){return this._lodUnderfillLimit}set splatBudget(e){this._splatBudget!==e&&(this._splatBudget=e,this.dirty=true);}get splatBudget(){return this._splatBudget}set colorRamp(e){this._colorRamp!==e&&(this._colorRamp=e,this.dirty=true);}get colorRamp(){return this._colorRamp}set colorizeColorUpdate(e){this.debug=2*!!e;}get colorizeColorUpdate(){return 2===this._debug}set colorUpdateDistance(e){}get colorUpdateDistance(){return 0}set colorUpdateDistanceLodScale(e){}get colorUpdateDistanceLodScale(){return 0}set colorUpdateAngleLodScale(e){}get colorUpdateAngleLodScale(){return 0}set alphaClip(e){this._material.setParameter("alphaClip",e),this._material.update();}get alphaClip(){return this._material.getParameter("alphaClip")?.data??.3}set minPixelSize(e){this._material.setParameter("minPixelSize",e),this._material.update();}get minPixelSize(){return this._material.getParameter("minPixelSize")?.data??2}set minContribution(e){this._material.setParameter("minContribution",e),this._material.update();}get minContribution(){return this._material.getParameter("minContribution")?.data??3}set antiAlias(e){this._material.setDefine("GSPLAT_AA",e),this._material.update();}get antiAlias(){return !!this._material.getDefine("GSPLAT_AA")}set twoDimensional(e){this._material.setDefine("GSPLAT_2DGS",e),this._material.update();}get twoDimensional(){return !!this._material.getDefine("GSPLAT_2DGS")}set fisheye(e){if(this._fisheye!==e){let t=this._fisheye>0;this._fisheye=e;let i=e>0;t!==i&&(this._material.setDefine("GSPLAT_FISHEYE",i),this._material.update());}}get fisheye(){return this._fisheye}set dataFormat(e){if(this._dataFormat!==e){this._dataFormat=e;let t=this._format.extraStreams.map(e=>({name:e.name,format:e.format,storage:e.storage}));this._format=this._createFormat(e),t.length>0&&this._format.addExtraStreams(t),this.dirty=true;}}get dataFormat(){return this._dataFormat}get material(){return this._material}get format(){return this._format}frameEnd(){this._material.dirty=false,this.dirty=false;}constructor(e){this._material=new cT,this._dataFormat=nz,this.debugAabbs=false,this.radialSorting=false,this._renderer=0,this._currentRenderer=1,this.debugNodeAabbs=false,this.dirty=false,this._debug=0,this._enableIds=false,this.lodUpdateDistance=1,this.lodUpdateAngle=0,this._lodBehindPenalty=1,this._lodRangeMin=0,this._lodRangeMax=10,this._lodUnderfillLimit=0,this._splatBudget=0,this._colorRamp=null,this.colorRampIntensity=1,this.useFog=true,this.colorUpdateAngle=10,this._fisheye=0,this.cooldownTicks=100,this._device=e,this._format=this._createFormat(nz),this._material.setParameter("alphaClip",.3),this._material.setParameter("minPixelSize",2),this._material.setParameter("minContribution",3);}}class cQ{update(e,t,i){1===i.data[15]&&(e=0);let s=i.data[0],r=i.data[5];if(e===this._lastT&&t===this._lastFov&&s===this._lastP00&&r===this._lastP11)return;if(this._lastT=e,this._lastFov=t,this._lastP00=s,this._lastP11=r,e<=0){this.enabled=false,this.k=1,this.invK=1,this.cornerScale=1,this.maxTheta=Math.PI;return}this.enabled=true;let a=Math.max(1,t/180+.05),n=a*Math.pow((t/180+.15)/a,e);this.k=n,this.invK=1/n,this.cornerScale=1+(Math.SQRT2-1)*e;let o=Math.min(n*Math.PI/2,3.13),l=this.cornerScale,h=Math.min(Math.atan2(1,s),o-.01);this.projMat00=l/(n*Math.tan(h/n));let c=Math.min(Math.atan2(1,r),o-.01);this.projMat11=l/(n*Math.tan(c/n)),this.maxTheta=o;}constructor(){this.enabled=false,this.k=1,this.invK=1,this.cornerScale=1,this.projMat00=1,this.projMat11=1,this.maxTheta=Math.PI,this._lastT=-1,this._lastFov=-1,this._lastP00=0,this._lastP11=0;}}let cJ={linear:"decodeLinear",srgb:"decodeGamma",rgbm:"decodeRGBM",rgbe:"decodeRGBE",rgbp:"decodeRGBP",xy:"unpackNormalXY",xyz:"unpackNormalXYZ"},c0={linear:"encodeLinear",srgb:"encodeGamma",rgbm:"encodeRGBM",rgbe:"encodeRGBE",rgbp:"encodeRGBP"};class c1{static decodeFunc(e){return cJ[e]??"decodeGamma"}static encodeFunc(e){return c0[e]??"encodeGamma"}}let c2=(e,t)=>{let i=t.length/3,s=e.length/3,r=new ed,a=new ed,n=new ed,o=new ed,l=new ed,h=new ed,c=[];for(let t=0;t{let r=s.length/3,a=e.length/3,n=new ed,o=new ed,l=new ed,h=new ef,c=new ef,d=new ef,u=new ed,f=new ed,p=new Float32Array(3*a),m=new Float32Array(3*a),_=[];for(let t=0;ty.dot(v)?-1:1;}return _};class c4{calculateNormals(){this.normals=c2(this.positions,this.indices);}calculateTangents(){this.tangents=c3(this.positions,this.normals,this.uvs,this.indices);}}class c5 extends c4{constructor(e={}){super();let t=e.halfExtents??new ed(.5,.5,.5),i=e.widthSegments??1,s=e.lengthSegments??1,r=e.heightSegments??1,a=e.yOffset??0,n=-t.y+a,o=t.y+a,l=[new ed(-t.x,n,t.z),new ed(t.x,n,t.z),new ed(t.x,o,t.z),new ed(-t.x,o,t.z),new ed(t.x,n,-t.z),new ed(-t.x,n,-t.z),new ed(-t.x,o,-t.z),new ed(t.x,o,-t.z)],h=[[0,1,3],[4,5,7],[3,2,6],[1,0,4],[1,4,2],[5,0,6]],c=[[0,0,1],[0,0,-1],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0]],d=[],u=[],f=[],p=[],m=[],_=0,g=(e,t,i)=>{let s=new ed,r=new ed,a=new ed,n=new ed;for(let o=0;o<=t;o++)for(let g=0;g<=i;g++){s.lerp(l[h[e][0]],l[h[e][1]],o/t),r.lerp(l[h[e][0]],l[h[e][2]],g/i),a.sub2(r,l[h[e][0]]),n.add2(s,a);let v=o/t,S=g/i;d.push(n.x,n.y,n.z),u.push(c[e][0],c[e][1],c[e][2]),f.push(v,1-S),S=(.75*S+.125)/3,v=(.75*v+.125)/3+e%3/3,S+=Math.floor(e/3)/3,p.push(v,1-S),o0;this._fisheye=e;let i=e>0;t!==i&&(this._fisheyeProj??(this._fisheyeProj=new cQ),this._type===nb&&this._setFisheyeDefine(i));}}get fisheye(){return this._fisheye}updateSkyMesh(){let e=this.scene._getSkyboxTex();e&&(this.resetSkyMesh(),this.skyMesh=new c7(this.device,this.scene,this.node,e,this.type),this.skyMesh.depthWrite=this._depthWrite,this._fisheye>0&&this.type===nb&&this._setFisheyeDefine(true),this.scene.fire("set:skybox",e));}resetSkyMesh(){this.skyMesh?.destroy(),this.skyMesh=null;}update(){if(this.type!==nb){let{center:e,centerArray:t}=this,i=new ed;this.node.getWorldTransform().transformPoint(e,i),t[0]=i.x,t[1]=i.y,t[2]=i.z,this.projectedSkydomeCenterId.setValue(t);}}_setFisheyeDefine(e){if(this.skyMesh?.meshInstance){let t=this.skyMesh.meshInstance.material;t.setDefine("SKY_FISHEYE",e),t.update();}}_onPreRender(e){if(this._fisheye>0&&this._fisheyeProj&&this.skyMesh?.meshInstance){let t=e.camera,i=this._fisheyeProj;i.update(this._fisheye,t.fov,t.projectionMatrix);let s=this.skyMesh.meshInstance.material;s.setParameter("fisheye_k",i.k),s.setParameter("fisheye_invK",i.invK),s.setParameter("fisheye_projMat00",i.projMat00),s.setParameter("fisheye_projMat11",i.projMat11);}}constructor(e){this._type=nb,this._center=new ed(0,1,0),this.skyMesh=null,this._depthWrite=false,this._fisheye=0,this._fisheyeProj=null,this.node=new oJ("SkyMeshNode"),this.device=e.device,this.scene=e,this.center=new ed(0,1,0),this.centerArray=new Float32Array(3),this.projectedSkydomeCenterId=this.device.scope.resolve("projectedSkydomeCenter"),this._preRenderEvt=e.on("prerender",this._onPreRender,this);}}let dt=new oJ;dt.worldTransform=ey.IDENTITY,dt._dirtyWorld=dt._dirtyNormal=false;class di{addLines(e,t){let i=this.positions,s=e.length;for(let t=0;t0&&this.material.transparent===t&&(this.mesh.setPositions(this.positions),this.mesh.setColors(this.colors),this.mesh.update(1,false),this.meshInstance||(this.meshInstance=new oS(this.mesh,this.material,dt)),e.push(this.meshInstance));}clear(){this.positions.length=0,this.colors.length=0;}constructor(e,t,i){this.material=t,this.layer=i,this.positions=[],this.colors=[],this.mesh=new on(e),this.meshInstance=null;}}class ds{getBatch(e,t){let i=this.map.get(e);return i||(i=new di(this.device,e,t),this.map.set(e,i)),i}onPreRender(e,t){this.map.forEach(i=>{i.onPreRender(e,t);});}clear(){this.map.forEach(e=>e.clear());}constructor(e){this.device=e,this.map=new Map;}}let dr=[],da=new ed;class dn{createMaterial(e){let t=new cT({uniqueName:"ImmediateLine",vertexGLSL:n$.get(this.device,tz).get("immediateLineVS"),fragmentGLSL:n$.get(this.device,tz).get("immediateLinePS"),vertexWGSL:n$.get(this.device,tV).get("immediateLineVS"),fragmentWGSL:n$.get(this.device,tV).get("immediateLinePS"),attributes:{vertex_position:e8,vertex_color:ti}});return t.blendType=2,t.depthTest=e,t.update(),t}get materialDepth(){return this._materialDepth||(this._materialDepth=this.createMaterial(true)),this._materialDepth}get materialNoDepth(){return this._materialNoDepth||(this._materialNoDepth=this.createMaterial(false)),this._materialNoDepth}getBatch(e,t){let i=this.batchesMap.get(e);i||(i=new ds(this.device),this.batchesMap.set(e,i)),this.allBatches.add(i);let s=t?this.materialDepth:this.materialNoDepth;return i.getBatch(s,e)}getShaderDesc(e,t,i){return this.shaderDescs.has(e)||this.shaderDescs.set(e,{uniqueName:`DebugShader:${e}`,vertexGLSL:` +`;var yy=class{constructor(t){n(this,"_material",new ct);n(this,"_format");n(this,"_device");n(this,"_dataFormat",iS);n(this,"radialSorting",!1);n(this,"_renderer",ET);n(this,"_currentRenderer",tl);n(this,"dirty",!1);n(this,"_debug",Wf);n(this,"_enableIds",!1);n(this,"lodUpdateDistance",1);n(this,"lodUpdateAngle",0);n(this,"_lodBehindPenalty",1);n(this,"_lodRangeMin",0);n(this,"_lodRangeMax",10);n(this,"_lodUnderfillLimit",0);n(this,"_splatBudget",0);n(this,"_colorRamp",null);n(this,"colorRampIntensity",1);n(this,"useFog",!0);n(this,"colorUpdateAngle",10);n(this,"_fisheye",0);n(this,"cooldownTicks",100);this._device=t,this._format=this._createFormat(iS),this._material.setParameter("alphaClip",.3),this._material.setParameter("alphaClipForward",1/255),this._material.setParameter("minPixelSize",2),this._material.setParameter("minContribution",3)}_createFormat(t){let e;if(t===iS)e=new Pr(this._device,[{name:"dataColor",format:zt},{name:"dataTransformA",format:At},{name:"dataTransformB",format:zt}],{readGLSL:wM,readWGSL:DM}),e.setWriteCode(IM,LM);else{let s=this._device.getRenderableHdrFormat([Me])||Rs;e=new Pr(this._device,[{name:"dataColor",format:s},{name:"dataTransformA",format:At},{name:"dataTransformB",format:Tn}],{readGLSL:RM,readWGSL:MM}),e.setWriteCode(bM,OM)}return e.allowStreamRemoval=!0,e}set renderer(t){this._renderer!==t&&(this._renderer=t,t===ET?this._currentRenderer=tl:(t===Hf||t===Cc)&&!this._device.isWebGPU?this._currentRenderer=tl:this._currentRenderer=t)}get renderer(){return this._renderer}get currentRenderer(){return this._currentRenderer}set debug(t){if(this._debug!==t){let e=this._debug;this._debug=t,(t===Pc||e===Pc||t===Ep||e===Ep)&&(this.dirty=!0)}}get debug(){return this._debug}set colorizeLod(t){this.debug=t?Pc:Wf}get colorizeLod(){return this._debug===Pc}set debugAabbs(t){this.debug=t?AT:Wf}get debugAabbs(){return this._debug===AT}set debugNodeAabbs(t){this.debug=t?CT:Wf}get debugNodeAabbs(){return this._debug===CT}set enableIds(t){t&&!this._enableIds?(this._enableIds=!0,this._format.getStream("pcId")||this._format.addExtraStreams([{name:"pcId",format:zt}])):!t&&this._enableIds&&(this._enableIds=!1,this._format.removeExtraStreams(["pcId"]))}get enableIds(){return this._enableIds}set lodBehindPenalty(t){this._lodBehindPenalty!==t&&(this._lodBehindPenalty=t,this.dirty=!0)}get lodBehindPenalty(){return this._lodBehindPenalty}set lodRangeMin(t){this._lodRangeMin!==t&&(this._lodRangeMin=t,this.dirty=!0)}get lodRangeMin(){return this._lodRangeMin}set lodRangeMax(t){this._lodRangeMax!==t&&(this._lodRangeMax=t,this.dirty=!0)}get lodRangeMax(){return this._lodRangeMax}set lodUnderfillLimit(t){this._lodUnderfillLimit!==t&&(this._lodUnderfillLimit=t,this.dirty=!0)}get lodUnderfillLimit(){return this._lodUnderfillLimit}set splatBudget(t){this._splatBudget!==t&&(this._splatBudget=t,this.dirty=!0)}get splatBudget(){return this._splatBudget}set colorRamp(t){this._colorRamp!==t&&(this._colorRamp=t,this.dirty=!0)}get colorRamp(){return this._colorRamp}set colorizeColorUpdate(t){this.debug=t?yp:Wf}get colorizeColorUpdate(){return this._debug===yp}set colorUpdateDistance(t){}get colorUpdateDistance(){return 0}set colorUpdateDistanceLodScale(t){}get colorUpdateDistanceLodScale(){return 0}set colorUpdateAngleLodScale(t){}get colorUpdateAngleLodScale(){return 0}set alphaClip(t){this._material.setParameter("alphaClip",t),this._material.update()}get alphaClip(){return this._material.getParameter("alphaClip")?.data??.3}set alphaClipForward(t){this._material.setParameter("alphaClipForward",t),this._material.update()}get alphaClipForward(){return this._material.getParameter("alphaClipForward")?.data??1/255}set minPixelSize(t){this._material.setParameter("minPixelSize",t),this._material.update()}get minPixelSize(){return this._material.getParameter("minPixelSize")?.data??2}set minContribution(t){this._material.setParameter("minContribution",t),this._material.update()}get minContribution(){return this._material.getParameter("minContribution")?.data??3}set antiAlias(t){this._material.setDefine("GSPLAT_AA",t),this._material.update()}get antiAlias(){return!!this._material.getDefine("GSPLAT_AA")}set twoDimensional(t){this._material.setDefine("GSPLAT_2DGS",t),this._material.update()}get twoDimensional(){return!!this._material.getDefine("GSPLAT_2DGS")}set fisheye(t){if(this._fisheye!==t){let e=this._fisheye>0;this._fisheye=t;let s=t>0;e!==s&&(this._material.setDefine("GSPLAT_FISHEYE",s),this._material.update())}}get fisheye(){return this._fisheye}set dataFormat(t){if(this._dataFormat!==t){this._dataFormat=t;let e=this._format.extraStreams.map(s=>({name:s.name,format:s.format,storage:s.storage}));this._format=this._createFormat(t),e.length>0&&this._format.addExtraStreams(e),this.dirty=!0}}get dataFormat(){return this._dataFormat}get material(){return this._material}get format(){return this._format}frameEnd(){this._material.dirty=!1,this.dirty=!1}};var Yp=class{constructor(){n(this,"enabled",!1);n(this,"k",1);n(this,"invK",1);n(this,"cornerScale",1);n(this,"projMat00",1);n(this,"projMat11",1);n(this,"maxTheta",Math.PI);n(this,"_lastT",-1);n(this,"_lastFov",-1);n(this,"_lastP00",0);n(this,"_lastP11",0)}update(t,e,s){s.data[15]===1&&(t=0);let i=s.data[0],r=s.data[5];if(t===this._lastT&&e===this._lastFov&&i===this._lastP00&&r===this._lastP11)return;if(this._lastT=t,this._lastFov=e,this._lastP00=i,this._lastP11=r,t<=0){this.enabled=!1,this.k=1,this.invK=1,this.cornerScale=1,this.maxTheta=Math.PI;return}this.enabled=!0;let a=e/180+.15,o=Math.max(1,e/180+.05),l=o*Math.pow(a/o,t);this.k=l,this.invK=1/l,this.cornerScale=1+(Math.SQRT2-1)*t;let h=Math.min(l*Math.PI/2,3.13),f=this.cornerScale,u=Math.atan2(1,i),d=Math.min(u,h-.01);this.projMat00=f/(l*Math.tan(d/l));let p=Math.atan2(1,r),m=Math.min(p,h-.01);this.projMat11=f/(l*Math.tan(m/l)),this.maxTheta=h}};var Kp=(c,t)=>{let e=t.length/3,s=c.length/3,i=new x,r=new x,a=new x,o=new x,l=new x,h=new x,f=[];for(let u=0;u{let i=s.length/3,r=c.length/3,a=new x,o=new x,l=new x,h=new B,f=new B,u=new B,d=new x,p=new x,m=new Float32Array(r*3),_=new Float32Array(r*3),S=[];for(let E=0;E{let P=new x,A=new x,w=new x,I=new x;for(let D=0;D<=E;D++)for(let O=0;O<=y;O++){P.lerp(h[f[v][0]],h[f[v][1]],D/E),A.lerp(h[f[v][0]],h[f[v][2]],O/y),w.sub2(A,h[f[v][0]]),I.add2(P,w);let G=D/E,M=O/y;p.push(I.x,I.y,I.z),m.push(u[v][0],u[v][1],u[v][2]),_.push(G,1-M),G=G*FM+gI,M=M*FM+gI,G/=3,M/=3,G+=v%3/3,M+=Math.floor(v/3)/3,S.push(G,1-M),D0;this._fisheye=t;let s=t>0;e!==s&&(this._fisheyeProj??(this._fisheyeProj=new Yp),this._type===Jn&&this._setFisheyeDefine(s))}}get fisheye(){return this._fisheye}updateSkyMesh(){let t=this.scene._getSkyboxTex();t&&(this.resetSkyMesh(),this.skyMesh=new Ay(this.device,this.scene,this.node,t,this.type),this.skyMesh.depthWrite=this._depthWrite,this._fisheye>0&&this.type===Jn&&this._setFisheyeDefine(!0),this.scene.fire("set:skybox",t))}resetSkyMesh(){this.skyMesh?.destroy(),this.skyMesh=null}update(){if(this.type!==Jn){let{center:t,centerArray:e}=this,s=new x;this.node.getWorldTransform().transformPoint(t,s),e[0]=s.x,e[1]=s.y,e[2]=s.z,this.projectedSkydomeCenterId.setValue(e)}}_setFisheyeDefine(t){if(this.skyMesh?.meshInstance){let e=this.skyMesh.meshInstance.material;e.setDefine("SKY_FISHEYE",t),e.update()}}_onPreRender(t){if(this._fisheye>0&&this._fisheyeProj&&this.skyMesh?.meshInstance){let e=t.camera,s=this._fisheyeProj;s.update(this._fisheye,e.fov,e.projectionMatrix);let i=this.skyMesh.meshInstance.material;i.setParameter("fisheye_k",s.k),i.setParameter("fisheye_invK",s.invK),i.setParameter("fisheye_projMat00",s.projMat00),i.setParameter("fisheye_projMat11",s.projMat11)}}};var Cy=new Pe;Cy.worldTransform=W.IDENTITY;Cy._dirtyWorld=Cy._dirtyNormal=!1;var Py=class{constructor(t,e,s){this.material=e,this.layer=s,this.positions=[],this.colors=[],this.mesh=new _e(t),this.meshInstance=null}addLines(t,e){let s=this.positions,i=t.length;for(let a=0;a0&&this.material.transparent===e&&(this.mesh.setPositions(this.positions),this.mesh.setColors(this.colors),this.mesh.update(Pn,!1),this.meshInstance||(this.meshInstance=new we(this.mesh,this.material,Cy)),t.push(this.meshInstance))}clear(){this.positions.length=0,this.colors.length=0}};var wy=class{constructor(t){this.device=t,this.map=new Map}getBatch(t,e){let s=this.map.get(t);return s||(s=new Py(this.device,t,e),this.map.set(t,s)),s}onPreRender(t,e){this.map.forEach(s=>{s.onPreRender(t,e)})}clear(){this.map.forEach(t=>t.clear())}};var la=[],$p=new x,Iy=class{constructor(t){n(this,"shaderDescs",new Map);this.device=t,this.quadMesh=null,this.textureShader=null,this.depthTextureShader=null,this.cubeLocalPos=null,this.cubeWorldPos=null,this.batchesMap=new Map,this.allBatches=new Set,this.updatedLayers=new Set,this._materialDepth=null,this._materialNoDepth=null,this.layerMeshInstances=new Map}createMaterial(t){let e=new ct({uniqueName:"ImmediateLine",vertexGLSL:ne.get(this.device,fe).get("immediateLineVS"),fragmentGLSL:ne.get(this.device,fe).get("immediateLinePS"),vertexWGSL:ne.get(this.device,se).get("immediateLineVS"),fragmentWGSL:ne.get(this.device,se).get("immediateLinePS"),attributes:{vertex_position:ee,vertex_color:Ct}});return e.blendType=ls,e.depthTest=t,e.update(),e}get materialDepth(){return this._materialDepth||(this._materialDepth=this.createMaterial(!0)),this._materialDepth}get materialNoDepth(){return this._materialNoDepth||(this._materialNoDepth=this.createMaterial(!1)),this._materialNoDepth}getBatch(t,e){let s=this.batchesMap.get(t);s||(s=new wy(this.device),this.batchesMap.set(t,s)),this.allBatches.add(s);let i=e?this.materialDepth:this.materialNoDepth;return s.getBatch(i,t)}getShaderDesc(t,e,s){return this.shaderDescs.has(t)||this.shaderDescs.set(t,{uniqueName:`DebugShader:${t}`,vertexGLSL:` attribute vec2 vertex_position; uniform mat4 matrix_model; varying vec2 uv0; @@ -701,12 +741,12 @@ fn writeSplat(center: vec3f, rotation: vec4f, scale: vec3f, color: vec4f) { output.uv0 = input.vertex_position.xy + vec2f(0.5); return output; } - `,fragmentGLSL:t,fragmentWGSL:i,attributes:{vertex_position:e8}}),this.shaderDescs.get(e)}getTextureShaderDesc(e){let t=c1.decodeFunc(e);return this.getShaderDesc(`textureShader-${e}`,` + `,fragmentGLSL:e,fragmentWGSL:s,attributes:{vertex_position:ee}}),this.shaderDescs.get(t)}getTextureShaderDesc(t){let e=li.decodeFunc(t);return this.getShaderDesc(`textureShader-${t}`,` #include "gammaPS" varying vec2 uv0; uniform sampler2D colorMap; void main (void) { - vec3 linearColor = ${t}(texture2D(colorMap, uv0)); + vec3 linearColor = ${e}(texture2D(colorMap, uv0)); gl_FragColor = vec4(gammaCorrectOutput(linearColor), 1); } `,` @@ -717,7 +757,7 @@ fn writeSplat(center: vec3f, rotation: vec4f, scale: vec3f, color: vec4f) { @fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput { var output: FragmentOutput; let sampledTex = textureSample(colorMap, colorMapSampler, input.uv0); - let linearColor: vec3f = ${t}(sampledTex); + let linearColor: vec3f = ${e}(sampledTex); output.color = vec4f(gammaCorrectOutput(linearColor), 1.0); return output; } @@ -756,7 +796,7 @@ fn writeSplat(center: vec3f, rotation: vec4f, scale: vec3f, color: vec4f) { output.color = vec4f(gammaCorrectOutput(vec3f(depth)), 1.0); return output; } - `)}getQuadMesh(){return this.quadMesh||(this.quadMesh=new on(this.device),this.quadMesh.setPositions([-0.5,-0.5,0,.5,-0.5,0,-0.5,.5,0,.5,.5,0]),this.quadMesh.update(5)),this.quadMesh}drawMesh(e,t,i,s,r){s||(s=new oS(i,e,this.getGraphNode(t)));let a=this.layerMeshInstances.get(r);a||(a=[],this.layerMeshInstances.set(r,a)),a.push(s);}drawWireAlignedBox(e,t,i,s,r,a){if(a){let i=(e,t,i)=>{da.set(e,t,i),a.transformPoint(da,da),dr.push(da.x,da.y,da.z);};i(e.x,e.y,e.z),i(e.x,t.y,e.z),i(e.x,t.y,e.z),i(t.x,t.y,e.z),i(t.x,t.y,e.z),i(t.x,e.y,e.z),i(t.x,e.y,e.z),i(e.x,e.y,e.z),i(e.x,e.y,t.z),i(e.x,t.y,t.z),i(e.x,t.y,t.z),i(t.x,t.y,t.z),i(t.x,t.y,t.z),i(t.x,e.y,t.z),i(t.x,e.y,t.z),i(e.x,e.y,t.z),i(e.x,e.y,e.z),i(e.x,e.y,t.z),i(e.x,t.y,e.z),i(e.x,t.y,t.z),i(t.x,t.y,e.z),i(t.x,t.y,t.z),i(t.x,e.y,e.z),i(t.x,e.y,t.z);}else dr.push(e.x,e.y,e.z,e.x,t.y,e.z,e.x,t.y,e.z,t.x,t.y,e.z,t.x,t.y,e.z,t.x,e.y,e.z,t.x,e.y,e.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,t.z,e.x,t.y,t.z,t.x,t.y,t.z,t.x,t.y,t.z,t.x,e.y,t.z,t.x,e.y,t.z,e.x,e.y,t.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,e.z,e.x,t.y,t.z,t.x,t.y,e.z,t.x,t.y,t.z,t.x,e.y,e.z,t.x,e.y,t.z);this.getBatch(r,s).addLinesArrays(dr,i),dr.length=0;}drawWireSphere(e,t,i,s,r,a){let n=2*Math.PI/s,o=0;for(let i=0;i{r===e&&s.onPreRender(t,i);}),!this.updatedLayers.has(e)){this.updatedLayers.add(e);let i=this.layerMeshInstances.get(e);if(i){for(let e=0;ee.clear()),this.allBatches.clear(),this.updatedLayers.clear();}constructor(e){this.shaderDescs=new Map,this.device=e,this.quadMesh=null,this.textureShader=null,this.depthTextureShader=null,this.cubeLocalPos=null,this.cubeWorldPos=null,this.batchesMap=new Map,this.allBatches=new Set,this.updatedLayers=new Set,this._materialDepth=null,this._materialNoDepth=null,this.layerMeshInstances=new Map;}}let dl={circlePoint(e){let t=Math.sqrt(Math.random()),i=2*Math.random()*Math.PI;e.x=t*Math.cos(i),e.y=t*Math.sin(i);},circlePointDeterministic(e,t,i){let s=2.399963229728653*t,r=Math.sqrt(t/i);e.x=r*Math.cos(s),e.y=r*Math.sin(s);},spherePointDeterministic(e,t,i,s=0,r=1){s=1-2*s,r=1-2*r;let a=ei.lerp(s,r,t/i),n=Math.sqrt(1-a*a),o=2.399963229728653*t;e.x=Math.cos(o)*n,e.y=a,e.z=Math.sin(o)*n;},radicalInverse(e){let t=(e<<16|e>>>16)>>>0;return 23283064365386963e-26*(t=((0xff00ff&(t=((0xf0f0f0f&(t=((0x33333333&(t=((0x55555555&t)<<1|(0xaaaaaaaa&t)>>>1)>>>0))<<2|(0xcccccccc&t)>>>2)>>>0))<<4|(0xf0f0f0f0&t)>>>4)>>>0))<<8|(0xff00ff00&t)>>>8)>>>0)}},dh=e=>{switch(e){case tB:return "Cubemap";case tU:return "Octahedral";default:return "Equirect"}},dc=(e,t,i)=>{if(e<=0)t[i+0]=0,t[i+1]=0,t[i+2]=0,t[i+3]=0;else if(e>=1)t[i+0]=255,t[i+1]=0,t[i+2]=0,t[i+3]=0;else {let s=e%1,r=255*e%1,a=65025*e%1,n=0xfd02ff*e%1;s-=r/255,r-=a/255,a-=n/255,t[i+0]=Math.min(255,Math.floor(256*s)),t[i+1]=Math.min(255,Math.floor(256*r)),t[i+2]=Math.min(255,Math.floor(256*a)),t[i+3]=Math.min(255,Math.floor(256*n));}},dd=(e,t,i,s)=>{let r=2*i*Math.PI,a=Math.pow(1-t,1/(s+1)),n=Math.sqrt(1-a*a);e.set(Math.cos(r)*n,Math.sin(r)*n,a).normalize();},du=(e,t,i)=>{let s=2*i*Math.PI,r=Math.sqrt(1-t),a=Math.sqrt(t);e.set(Math.cos(s)*a,Math.sin(s)*a,r).normalize();},df=(e,t,i,s)=>{let r=2*i*Math.PI,a=Math.sqrt((1-t)/(1+(s*s-1)*t)),n=Math.sqrt(1-a*a);e.set(Math.cos(r)*n,Math.sin(r)*n,a).normalize();},dp=(e,t)=>{let i=e*t,s=t/(1-e*e+i*i);return s*s*(1/Math.PI)},dm={16:{2:26,8:20,32:17,128:16,512:16},32:{2:53,8:40,32:34,128:32,512:32},128:{2:214,8:163,32:139,128:130,512:128},1024:{2:1722,8:1310,32:1114,128:1041,512:1025}};class d_{destroy(){this.destroyContent&&this.map.forEach((e,t)=>{e.destroy();});}get(e,t){if(!this.map.has(e)){let i=t();return this.map.set(e,i),i}return this.map.get(e)}constructor(e=true){this.map=new Map,this.destroyContent=e;}}let dg=new d_(false),dv=new is,dS=(e,t,i)=>dv.get(e,()=>new d_).get(t,()=>{let s;return s=(e=>{let t=e.length,i=Math.min(t,512),s=Math.ceil(t/i),r=new Uint8Array(i*s*4),a=0;for(let i=0;i0?y.setValue([(r+2*s)/r,(a+2*s)/a,-s/r,-s/a]):y.setValue([1,1,0,0]);let x=[0,t.width*t.height*(t.cubemap?6:1),e.width*e.height*(e.cubemap?6:1)];if(c){let t=e.width*e.height*(e.cubemap?6:1),i="ggx"===l?dS(g,`ggx-samples-${m}-${n}-${t}`,()=>((e,t,i)=>{let s,r=i/e,a=1-Math.log2(t)/11,n=a*a,o=new ed,l=new ed,h=new ed(0,0,1),c=[],d=(s=dm[e])&&s[t]||e;for(let e=0;e0){let e=.5*Math.log2(r/(dp(Math.min(1,t),n)/4+.001));c.push(l.x,l.y,l.z,e);}}for(;c.length<4*e;)c.push(0,0,0,0);return c})(m,n,t)):"lambert"===l?dS(g,`lambert-samples-${m}-${t}`,()=>((e,t)=>{let i=t/e,s=new ed,r=[];for(let t=0;t((e,t)=>{let i=new ed,s=[];for(let r=0;r1+Math.floor(Math.log2(Math.max(e,t)));class dT{static generateSkyboxCubemap(e,t){let i,s,r=(i=e.device,s=t||(e.cubemap?e.width:e.width/4),new ic(i,{name:`lighting-${s}`,cubemap:true,width:s,height:s,format:7,type:tR,addressU:1,addressV:1,mipmaps:false}));return dy(e,r,{numSamples:1024}),r}static generateLightingSource(e,t){let i,s=e.device,r=(i=s).textureHalfFloatRenderable?12:i.textureFloatRenderable?14:7,a=t?.target||new ic(s,{name:"lighting-source",cubemap:true,width:t?.size||128,height:t?.size||128,format:r,type:7===r?tR:tP,addressU:1,addressV:1,mipmaps:true});return dy(e,a,{numSamples:e.mipmaps?1:1024}),a}static generateAtlas(e,t){let i=e.device,s=t?.target||new ic(i,{name:"envAtlas",width:t?.size||512,height:t?.size||512,format:7,type:tR,projection:tk,addressU:1,addressV:1,mipmaps:false}),r=s.width/512,a=new ep(0,0,512*r,256*r),n=dx(256)-dx(4);for(let t=0;t>2*i),rect:a,seamPixels:r}),a.y+=a.w,a.z=Math.max(1,Math.floor(.5*a.z)),a.w=Math.max(1,Math.floor(.5*a.w));return a.set(128*r,384*r,64*r,32*r),dy(e,s,{numSamples:t?.numAmbientSamples||2048,distribution:"lambert",rect:a,seamPixels:r}),s}static generatePrefilteredAtlas(e,t){let i=e[0].device,s=e[0].format,r=e[0].type,a=t?.target||new ic(i,{name:"envPrefilteredAtlas",width:t?.size||512,height:t?.size||512,format:s,type:r,projection:tk,addressU:1,addressV:1,mipmaps:false}),n=a.width/512,o=new ep(0,0,512*n,256*n),l=dx(512);for(let t=0;tt!==e[i]))&&(6===e.length&&e.every(e=>!!e)?(this._internalEnvAtlas=dT.generatePrefilteredAtlas(e,{target:this._internalEnvAtlas}),this._envAtlas=this._internalEnvAtlas):(this._internalEnvAtlas&&(this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null),this._envAtlas=null),this._prefilteredCubemaps=e.slice(),this._resetSkyMesh());}get prefilteredCubemaps(){return this._prefilteredCubemaps}set skybox(e){e!==this._skyboxCubeMap&&(this._skyboxCubeMap=e,this._resetSkyMesh());}get skybox(){return this._skyboxCubeMap}set skyboxIntensity(e){e!==this._skyboxIntensity&&(this._skyboxIntensity=e,this._resetSkyMesh());}get skyboxIntensity(){return this._skyboxIntensity}set skyboxLuminance(e){e!==this._skyboxLuminance&&(this._skyboxLuminance=e,this._resetSkyMesh());}get skyboxLuminance(){return this._skyboxLuminance}set skyboxMip(e){e!==this._skyboxMip&&(this._skyboxMip=e,this._resetSkyMesh());}get skyboxMip(){return this._skyboxMip}set skyboxHighlightMultiplier(e){e!==this._skyboxHighlightMultiplier&&(this._skyboxHighlightMultiplier=e,this._resetSkyMesh());}get skyboxHighlightMultiplier(){return this._skyboxHighlightMultiplier}set skyboxRotation(e){if(!this._skyboxRotation.equals(e)){let t=e.equals(ex.IDENTITY);this._skyboxRotation.copy(e),t?this._skyboxRotationMat3.setIdentity():(this._skyboxRotationMat4.setTRS(ed.ZERO,e,ed.ONE),this._skyboxRotationMat3.invertMat4(this._skyboxRotationMat4)),this._skyboxRotationShaderInclude||t||(this._skyboxRotationShaderInclude=true,this._resetSkyMesh());}}get skyboxRotation(){return this._skyboxRotation}destroy(){this._sky.destroy(),this.root=null,this.off();}drawLine(e,t,i=es.WHITE,s=true,r=this.defaultDrawLayer){this.immediate.getBatch(r,s).addLines([e,t],[i,i]);}drawLines(e,t,i=true,s=this.defaultDrawLayer){this.immediate.getBatch(s,i).addLines(e,t);}drawLineArrays(e,t,i=true,s=this.defaultDrawLayer){this.immediate.getBatch(s,i).addLinesArrays(e,t);}applySettings(e){let t=e.physics,i=e.render;this._gravity.set(t.gravity[0],t.gravity[1],t.gravity[2]),this.ambientLight.set(i.global_ambient[0],i.global_ambient[1],i.global_ambient[2]),this.ambientLuminance=i.ambientLuminance,this.fog.type=i.fog,this.fog.color.set(i.fog_color[0],i.fog_color[1],i.fog_color[2]),this.fog.start=i.fog_start,this.fog.end=i.fog_end,this.fog.density=i.fog_density,this.lightmapSizeMultiplier=i.lightmapSizeMultiplier,this.lightmapMaxResolution=i.lightmapMaxResolution,this.lightmapMode=i.lightmapMode,this.exposure=i.exposure,this._skyboxIntensity=i.skyboxIntensity??1,this._skyboxLuminance=i.skyboxLuminance??2e4,this._skyboxMip=i.skyboxMip??0,i.skyboxRotation&&(this.skyboxRotation=new ex().setFromEulerAngles(i.skyboxRotation[0],i.skyboxRotation[1],i.skyboxRotation[2])),this.sky.applySettings(i),this.clusteredLightingEnabled=i.clusteredLightingEnabled??false,this.lighting.applySettings(i),["lightmapFilterEnabled","lightmapFilterRange","lightmapFilterSmoothness","ambientBake","ambientBakeNumSamples","ambientBakeSpherePart","ambientBakeOcclusionBrightness","ambientBakeOcclusionContrast"].forEach(e=>{i.hasOwnProperty(e)&&(this[e]=i[e]);}),this._resetSkyMesh();}_getSkyboxTex(){let e=this._prefilteredCubemaps;return this._skyboxMip?e[[0,1,3,4,5,6][this._skyboxMip]]||this._envAtlas||e[0]||this._skyboxCubeMap:this._skyboxCubeMap||e[0]||this._envAtlas}_updateSkyMesh(){this.sky.skyMesh||this.sky.updateSkyMesh(),this.sky.update();}_resetSkyMesh(){this.sky.resetSkyMesh(),this.updateShaders=true;}setSkybox(e){e?(this.skybox=e[0]||null,e[1]&&!e[1].cubemap?this.envAtlas=e[1]:this.prefilteredCubemaps=e.slice(1)):(this.skybox=null,this.envAtlas=null);}get lightmapPixelFormat(){return this.lightmapHDR&&this.device.getRenderableHdrFormat()||7}constructor(e){super(),this.ambientBake=false,this.ambientBakeOcclusionBrightness=0,this.ambientBakeOcclusionContrast=0,this.ambientLight=new es(0,0,0),this.ambientLuminance=0,this.exposure=1,this.lightmapSizeMultiplier=1,this.lightmapMaxResolution=2048,this.lightmapMode=1,this.lightmapFilterEnabled=false,this.lightmapHDR=false,this.root=null,this.physicalUnits=false,this._envAtlas=null,this._skyboxCubeMap=null,this._fogParams=new dE,this.forcePassThroughSpecular=false,this.device=e,this._gravity=new ed(0,-9.8,0),this._layers=null,this._prefilteredCubemaps=[],this._internalEnvAtlas=null,this._skyboxIntensity=1,this._skyboxLuminance=0,this._skyboxMip=0,this._skyboxHighlightMultiplier=1,this._skyboxRotationShaderInclude=false,this._skyboxRotation=new ex,this._skyboxRotationMat3=new eu,this._skyboxRotationMat4=new ey,this._ambientBakeNumSamples=1,this._ambientBakeSpherePart=.4,this._lightmapFilterRange=10,this._lightmapFilterSmoothness=.2,this._clusteredLightingEnabled=true,this._lightingParams=new hM(this.device.supportsAreaLights,this.device.maxTextureSize,()=>{this.updateShaders=true;}),this._gsplatParams=new cZ(this.device),this._sky=new de(this),this._stats={meshInstances:0,lights:0,dynamicLights:0,bakedLights:0,updateShadersTime:0},this.updateShaders=true,this._shaderVersion=0,this.immediate=new dn(this.device);}}dw.EVENT_SETLAYERS="set:layers",dw.EVENT_SETSKYBOX="set:skybox",dw.EVENT_PRERENDER="prerender",dw.EVENT_POSTRENDER="postrender",dw.EVENT_PRERENDER_LAYER="prerender:layer",dw.EVENT_POSTRENDER_LAYER="postrender:layer",dw.EVENT_PRECULL="precull",dw.EVENT_POSTCULL="postcull";class db{constructor(e,t,i){this.device=e,this.inverseBindPose=t,this.boneNames=i;}}let dC=[0,0,1,0,0,1,0,0,1,0,0,1],dA=[0,1,3,2,3,1];class dP extends X{set frameKeys(e){this._frameKeys=e,this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=true:this._createMeshes()),this.fire("set:frameKeys",e);}get frameKeys(){return this._frameKeys}set atlas(e){e!==this._atlas&&(this._atlas&&(this._atlas.off("set:frames",this._onSetFrames,this),this._atlas.off("set:frame",this._onFrameChanged,this),this._atlas.off("remove:frame",this._onFrameRemoved,this)),this._atlas=e,this._atlas&&this._frameKeys&&(this._atlas.on("set:frames",this._onSetFrames,this),this._atlas.on("set:frame",this._onFrameChanged,this),this._atlas.on("remove:frame",this._onFrameRemoved,this),this._updatingProperties?this._meshesDirty=true:this._createMeshes()),this.fire("set:atlas",e));}get atlas(){return this._atlas}set pixelsPerUnit(e){this._pixelsPerUnit!==e&&(this._pixelsPerUnit=e,this.fire("set:pixelsPerUnit",e),this._atlas&&this._frameKeys&&0===this.renderMode&&(this._updatingProperties?this._meshesDirty=true:this._createMeshes()));}get pixelsPerUnit(){return this._pixelsPerUnit}set renderMode(e){if(this._renderMode===e)return;let t=this._renderMode;this._renderMode=e,this.fire("set:renderMode",e),(0===t||0===e)&&this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=true:this._createMeshes());}get renderMode(){return this._renderMode}get meshes(){return this._meshes}_createMeshes(){let e=this._meshes.length;for(let t=0;ti){this._time=this.looping?0:i;for(let e=0;e=0?1:-1;for(let e=0;e=0;e+=s){let t=a[e],i=a[e+1];if(t.time<=this._time&&i.time>=this._time){let s=(this._time-t.time)/(i.time-t.time);n._pos.lerp(t.position,i.position,s),n._quat.slerp(t.rotation,i.rotation,s),n._scale.lerp(t.scale,i.scale,s),n._written=true,this._currKeyIndices[r]=e,o=true;break}}(1===a.length||!o&&0===this._time&&this.looping)&&(n._pos.copy(a[0].position),n._quat.copy(a[0].rotation),n._scale.copy(a[0].scale),n._written=true);}}}blend(e,t,i){let s=this._interpolatedKeys.length;for(let r=0;r{let i=new dM;i._name=e.name,this._interpolatedKeys.push(i),this._interpolatedKeyDict[e.name]=i,this._currKeyIndices[e.name]=0;for(let i=0;i{$p.set(h,f,u),a.transformPoint($p,$p),la.push($p.x,$p.y,$p.z)};l(t.x,t.y,t.z),l(t.x,e.y,t.z),l(t.x,e.y,t.z),l(e.x,e.y,t.z),l(e.x,e.y,t.z),l(e.x,t.y,t.z),l(e.x,t.y,t.z),l(t.x,t.y,t.z),l(t.x,t.y,e.z),l(t.x,e.y,e.z),l(t.x,e.y,e.z),l(e.x,e.y,e.z),l(e.x,e.y,e.z),l(e.x,t.y,e.z),l(e.x,t.y,e.z),l(t.x,t.y,e.z),l(t.x,t.y,t.z),l(t.x,t.y,e.z),l(t.x,e.y,t.z),l(t.x,e.y,e.z),l(e.x,e.y,t.z),l(e.x,e.y,e.z),l(e.x,t.y,t.z),l(e.x,t.y,e.z)}else la.push(t.x,t.y,t.z,t.x,e.y,t.z,t.x,e.y,t.z,e.x,e.y,t.z,e.x,e.y,t.z,e.x,t.y,t.z,e.x,t.y,t.z,t.x,t.y,t.z,t.x,t.y,e.z,t.x,e.y,e.z,t.x,e.y,e.z,e.x,e.y,e.z,e.x,e.y,e.z,e.x,t.y,e.z,e.x,t.y,e.z,t.x,t.y,e.z,t.x,t.y,t.z,t.x,t.y,e.z,t.x,e.y,t.z,t.x,e.y,e.z,e.x,e.y,t.z,e.x,e.y,e.z,e.x,t.y,t.z,e.x,t.y,e.z);this.getBatch(r,i).addLinesArrays(la,s),la.length=0}drawWireSphere(t,e,s,i,r,a){let o=2*Math.PI/i,l=0;for(let f=0;f{r===t&&i.onPreRender(e,s)}),!this.updatedLayers.has(t)){this.updatedLayers.add(t);let i=this.layerMeshInstances.get(t);if(i){for(let r=0;rt.clear()),this.allBatches.clear(),this.updatedLayers.clear()}};var Zp=class{constructor(){n(this,"type",Mi);n(this,"color",new F(0,0,0));n(this,"density",0);n(this,"start",1);n(this,"end",1e3)}};var Bt=class extends J{constructor(e){super();n(this,"ambientBake",!1);n(this,"ambientBakeOcclusionBrightness",0);n(this,"ambientBakeOcclusionContrast",0);n(this,"ambientLight",new F(0,0,0));n(this,"ambientLuminance",0);n(this,"exposure",1);n(this,"lightmapSizeMultiplier",1);n(this,"lightmapMaxResolution",2048);n(this,"lightmapMode",zf);n(this,"lightmapFilterEnabled",!1);n(this,"lightmapHDR",!1);n(this,"root",null);n(this,"physicalUnits",!1);n(this,"_envAtlas",null);n(this,"_skyboxCubeMap",null);n(this,"_fogParams",new Zp);n(this,"forcePassThroughSpecular",!1);this.device=e,this._gravity=new x(0,-9.8,0),this._layers=null,this._prefilteredCubemaps=[],this._internalEnvAtlas=null,this._skyboxIntensity=1,this._skyboxLuminance=0,this._skyboxMip=0,this._skyboxHighlightMultiplier=1,this._skyboxRotationShaderInclude=!1,this._skyboxRotation=new $,this._skyboxRotationMat3=new Ws,this._skyboxRotationMat4=new W,this._ambientBakeNumSamples=1,this._ambientBakeSpherePart=.4,this._lightmapFilterRange=10,this._lightmapFilterSmoothness=.2,this._clusteredLightingEnabled=!0,this._lightingParams=new zc(this.device.supportsAreaLights,this.device.maxTextureSize,()=>{this.updateShaders=!0}),this.gsplatCentersEnabled=!0,this._gsplatParams=new yy(this.device),this._sky=new qp(this),this._stats={meshInstances:0,lights:0,dynamicLights:0,bakedLights:0,updateShadersTime:0},this.updateShaders=!0,this._shaderVersion=0,this.immediate=new Iy(this.device)}get defaultDrawLayer(){return this.layers.getLayerById(Zn)}set ambientBakeNumSamples(e){this._ambientBakeNumSamples=R.clamp(Math.floor(e),1,255)}get ambientBakeNumSamples(){return this._ambientBakeNumSamples}set ambientBakeSpherePart(e){this._ambientBakeSpherePart=R.clamp(e,.001,1)}get ambientBakeSpherePart(){return this._ambientBakeSpherePart}set clusteredLightingEnabled(e){this.device.isWebGPU&&!e||!this._clusteredLightingEnabled&&e||(this._clusteredLightingEnabled=e)}get clusteredLightingEnabled(){return this._clusteredLightingEnabled}set envAtlas(e){e!==this._envAtlas&&(this._envAtlas=e,e&&(e.addressU=1,e.addressV=1,e.minFilter=1,e.magFilter=1,e.mipmaps=!1),this._prefilteredCubemaps=[],this._internalEnvAtlas&&(this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null),this._resetSkyMesh())}get envAtlas(){return this._envAtlas}set layers(e){let s=this._layers;this._layers=e,this.fire("set:layers",s,e)}get layers(){return this._layers}get sky(){return this._sky}get lighting(){return this._lightingParams}get gsplat(){return this._gsplatParams}get fog(){return this._fogParams}set lightmapFilterRange(e){this._lightmapFilterRange=Math.max(e,.001)}get lightmapFilterRange(){return this._lightmapFilterRange}set lightmapFilterSmoothness(e){this._lightmapFilterSmoothness=Math.max(e,.001)}get lightmapFilterSmoothness(){return this._lightmapFilterSmoothness}set prefilteredCubemaps(e){e=e||[];let s=this._prefilteredCubemaps;(s.length!==e.length||s.some((r,a)=>r!==e[a]))&&(e.length===6&&e.every(a=>!!a)?(this._internalEnvAtlas=bc.generatePrefilteredAtlas(e,{target:this._internalEnvAtlas}),this._envAtlas=this._internalEnvAtlas):(this._internalEnvAtlas&&(this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null),this._envAtlas=null),this._prefilteredCubemaps=e.slice(),this._resetSkyMesh())}get prefilteredCubemaps(){return this._prefilteredCubemaps}set skybox(e){e!==this._skyboxCubeMap&&(this._skyboxCubeMap=e,this._resetSkyMesh())}get skybox(){return this._skyboxCubeMap}set skyboxIntensity(e){e!==this._skyboxIntensity&&(this._skyboxIntensity=e,this._resetSkyMesh())}get skyboxIntensity(){return this._skyboxIntensity}set skyboxLuminance(e){e!==this._skyboxLuminance&&(this._skyboxLuminance=e,this._resetSkyMesh())}get skyboxLuminance(){return this._skyboxLuminance}set skyboxMip(e){e!==this._skyboxMip&&(this._skyboxMip=e,this._resetSkyMesh())}get skyboxMip(){return this._skyboxMip}set skyboxHighlightMultiplier(e){e!==this._skyboxHighlightMultiplier&&(this._skyboxHighlightMultiplier=e,this._resetSkyMesh())}get skyboxHighlightMultiplier(){return this._skyboxHighlightMultiplier}set skyboxRotation(e){if(!this._skyboxRotation.equals(e)){let s=e.equals($.IDENTITY);this._skyboxRotation.copy(e),s?this._skyboxRotationMat3.setIdentity():(this._skyboxRotationMat4.setTRS(x.ZERO,e,x.ONE),this._skyboxRotationMat3.invertMat4(this._skyboxRotationMat4)),!this._skyboxRotationShaderInclude&&!s&&(this._skyboxRotationShaderInclude=!0,this._resetSkyMesh())}}get skyboxRotation(){return this._skyboxRotation}destroy(){this._sky.destroy(),this.root=null,this.off()}drawLine(e,s,i=F.WHITE,r=!0,a=this.defaultDrawLayer){this.immediate.getBatch(a,r).addLines([e,s],[i,i])}drawLines(e,s,i=!0,r=this.defaultDrawLayer){this.immediate.getBatch(r,i).addLines(e,s)}drawLineArrays(e,s,i=!0,r=this.defaultDrawLayer){this.immediate.getBatch(r,i).addLinesArrays(e,s)}applySettings(e){let s=e.physics,i=e.render;this._gravity.set(s.gravity[0],s.gravity[1],s.gravity[2]),this.ambientLight.set(i.global_ambient[0],i.global_ambient[1],i.global_ambient[2]),this.ambientLuminance=i.ambientLuminance,this.fog.type=i.fog,this.fog.color.set(i.fog_color[0],i.fog_color[1],i.fog_color[2]),this.fog.start=i.fog_start,this.fog.end=i.fog_end,this.fog.density=i.fog_density,this.lightmapSizeMultiplier=i.lightmapSizeMultiplier,this.lightmapMaxResolution=i.lightmapMaxResolution,this.lightmapMode=i.lightmapMode,this.exposure=i.exposure,this._skyboxIntensity=i.skyboxIntensity??1,this._skyboxLuminance=i.skyboxLuminance??2e4,this._skyboxMip=i.skyboxMip??0,i.skyboxRotation&&(this.skyboxRotation=new $().setFromEulerAngles(i.skyboxRotation[0],i.skyboxRotation[1],i.skyboxRotation[2])),this.sky.applySettings(i),this.clusteredLightingEnabled=i.clusteredLightingEnabled??!1,this.lighting.applySettings(i),["lightmapFilterEnabled","lightmapFilterRange","lightmapFilterSmoothness","ambientBake","ambientBakeNumSamples","ambientBakeSpherePart","ambientBakeOcclusionBrightness","ambientBakeOcclusionContrast"].forEach(r=>{i.hasOwnProperty(r)&&(this[r]=i[r])}),this._resetSkyMesh()}_getSkyboxTex(){let e=this._prefilteredCubemaps;return this._skyboxMip?e[[0,1,3,4,5,6][this._skyboxMip]]||this._envAtlas||e[0]||this._skyboxCubeMap:this._skyboxCubeMap||e[0]||this._envAtlas}_updateSkyMesh(){this.sky.skyMesh||this.sky.updateSkyMesh(),this.sky.update()}_resetSkyMesh(){this.sky.resetSkyMesh(),this.updateShaders=!0}setSkybox(e){e?(this.skybox=e[0]||null,e[1]&&!e[1].cubemap?this.envAtlas=e[1]:this.prefilteredCubemaps=e.slice(1)):(this.skybox=null,this.envAtlas=null)}get lightmapPixelFormat(){return this.lightmapHDR&&this.device.getRenderableHdrFormat()||ce}};n(Bt,"EVENT_SETLAYERS","set:layers"),n(Bt,"EVENT_SETSKYBOX","set:skybox"),n(Bt,"EVENT_PRERENDER","prerender"),n(Bt,"EVENT_POSTRENDER","postrender"),n(Bt,"EVENT_PRERENDER_LAYER","prerender:layer"),n(Bt,"EVENT_POSTRENDER_LAYER","postrender:layer"),n(Bt,"EVENT_PRECULL","precull"),n(Bt,"EVENT_POSTCULL","postcull");var Vc=class{constructor(t,e,s){this.device=t,this.inverseBindPose=e,this.boneNames=s}};var N6=[0,0,1,0,0,1,0,0,1,0,0,1],B6=[0,1,3,2,3,1],Qp=class extends J{constructor(t,e){super(),this._device=t,this._pixelsPerUnit=e&&e.pixelsPerUnit!==void 0?e.pixelsPerUnit:1,this._renderMode=e&&e.renderMode!==void 0?e.renderMode:Ti,this._atlas=e&&e.atlas!==void 0?e.atlas:null,this._frameKeys=e&&e.frameKeys!==void 0?e.frameKeys:null,this._meshes=[],this._updatingProperties=!1,this._meshesDirty=!1,this._atlas&&this._frameKeys&&this._createMeshes()}set frameKeys(t){this._frameKeys=t,this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes()),this.fire("set:frameKeys",t)}get frameKeys(){return this._frameKeys}set atlas(t){t!==this._atlas&&(this._atlas&&(this._atlas.off("set:frames",this._onSetFrames,this),this._atlas.off("set:frame",this._onFrameChanged,this),this._atlas.off("remove:frame",this._onFrameRemoved,this)),this._atlas=t,this._atlas&&this._frameKeys&&(this._atlas.on("set:frames",this._onSetFrames,this),this._atlas.on("set:frame",this._onFrameChanged,this),this._atlas.on("remove:frame",this._onFrameRemoved,this),this._updatingProperties?this._meshesDirty=!0:this._createMeshes()),this.fire("set:atlas",t))}get atlas(){return this._atlas}set pixelsPerUnit(t){this._pixelsPerUnit!==t&&(this._pixelsPerUnit=t,this.fire("set:pixelsPerUnit",t),this._atlas&&this._frameKeys&&this.renderMode===Ti&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes()))}get pixelsPerUnit(){return this._pixelsPerUnit}set renderMode(t){if(this._renderMode===t)return;let e=this._renderMode;this._renderMode=t,this.fire("set:renderMode",t),(e===Ti||t===Ti)&&this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes())}get renderMode(){return this._renderMode}get meshes(){return this._meshes}_createMeshes(){let t=this._meshes.length;for(let i=0;i{let i=new SI;i._name=s.name,this._interpolatedKeys.push(i),this._interpolatedKeyDict[s.name]=i,this._currKeyIndices[s.name]=0;for(let r=0;rs){this._time=this.looping?0:s;for(let r=0;r=0?1:-1;for(let r=0;r=0;u+=i){let d=l[u],p=l[u+1];if(d.time<=this._time&&p.time>=this._time){let m=(this._time-d.time)/(p.time-d.time);h._pos.lerp(d.position,p.position,m),h._quat.slerp(d.rotation,p.rotation,m),h._scale.lerp(d.scale,p.scale,m),h._written=!0,this._currKeyIndices[o]=u,f=!0;break}}(l.length===1||!f&&this._time===0&&this.looping)&&(h._pos.copy(l[0].position),h._quat.copy(l[0].rotation),h._scale.copy(l[0].scale),h._written=!0)}}}blend(t,e,s){let i=this._interpolatedKeys.length;for(let r=0;r items: array; @group(0) @binding(1) var blockSums: array; struct PrefixSumUniforms { @@ -837,7 +877,7 @@ fn add_block_sums( } items[ELM_ID + 1u] += blockSum; } -`;class dN{destroy(){this.destroyPasses(),this._scanShader?.destroy(),this._addBlockShader?.destroy(),this._bindGroupFormat?.destroy(),this._scanShader=null,this._addBlockShader=null,this._bindGroupFormat=null,this._uniformBufferFormat=null;}_createFormatsAndShaders(){this._uniformBufferFormat=new sg(this.device,[new s_("elementCount",26)]),this._bindGroupFormat=new ii(this.device,[new t7("items",4,false),new t7("blockSums",4,false),new t9("uniforms",4)]),this._scanShader=this._createShader("PrefixSumScan","reduce_downsweep"),this._addBlockShader=this._createShader("PrefixSumAddBlock","add_block_sums");}createPassesRecursive(e,t){let i=Math.ceil(t/512),{x:s,y:r}=this.findOptimalDispatchSize(i),a=new rO(this.device,4*i),n=new ar(this.device,this._scanShader,"PrefixSumScan");n.setParameter("items",e),n.setParameter("blockSums",a);let o={scanCompute:n,addBlockCompute:null,blockSumBuffer:a,dispatchX:s,dispatchY:r,count:t,allocatedCount:t};if(this.passes.push(o),i>1){this.createPassesRecursive(a,i);let t=new ar(this.device,this._addBlockShader,"PrefixSumAddBlock");t.setParameter("items",e),t.setParameter("blockSums",a),o.addBlockCompute=t;}}_createShader(e,t){let i=new Map;return i.set("{WORKGROUP_SIZE_X}",16),i.set("{WORKGROUP_SIZE_Y}",16),i.set("{THREADS_PER_WORKGROUP}",256),i.set("{ITEMS_PER_WORKGROUP}",512),new r_(this.device,{name:e,shaderLanguage:tV,cshader:dF,cdefines:i,computeEntryPoint:t,computeBindGroupFormat:this._bindGroupFormat,computeUniformBufferFormats:{uniforms:this._uniformBufferFormat}})}findOptimalDispatchSize(e){if(e<=(this.device.limits.maxComputeWorkgroupsPerDimension||65535))return {x:e,y:1};let t=Math.floor(Math.sqrt(e)),i=Math.ceil(e/t);return {x:t,y:i}}resize(e,t){if(this._countPassesNeeded(t)>this.passes.length){this.destroyPasses(),this.createPassesRecursive(e,t);return}let i=t;for(let e=0;e0;){t++;let e=Math.ceil(i/512);if(e<=1)break;i=e;}return t}dispatch(e){for(let t=0;t=0;t--){let i=this.passes[t];i.addBlockCompute&&(i.addBlockCompute.setParameter("elementCount",i.count),i.addBlockCompute.setupDispatch(i.dispatchX,i.dispatchY,1),e.computeDispatch([i.addBlockCompute],"PrefixSumAddBlock"));}}constructor(e){this.passes=[],this._uniformBufferFormat=null,this._bindGroupFormat=null,this._scanShader=null,this._addBlockShader=null,this.device=e,this._createFormatsAndShaders();}}let dB=` +`;var BM=16,UM=16,kM=BM*UM,Ry=2*kM,Wc=class{constructor(t){n(this,"device");n(this,"passes",[]);n(this,"_uniformBufferFormat",null);n(this,"_bindGroupFormat",null);n(this,"_scanShader",null);n(this,"_addBlockShader",null);this.device=t,this._createFormatsAndShaders()}destroy(){this.destroyPasses(),this._scanShader?.destroy(),this._addBlockShader?.destroy(),this._bindGroupFormat?.destroy(),this._scanShader=null,this._addBlockShader=null,this._bindGroupFormat=null,this._uniformBufferFormat=null}_createFormatsAndShaders(){this._uniformBufferFormat=new Xe(this.device,[new Y("elementCount",pe)]),this._bindGroupFormat=new Ue(this.device,[new K("items",X,!1),new K("blockSums",X,!1),new Qe("uniforms",X)]),this._scanShader=this._createShader("PrefixSumScan","reduce_downsweep"),this._addBlockShader=this._createShader("PrefixSumAddBlock","add_block_sums")}createPassesRecursive(t,e){let s=Math.ceil(e/Ry),{x:i,y:r}=this.findOptimalDispatchSize(s),a=new Ee(this.device,s*4),o=new Ye(this.device,this._scanShader,"PrefixSumScan");o.setParameter("items",t),o.setParameter("blockSums",a);let l={scanCompute:o,addBlockCompute:null,blockSumBuffer:a,dispatchX:i,dispatchY:r,count:e,allocatedCount:e};if(this.passes.push(l),s>1){this.createPassesRecursive(a,s);let h=new Ye(this.device,this._addBlockShader,"PrefixSumAddBlock");h.setParameter("items",t),h.setParameter("blockSums",a),l.addBlockCompute=h}}_createShader(t,e){let s=new Map;return s.set("{WORKGROUP_SIZE_X}",BM),s.set("{WORKGROUP_SIZE_Y}",UM),s.set("{THREADS_PER_WORKGROUP}",kM),s.set("{ITEMS_PER_WORKGROUP}",Ry),new Be(this.device,{name:t,shaderLanguage:se,cshader:NM,cdefines:s,computeEntryPoint:e,computeBindGroupFormat:this._bindGroupFormat,computeUniformBufferFormats:{uniforms:this._uniformBufferFormat}})}findOptimalDispatchSize(t){let e=this.device.limits.maxComputeWorkgroupsPerDimension||65535;if(t<=e)return{x:t,y:1};let s=Math.floor(Math.sqrt(t)),i=Math.ceil(t/s);return{x:s,y:i}}resize(t,e){let s=this._countPassesNeeded(e),i=this.passes.length;if(s>i){this.destroyPasses(),this.createPassesRecursive(t,e);return}let r=e;for(let a=0;a0;){e++;let i=Math.ceil(s/Ry);if(i<=1)break;s=i}return e}dispatch(t){for(let e=0;e=0;e--){let s=this.passes[e];s.addBlockCompute&&(s.addBlockCompute.setParameter("elementCount",s.count),s.addBlockCompute.setupDispatch(s.dispatchX,s.dispatchY,1),t.computeDispatch([s.addBlockCompute],"PrefixSumAddBlock"))}}};var zM=` @group(0) @binding(0) var input: array; @group(0) @binding(1) var block_sums: array; struct RadixSortUniforms { @@ -886,7 +926,7 @@ fn main( block_sums[TID * uniforms.workgroupCount + WORKGROUP_ID] = atomicLoad(&histogram[TID]); } } -`,dk=` +`;var GM=` @group(0) @binding(0) var inputKeys: array; @group(0) @binding(1) var outputKeys: array; @group(0) @binding(2) var prefix_block_sum: array; @@ -971,15 +1011,407 @@ fn main( } } } -`,dU=2048;class dz{destroy(){this._destroyBuffers(),this._destroyPasses(),this._histogramBindGroupFormat?.destroy(),this._reorderBindGroupFormat?.destroy(),this._histogramBindGroupFormat=null,this._reorderBindGroupFormat=null,this._uniformBufferFormat=null;}_destroyPasses(){for(let e of this._passes)e.histogramCompute.shader?.destroy(),e.reorderCompute.shader?.destroy();this._passes.length=0,this._numBits=0;}_destroyBuffers(){this._keys0?.destroy(),this._keys1?.destroy(),this._values0?.destroy(),this._values1?.destroy(),this._blockSums?.destroy(),this._sortedIndices?.destroy(),this._prefixSumKernel?.destroy(),this._keys0=null,this._keys1=null,this._values0=null,this._values1=null,this._blockSums=null,this._sortedIndices=null,this._prefixSumKernel=null,this._workgroupCount=0,this._allocatedWorkgroupCount=0;}get sortedIndices(){return this._sortedIndices}get sortedKeys(){return this._keys0?this._numBits/4%2==0?this._keys1:this._keys0:null}_ensureBindGroupFormats(e){if(this._histogramBindGroupFormat&&this._indirect===e)return;this._histogramBindGroupFormat?.destroy(),this._reorderBindGroupFormat?.destroy();let t=this.device,i=[new t7("input",4,true),new t7("block_sums",4,false),new t9("uniforms",4)],s=[new t7("inputKeys",4,true),new t7("outputKeys",4,false),new t7("prefix_block_sum",4,true),new t7("inputValues",4,true),new t7("outputValues",4,false),new t9("uniforms",4)];e&&(i.push(new t7("sortElementCount",4,true)),s.push(new t7("sortElementCount",4,true))),this._histogramBindGroupFormat=new ii(t,i),this._reorderBindGroupFormat=new ii(t,s);}_createPasses(e,t,i,s){this._destroyPasses(),this._numBits=e,this._ensureBindGroupFormats(t),this._indirect=t,this._hasInitialValues=i,this._skipLastPassKeyWrite=s;let r=e/4,a=t?"-Indirect":"";for(let e=0;e b_sort: array>; +@group(0) @binding(1) var b_globalHist: array>; +struct OneSweepUniforms { + numKeys: u32, + threadBlocks: u32, + numPasses: u32, + _pad: u32 +}; +@group(0) @binding(2) var uniforms: OneSweepUniforms; +#ifdef USE_INDIRECT_SORT +@group(0) @binding(3) var b_sortElementCount: array; +#endif +const RADIX: u32 = 256u; +const MAX_PASSES: u32 = 4u; +const G_HIST_DIM: u32 = {G_HIST_DIM}u; +const G_HIST_PART_SIZE: u32 = {G_HIST_PART_SIZE}u; +const G_HIST_PART_SIZE_VEC: u32 = G_HIST_PART_SIZE / 4u; +const SHARED_HIST_SIZE: u32 = 2u * MAX_PASSES * RADIX; +var g_gHist: array, SHARED_HIST_SIZE>; +fn histOffset(row: u32, pass_: u32) -> u32 { + return row * RADIX + pass_ * 2u * RADIX; +} +@compute @workgroup_size(G_HIST_DIM, 1, 1) +fn main( + @builtin(local_invocation_index) gtid: u32, + @builtin(workgroup_id) gid: vec3, + @builtin(num_workgroups) nwg: vec3, +) { + let flatGid = gid.x + gid.y * nwg.x; + let numPasses = uniforms.numPasses; + #ifdef USE_INDIRECT_SORT + let numKeys = b_sortElementCount[0]; + #else + let numKeys = uniforms.numKeys; + #endif + let sharedEnd = 2u * numPasses * RADIX; + for (var i = gtid; i < sharedEnd; i = i + G_HIST_DIM) { + atomicStore(&g_gHist[i], 0u); + } + workgroupBarrier(); + let row = gtid / 64u; + let numKeysVecFull = numKeys >> 2u; + let partitionStartVec = flatGid * G_HIST_PART_SIZE_VEC; + let partitionEndVec = min(partitionStartVec + G_HIST_PART_SIZE_VEC, numKeysVecFull); + for (var i = partitionStartVec + gtid; i < partitionEndVec; i = i + G_HIST_DIM) { + let q = b_sort[i]; + if (numPasses >= 1u) { + let off = histOffset(row, 0u); + atomicAdd(&g_gHist[(q.x & 0xFFu) + off], 1u); + atomicAdd(&g_gHist[(q.y & 0xFFu) + off], 1u); + atomicAdd(&g_gHist[(q.z & 0xFFu) + off], 1u); + atomicAdd(&g_gHist[(q.w & 0xFFu) + off], 1u); + } + if (numPasses >= 2u) { + let off = histOffset(row, 1u); + atomicAdd(&g_gHist[((q.x >> 8u) & 0xFFu) + off], 1u); + atomicAdd(&g_gHist[((q.y >> 8u) & 0xFFu) + off], 1u); + atomicAdd(&g_gHist[((q.z >> 8u) & 0xFFu) + off], 1u); + atomicAdd(&g_gHist[((q.w >> 8u) & 0xFFu) + off], 1u); + } + if (numPasses >= 3u) { + let off = histOffset(row, 2u); + atomicAdd(&g_gHist[((q.x >> 16u) & 0xFFu) + off], 1u); + atomicAdd(&g_gHist[((q.y >> 16u) & 0xFFu) + off], 1u); + atomicAdd(&g_gHist[((q.z >> 16u) & 0xFFu) + off], 1u); + atomicAdd(&g_gHist[((q.w >> 16u) & 0xFFu) + off], 1u); + } + if (numPasses >= 4u) { + let off = histOffset(row, 3u); + atomicAdd(&g_gHist[((q.x >> 24u) & 0xFFu) + off], 1u); + atomicAdd(&g_gHist[((q.y >> 24u) & 0xFFu) + off], 1u); + atomicAdd(&g_gHist[((q.z >> 24u) & 0xFFu) + off], 1u); + atomicAdd(&g_gHist[((q.w >> 24u) & 0xFFu) + off], 1u); + } + } + let tailIdx = numKeysVecFull; + if ((numKeys & 3u) != 0u && + tailIdx >= partitionStartVec && + tailIdx < partitionStartVec + G_HIST_PART_SIZE_VEC && + (tailIdx - partitionStartVec) % G_HIST_DIM == gtid) { + let q = b_sort[tailIdx]; + let base = tailIdx << 2u; + if (numPasses >= 1u) { + let off = histOffset(row, 0u); + if (base + 0u < numKeys) { atomicAdd(&g_gHist[(q.x & 0xFFu) + off], 1u); } + if (base + 1u < numKeys) { atomicAdd(&g_gHist[(q.y & 0xFFu) + off], 1u); } + if (base + 2u < numKeys) { atomicAdd(&g_gHist[(q.z & 0xFFu) + off], 1u); } + } + if (numPasses >= 2u) { + let off = histOffset(row, 1u); + if (base + 0u < numKeys) { atomicAdd(&g_gHist[((q.x >> 8u) & 0xFFu) + off], 1u); } + if (base + 1u < numKeys) { atomicAdd(&g_gHist[((q.y >> 8u) & 0xFFu) + off], 1u); } + if (base + 2u < numKeys) { atomicAdd(&g_gHist[((q.z >> 8u) & 0xFFu) + off], 1u); } + } + if (numPasses >= 3u) { + let off = histOffset(row, 2u); + if (base + 0u < numKeys) { atomicAdd(&g_gHist[((q.x >> 16u) & 0xFFu) + off], 1u); } + if (base + 1u < numKeys) { atomicAdd(&g_gHist[((q.y >> 16u) & 0xFFu) + off], 1u); } + if (base + 2u < numKeys) { atomicAdd(&g_gHist[((q.z >> 16u) & 0xFFu) + off], 1u); } + } + if (numPasses >= 4u) { + let off = histOffset(row, 3u); + if (base + 0u < numKeys) { atomicAdd(&g_gHist[((q.x >> 24u) & 0xFFu) + off], 1u); } + if (base + 1u < numKeys) { atomicAdd(&g_gHist[((q.y >> 24u) & 0xFFu) + off], 1u); } + if (base + 2u < numKeys) { atomicAdd(&g_gHist[((q.z >> 24u) & 0xFFu) + off], 1u); } + } + } + workgroupBarrier(); + for (var i = gtid; i < RADIX; i = i + G_HIST_DIM) { + for (var p = 0u; p < numPasses; p = p + 1u) { + let row0 = atomicLoad(&g_gHist[i + histOffset(0u, p)]); + let row1 = atomicLoad(&g_gHist[i + histOffset(1u, p)]); + let total = row0 + row1; + if (total != 0u) { + atomicAdd(&b_globalHist[i + p * RADIX], total); + } + } + } +} +`;var jM=` +@group(0) @binding(0) var b_globalHist: array; +@group(0) @binding(1) var b_passHist: array>; +struct OneSweepScanUniforms { + threadBlocks: u32, + _pad0: u32, + _pad1: u32, + _pad2: u32 +}; +@group(0) @binding(2) var uniforms: OneSweepScanUniforms; +#ifdef USE_INDIRECT_SORT +@group(0) @binding(3) var b_sortElementCount: array; +#endif +const RADIX: u32 = 256u; +const FLAG_INCLUSIVE: u32 = 2u; +const PART_SIZE: u32 = {PART_SIZE}u; +const MAX_SUBGROUPS: u32 = {MAX_SUBGROUPS}u; +var g_scan: array; +var sg_totals: array; +@compute @workgroup_size(RADIX, 1, 1) +fn main( + @builtin(local_invocation_index) gtid: u32, + @builtin(workgroup_id) gid: vec3, + @builtin(subgroup_invocation_id) sgInvId: u32, + @builtin(subgroup_size) sgSize: u32, +) { + let pass_ = gid.x; + #ifdef USE_INDIRECT_SORT + let numKeys = b_sortElementCount[0]; + let threadBlocks = (numKeys + PART_SIZE - 1u) / PART_SIZE; + #else + let threadBlocks = uniforms.threadBlocks; + #endif + let waveIndex = gtid / sgSize; + let t = b_globalHist[gtid + pass_ * RADIX]; + let sgExcl = subgroupExclusiveAdd(t); + let sgTotal = subgroupAdd(t); + if (sgInvId == 0u) { + sg_totals[waveIndex] = sgTotal; + } + workgroupBarrier(); + if (gtid == 0u) { + var acc: u32 = 0u; + for (var i = 0u; i < MAX_SUBGROUPS; i = i + 1u) { + let v = sg_totals[i]; + sg_totals[i] = acc; + acc = acc + v; + } + } + workgroupBarrier(); + let excl = sgExcl + sg_totals[waveIndex]; + g_scan[gtid] = excl; + let dst = pass_ * threadBlocks * RADIX + gtid; + atomicStore(&b_passHist[dst], (excl << 2u) | FLAG_INCLUSIVE); +} +`;var qM=` +@group(0) @binding(0) var inputKeys: array; +@group(0) @binding(1) var outputKeys: array; +@group(0) @binding(2) var inputValues: array; +@group(0) @binding(3) var outputValues: array; +@group(0) @binding(4) var b_passHist: array>; +@group(0) @binding(5) var b_index: array>; +struct OneSweepBinningUniforms { + numKeys: u32, + threadBlocks: u32, + pass_: u32, + flags: u32 +}; +@group(0) @binding(6) var uniforms: OneSweepBinningUniforms; +#ifdef USE_INDIRECT_SORT +@group(0) @binding(7) var b_sortElementCount: array; +#endif +const RADIX: u32 = 256u; +const RADIX_MASK: u32 = 255u; +const RADIX_LOG: u32 = 8u; +const D_DIM: u32 = {D_DIM}u; +const KEYS_PER_THREAD: u32 = {KEYS_PER_THREAD}u; +const PART_SIZE: u32 = D_DIM * KEYS_PER_THREAD; +const MAX_SUBGROUPS: u32 = {MAX_SUBGROUPS}u; +const WAVE_HISTS_SIZE: u32 = MAX_SUBGROUPS * RADIX; +const G_D_SIZE: u32 = max(PART_SIZE, WAVE_HISTS_SIZE); +const FLAG_NOT_READY: u32 = 0u; +const FLAG_REDUCTION: u32 = 1u; +const FLAG_INCLUSIVE: u32 = 2u; +const FLAG_MASK: u32 = 3u; +var g_d: array, G_D_SIZE>; +var digit_base: array; +var sg_totals: array; +var wg_partIndex: u32; +fn passHistOffset(tb: u32, pass_: u32, partitionIdx: u32) -> u32 { + return pass_ * tb * RADIX + partitionIdx * RADIX; +} +@compute @workgroup_size(D_DIM, 1, 1) +fn main( + @builtin(local_invocation_index) TID: u32, + @builtin(subgroup_invocation_id) sgInvId: u32, + @builtin(subgroup_size) sgSize: u32, +) { + let waveIndex = TID / sgSize; + let ltMask = (1u << sgInvId) - 1u; + let activeMask = select(0xFFFFFFFFu, (1u << sgSize) - 1u, sgSize < 32u); + let pass_ = uniforms.pass_; + let currentBit = pass_ << 3u; + #ifdef USE_INDIRECT_SORT + let numKeys = b_sortElementCount[0]; + let threadBlocks = (numKeys + PART_SIZE - 1u) / PART_SIZE; + #else + let numKeys = uniforms.numKeys; + let threadBlocks = uniforms.threadBlocks; + #endif + let isFirstPass = (uniforms.flags & 1u) != 0u; + let isLastPass = (uniforms.flags & 2u) != 0u; + if (TID == 0u) { + wg_partIndex = atomicAdd(&b_index[pass_], 1u); + } + let partitionIndex = workgroupUniformLoad(&wg_partIndex); + for (var i = TID; i < WAVE_HISTS_SIZE; i = i + D_DIM) { + atomicStore(&g_d[i], 0u); + } + workgroupBarrier(); + let tileStart = partitionIndex * PART_SIZE; + let validInBlock = select( + 0u, + min(PART_SIZE, numKeys - tileStart), + tileStart < numKeys + ); + let subPartSize = sgSize * KEYS_PER_THREAD; + let waveBase = tileStart + waveIndex * subPartSize; + var keys: array; + var values: array; + var validMask: u32 = 0u; + for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { + let gid = waveBase + sgInvId + i * sgSize; + let is_valid = gid < numKeys; + keys[i] = select(0xFFFFFFFFu, inputKeys[gid], is_valid); + values[i] = select( + select(0u, inputValues[gid], is_valid), + gid, + isFirstPass + ); + if (is_valid) { + validMask = validMask | (1u << i); + } + } + var offsets: array; + for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { + let k = keys[i]; + let isValid = ((validMask >> i) & 1u) == 1u; + let digit = (k >> currentBit) & RADIX_MASK; + var waveFlag: u32 = activeMask; + for (var b = 0u; b < 8u; b = b + 1u) { + let t = ((digit >> b) & 1u) == 1u; + let ballot = subgroupBallot(t).x; + waveFlag = waveFlag & select(~ballot, ballot, t); + } + let validBallot = subgroupBallot(isValid).x; + waveFlag = waveFlag & validBallot; + let peerBits = countOneBits(waveFlag & ltMask); + let totalBits = countOneBits(waveFlag); + let lowestRankPeer = firstTrailingBit(waveFlag); + var preIncrementVal: u32 = 0u; + if (isValid && peerBits == 0u) { + preIncrementVal = atomicAdd(&g_d[waveIndex * RADIX + digit], totalBits); + } + offsets[i] = subgroupShuffle(preIncrementVal, lowestRankPeer) + peerBits; + workgroupBarrier(); + } + var myHistRed: u32 = 0u; + { + var histReduction = atomicLoad(&g_d[TID]); + for (var w = 1u; w < MAX_SUBGROUPS; w = w + 1u) { + let idx = TID + w * RADIX; + let cnt = atomicLoad(&g_d[idx]); + histReduction = histReduction + cnt; + atomicStore(&g_d[idx], histReduction - cnt); + } + myHistRed = histReduction; + } + if (partitionIndex + 1u < threadBlocks) { + let dst = passHistOffset(threadBlocks, pass_, partitionIndex + 1u) + TID; + atomicAdd(&b_passHist[dst], FLAG_REDUCTION | (myHistRed << 2u)); + } + let warpExcl = subgroupExclusiveAdd(myHistRed); + let warpTotal = subgroupAdd(myHistRed); + if (sgInvId == 0u) { + sg_totals[waveIndex] = warpTotal; + } + workgroupBarrier(); + if (TID == 0u) { + var acc: u32 = 0u; + for (var w = 0u; w < MAX_SUBGROUPS; w = w + 1u) { + let t = sg_totals[w]; + sg_totals[w] = acc; + acc = acc + t; + } + } + workgroupBarrier(); + let myDigitBase = warpExcl + sg_totals[waveIndex]; + var scatterPos: array; + for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { + let k = keys[i]; + let digit = (k >> currentBit) & RADIX_MASK; + let warpBase = select(0u, atomicLoad(&g_d[waveIndex * RADIX + digit]), waveIndex > 0u); + scatterPos[i] = offsets[i] + warpBase; + } + digit_base[TID] = myDigitBase; + workgroupBarrier(); + for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { + let k = keys[i]; + let digit = (k >> currentBit) & RADIX_MASK; + scatterPos[i] = scatterPos[i] + digit_base[digit]; + } + workgroupBarrier(); + if (TID < RADIX) { + var lookbackReduction: u32 = 0u; + var k: u32 = partitionIndex; + var done: bool = false; + loop { + if (done) { break; } + let flagPayload = atomicLoad(&b_passHist[passHistOffset(threadBlocks, pass_, k) + TID]); + let flag = flagPayload & FLAG_MASK; + if (flag == FLAG_INCLUSIVE) { + lookbackReduction = lookbackReduction + (flagPayload >> 2u); + if (partitionIndex + 1u < threadBlocks) { + let dst = passHistOffset(threadBlocks, pass_, partitionIndex + 1u) + TID; + atomicAdd(&b_passHist[dst], 1u | (lookbackReduction << 2u)); } - `;class dH extends ah{set shader(e){this.quadRender?.destroy(),this.quadRender=null,this._shader=e,e&&(this.quadRender=new n4(e));}get shader(){return this._shader}execute(){this.device.setDrawStates(this.blendState,this.depthState,this.cullMode,this.frontFace,this.stencilFront,this.stencilBack),this.quadRender?.render(this.viewport,this.scissor);}constructor(...e){super(...e),this._shader=null,this.quadRender=null,this.cullMode=0,this.frontFace=0,this.blendState=iy.NOBLEND,this.depthState=iT.NODEPTH,this.stencilFront=null,this.stencilBack=null;}}var dW=` + digit_base[TID] = lookbackReduction - myDigitBase; + done = true; + } else if (flag == FLAG_REDUCTION) { + lookbackReduction = lookbackReduction + (flagPayload >> 2u); + if (k == 0u) { done = true; } + else { k = k - 1u; } + } + } + } + for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { + if (((validMask >> i) & 1u) == 1u) { + atomicStore(&g_d[scatterPos[i]], keys[i]); + } + } + workgroupBarrier(); + var linearDigits: array; + for (var r = 0u; r < KEYS_PER_THREAD; r = r + 1u) { + let linearIdx = TID + r * D_DIM; + if (linearIdx < validInBlock) { + let k = atomicLoad(&g_d[linearIdx]); + let digit = (k >> currentBit) & RADIX_MASK; + linearDigits[r] = digit; + let globalPos = digit_base[digit] + linearIdx; + if (!isLastPass) { + outputKeys[globalPos] = k; + } + } + } + workgroupBarrier(); + for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { + if (((validMask >> i) & 1u) == 1u) { + atomicStore(&g_d[scatterPos[i]], values[i]); + } + } + workgroupBarrier(); + for (var r = 0u; r < KEYS_PER_THREAD; r = r + 1u) { + let linearIdx = TID + r * D_DIM; + if (linearIdx < validInBlock) { + let v = atomicLoad(&g_d[linearIdx]); + let digit = linearDigits[r]; + let globalPos = digit_base[digit] + linearIdx; + outputValues[globalPos] = v; + } + } +} +`;var $M=256,ZM=15,Ly=$M*ZM,U6=128,vI=32768,My=256,vS=4,Oy=class extends em{constructor(e,s=!1){super(e,s);n(this,"_threadBlocks",0);n(this,"_allocatedThreadBlocks",0);n(this,"_globalHist",null);n(this,"_passHist",null);n(this,"_index",null);n(this,"_binningDispatchSize",new B(1,1));n(this,"_globalHistDispatchSize",new B(1,1));n(this,"_globalHistBindGroupFormat",null);n(this,"_scanBindGroupFormat",null);n(this,"_binningBindGroupFormat",null);n(this,"_globalHistUniformFormat",null);n(this,"_scanUniformFormat",null);n(this,"_binningUniformFormat",null);n(this,"_globalHistShader",null);n(this,"_scanShader",null);n(this,"_binningShader",null);n(this,"_globalHistCompute",null);n(this,"_scanCompute",null);n(this,"_binningComputes",[]);let i=this._indirectInfo;i[0]=2,i[1]=Ly,i[2]=vI,this._globalHistUniformFormat=new Xe(e,[new Y("numKeys",pe),new Y("threadBlocks",pe),new Y("numPasses",pe),new Y("_pad",pe)]),this._scanUniformFormat=new Xe(e,[new Y("threadBlocks",pe),new Y("_pad0",pe),new Y("_pad1",pe),new Y("_pad2",pe)]),this._binningUniformFormat=new Xe(e,[new Y("numKeys",pe),new Y("threadBlocks",pe),new Y("pass_",pe),new Y("flags",pe)]);let r=e.minSubgroupSize||e.maxSubgroupSize||32,a=Math.max(1,Math.ceil(256/r)),o=s?"Indirect":"",l=[new K("b_sort",X,!0),new K("b_globalHist",X,!1),new Qe("uniforms",X)],h=[new K("b_globalHist",X,!0),new K("b_passHist",X,!1),new Qe("uniforms",X)],f=[new K("inputKeys",X,!0),new K("outputKeys",X,!1),new K("inputValues",X,!0),new K("outputValues",X,!1),new K("b_passHist",X,!1),new K("b_index",X,!1),new Qe("uniforms",X)];s&&(l.push(new K("b_sortElementCount",X,!0)),h.push(new K("b_sortElementCount",X,!0)),f.push(new K("b_sortElementCount",X,!0))),this._globalHistBindGroupFormat=new Ue(e,l),this._scanBindGroupFormat=new Ue(e,h),this._binningBindGroupFormat=new Ue(e,f);let u=new Map;u.set("{G_HIST_DIM}",U6),u.set("{G_HIST_PART_SIZE}",vI),s&&u.set("USE_INDIRECT_SORT",""),this._globalHistShader=new Be(e,{name:`OneSweepGlobalHist${o}`,shaderLanguage:se,cshader:KM,cdefines:u,computeBindGroupFormat:this._globalHistBindGroupFormat,computeUniformBufferFormats:{uniforms:this._globalHistUniformFormat}});let d=new Map;d.set("{MAX_SUBGROUPS}",a),d.set("{PART_SIZE}",Ly),s&&d.set("USE_INDIRECT_SORT",""),this._scanShader=new Be(e,{name:`OneSweepScan${o}`,shaderLanguage:se,cshader:jM,cdefines:d,computeBindGroupFormat:this._scanBindGroupFormat,computeUniformBufferFormats:{uniforms:this._scanUniformFormat}});let p=new Map;p.set("{D_DIM}",$M),p.set("{KEYS_PER_THREAD}",ZM),p.set("{MAX_SUBGROUPS}",a),s&&p.set("USE_INDIRECT_SORT",""),this._binningShader=new Be(e,{name:`OneSweepBinning${o}`,shaderLanguage:se,cshader:qM,cdefines:p,computeBindGroupFormat:this._binningBindGroupFormat,computeUniformBufferFormats:{uniforms:this._binningUniformFormat}}),this._globalHistCompute=new Ye(e,this._globalHistShader,this._globalHistShader.name),this._scanCompute=new Ye(e,this._scanShader,this._scanShader.name)}destroy(){this._destroyBuffers(),this._globalHistShader?.destroy(),this._scanShader?.destroy(),this._binningShader?.destroy(),this._globalHistBindGroupFormat?.destroy(),this._scanBindGroupFormat?.destroy(),this._binningBindGroupFormat?.destroy(),this._globalHistShader=null,this._scanShader=null,this._binningShader=null,this._globalHistCompute=null,this._scanCompute=null,this._binningComputes.length=0,this._globalHistBindGroupFormat=null,this._scanBindGroupFormat=null,this._binningBindGroupFormat=null,this._globalHistUniformFormat=null,this._scanUniformFormat=null,this._binningUniformFormat=null,super.destroy()}_destroyBuffers(){this._destroyPingPongBuffers(),this._globalHist?.destroy(),this._passHist?.destroy(),this._index?.destroy(),this._globalHist=null,this._passHist=null,this._index=null,this._allocatedThreadBlocks=0,this._threadBlocks=0}get radixBits(){return 8}_ensureBinningComputes(e){for(;this._binningComputes.length32)}get sortedIndices(){return this._impl.sortedIndices}get sortedKeys(){return this._impl.sortedKeys}get radixBits(){return this._impl.radixBits}set capacity(t){this._impl.capacity=t}get capacity(){return this._impl.capacity}sort(t,e,s=16,i,r,a=!1){return this._impl.sort(t,e,s,i,r,a)}sortIndirect(t,e,s,i,r,a,o,l=!1){return this._impl.sortIndirect(t,e,s,i,r,a,o,l)}prepareIndirect(){return this._impl.prepareIndirect()}destroy(){this._impl.destroy()}};var k6=new Q,TS=class{constructor(t){this.device=t,this.needsDepthBuffer=!1}render(t,e,s){}drawQuad(t,e,s){let i;if(s){let r=t?t.width:this.device.width,a=t?t.height:this.device.height;i=k6.set(s.x*r,s.y*a,s.z*r,s.w*a)}this.device.setBlendState(Oe.NOBLEND),Qt(this.device,t,e,i)}};n(TS,"quadVertexShader",` + attribute vec2 aPosition; + varying vec2 vUv0; + void main(void) + { + gl_Position = vec4(aPosition, 0.0, 1.0); + vUv0 = getImageEffectUV((aPosition.xy + 1.0) * 0.5); + } + `);var Ut=class extends yt{constructor(){super(...arguments);n(this,"_shader",null);n(this,"quadRender",null);n(this,"cullMode",0);n(this,"frontFace",0);n(this,"blendState",Oe.NOBLEND);n(this,"depthState",Pt.NODEPTH);n(this,"stencilFront",null);n(this,"stencilBack",null);n(this,"viewport");n(this,"scissor")}set shader(e){this.quadRender?.destroy(),this.quadRender=null,this._shader=e,e&&(this.quadRender=new hs(e))}get shader(){return this._shader}execute(){this.device.setDrawStates(this.blendState,this.depthState,this.cullMode,this.frontFace,this.stencilFront,this.stencilBack),this.quadRender?.render(this.viewport,this.scissor)}};var QM=` uniform highp usampler2D keysTexture; uniform int bitsPerStep; uniform int groupSize; @@ -1048,7 +1480,7 @@ void main() { pcFragColor0 = float(count); } -`,dX=` +`;var JM=` { uint base = {i}u * 4u; uvec4 mi4 = (keyIndex + base) + QUAD_OFFSETS; @@ -1076,7 +1508,7 @@ void main() { #endif count += m4.x + m4.y + m4.z + m4.w; } -`,dY=` +`;var e2=` var keysTexture: texture_2d; uniform bitsPerStep: i32; uniform groupSize: i32; @@ -1150,7 +1582,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { output.color = f32(count); return output; } -`,dq=` +`;var t2=` { let base = {i}u * 4u; var mi4 = (keyIndex + base) + QUAD_OFFSETS; @@ -1178,7 +1610,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { #endif count += m4.x + m4.y + m4.z + m4.w; } -`;class dj extends dH{setKeysTexture(e){this._keysTexture=e;}setDynamicParams(e,t){this._dynamicParams.elementCount=e,this._dynamicParams.imageElementsLog2=t;}execute(){this.keysTextureId.setValue(this._keysTexture),this.bitsPerStepId.setValue(this.bitsPerStep),this.groupSizeId.setValue(this.groupSize),this.elementCountId.setValue(this._dynamicParams.elementCount),this.imageElementsLog2Id.setValue(this._dynamicParams.imageElementsLog2),this.currentBitId.setValue(this.currentBit),super.execute();}constructor(e,t,i,s,r){super(e),this.sourceLinear=false,this.bitsPerStep=0,this.groupSize=0,this.currentBit=0,this._dynamicParams={elementCount:0,imageElementsLog2:0},this.sourceLinear=t,this.bitsPerStep=i,this.groupSize=s,this.currentBit=r,n$.get(e,tz).set("radixSortCountPS",dW),n$.get(e,tz).set("radixSortCountQuad",dX),n$.get(e,tV).set("radixSortCountPS",dY),n$.get(e,tV).set("radixSortCountQuad",dq);let a=new Map;t&&a.set("SOURCE_LINEAR",""),this.shader=nJ.createShader(e,{uniqueName:t?"RadixSortCountShaderLinear":"RadixSortCountShader",attributes:{aPosition:e8},vertexChunk:"quadVS",fragmentChunk:"radixSortCountPS",fragmentDefines:a,fragmentOutputTypes:"float"}),this.keysTextureId=e.scope.resolve("keysTexture"),this.bitsPerStepId=e.scope.resolve("bitsPerStep"),this.groupSizeId=e.scope.resolve("groupSize"),this.elementCountId=e.scope.resolve("elementCount"),this.imageElementsLog2Id=e.scope.resolve("imageElementsLog2"),this.currentBitId=e.scope.resolve("currentBit");}}var dK=` +`;var Fy=class extends Ut{constructor(e,s,i,r,a){super(e);n(this,"sourceLinear",!1);n(this,"bitsPerStep",0);n(this,"groupSize",0);n(this,"currentBit",0);n(this,"_dynamicParams",{elementCount:0,imageElementsLog2:0});this.sourceLinear=s,this.bitsPerStep=i,this.groupSize=r,this.currentBit=a,ne.get(e,fe).set("radixSortCountPS",QM),ne.get(e,fe).set("radixSortCountQuad",JM),ne.get(e,se).set("radixSortCountPS",e2),ne.get(e,se).set("radixSortCountQuad",t2);let o=new Map;s&&o.set("SOURCE_LINEAR","");let l=s?"RadixSortCountShaderLinear":"RadixSortCountShader";this.shader=Se.createShader(e,{uniqueName:l,attributes:{aPosition:ee},vertexChunk:"quadVS",fragmentChunk:"radixSortCountPS",fragmentDefines:o,fragmentOutputTypes:"float"}),this.keysTextureId=e.scope.resolve("keysTexture"),this.bitsPerStepId=e.scope.resolve("bitsPerStep"),this.groupSizeId=e.scope.resolve("groupSize"),this.elementCountId=e.scope.resolve("elementCount"),this.imageElementsLog2Id=e.scope.resolve("imageElementsLog2"),this.currentBitId=e.scope.resolve("currentBit")}setKeysTexture(e){this._keysTexture=e}setDynamicParams(e,s){this._dynamicParams.elementCount=e,this._dynamicParams.imageElementsLog2=s}execute(){this.keysTextureId.setValue(this._keysTexture),this.bitsPerStepId.setValue(this.bitsPerStep),this.groupSizeId.setValue(this.groupSize),this.elementCountId.setValue(this._dynamicParams.elementCount),this.imageElementsLog2Id.setValue(this._dynamicParams.imageElementsLog2),this.currentBitId.setValue(this.currentBit),super.execute()}};var s2=` uniform highp usampler2D keysTexture; #ifdef SOURCE_LINEAR #define FIRST_PASS @@ -1353,7 +1785,7 @@ void main() { pcFragColor0 = uvec4(outKey, 0u, 0u, 1u); pcFragColor1 = uvec4(outIndex, 0u, 0u, 1u); } -`,d$=` +`;var i2=` var keysTexture: texture_2d; #ifdef SOURCE_LINEAR #define FIRST_PASS @@ -1535,22 +1967,14 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { output.color1 = vec4u(outIndex, 0u, 0u, 1u); return output; } -`;class dZ extends dH{setKeysTexture(e){this._keysTexture=e;}setIndicesTexture(e){this._indicesTexture=e;}setPrefixSumsTexture(e){this._prefixSums=e;}setDynamicParams(e,t,i){this._dynamicParams.elementCount=e,this._dynamicParams.imageElementsLog2=t,this._dynamicParams.imageSize=i;}execute(){this.keysTextureId.setValue(this._keysTexture),this.sourceLinear||this.indicesTextureId.setValue(this._indicesTexture),this.prefixSumsId.setValue(this._prefixSums),this.bitsPerStepId.setValue(this.bitsPerStep),this.groupSizeId.setValue(this.groupSize),this.elementCountId.setValue(this._dynamicParams.elementCount),this.imageElementsLog2Id.setValue(this._dynamicParams.imageElementsLog2),this.currentBitId.setValue(this.currentBit),this.imageSizeId.setValue(this._dynamicParams.imageSize),super.execute();}constructor(e,t,i,s,r,a){super(e),this.sourceLinear=false,this.outputLinear=false,this.bitsPerStep=0,this.groupSize=0,this.currentBit=0,this._dynamicParams={elementCount:0,imageElementsLog2:0,imageSize:0},this.sourceLinear=t,this.outputLinear=i,this.bitsPerStep=s,this.groupSize=r,this.currentBit=a,n$.get(e,tz).set("radixSortReorderPS",dK),n$.get(e,tV).set("radixSortReorderPS",d$);let n=new Map;t&&n.set("SOURCE_LINEAR",""),i&&n.set("OUTPUT_LINEAR","");let o="RadixSortReorderShader";t&&(o+="SourceLinear"),i&&(o+="OutputLinear"),this.shader=nJ.createShader(e,{uniqueName:o,attributes:{aPosition:e8},vertexChunk:"quadVS",fragmentChunk:"radixSortReorderPS",fragmentDefines:n,fragmentOutputTypes:["uvec4","uvec4"]}),this.keysTextureId=e.scope.resolve("keysTexture"),t||(this.indicesTextureId=e.scope.resolve("indicesTexture")),this.prefixSumsId=e.scope.resolve("prefixSums"),this.bitsPerStepId=e.scope.resolve("bitsPerStep"),this.groupSizeId=e.scope.resolve("groupSize"),this.elementCountId=e.scope.resolve("elementCount"),this.imageElementsLog2Id=e.scope.resolve("imageElementsLog2"),this.currentBitId=e.scope.resolve("currentBit"),this.imageSizeId=e.scope.resolve("imageSize");}}class dQ{constructor(){this.hasTangents=false,this.shaderChunks=null,this.pass=0,this.alphaTest=false,this.blendType=3,this.separateAmbient=false,this.screenSpace=false,this.skin=false,this.batch=false,this.useInstancing=false,this.useMorphPosition=false,this.useMorphNormal=false,this.useMorphTextureBasedInt=false,this.nineSlicedMode=0,this.clusteredLightingEnabled=true,this.clusteredLightingCookiesEnabled=false,this.clusteredLightingShadowsEnabled=false,this.clusteredLightingShadowType=0,this.clusteredLightingAreaLightsEnabled=false,this.vertexColors=false,this.useVertexColorGamma=false,this.lightMapEnabled=false,this.dirLightMapEnabled=false,this.useHeights=false,this.useNormals=false,this.useClearCoatNormals=false,this.useAo=false,this.diffuseMapEnabled=false,this.pixelSnap=false,this.ambientSH=false,this.ssao=false,this.twoSidedLighting=false,this.occludeDirect=false,this.occludeSpecular=0,this.occludeSpecularFloat=false,this.useMsdf=false,this.msdfTextAttribute=false,this.alphaToCoverage=false,this.opacityFadesSpecular=false,this.opacityDither=nA,this.opacityShadowDither=nA,this.cubeMapProjection=0,this.useSpecular=false,this.useSpecularityFactor=false,this.enableGGXSpecular=false,this.fresnelModel=0,this.useRefraction=false,this.useClearCoat=false,this.useSheen=false,this.useIridescence=false,this.useMetalness=false,this.useDynamicRefraction=false,this.dispersion=false,this.fog=ns,this.gamma=0,this.toneMap=-1,this.reflectionSource=np,this.reflectionEncoding=null,this.reflectionCubemapEncoding=null,this.ambientSource="constant",this.ambientEncoding=null,this.skyboxIntensity=1,this.useCubeMapRotation=false,this.lightMapWithoutAmbient=false,this.lights=[],this.noShadow=false,this.lightMaskDynamic=0,this.userAttributes={},this.linearDepth=false,this.shadowCatcher=false;}}class dJ{static update(e,t,i,s,r,a,n){dJ.updateSharedOptions(e,t,i,r,a),dJ.updateMaterialOptions(e,t),dJ.updateEnvOptions(e,t,i,s),dJ.updateLightingOptions(e,t,i,r,n);}static updateSharedOptions(e,t,i,s,r){e.shaderChunks=t.shaderChunks,e.pass=r,e.alphaTest=t.alphaTest>0,e.blendType=t.blendType,e.screenSpace=s&&(256&s)!=0,e.skin=s&&(2&s)!=0,e.useInstancing=s&&(32&s)!=0,e.useMorphPosition=s&&(1024&s)!=0,e.useMorphNormal=s&&(2048&s)!=0,e.useMorphTextureBasedInt=s&&(8192&s)!=0,e.hasTangents=s&&(512&s)!=0,e.nineSlicedMode=t.nineSlicedMode||0,t.useLighting&&i.clusteredLightingEnabled?(e.clusteredLightingEnabled=true,e.clusteredLightingCookiesEnabled=i.lighting.cookiesEnabled,e.clusteredLightingShadowsEnabled=i.lighting.shadowsEnabled,e.clusteredLightingShadowType=i.lighting.shadowType,e.clusteredLightingAreaLightsEnabled=i.lighting.areaLightsEnabled):(e.clusteredLightingEnabled=false,e.clusteredLightingCookiesEnabled=false,e.clusteredLightingShadowsEnabled=false,e.clusteredLightingAreaLightsEnabled=false);}static updateMaterialOptions(e,t){e.separateAmbient=false,e.pixelSnap=t.pixelSnap,e.ambientSH=t.ambientSH,e.twoSidedLighting=t.twoSidedLighting,e.occludeDirect=t.occludeDirect,e.occludeSpecular=t.occludeSpecular,e.occludeSpecularFloat=1!==t.occludeSpecularIntensity,e.useMsdf=false,e.msdfTextAttribute=false,e.alphaToCoverage=t.alphaToCoverage,e.opacityFadesSpecular=t.opacityFadesSpecular,e.opacityDither=t.opacityDither,e.cubeMapProjection=0,e.useSpecular=t.hasSpecular,e.useSpecularityFactor=t.hasSpecularityFactor,e.enableGGXSpecular=t.ggxSpecular,e.useAnisotropy=false,e.fresnelModel=t.fresnelModel,e.useRefraction=t.hasRefraction,e.useClearCoat=t.hasClearCoat,e.useSheen=t.hasSheen,e.useIridescence=t.hasIrridescence,e.useMetalness=t.hasMetalness,e.useDynamicRefraction=t.dynamicRefraction,e.dispersion=t.dispersion>0,e.vertexColors=false,e.lightMapEnabled=t.hasLighting,e.dirLightMapEnabled=t.dirLightMap,e.useHeights=t.hasHeights,e.useNormals=t.hasNormals,e.useClearCoatNormals=t.hasClearCoatNormals,e.useAo=t.hasAo,e.diffuseMapEnabled=t.hasDiffuseMap;}static updateEnvOptions(e,t,i,s){e.fog=t.useFog?s.fog:ns,e.gamma=s.shaderOutputGamma,e.toneMap=t.useTonemap?s.toneMapping:6,t.useSkybox&&i.envAtlas&&i.skybox?(e.reflectionSource=n_,e.reflectionEncoding=i.envAtlas.encoding,e.reflectionCubemapEncoding=i.skybox.encoding):t.useSkybox&&i.envAtlas?(e.reflectionSource=nm,e.reflectionEncoding=i.envAtlas.encoding):t.useSkybox&&i.skybox?(e.reflectionSource=ng,e.reflectionEncoding=i.skybox.encoding):(e.reflectionSource=np,e.reflectionEncoding=null),t.ambientSH?(e.ambientSource=ny,e.ambientEncoding=null):e.reflectionSource!==np&&i.envAtlas?(e.ambientSource=nx,e.ambientEncoding=i.envAtlas.encoding):(e.ambientSource=nT,e.ambientEncoding=null);let r=e.reflectionSource!==np;e.skyboxIntensity=r,e.useCubeMapRotation=r&&i._skyboxRotationShaderInclude;}static updateLightingOptions(e,t,i,s,r){if(e.lightMapWithoutAmbient=false,t.useLighting){let t=[],a=s?s>>16:1;e.lightMaskDynamic=!!(1&a),e.lightMapWithoutAmbient=false,r&&(dJ.collectLights(0,r[0],t,a),i.clusteredLightingEnabled||(dJ.collectLights(1,r[1],t,a),dJ.collectLights(2,r[2],t,a))),e.lights=t;}else e.lights=[];(0!==e.lights.length||i.clusteredLightingEnabled)&&(1&s)==0||(e.noShadow=true);}static collectLights(e,t,i,s){for(let e=0;e{let{id:t,uv:i,name:s}=e,a=t+100*i;if(!l.has(a)){l.add(a),n.set(`vUV${i}_${t}`,"vec2");let e=`texture_${s}MapTransform`;r.set(`{TRANSFORM_NAME_${o}}`,e),r.set(`{TRANSFORM_UV_${o}}`,i),r.set(`{TRANSFORM_ID_${o}}`,t),o++;}}),r.set("UV_TRANSFORMS_COUNT",o),s.vertexColors&&(a.vertex_color=ti,r.set("VERTEX_COLOR",true),n.set("vVertexColor","vec4"),s.useVertexColorGamma&&r.set("STD_VERTEX_COLOR_GAMMA","")),s.useMsdf&&s.msdfTextAttribute&&(a.vertex_outlineParameters=ty,a.vertex_shadowParameters=tx,r.set("MSDF",true)),(s.useMorphPosition||s.useMorphNormal)&&(r.set("MORPHING",true),s.useMorphTextureBasedInt&&r.set("MORPHING_INT",true),s.useMorphPosition&&r.set("MORPHING_POSITION",true),s.useMorphNormal&&r.set("MORPHING_NORMAL",true),a.morph_vertex_id=tA),s.skin&&(a.vertex_boneIndices=tt,s.batch?r.set("BATCH",true):(a.vertex_boneWeights=te,r.set("SKIN",true))),s.useInstancing&&r.set("INSTANCING",true),s.screenSpace&&r.set("SCREENSPACE",true),s.pixelSnap&&r.set("PIXELSNAP",true),n.forEach((e,t)=>{this.varyingsCode+=`#define VARYING_${t.toUpperCase()} -`,this.varyingsCode+=this.shaderLanguage===tV?`varying ${t}: ${t4.get(e)}; -`:`varying ${e} ${t}; -`;}),this.includes.set("varyingsVS",this.varyingsCode),this.includes.set("varyingsPS",this.varyingsCode),this.vshader=` - #include "litMainVS" - `;}_setupLightingDefines(e,t){let i=this.fDefines,s=this.options;if(this.fDefines.set("LIGHT_COUNT",s.lights.length),e&&i.set("AREA_LIGHTS",true),t&&this.lighting&&(i.set("LIT_CLUSTERED_LIGHTS",true),s.clusteredLightingCookiesEnabled&&i.set("CLUSTER_COOKIES",true),s.clusteredLightingAreaLightsEnabled&&i.set("CLUSTER_AREALIGHTS",true),s.lightMaskDynamic&&i.set("CLUSTER_MESH_DYNAMIC_LIGHTS",true),s.clusteredLightingShadowsEnabled&&!s.noShadow)){let e=nh.get(s.clusteredLightingShadowType);i.set("CLUSTER_SHADOWS",true),i.set(`SHADOW_KIND_${e.kind}`,true),i.set(`CLUSTER_SHADOW_TYPE_${e.kind}`,true);}for(let r=0;r0&&i.set(`LIGHT${r}_SHADOW_CASCADE_BLEND`,true),a.numCascades>1&&i.set(`LIGHT${r}_SHADOW_CASCADES`,true)),(c.pcf||c.pcss||this.device.isWebGPU)&&i.set(`LIGHT${r}_SHADOW_SAMPLE_SOURCE_ZBUFFER`,true),1===n&&i.set(`LIGHT${r}_SHADOW_SAMPLE_POINT`,true)),h&&(i.set(`SHADOW_KIND_${c.kind}`,true),0===n&&i.set("SHADOW_DIRECTIONAL",true));}}prepareForwardPass(e){let{options:t}=this,i=t.clusteredLightingEnabled&&t.clusteredLightingAreaLightsEnabled||t.lights.some(e=>e._shape&&0!==e._shape),s=!t.lightMapEnabled||t.lightMapWithoutAmbient,r=this.needsNormal&&(t.useNormals||t.useClearCoatNormals||t.enableGGXSpecular&&!t.useHeights);t.useSpecular&&(this.fDefineSet(true,"LIT_SPECULAR"),this.fDefineSet(this.reflections,"LIT_REFLECTIONS"),this.fDefineSet(t.useClearCoat,"LIT_CLEARCOAT"),this.fDefineSet(t.fresnelModel>0,"LIT_SPECULAR_FRESNEL"),this.fDefineSet(t.useSheen,"LIT_SHEEN"),this.fDefineSet(t.useIridescence,"LIT_IRIDESCENCE")),this.fDefineSet(this.lighting&&t.useSpecular||this.reflections,"LIT_SPECULAR_OR_REFLECTION"),this.fDefineSet(this.needsSceneColor,"LIT_SCENE_COLOR"),this.fDefineSet(this.needsScreenSize,"LIT_SCREEN_SIZE"),this.fDefineSet(this.needsTransforms,"LIT_TRANSFORMS"),this.fDefineSet(this.needsNormal,"LIT_NEEDS_NORMAL"),this.fDefineSet(this.lighting,"LIT_LIGHTING"),this.fDefineSet(t.useMetalness,"LIT_METALNESS"),this.fDefineSet(t.enableGGXSpecular,"LIT_GGX_SPECULAR"),this.fDefineSet(t.useAnisotropy,"LIT_ANISOTROPY"),this.fDefineSet(t.useSpecularityFactor,"LIT_SPECULARITY_FACTOR"),this.fDefineSet(t.useCubeMapRotation,"CUBEMAP_ROTATION"),this.fDefineSet(t.occludeSpecularFloat,"LIT_OCCLUDE_SPECULAR_FLOAT"),this.fDefineSet(t.separateAmbient,"LIT_SEPARATE_AMBIENT"),this.fDefineSet(t.twoSidedLighting,"LIT_TWO_SIDED_LIGHTING"),this.fDefineSet(t.lightMapEnabled,"LIT_LIGHTMAP"),this.fDefineSet(t.dirLightMapEnabled,"LIT_DIR_LIGHTMAP"),this.fDefineSet(t.skyboxIntensity>0,"LIT_SKYBOX_INTENSITY"),this.fDefineSet(t.clusteredLightingShadowsEnabled,"LIT_CLUSTERED_SHADOWS"),this.fDefineSet(t.clusteredLightingAreaLightsEnabled,"LIT_CLUSTERED_AREA_LIGHTS"),this.fDefineSet(r,"LIT_TBN"),this.fDefineSet(s,"LIT_ADD_AMBIENT"),this.fDefineSet(t.hasTangents,"LIT_TANGENTS"),this.fDefineSet(t.useNormals,"LIT_USE_NORMALS"),this.fDefineSet(t.useClearCoatNormals,"LIT_USE_CLEARCOAT_NORMALS"),this.fDefineSet(t.useRefraction,"LIT_REFRACTION"),this.fDefineSet(t.useDynamicRefraction,"LIT_DYNAMIC_REFRACTION"),this.fDefineSet(t.dispersion,"LIT_DISPERSION"),this.fDefineSet(t.useHeights,"LIT_HEIGHTS"),this.fDefineSet(t.opacityFadesSpecular,"LIT_OPACITY_FADES_SPECULAR"),this.fDefineSet(t.alphaToCoverage,"LIT_ALPHA_TO_COVERAGE"),this.fDefineSet(t.alphaTest,"LIT_ALPHA_TEST"),this.fDefineSet(t.useMsdf,"LIT_MSDF"),this.fDefineSet(t.ssao,"LIT_SSAO"),this.fDefineSet(t.useAo,"LIT_AO"),this.fDefineSet(t.occludeDirect,"LIT_OCCLUDE_DIRECT"),this.fDefineSet(t.msdfTextAttribute,"LIT_MSDF_TEXT_ATTRIBUTE"),this.fDefineSet(t.diffuseMapEnabled,"LIT_DIFFUSE_MAP"),this.fDefineSet(t.shadowCatcher,"LIT_SHADOW_CATCHER"),this.fDefineSet(true,"LIT_FRESNEL_MODEL",na[t.fresnelModel]),this.fDefineSet(true,"LIT_NONE_SLICE_MODE",nw[t.nineSlicedMode]),this.fDefineSet(true,"LIT_BLEND_TYPE",ni[t.blendType]),this.fDefineSet(true,"LIT_CUBEMAP_PROJECTION",nc[t.cubeMapProjection]),this.fDefineSet(true,"LIT_OCCLUDE_SPECULAR",nf[t.occludeSpecular]),this.fDefineSet(true,"LIT_REFLECTION_SOURCE",nS[t.reflectionSource]),this.fDefineSet(true,"LIT_AMBIENT_SOURCE",nE[t.ambientSource]),this.fDefineSet(true,"{lightingUv}",e??""),this.fDefineSet(true,"{reflectionDecode}",c1.decodeFunc(t.reflectionEncoding)),this.fDefineSet(true,"{reflectionCubemapDecode}",c1.decodeFunc(t.reflectionCubemapEncoding)),this.fDefineSet(true,"{ambientDecode}",c1.decodeFunc(t.ambientEncoding)),this._setupLightingDefines(i,t.clusteredLightingEnabled);}preparePrepassPass(){let{options:e}=this;this.fDefineSet(e.alphaTest,"LIT_ALPHA_TEST"),this.fDefineSet(true,"STD_OPACITY_DITHER",nR[e.opacityShadowDither]);}prepareShadowPass(){let{options:e}=this,t=this.shaderPassInfo.lightType,i=this.shaderPassInfo.shadowType,s=nh.get(i),r=0===t||!s.vsm&&2===t;this.fDefineSet(r,"PERSPECTIVE_DEPTH"),this.fDefineSet(true,"LIGHT_TYPE",`${nn[t]}`),this.fDefineSet(true,"SHADOW_TYPE",`${s.name}`),this.fDefineSet(e.alphaTest,"LIT_ALPHA_TEST");}generateFragmentShader(e,t,i){let s=this.options;this.includes.set("frontendDeclPS",e??""),this.includes.set("frontendCodePS",t??""),3===s.pass||(1===s.pass?this.preparePrepassPass():this.shadowPass?this.prepareShadowPass():this.prepareForwardPass(i)),this.fshader=` - #include "litMainPS" - `;}constructor(e,t,i=true){this.varyingsCode="",this.vDefines=new Map,this.fDefines=new Map,this.includes=new Map,this.chunks=null,this.device=e,this.options=t;let s=t.shaderChunks;if(this.shaderLanguage=e.isWebGPU&&i&&(!s||s.useWGSL)?tV:tz,e.isWebGPU&&this.shaderLanguage===tz&&!e.hasTranspilers,this.attributes={vertex_position:e8},t.userAttributes)for(let[e,i]of Object.entries(t.userAttributes))this.attributes[i]=e;let r=n$.get(e,this.shaderLanguage);this.chunks=new Map(r),s&&(this.shaderLanguage===tz?s.glsl:s.wgsl).forEach((e,t)=>{for(let t in d0)d0.hasOwnProperty(t)&&e.indexOf(t)>=0&&(this.attributes[t]=d0[t]);this.chunks.set(t,e);}),this.shaderPassInfo=nq.get(this.device).getByIndex(t.pass),this.shadowPass=this.shaderPassInfo.isShadow,this.lighting=t.lights.length>0||t.dirLightMapEnabled||t.clusteredLightingEnabled,this.reflections=t.reflectionSource!==np,this.needsNormal=this.lighting||this.reflections||t.useSpecular||t.ambientSH||t.useHeights||t.enableGGXSpecular||t.clusteredLightingEnabled&&!this.shadowPass||t.useClearCoatNormals,this.needsNormal=this.needsNormal&&!this.shadowPass,this.needsSceneColor=t.useDynamicRefraction,this.needsScreenSize=t.useDynamicRefraction,this.needsTransforms=t.useDynamicRefraction,this.vshader=null,this.fshader=null;}}let d2={generateKey:e=>`lit${Object.keys(e).sort().map(t=>"shaderChunks"===t?e.shaderChunks?.key??"":"lights"===t?d2.generateLightsKey(e):t+e[t]).join("\n")}`,generateLightsKey:e=>`lights:${e.lights.map(t=>e.clusteredLightingEnabled&&0!==t._type?"":`${t.key},`).join("")}`},d3=[0,1,2,3,4,5,6,7],d4=new class extends nW{generateKey(e){let t=nW.definesHash(e.defines),i=iL(e.shaderChunkGLSL??""),s=iL(e.shaderChunkWGSL??""),r=d2.generateKey(e.litOptions),a=`${d3.map((t,i)=>e.usedUvs[i]?"1":"0").join("")}`;return `lit_${t}_${a}_${i}_${s}_${r}`}createShaderDefinition(e,t){let i=!!t.shaderChunkWGSL,s=new d1(e,t.litOptions,i),r={name:"LitShader",shaderLanguage:s.shaderLanguage,tag:s.shaderPassInfo.isForward?1:void 0},a=t.usedUvs||[true];s.generateVertexShader(a,a,[]),s.generateFragmentShader("",s.shaderLanguage===tV?t.shaderChunkWGSL:t.shaderChunkGLSL,"vUv0");let n=nZ.merge(s.chunks,s.includes),o=s.vDefines;t.defines.forEach((e,t)=>o.set(t,e));let l=s.fDefines;return t.defines.forEach((e,t)=>l.set(t,e)),r.attributes=s.attributes,r.vertexCode=s.vshader,r.vertexIncludes=n,r.vertexDefines=o,r.fragmentCode=s.fshader,r.fragmentIncludes=n,r.fragmentDefines=l,rp.createDefinition(e,r)}},d5=new class{constructor(){this.litOptions=new dQ;}};class d6{get pass(){return this.litOptions.pass}constructor(){this.defines=new Map,this.forceUv1=false,this.specularTint=false,this.metalnessTint=false,this.glossTint=false,this.emissiveEncoding="linear",this.lightMapEncoding="linear",this.vertexColorGamma=false,this.packedNormal=false,this.normalDetailPackedNormal=false,this.clearCoatPackedNormal=false,this.glossInvert=false,this.sheenGlossInvert=false,this.clearCoatGlossInvert=false,this.useAO=false,this.litOptions=new dQ;}}let d8=[],d9=e=>Object.keys(e).filter(e=>"litOptions"!==e).sort(),d7=new class extends nW{generateKey(e){let t;e===this.optionsContextMin?(this.propsMin||(this.propsMin=d9(e)),t=this.propsMin):e===this.optionsContext?(this.props||(this.props=d9(e)),t=this.props):t=d9(e);let i=nW.definesHash(e.defines);return `standard: -${i} -${t.map(t=>t+e[t]).join("\n")}${d2.generateKey(e.litOptions)}`}_getUvSourceExpression(e,t,i){let s,r=i[e],a=i[t],n=0===i.litOptions.pass;return n&&1===i.litOptions.nineSlicedMode||n&&2===i.litOptions.nineSlicedMode?s="nineSlicedUv":(s=0===r?`vUv${a}`:`vUV${a}_${r}`,i.heightMap&&"heightMapTransform"!==e&&(s+=" + dUvOffset")),s}_validateMapChunk(e,t,i,s){}_addMapDefines(e,t,i,s,r,a,n=null){let o=`${t}Map`,l=t.toUpperCase(),h=`${o}Uv`,c=`${o}Identifier`,d=`${o}Transform`,u=`${o}Channel`,f=`${t}VertexColorChannel`,p=`${t}Tint`,m=`${t}VertexColor`,_=`${t}Mode`,g=`${t}Invert`,v=s[p],S=s[m],y=s[o],x=s[c],T=s[_],E=r.get(i);if(y){e.set(`STD_${l}_TEXTURE`,"");let t=this._getUvSourceExpression(d,h,s);e.set(`{STD_${l}_TEXTURE_UV}`,t),e.set(`{STD_${l}_TEXTURE_CHANNEL}`,s[u]);let i=`{STD_${l}_TEXTURE_NAME}`;if(E.includes(i)){let t=`texture_${o}`,s=a[x];s?t=s:(a[x]=t,e.set(`STD_${l}_TEXTURE_ALLOCATE`,"")),e.set(i,t);}if(n){let t="aaa"===s[u]?"passThrough":c1.decodeFunc(n);e.set(`{STD_${l}_TEXTURE_DECODE}`,t);}}S&&(e.set(`STD_${l}_VERTEX`,""),e.set(`{STD_${l}_VERTEX_CHANNEL}`,s[f])),T&&e.set(`{STD_${l}_DETAILMODE}`,T),v&&e.set(`STD_${l}_CONSTANT`,""),s[g]&&e.set(`STD_${l}_INVERT`,"");}_correctChannel(e,t,i){if(i[e]>0){if(i[e]t.length){let s=t,r=s.charAt(s.length-1),a=i[e]-s.length;for(let e=0;e{e&&t.set(i,s);};s(e.lightMap,"STD_LIGHTMAP",""),s(e.lightVertexColor,"STD_LIGHT_VERTEX_COLOR",""),s(e.dirLightMap&&e.litOptions.useSpecular,"STD_LIGHTMAP_DIR",""),s(e.heightMap,"STD_HEIGHT_MAP",""),s(e.useSpecularColor,"STD_SPECULAR_COLOR",""),s(e.aoMap||e.aoVertexColor||e.useAO,"STD_AO",""),s(true,"STD_OPACITY_DITHER",nR[i.isForward?e.litOptions.opacityDither:e.litOptions.opacityShadowDither]);}createShaderDefinition(e,t){let i=nq.get(e).getByIndex(t.litOptions.pass),s=i.isForward,r=new d1(e,t.litOptions);this.createVertexShader(r,t);let a={};t.litOptions.fresnelModel=0===t.litOptions.fresnelModel?2:t.litOptions.fresnelModel;let n=r.fDefines;this.prepareFragmentDefines(t,n,i);let o="";if(s){if(t.heightMap&&this._addMapDefines(n,"height","parallaxPS",t,r.chunks,a),(3!==t.litOptions.blendType||t.litOptions.alphaTest||t.litOptions.alphaToCoverage||t.litOptions.opacityDither!==nA)&&this._addMapDefines(n,"opacity","opacityPS",t,r.chunks,a),r.needsNormal){if((t.normalMap||t.clearCoatNormalMap)&&!t.litOptions.hasTangents){let e=t.normalMap?"normalMap":"clearCoatNormalMap";o=this._getUvSourceExpression(`${e}Transform`,`${e}Uv`,t);}this._addMapDefines(n,"normalDetail","normalMapPS",t,r.chunks,a,t.normalDetailPackedNormal?"xy":"xyz"),this._addMapDefines(n,"normal","normalMapPS",t,r.chunks,a,t.packedNormal?"xy":"xyz");}t.diffuseDetail&&this._addMapDefines(n,"diffuseDetail","diffusePS",t,r.chunks,a,t.diffuseDetailEncoding),this._addMapDefines(n,"diffuse","diffusePS",t,r.chunks,a,t.diffuseEncoding),t.litOptions.useRefraction&&(this._addMapDefines(n,"refraction","transmissionPS",t,r.chunks,a),this._addMapDefines(n,"thickness","thicknessPS",t,r.chunks,a)),t.litOptions.useIridescence&&(this._addMapDefines(n,"iridescence","iridescencePS",t,r.chunks,a),this._addMapDefines(n,"iridescenceThickness","iridescenceThicknessPS",t,r.chunks,a)),(r.lighting&&t.litOptions.useSpecular||r.reflections)&&(t.litOptions.useSheen&&(this._addMapDefines(n,"sheen","sheenPS",t,r.chunks,a,t.sheenEncoding),this._addMapDefines(n,"sheenGloss","sheenGlossPS",t,r.chunks,a)),t.litOptions.useMetalness&&(this._addMapDefines(n,"metalness","metalnessPS",t,r.chunks,a),this._addMapDefines(n,"ior","iorPS",t,r.chunks,a)),t.litOptions.useSpecularityFactor&&this._addMapDefines(n,"specularityFactor","specularityFactorPS",t,r.chunks,a),t.useSpecularColor&&this._addMapDefines(n,"specular","specularPS",t,r.chunks,a,t.specularEncoding),this._addMapDefines(n,"gloss","glossPS",t,r.chunks,a)),t.aoDetail&&this._addMapDefines(n,"aoDetail","aoPS",t,r.chunks,a),(t.aoMap||t.aoVertexColor||t.useAO)&&this._addMapDefines(n,"ao","aoPS",t,r.chunks,a),this._addMapDefines(n,"emissive","emissivePS",t,r.chunks,a,t.emissiveEncoding),t.litOptions.useClearCoat&&(this._addMapDefines(n,"clearCoat","clearCoatPS",t,r.chunks,a),this._addMapDefines(n,"clearCoatGloss","clearCoatGlossPS",t,r.chunks,a),this._addMapDefines(n,"clearCoatNormal","clearCoatNormalPS",t,r.chunks,a,t.clearCoatPackedNormal?"xy":"xyz")),t.litOptions.enableGGXSpecular&&this._addMapDefines(n,"anisotropy","anisotropyPS",t,r.chunks,a),(t.lightMap||t.lightVertexColor)&&this._addMapDefines(n,"light","lightmapPS",t,r.chunks,a,t.lightMapEncoding);}else {let e=t.litOptions.opacityShadowDither;(t.litOptions.alphaTest||e)&&this._addMapDefines(n,"opacity","opacityPS",t,r.chunks,a);}r.generateFragmentShader(r.chunks.get("stdDeclarationPS"),r.chunks.get("stdFrontEndPS"),o);let l=nZ.merge(r.chunks,r.includes),h=r.vDefines;t.defines.forEach((e,t)=>h.set(t,e)),t.defines.forEach((e,t)=>n.set(t,e));let c=rp.createDefinition(e,{name:"StandardShader",attributes:r.attributes,shaderLanguage:r.shaderLanguage,vertexCode:r.vshader,fragmentCode:r.fshader,vertexIncludes:l,fragmentIncludes:l,fragmentDefines:n,vertexDefines:h});return r.shaderPassInfo.isForward&&(c.tag=1),c}constructor(...e){super(...e),this.optionsContext=new d6,this.optionsContextMin=new d6;}},ue=(e,t)=>{if(e.length!==t.length)return false;for(let i=0;i0,e.litOptions.blendType=i.blendType,e.litOptions.screenSpace=s&&(256&s)!=0,e.litOptions.skin=s&&(2&s)!=0,e.litOptions.batch=s&&(16384&s)!=0,e.litOptions.useInstancing=s&&(32&s)!=0,e.litOptions.useMorphPosition=s&&(1024&s)!=0,e.litOptions.useMorphNormal=s&&(2048&s)!=0,e.litOptions.useMorphTextureBasedInt=s&&(8192&s)!=0,e.litOptions.nineSlicedMode=i.nineSlicedMode||0,t.clusteredLightingEnabled&&i.useLighting?(e.litOptions.clusteredLightingEnabled=true,e.litOptions.clusteredLightingCookiesEnabled=t.lighting.cookiesEnabled,e.litOptions.clusteredLightingShadowsEnabled=t.lighting.shadowsEnabled,e.litOptions.clusteredLightingShadowType=t.lighting.shadowType,e.litOptions.clusteredLightingAreaLightsEnabled=t.lighting.areaLightsEnabled):(e.litOptions.clusteredLightingEnabled=false,e.litOptions.clusteredLightingCookiesEnabled=false,e.litOptions.clusteredLightingShadowsEnabled=false,e.litOptions.clusteredLightingAreaLightsEnabled=false);}_updateUVOptions(e,t,i,s,r){let a=false,n=false,o=false;i&&(a=(4&i)!=0,n=(8&i)!=0,o=(16&i)!=0),e.litOptions.vertexColors=false,this._mapXForms=[];let l={};for(let i in d8)this._updateTexOptions(e,t,i,a,n,o,s,l);this._mapXForms=null,e.litOptions.ssao=r?.ssaoEnabled,e.useAO=e.litOptions.ssao,e.litOptions.lightMapEnabled=e.lightMap,e.litOptions.dirLightMapEnabled=e.dirLightMap,e.litOptions.useHeights=e.heightMap,e.litOptions.useNormals=e.normalMap,e.litOptions.useClearCoatNormals=e.clearCoatNormalMap,e.litOptions.useAo=e.aoMap||e.aoVertexColor||e.litOptions.ssao,e.litOptions.diffuseMapEnabled=e.diffuseMap;}_updateTexOptions(e,t,i,s,r,a,n,o){let l="opacity"===i;if(!n||l){let n=`${i}Map`,h=`${i}VertexColor`,c=`${i}VertexColorChannel`,d=`${n}Channel`,u=`${n}Transform`,f=`${n}Uv`,p=`${n}Identifier`;if("light"!==i&&(e[n]=false,e[p]=void 0,e[d]="",e[u]=0,e[f]=0),e[h]=false,e[c]="",l&&3===t.blendType&&0===t.alphaTest&&!t.alphaToCoverage&&t.opacityDither===nA)return;if("height"!==i&&t[h]&&a&&(e[h]=t[h],e[c]=t[c],e.litOptions.vertexColors=true),t[n]){let a=true;if(0!==t[f]||s||(a=false),1!==t[f]||r||(a=false),a){let s=t[n].id,r=o[s];void 0===r&&(o[s]=i,r=i),e[n]=!!t[n],e[p]=r,e[u]=this._getMapTransformID(t.getUniform(u),t[f]),e[d]=t[d],e[f]=t[f];}}}}_updateMinOptions(e,t,i){let s=1===i;e.litOptions.opacityShadowDither=s?t.opacityDither:t.opacityShadowDither,e.litOptions.linearDepth=s,e.litOptions.lights=[];}_updateMaterialOptions(e,t,i){let s,r,a=!!(t.useMetalness||t.specularMap||t.sphereMap||t.cubeMap||0!==(s=t.specular).r||0!==s.g||0!==s.b||t.specularityFactor>0&&t.useMetalness||t.enableGGXSpecular||t.clearCoat>0),n=!t.useMetalness||t.useMetalnessSpecularColor,o=a&&(t.specularTint||!t.specularMap&&!t.specularVertexColor)&&(1!==(r=t.specular).r||1!==r.g||1!==r.b),l=a&&t.useMetalnessSpecularColor&&(t.specularityFactorTint||t.specularityFactor<1&&!t.specularityFactorMap),h=e=>!!e&&(10===e.format||e.type===tL),c=(e,t)=>1e-4>Math.abs(e-t);e.specularTint=o,e.specularityFactorTint=l,e.metalnessTint=t.useMetalness&&t.metalness<1,e.glossTint=true,e.diffuseEncoding=t.diffuseMap?.encoding,e.diffuseDetailEncoding=t.diffuseDetailMap?.encoding,e.emissiveEncoding=t.emissiveMap?.encoding,e.lightMapEncoding=t.lightMap?.encoding,e.packedNormal=h(t.normalMap),e.refractionTint=!c(t.refraction,1),e.refractionIndexTint=!c(t.refractionIndex,1/1.5),e.thicknessTint=t.useDynamicRefraction&&1!==t.thickness,e.specularEncoding=t.specularMap?.encoding,e.sheenEncoding=t.sheenMap?.encoding,e.aoMapUv=t.aoUvSet,e.aoDetail=!!t.aoDetailMap,e.diffuseDetail=!!t.diffuseDetailMap,e.normalDetail=!!t.normalMap,e.normalDetailPackedNormal=h(t.normalDetailMap),e.diffuseDetailMode=t.diffuseDetailMode,e.aoDetailMode=t.aoDetailMode,e.clearCoatGloss=!!t.clearCoatGloss,e.clearCoatPackedNormal=h(t.clearCoatNormalMap),e.iorTint=!c(t.refractionIndex,1/1.5),i.forcePassThroughSpecular&&(e.specularEncoding="linear",e.sheenEncoding="linear"),e.iridescenceTint=1!==t.iridescence,e.glossInvert=t.glossInvert,e.sheenGlossInvert=t.sheenGlossInvert,e.clearCoatGlossInvert=t.clearCoatGlossInvert,e.useSpecularColor=n,e.litOptions.separateAmbient=false,e.litOptions.pixelSnap=t.pixelSnap,e.litOptions.ambientSH=!!t.ambientSH,e.litOptions.twoSidedLighting=t.twoSidedLighting,e.litOptions.occludeSpecular=t.occludeSpecular,e.litOptions.occludeSpecularFloat=1!==t.occludeSpecularIntensity,e.litOptions.useMsdf=!!t.msdfMap,e.litOptions.msdfTextAttribute=!!t.msdfTextAttribute,e.litOptions.alphaToCoverage=t.alphaToCoverage,e.litOptions.opacityFadesSpecular=t.opacityFadesSpecular,e.litOptions.opacityDither=t.opacityDither,e.litOptions.cubeMapProjection=t.cubeMapProjection,e.litOptions.occludeDirect=t.occludeDirect,e.litOptions.useSpecular=a,e.litOptions.useSpecularityFactor=(l||!!t.specularityFactorMap)&&t.useMetalnessSpecularColor,e.litOptions.enableGGXSpecular=t.enableGGXSpecular,e.litOptions.useAnisotropy=t.enableGGXSpecular&&(t.anisotropyIntensity>0||!!t.anisotropyMap),e.litOptions.fresnelModel=t.fresnelModel,e.litOptions.useRefraction=(t.refraction||!!t.refractionMap)&&(t.useDynamicRefraction||e.litOptions.reflectionSource!==np),e.litOptions.useClearCoat=!!t.clearCoat,e.litOptions.useSheen=t.useSheen,e.litOptions.useIridescence=t.useIridescence&&0!==t.iridescence,e.litOptions.useMetalness=t.useMetalness,e.litOptions.useDynamicRefraction=t.useDynamicRefraction,e.litOptions.dispersion=t.dispersion>0,e.litOptions.shadowCatcher=t.shadowCatcher,e.litOptions.useVertexColorGamma=t.vertexColorGamma;}_updateEnvOptions(e,t,i,s){e.litOptions.fog=t.useFog?s.fog:ns,e.litOptions.gamma=s.shaderOutputGamma,e.litOptions.toneMap=t.useTonemap?s.toneMapping:6;let r=false;if(t.envAtlas&&t.cubeMap?(e.litOptions.reflectionSource=n_,e.litOptions.reflectionEncoding=t.envAtlas.encoding,e.litOptions.reflectionCubemapEncoding=t.cubeMap.encoding):t.envAtlas?(e.litOptions.reflectionSource=nm,e.litOptions.reflectionEncoding=t.envAtlas.encoding):t.cubeMap?(e.litOptions.reflectionSource=ng,e.litOptions.reflectionEncoding=t.cubeMap.encoding):t.sphereMap?(e.litOptions.reflectionSource=nv,e.litOptions.reflectionEncoding=t.sphereMap.encoding):t.useSkybox&&i.envAtlas&&i.skybox?(e.litOptions.reflectionSource=n_,e.litOptions.reflectionEncoding=i.envAtlas.encoding,e.litOptions.reflectionCubemapEncoding=i.skybox.encoding,r=true):t.useSkybox&&i.envAtlas?(e.litOptions.reflectionSource=nm,e.litOptions.reflectionEncoding=i.envAtlas.encoding,r=true):t.useSkybox&&i.skybox?(e.litOptions.reflectionSource=ng,e.litOptions.reflectionEncoding=i.skybox.encoding,r=true):(e.litOptions.reflectionSource=np,e.litOptions.reflectionEncoding=null),t.ambientSH)e.litOptions.ambientSource=ny,e.litOptions.ambientEncoding=null;else {let s=t.envAtlas||(t.useSkybox&&i.envAtlas?i.envAtlas:null);s&&!t.sphereMap?(e.litOptions.ambientSource=nx,e.litOptions.ambientEncoding=s.encoding):(e.litOptions.ambientSource=nT,e.litOptions.ambientEncoding=null);}e.litOptions.skyboxIntensity=r,e.litOptions.useCubeMapRotation=r&&i._skyboxRotationShaderInclude;}_updateLightOptions(e,t,i,s,r){if(e.lightMap=false,e.lightMapChannel="",e.lightMapUv=0,e.lightMapTransform=0,e.litOptions.lightMapWithoutAmbient=false,e.dirLightMap=false,s&&(e.litOptions.noShadow=(1&s)!=0,(64&s)!=0&&(e.lightMapEncoding=7===t.lightmapPixelFormat?"rgbm":"linear",e.lightMap=true,e.lightMapChannel="rgb",e.lightMapUv=1,e.lightMapTransform=0,e.litOptions.lightMapWithoutAmbient=!i.lightMap,(128&s)!=0&&(e.dirLightMap=true),(4096&s)!=0&&(e.litOptions.lightMapWithoutAmbient=false))),i.useLighting){let i=[],a=s?s>>16:1;e.litOptions.lightMaskDynamic=!!(1&a),r&&(dJ.collectLights(0,r[0],i,a),t.clusteredLightingEnabled||(dJ.collectLights(1,r[1],i,a),dJ.collectLights(2,r[2],i,a))),e.litOptions.lights=i;}else e.litOptions.lights=[];0!==e.litOptions.lights.length||t.clusteredLightingEnabled||(e.litOptions.noShadow=true);}_getMapTransformID(e,t){if(!e)return 0;let i=this._mapXForms[t];i||(i=[],this._mapXForms[t]=i);for(let t=0;t{this[`_${e}`]=uo[e].value();}),this._uniformCache={};}copy(e){return super.copy(e),Object.keys(uo).forEach(t=>{this[t]=e[t];}),this.userAttributes=new Map(e.userAttributes),this}setAttribute(e,t){this.userAttributes.set(t,e);}_setParameter(e,t){uh.add(e),this.setParameter(e,t);}_setParameters(e){e.forEach(e=>{this._setParameter(e.name,e.value);});}_processParameters(e){let t=this[e];t.forEach(e=>{uh.has(e)||delete this.parameters[e];}),this[e]=uh,(uh=t).clear();}_updateMap(e){let t=`${e}Map`,i=this[t];if(i){this._setParameter(`texture_${t}`,i);let e=`${t}Transform`,s=this.getUniform(e);s&&this._setParameters(s);}}_allocUniform(e,t){let i=this._uniformCache[e];return i||(i=t(),this._uniformCache[e]=i),i}getUniform(e,t,i){return ul[e](this,t,i)}updateUniforms(e,t){let i=i=>this.getUniform(i,e,t);for(let e in this._setParameter("material_ambient",i("ambient")),this._setParameter("material_diffuse",i("diffuse")),this._setParameter("material_aoIntensity",this.aoIntensity),this.useMetalness?((!this.metalnessMap||this.metalness<1)&&this._setParameter("material_metalness",this.metalness),(!this.specularMap||this.specularTint)&&this._setParameter("material_specular",i("specular")),(!this.specularityFactorMap||this.specularityFactorTint)&&this._setParameter("material_specularityFactor",this.specularityFactor),this._setParameter("material_sheen",i("sheen")),this._setParameter("material_sheenGloss",this.sheenGloss),this._setParameter("material_refractionIndex",this.refractionIndex)):(!this.specularMap||this.specularTint)&&this._setParameter("material_specular",i("specular")),this.enableGGXSpecular&&(this._setParameter("material_anisotropyIntensity",this.anisotropyIntensity),this._setParameter("material_anisotropyRotation",[Math.cos(this.anisotropyRotation*ei.DEG_TO_RAD),Math.sin(this.anisotropyRotation*ei.DEG_TO_RAD)])),this.clearCoat>0&&(this._setParameter("material_clearCoat",this.clearCoat),this._setParameter("material_clearCoatGloss",this.clearCoatGloss),this._setParameter("material_clearCoatBumpiness",this.clearCoatBumpiness)),this._setParameter("material_gloss",this.gloss),this._setParameter("material_emissive",i("emissive")),this._setParameter("material_emissiveIntensity",this.emissiveIntensity),this.refraction>0&&this._setParameter("material_refraction",this.refraction),this.dispersion>0&&this._setParameter("material_dispersion",this.dispersion),this.useDynamicRefraction&&(this._setParameter("material_thickness",this.thickness),this._setParameter("material_attenuation",i("attenuation")),this._setParameter("material_invAttenuationDistance",0===this.attenuationDistance?0:1/this.attenuationDistance)),this.useIridescence&&(this._setParameter("material_iridescence",this.iridescence),this._setParameter("material_iridescenceRefractionIndex",this.iridescenceRefractionIndex),this._setParameter("material_iridescenceThicknessMin",this.iridescenceThicknessMin),this._setParameter("material_iridescenceThicknessMax",this.iridescenceThicknessMax)),this._setParameter("material_opacity",this.opacity),false===this.opacityFadesSpecular&&this._setParameter("material_alphaFade",this.alphaFade),this.occludeSpecular&&this._setParameter("material_occludeSpecularIntensity",this.occludeSpecularIntensity),1===this.cubeMapProjection&&this._setParameter(i("cubeMapProjectionBox")),d8)this._updateMap(e);this.ambientSH&&this._setParameter("ambientSH[0]",this.ambientSH),this.normalMap&&this._setParameter("material_bumpiness",this.bumpiness),this.normalMap&&this.normalDetailMap&&this._setParameter("material_normalDetailMapBumpiness",this.normalDetailMapBumpiness),this.heightMap&&this._setParameter("material_heightMapFactor",i("heightMapFactor")),this.envAtlas&&this.cubeMap?(this._setParameter("texture_envAtlas",this.envAtlas),this._setParameter("texture_cubeMap",this.cubeMap)):this.envAtlas?this._setParameter("texture_envAtlas",this.envAtlas):this.cubeMap?this._setParameter("texture_cubeMap",this.cubeMap):this.sphereMap&&this._setParameter("texture_sphereMap",this.sphereMap),this._setParameter("material_reflectivity",this.reflectivity),this._processParameters("_activeParams"),super.updateUniforms(e,t);}updateEnvUniforms(e,t){!(this.envAtlas||this.cubeMap||this.sphereMap)&&this.useSkybox&&(t.envAtlas&&t.skybox?(this._setParameter("texture_envAtlas",t.envAtlas),this._setParameter("texture_cubeMap",t.skybox)):t.envAtlas?this._setParameter("texture_envAtlas",t.envAtlas):t.skybox&&this._setParameter("texture_cubeMap",t.skybox)),this._processParameters("_activeLightingParams");}getShaderVariant(e){let{device:t,scene:i,pass:s,objDefs:r,sortedLights:a,cameraShaderParams:n}=e;this.updateEnvUniforms(t,i);let o=nq.get(t).getByIndex(s),l=3===s||1===s||o.isShadow,h=l?d7.optionsContextMin:d7.optionsContext;h.defines=nJ.getCoreDefines(this,e),l?this.shaderOptBuilder.updateMinRef(h,i,this,r,s,a):this.shaderOptBuilder.updateRef(h,i,n,this,r,s,a),this.useFog||h.defines.set("FOG","NONE"),h.defines.set("TONEMAP",nu[h.litOptions.toneMap]),this.onUpdateShader&&(h=this.onUpdateShader(h));let c=new nV(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),d=nH(t);d.register("standard",d7);let u=d.getProgram("standard",h,c,this.userId);return this._dirtyShader=false,u}destroy(){for(let e in this._assetReferences)this._assetReferences[e]._unbind();this._assetReferences=null,super.destroy();}constructor(){super(),this.userAttributes=new Map,this._assetReferences={},this._activeParams=new Set,this._activeLightingParams=new Set,this.shaderOptBuilder=new ut,this.reset();}}ud.TEXTURE_PARAMETERS=ur,ud.CUBEMAP_PARAMETERS=ua;let uu=(e,t)=>{ul[e]=t;},uf=(e,t,i,s)=>{Object.defineProperty(ud.prototype,e,{get:s||function(){return this[`_${e}`]},set:i}),uo[e]={value:t};},up=e=>{let t,i,s,r;return e.defaultValue&&e.defaultValue.clone?(t=`_${e.name}`,i=e.dirtyShaderFunc||(()=>true),void uf(e.name,()=>e.defaultValue.clone(),function(e){let s=this[t];s.equals(e)||(this._dirtyShader=this._dirtyShader||i(s,e),this[t]=s.copy(e));},e.getterFunc)):(s=`_${e.name}`,r=e.dirtyShaderFunc||(()=>true),void uf(e.name,()=>e.defaultValue,function(e){let t=this[s];t!==e&&(this._dirtyShader=this._dirtyShader||r(t,e),this[s]=e);},e.getterFunc))};function um(e,t="rgb",i=true,s=0){d8[e]=t.length||-1,up({name:`${e}Map`,defaultValue:null,dirtyShaderFunc:(e,t)=>!!e!=!!t||e&&(e.type!==t.type||e.format!==t.format)}),up({name:`${e}MapTiling`,defaultValue:new ef(1,1)}),up({name:`${e}MapOffset`,defaultValue:new ef(0,0)}),up({name:`${e}MapRotation`,defaultValue:0}),up({name:`${e}MapUv`,defaultValue:s}),t&&(up({name:`${e}MapChannel`,defaultValue:t}),i&&(up({name:`${e}VertexColor`,defaultValue:false}),up({name:`${e}VertexColorChannel`,defaultValue:t})));let r=`${e}MapTiling`,a=`${e}MapOffset`,n=`${e}MapRotation`,o=`${e}MapTransform`;uu(o,(e,t,i)=>{let s=e[r],l=e[a],h=e[n];if(1===s.x&&1===s.y&&0===l.x&&0===l.y&&0===h)return null;let c=e._allocUniform(o,()=>[{name:`texture_${o}0`,value:new Float32Array(3)},{name:`texture_${o}1`,value:new Float32Array(3)}]),d=Math.cos(h*ei.DEG_TO_RAD),u=Math.sin(h*ei.DEG_TO_RAD),f=c[0].value;f[0]=d*s.x,f[1]=-u*s.y,f[2]=l.x;let p=c[1].value;return p[0]=u*s.x,p[1]=d*s.y,p[2]=1-s.y-l.y,c});}function u_(e,t){up({name:e,defaultValue:t,getterFunc:function(){return this._dirtyShader=true,this[`_${e}`]}}),uu(e,(t,i,s)=>{let r=t._allocUniform(e,()=>new Float32Array(3)),a=t[e];return uc.linear(a),r[0]=uc.r,r[1]=uc.g,r[2]=uc.b,r});}function ug(e,t,i){up({name:e,defaultValue:t,dirtyShaderFunc:(e,t)=>(0===e||1===e)!=(0===t||1===t)}),uu(e,i);}function uv(e,t){up({name:e,defaultValue:null,dirtyShaderFunc:(e,t)=>!!e==!!t}),uu(e,t);}function uS(e,t){up({name:e,defaultValue:t});}u_("ambient",new es(1,1,1)),u_("diffuse",new es(1,1,1)),u_("specular",new es(0,0,0)),u_("emissive",new es(0,0,0)),u_("sheen",new es(1,1,1)),u_("attenuation",new es(1,1,1)),ug("emissiveIntensity",1),ug("specularityFactor",1),ug("sheenGloss",0),ug("gloss",.25),ug("aoIntensity",1),ug("heightMapFactor",1,(e,t,i)=>.025*e.heightMapFactor),ug("opacity",1),ug("alphaFade",1),ug("alphaTest",0),ug("bumpiness",1),ug("normalDetailMapBumpiness",1),ug("reflectivity",1),ug("occludeSpecularIntensity",1),ug("refraction",0),ug("refractionIndex",1/1.5,(e,t,i)=>Math.max(.001,e.refractionIndex)),ug("dispersion",0),ug("thickness",0),ug("attenuationDistance",0),ug("metalness",1),ug("anisotropyIntensity",0),ug("anisotropyRotation",0),ug("clearCoat",0),ug("clearCoatGloss",1),ug("clearCoatBumpiness",1),ug("aoUvSet",0,null),ug("iridescence",0),ug("iridescenceRefractionIndex",1/1.5),ug("iridescenceThicknessMin",0),ug("iridescenceThicknessMax",0),uv("ambientSH"),uv("cubeMapProjectionBox",(e,t,i)=>{let s=e._allocUniform("cubeMapProjectionBox",()=>[{name:"envBoxMin",value:new Float32Array(3)},{name:"envBoxMax",value:new Float32Array(3)}]),r=e.cubeMapProjectionBox.getMin(),a=s[0].value;a[0]=r.x,a[1]=r.y,a[2]=r.z;let n=e.cubeMapProjectionBox.getMax(),o=s[1].value;return o[0]=n.x,o[1]=n.y,o[2]=n.z,s}),uS("specularTint",false),uS("specularityFactorTint",false),uS("useMetalness",false),uS("useMetalnessSpecularColor",false),uS("useSheen",false),uS("enableGGXSpecular",false),uS("occludeDirect",false),uS("opacityFadesSpecular",true),uS("occludeSpecular",1),uS("fresnelModel",2),uS("useDynamicRefraction",false),uS("cubeMapProjection",0),uS("useFog",true),uS("useLighting",true),uS("useTonemap",true),uS("useSkybox",true),uS("forceUv1",false),uS("pixelSnap",false),uS("twoSidedLighting",false),uS("nineSlicedMode",void 0),uS("msdfTextAttribute",false),uS("useIridescence",false),uS("glossInvert",false),uS("sheenGlossInvert",false),uS("clearCoatGlossInvert",false),uS("opacityDither",nA),uS("opacityShadowDither",nA),uS("shadowCatcher",false),uS("vertexColorGamma",false),um("diffuse"),um("specular"),um("emissive"),um("thickness","g"),um("specularityFactor","g"),um("normal",""),um("metalness","g"),um("gloss","g"),um("opacity","a"),um("refraction","g"),um("height","g",false),um("ao","g"),um("light","rgb",true,1),um("msdf",""),um("diffuseDetail","rgb",false),um("normalDetail",""),um("aoDetail","g",false),um("clearCoat","g"),um("clearCoatGloss","g"),um("clearCoatNormal",""),um("sheen","rgb"),um("sheenGloss","g"),um("iridescence","g"),um("iridescenceThickness","g"),um("anisotropy",""),uS("diffuseDetailMode","mul"),uS("aoDetailMode","mul"),uv("cubeMap"),uv("sphereMap"),uv("envAtlas"),x=[null,null,null,null,null,null],uf("prefilteredCubemaps",()=>x.slice(),function(e){let t=this._prefilteredCubemaps;e=e||[];let i=false,s=true;for(let r=0;r<6;++r){let a=e[r]||null;t[r]!==a&&(t[r]=a,i=true),s=s&&!!t[r];}i&&(s?this.envAtlas=dT.generatePrefilteredAtlas(t,{target:this.envAtlas}):this.envAtlas&&(this.envAtlas.destroy(),this.envAtlas=null),this._dirtyShader=true);},function(){return this._prefilteredCubemaps});class uy extends c4{constructor(e,t,i,s,r,a){let n;super();let o=new ed,l=new ed,h=new ed,c=new ed,d=new ed,u=new ed,f=[],p=[],m=[],_=[],g=[];if(i>0)for(let a=0;a<=s;a++)for(let n=0;n<=r;n++){let v=n/r*2*Math.PI-Math.PI,S=Math.sin(v),y=Math.cos(v);d.set(S*e,-i/2,y*e),c.set(S*t,i/2,y*t),o.lerp(d,c,a/s),l.sub2(c,d).normalize(),u.set(y,0,-S),h.cross(u,l).normalize(),f.push(o.x,o.y,o.z),p.push(h.x,h.y,h.z);let x=n/r,T=a/s;m.push(x,1-T);let E=T;if(T=x,x=.75*(x=E)+.125,T=.75*T+.125,x/=3,_.push(x,1-T),a0)for(let t=0;t1&&g.push(n,n+t,n+t-1);}if(n+=r,t>0)for(let e=0;e1&&g.push(n,n+e-1,n+e);}}this.positions=f,this.normals=p,this.uvs=m,this.uvs1=_,this.indices=g;}}class ux extends uy{constructor(e={}){let t=e.radius??.3;super(t,t,(e.height??1)-2*t,e.heightSegments??1,e.sides??20,true),e.calculateTangents&&(this.tangents=c3(this.positions,this.normals,this.uvs,this.indices));}}class uT extends uy{constructor(e={}){super(e.baseRadius??.5,e.peakRadius??0,e.height??1,e.heightSegments??5,e.capSegments??18,false),e.calculateTangents&&(this.tangents=c3(this.positions,this.normals,this.uvs,this.indices));}}class uE extends uy{constructor(e={}){let t=e.radius??.5;super(t,t,e.height??1,e.heightSegments??5,e.capSegments??20,false),e.calculateTangents&&(this.tangents=c3(this.positions,this.normals,this.uvs,this.indices));}}class uw extends c4{constructor(e={}){super();let t=e.halfExtents??new ef(.5,.5),i=e.widthSegments??5,s=e.lengthSegments??5,r=[],a=[],n=[],o=[],l=0;for(let e=0;e<=i;e++)for(let h=0;h<=s;h++){let c=-t.x+2*t.x*e/i,d=-(-t.y+2*t.y*h/s),u=e/i,f=h/s;r.push(c,0,d),a.push(0,1,0),n.push(u,1-f),e{let t=e.clone?e.clone():e;return t.key=e.key,t})),this.storeNewProgram(t,s),s.litOptions?.lights&&(s.litOptions.lights=a),this._precached;let n=this._device;(r=e.createShaderDefinition(n,s)).name=r.name??(s.pass?`${t}-pass:${s.pass}`:t),this.definitionsCache.set(i,r);}return r}getCachedShader(e){return this.processedCache.get(e)}setCachedShader(e,t){this.processedCache.set(e,t);}getProgram(e,t,i,s){let r=this._generators.get(e);if(!r)return null;let a=iL(r.generateKey(t)),n=iL(i.generateKey(this._device)),o=`${a}#${n}`,l=this.getCachedShader(o);if(!l){let n,h=this.generateShaderDefinition(r,e,a,t),c="";void 0!==t.pass&&(n=nq.get(this._device).getByIndex(t.pass),c=`-${n.name}`),this._device.fire("shader:generate",{userMaterialId:s,shaderPassInfo:n,definition:h});let d={name:`${h.name}${c}-proc`,attributes:h.attributes,vshader:h.vshader,vincludes:h.vincludes,fincludes:h.fincludes,fshader:h.fshader,processingOptions:i,shaderLanguage:h.shaderLanguage,meshUniformBufferFormat:h.meshUniformBufferFormat,meshBindGroupFormat:h.meshBindGroupFormat};l=new r_(this._device,d),this.setCachedShader(o,l);}return l}storeNewProgram(e,t){let i={};if("standard"===e){let e=this._getDefaultStdMatOptions(t.pass);for(let s in t)(t.hasOwnProperty(s)&&e[s]!==t[s]||"pass"===s)&&(i[s]=t[s]);for(let e in t.litOptions)i[e]=t.litOptions[e];}else i=t;this._programsCollection.push(JSON.stringify({name:e,options:i}));}dumpPrograms(){let e="let device = pc.app ? pc.app.graphicsDevice : pc.Application.getApplication().graphicsDevice;\n";e+="let shaders = [",this._programsCollection[0]&&(e+=` - ${this._programsCollection[0]}`);for(let t=1;tt.usedUvs[l]?"1":"0").join("")}`;return`lit_${e}_${a}_${s}_${i}_${r}`}createShaderDefinition(t,e){let s=!!e.shaderChunkWGSL,i=new Lp(t,e.litOptions,s),r={name:"LitShader",shaderLanguage:i.shaderLanguage,tag:i.shaderPassInfo.isForward?Cg:void 0},a=e.usedUvs||[!0],o=[];i.generateVertexShader(a,a,o),i.generateFragmentShader("",i.shaderLanguage===se?e.shaderChunkWGSL:e.shaderChunkGLSL,"vUv0");let l=Ha.merge(i.chunks,i.includes),h=i.vDefines;e.defines.forEach((u,d)=>h.set(d,u));let f=i.fDefines;return e.defines.forEach((u,d)=>f.set(d,u)),r.attributes=i.attributes,r.vertexCode=i.vshader,r.vertexIncludes=l,r.vertexDefines=h,r.fragmentCode=i.fshader,r.fragmentIncludes=l,r.fragmentDefines=f,ns.createDefinition(t,r)}},r2=new yI;var sm=new Uy,ky=class extends Us{constructor(){super(...arguments);n(this,"usedUvs",[!0]);n(this,"shaderChunkGLSL",null);n(this,"shaderChunkWGSL",null);n(this,"useLighting",!0);n(this,"useFog",!0);n(this,"useTonemap",!0);n(this,"useSkybox",!0);n(this,"ambientSH",null);n(this,"pixelSnap",!1);n(this,"nineSlicedMode",null);n(this,"twoSidedLighting",!1);n(this,"occludeDirect",!1);n(this,"occludeSpecular",Bo);n(this,"occludeSpecularIntensity",1);n(this,"opacityFadesSpecular",!0);n(this,"opacityDither",Bi);n(this,"opacityShadowDither",Bi);n(this,"shadowCatcher",!1);n(this,"ggxSpecular",!1);n(this,"fresnelModel",Sc);n(this,"dynamicRefraction",!1);n(this,"hasAo",!1);n(this,"hasSpecular",!1);n(this,"hasSpecularityFactor",!1);n(this,"hasLighting",!1);n(this,"hasHeights",!1);n(this,"hasNormals",!1);n(this,"hasSheen",!1);n(this,"hasRefraction",!1);n(this,"hasIrridescence",!1);n(this,"hasMetalness",!1);n(this,"hasClearCoat",!1);n(this,"hasClearCoatNormals",!1)}getShaderVariant(e){sm.usedUvs=this.usedUvs.slice(),sm.shaderChunkGLSL=this.shaderChunkGLSL,sm.shaderChunkWGSL=this.shaderChunkWGSL,sm.defines=Se.getCoreDefines(this,e),Lc.update(sm.litOptions,this,e.scene,e.cameraShaderParams,e.objDefs,e.pass,e.sortedLights);let s=new sa(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),i=Ji(e.device);return i.register("lit",r2),i.getProgram("lit",sm,s,this.userId)}};var ja=8/64,qo=1-ja*2,Xc=class extends Jt{constructor(t,e,s,i,r,a){super();let o=new x,l=new x,h=new x,f=new x,u=new x,d=new x,p=[],m=[],_=[],S=[],g=[],T;if(s>0)for(let C=0;C<=i;C++)for(let v=0;v<=r;v++){let E=v/r*2*Math.PI-Math.PI,y=Math.sin(E),P=Math.cos(E);u.set(y*t,-s/2,P*t),f.set(y*e,s/2,P*e),o.lerp(u,f,C/i),l.sub2(f,u).normalize(),d.set(P,0,-y),h.cross(d,l).normalize(),p.push(o.x,o.y,o.z),m.push(h.x,h.y,h.z);let A=v/r,w=C/i;_.push(A,1-w);let I=w;if(w=A,A=I,A=A*qo+ja,w=w*qo+ja,A/=3,S.push(A,1-w),C0)for(let C=0;C1&&g.push(T,T+C,T+C-1)}if(T+=r,e>0)for(let C=0;C1&&g.push(T,T+C-1,T+C)}}this.positions=p,this.normals=m,this.uvs=_,this.uvs1=S,this.indices=g}};var Yc=class extends Xc{constructor(t={}){let e=t.radius??.3,s=t.height??1,i=t.heightSegments??1,r=t.sides??20;super(e,e,s-2*e,i,r,!0),t.calculateTangents&&(this.tangents=Zs(this.positions,this.normals,this.uvs,this.indices))}};var qa=class extends Xc{constructor(t={}){let e=t.baseRadius??.5,s=t.peakRadius??0,i=t.height??1,r=t.heightSegments??5,a=t.capSegments??18;super(e,s,i,r,a,!1),t.calculateTangents&&(this.tangents=Zs(this.positions,this.normals,this.uvs,this.indices))}};var Ci=class extends Xc{constructor(t={}){let e=t.radius??.5,s=t.height??1,i=t.heightSegments??5,r=t.capSegments??20;super(e,e,s,i,r,!1),t.calculateTangents&&(this.tangents=Zs(this.positions,this.normals,this.uvs,this.indices))}};var $a=class extends Jt{constructor(t={}){super();let e=t.halfExtents??new B(.5,.5),s=t.widthSegments??5,i=t.lengthSegments??5,r=[],a=[],o=[],l=[],h=0;for(let f=0;f<=s;f++)for(let u=0;u<=i;u++){let d=-e.x+2*e.x*f/s,p=0,m=-(-e.y+2*e.y*u/i),_=f/s,S=u/i;r.push(d,p,m),a.push(0,1,0),o.push(_,1-S),f{this.removeFromCache(i)})}destroy(){this.clearCache()}register(t,e){this._generators.has(t)||this._generators.set(t,e)}unregister(t){this._generators.has(t)&&this._generators.delete(t)}isRegistered(t){return this._generators.has(t)}generateShaderDefinition(t,e,s,i){let r=this.definitionsCache.get(s);if(!r){let a;i.litOptions?.lights&&(a=i.litOptions.lights,i.litOptions.lights=a.map(l=>{let h=l.clone?l.clone():l;return h.key=l.key,h})),this.storeNewProgram(e,i),i.litOptions?.lights&&(i.litOptions.lights=a),this._precached;let o=this._device;r=t.createShaderDefinition(o,i),r.name=r.name??(i.pass?`${e}-pass:${i.pass}`:e),this.definitionsCache.set(s,r)}return r}getCachedShader(t){return this.processedCache.get(t)}setCachedShader(t,e){this.processedCache.set(t,e)}getProgram(t,e,s,i){let r=this._generators.get(t);if(!r)return null;let a=r.generateKey(e),o=xt(a),l=s.generateKey(this._device),h=xt(l),f=`${o}#${h}`,u=this.getCachedShader(f);if(!u){let d=this.generateShaderDefinition(r,t,o,e),p="",m;e.pass!==void 0&&(m=Ns.get(this._device).getByIndex(e.pass),p=`-${m.name}`),this._device.fire("shader:generate",{userMaterialId:i,shaderPassInfo:m,definition:d});let _={name:`${d.name}${p}-proc`,attributes:d.attributes,vshader:d.vshader,vincludes:d.vincludes,fincludes:d.fincludes,fshader:d.fshader,processingOptions:s,shaderLanguage:d.shaderLanguage,meshUniformBufferFormat:d.meshUniformBufferFormat,meshBindGroupFormat:d.meshBindGroupFormat};u=new Be(this._device,_),this.setCachedShader(f,u)}return u}storeNewProgram(t,e){let s={};if(t==="standard"){let i=this._getDefaultStdMatOptions(e.pass);for(let r in e)(e.hasOwnProperty(r)&&i[r]!==e[r]||r==="pass")&&(s[r]=e[r]);for(let r in e.litOptions)s[r]=e.litOptions[r]}else s=e;this._programsCollection.push(JSON.stringify({name:t,options:s}))}dumpPrograms(){let t=`let device = pc.app ? pc.app.graphicsDevice : pc.Application.getApplication().graphicsDevice; +`;t+="let shaders = [",this._programsCollection[0]&&(t+=` + ${this._programsCollection[0]}`);for(let s=1;s{e.destroy();}),this.processedCache.clear(),this._isClearingCache=false;}removeFromCache(e){this._isClearingCache||this.processedCache.forEach((t,i)=>{e===t&&this.processedCache.delete(i);});}_getDefaultStdMatOptions(e){let t=nq.get(this._device).getByIndex(e);return 3===e||1===e||t.isShadow?this._defaultStdMatOptionMin:this._defaultStdMatOption}precompile(e){if(e){let t=Array(e.length);for(let i=0;i{this.removeFromCache(e);});}}class uA{destroy(){this._deviceLostEvent?.off(),this._deviceLostEvent=null,this.impl?.destroy(),this.impl=null;}upload(e,t,i=0,s=e.length){this.impl?.upload(e,t,i,s);}_onDeviceLost(){this.impl?._onDeviceLost?.();}constructor(e,t=false){this._deviceLostEvent=null,this.device=e,this.useSingleBuffer=t,this.impl=e.createUploadStreamImpl(this),this._deviceLostEvent=this.device.on("devicelost",this._onDeviceLost,this);}}var uP=` +`,t+=`pc.getProgramLibrary(device).precompile(shaders); +`,t+=`if (pc.version != "${Ju}" || pc.revision != "${Rx}") +`,t+=' console.warn("precompile-shaders.js: engine version mismatch, rebuild shaders lib with current engine");';let e=document.createElement("a");e.setAttribute("href",`data:text/plain;charset=utf-8,${encodeURIComponent(t)}`),e.setAttribute("download","precompile-shaders.js"),e.style.display="none",document.body.appendChild(e),e.click(),document.body.removeChild(e)}clearCache(){this._isClearingCache=!0,this.processedCache.forEach(t=>{t.destroy()}),this.processedCache.clear(),this._isClearingCache=!1}removeFromCache(t){this._isClearingCache||this.processedCache.forEach((e,s)=>{t===e&&this.processedCache.delete(s)})}_getDefaultStdMatOptions(t){let e=Ns.get(this._device).getByIndex(t);return t===ta||t===xr||e.isShadow?this._defaultStdMatOptionMin:this._defaultStdMatOption}precompile(t){if(t){let e=new Array(t.length);for(let s=0;s FragmentOutput { #endif return processOutput; } -`,uD=` +`;var n2=` attribute vec2 vertex_position; precision highp usampler2D; uniform usampler2D uSubDrawData; @@ -1683,7 +2107,7 @@ void main(void) { gl_Position = vec4(mix(ndc.x, ndc.y, u), mix(ndc.z, ndc.w, v), 0.5, 1.0); vSubDraw = ivec4(sourceBase, colStart, colEnd - colStart, rowStart); } -`,uR=` +`;var l2=` attribute vertex_position: vec2f; var uSubDrawData: texture_2d; uniform uTextureSize: vec2i; @@ -1707,13 +2131,13 @@ fn vertexMain(input: VertexInput) -> VertexOutput { output.vSubDraw = vec4i(sourceBase, colStart, colEnd - colStart, rowStart); return output; } -`;let uL=new ey,uM=new eL;class uO{destroy(){this.boundsBuffer?.destroy(),this.transformsBuffer?.destroy();}updateBoundsData(e){let t=0;for(let i=0;ithis._allocatedBoundsEntries){this.boundsBuffer?.destroy(),this._allocatedBoundsEntries=t,this.boundsBuffer=new rO(this.device,8*t*4,8);let e=new ArrayBuffer(8*t*4);this._boundsFloatView=new Float32Array(e),this._boundsUintView=new Uint32Array(e),this._tmpSpheres=new Float32Array(4*t);}let i=this._boundsFloatView,s=this._boundsUintView,r=this._tmpSpheres;for(let t=0;tthis._allocatedTransformCount&&(this.transformsBuffer?.destroy(),this._allocatedTransformCount=t,this.transformsBuffer=new rO(this.device,12*t*4,8),this._transformsData=new Float32Array(12*t));let i=this._transformsData,s=0;for(let t=0;t0&&(this.splats.push(n),this._partialData.push(e,h));}}this._subDrawTexture.unlock();}else for(let t=0;t0&&(this.splats.push(i),this._partialData.push(0,0));}for(let e=0;e0}execute(){let{device:e,splats:t,cameraNode:i,_partialData:s}=this;e.setDrawStates();let r=i.getWorldTransform(),a=uF.copy(r).invert();e.scope.resolve("matrix_view").setValue(a.data);for(let e=0;e0?this.renderSplat(t[e],this._subDrawTexture,i,s[2*e]):this.renderSplat(t[e]);}}renderSplat(e,t,i,s=0){let{device:r,resource:a}=e,n=r.scope,o=t??e.subDrawTexture,l=i??e.subDrawCount,h=e.getWorkBufferModifier?.()??null,c=a.format.hash,d=a.format.getInputDeclarations(),u=a.getWorkBufferRenderInfo(this.colorOnly,h,c,d,this.workBuffer.format);u.material.setParameters(r);let f=this.colorsByLod?.[e.lodIndex]??this.colorsByLod?.[0]??uU;n.resolve("uColorMultiply").setValue(f);let p=e.node.getWorldTransform();if(p.getScale(uN),uB.setFromMat4(p),uB.w<0&&uB.mulScalar(-1),this._modelScaleData[0]=uN.x,this._modelScaleData[1]=uN.y,this._modelScaleData[2]=uN.z,this._modelRotationData[0]=uB.x,this._modelRotationData[1]=uB.y,this._modelRotationData[2]=uB.z,this._modelRotationData[3]=uB.w,n.resolve("matrix_model").setValue(p.data),n.resolve("model_scale").setValue(this._modelScaleData),n.resolve("model_rotation").setValue(this._modelRotationData),n.resolve("uId").setValue(e.placementId),e.parameters)for(let t of e.parameters.values())t.scopeId.setValue(t.data);let m=e.getInstanceStreams?.();if(m)for(let[t,i]of(m.syncWithFormat(e.resource.format),m.textures))n.resolve(t).setValue(i);n.resolve("uSubDrawData").setValue(o),n.resolve("uSubDrawBase").setValue(s);let _=this.workBuffer.textureSize;this._textureSize[0]=_,this._textureSize[1]=_,n.resolve("uTextureSize").setValue(this._textureSize),u.quadRender.render(void 0,void 0,l);}constructor(e,t,i=false){super(e),this.splats=[],this.colorsByLod=void 0,this.cameraNode=null,this._modelScaleData=new Float32Array(3),this._modelRotationData=new Float32Array(4),this._textureSize=new Int32Array(2),this._partialData=[],this.workBuffer=t,this.colorOnly=i,this._subDrawTexture=ic.createDataTexture2D(e,"GsplatSubDrawData",1,1,49);}}class uV{get textureDimensions(){return this._textureDimensions}destroy(){for(let e of this.textures.values())e.destroy();this.textures.clear();}init(e,t){for(let i of(this.format=e,this._textureDimensions=ir.calcTextureSize(t,new ef),this._isInstance?e.instanceStreams:e.resourceStreams)){let e=this.createTexture(i.name,i.format,this._textureDimensions);this.textures.set(i.name,e);}this._formatVersion=e.extraStreamsVersion;}getTexture(e){return this.syncWithFormat(this.format),this.textures.get(e)}getTexturesInOrder(){let e=[];if(this.format)for(let t of this._isInstance?this.format.instanceStreams:this.format.resourceStreams){let i=this.textures.get(t.name);i&&e.push(i);}return e}syncWithFormat(e){if(e&&(this.format!==e||this._formatVersion!==e.extraStreamsVersion)){for(let t of(this.format=e,this._isInstance?e.instanceStreams:e.resourceStreams))if(!this.textures.has(t.name)){let e=this.createTexture(t.name,t.format,this._textureDimensions);this.textures.set(t.name,e);}this._formatVersion=e.extraStreamsVersion;}}resize(e,t){for(let i of(this._textureDimensions.set(e,t),this.textures.values()))i.resize(e,t);}createTexture(e,t,i,s){return ic.createDataTexture2D(this.device,e,i.x,i.y,t,s?[s]:void 0)}constructor(e,t=false){this.format=null,this.textures=new Map,this._textureDimensions=new ef,this._isInstance=false,this._formatVersion=-1,this.device=e,this._isInstance=t;}}let uG=0;class uH{destroy(){this.material?.destroy(),this.quadRender?.destroy();}constructor(e,t,i,s,r){this.material=i;let a=new Map(i.defines),n=r.getStream("dataColor");47===n.format&&a.set("GSPLAT_COLOR_UINT",""),s&&a.set("GSPLAT_COLOR_ONLY",""),r.getStream("pcId")&&a.set("GSPLAT_ID","");let o=i.hasShaderChunks?e.isWebGPU?i.shaderChunks.wgsl:i.shaderChunks.glsl:void 0,l=s?[n]:[...r.streams,...r.extraStreams],h=[];for(let e of l){let t=e1(e.format);h.push(t.returnType);}let c=a.has("GSPLAT_LOD"),d={uniqueName:`SplatCopyToWorkBuffer:${t}`,attributes:{vertex_position:e8},vertexDefines:a,fragmentDefines:a,fragmentGLSL:uP,fragmentWGSL:uI,fragmentIncludes:o,fragmentOutputTypes:h};c?(d.vertexGLSL=uD,d.vertexWGSL=uR):d.vertexChunk="fullscreenQuadVS";let u=nJ.createShader(e,d);this.quadRender=new n4(u);}}class uW{_createRenderTargets(){this.renderTarget?.destroy(),this.colorRenderTarget?.destroy();let e=this.streams.getTexturesInOrder();this.renderTarget=new iG({name:`GsplatWorkBuffer-MRT-${this.id}`,colorBuffers:e,depth:false,flipY:true});let t=this.streams.getTexture("dataColor");this.colorRenderTarget=new iG({name:`GsplatWorkBuffer-Color-${this.id}`,colorBuffer:t,depth:false,flipY:true}),this.renderPass?.init(this.renderTarget),this.colorRenderPass?.init(this.colorRenderTarget);}syncWithFormat(){let e=this.streams._formatVersion;this.streams.syncWithFormat(this.format),e!==this.streams._formatVersion&&this._createRenderTargets();}getTexture(e){return this.streams.getTexture(e)}destroy(){this.renderPass?.destroy(),this.colorRenderPass?.destroy(),this.streams.destroy(),this.orderTexture?.destroy(),this.orderBuffer?.destroy(),this.renderTarget?.destroy(),this.colorRenderTarget?.destroy(),this.uploadStream.destroy(),this.frustumCuller.destroy();}get textureSize(){return this.streams.textureDimensions.x}setOrderData(e){this.textureSize,this.device.isWebGPU?this.uploadStream.upload(e,this.orderBuffer,0,e.length):this.uploadStream.upload(e,this.orderTexture,0,e.length);}resize(e){if(this.renderTarget.resize(e,e),this.colorRenderTarget.resize(e,e),this.streams.resize(e,e),this.device.isWebGPU){let t=e*e*4;this.orderBuffer.byteSizenew uX)._pendingDestroy.add(t);}static process(e){let t=this._cache.get(e,()=>new uX)._pendingDestroy;for(let e of t)0===e.refCount&&(e._actualDestroy(),t.delete(e));}destroy(){this._pendingDestroy.clear();}constructor(){this._pendingDestroy=new Set;}}uX._cache=new is;let uY=0,uq=new Map;class uj{destroy(){this.refCount>0?uX.queueDestroy(this.device,this):this._actualDestroy();}_actualDestroy(){this.streams.destroy(),this.mesh?.destroy(),this.workBufferRenderInfos.forEach(e=>e.destroy()),this.workBufferRenderInfos.clear();}incRefCount(){this._refCount++;}decRefCount(){this._refCount--;}get refCount(){return this._refCount}ensureMesh(){this.mesh||(this.mesh=uj.createMesh(this.device),this.mesh.aabb.copy(this.aabb)),this._meshRefCount++;}releaseMesh(){this._meshRefCount--,this._meshRefCount<1&&(this.mesh=null);}getWorkBufferRenderInfo(e,t,i,s,r){this.configureMaterialDefines(uq),uq.set("GSPLAT_LOD",""),e&&uq.set("GSPLAT_COLOR_ONLY","");let a="";for(let[e,t]of uq)a&&(a+=";"),a+=`${e}=${t}`;let n=`${i};${r.hash};${t?.hash??0};${a}`,o=this.workBufferRenderInfos.get(n);if(!o){let i=new cT;this.configureMaterial(i,t,s);let a=this.device.isWebGPU?i.shaderChunks.wgsl:i.shaderChunks.glsl,l=e?[r.getStream("dataColor")]:[...r.streams,...r.extraStreams],h=r.getOutputDeclarations(l);e&&r.extraStreams.length>0&&(h+=` -${r.getOutputStubs(r.extraStreams)}`),a.set("gsplatWorkBufferOutputVS",h);let c=r.getWriteCode();c&&a.set("gsplatWriteVS",c),uq.forEach((e,t)=>i.setDefine(t,e)),o=new uH(this.device,n,i,e,r),this.workBufferRenderInfos.set(n,o);}return uq.clear(),o}static createMesh(e){let t=uj.instanceSize,i=new Float32Array(12*t),s=new Uint32Array(6*t);for(let e=0;e0&&e.setParameter("splatTextureSize",this.textureDimensions.x);}configureMaterialDefines(e){}instantiate(){}constructor(e,t){this.centersVersion=0,this.mesh=null,this.id=uY++,this.workBufferRenderInfos=new Map,this._format=null,this.parameters=new Map,this._refCount=0,this._meshRefCount=0,this.device=e,this.gsplatData=t,this.streams=new uV(e),this.centers=t.getCenters(),this.aabb=new eA,t.calcAabb(this.aabb);}}let uK=new ey,u$=new ex,uZ=new eA,uQ=new eA,uJ=new es(1,1,0,.4);class u0{constructor(e,t,i,s,r){let a=e.getProp("x"),n=e.getProp("y"),o=e.getProp("z"),l=e.getProp("rot_1"),h=e.getProp("rot_2"),c=e.getProp("rot_3"),d=e.getProp("rot_0"),u=e.getProp("scale_0"),f=e.getProp("scale_1"),p=e.getProp("scale_2"),m=e.getProp("f_dc_0"),_=e.getProp("f_dc_1"),g=e.getProp("f_dc_2"),v=e.getProp("opacity");this.read=e=>{t&&(t.x=a[e],t.y=n[e],t.z=o[e]),i&&i.set(l[e],h[e],c[e],d[e]),s&&s.set(Math.exp(u[e]),Math.exp(f[e]),Math.exp(p[e])),r&&r.set(.5+.28209479177387814*m[e],.5+.28209479177387814*_[e],.5+.28209479177387814*g[e],(e=>{if(e>0)return 1/(1+Math.exp(-e));let t=Math.exp(e);return t/(1+t)})(v[e]));};}}let u1=(e,t,i)=>{u$.set(i.x,i.y,i.z,i.w).normalize(),e.setTRS(t,u$,ed.ONE);};class u2{static calcSplatAabb(e,t,i,s){u1(uK,t,i),uZ.center.set(0,0,0),uZ.halfExtents.set(2*s.x,2*s.y,2*s.z),e.setFromTransformedAabb(uZ,uK);}getProp(e,t="vertex"){return this.getElement(t)?.properties.find(t=>t.name===e)?.storage}getElement(e){return this.elements.find(t=>t.name===e)}addProp(e,t){this.getElement("vertex").properties.push({type:"float",name:e,storage:t,byteSize:4});}createIter(e,t,i,s){return new u0(this,e,t,i,s)}calcAabb(e,t){let i,s,r,a,n,o,l=true,h=this.getProp("x"),c=this.getProp("y"),d=this.getProp("z"),u=this.getProp("scale_0"),f=this.getProp("scale_1"),p=this.getProp("scale_2");for(let e=0;e{for(let e=0;e<45;++e)if(!this.getProp(`f_rest_${e}`))return e;return 45})()]??0}calcMortonOrder(){let e=e=>{let t=e[0],i=e[0];for(let s=1;si&&(i=e[s]);return {min:t,max:i}},t=(e,t,i)=>{let s=e=>(e&=1023,e=((e=((e=((e=(e^e<<16)&0xff0000ff)^e<<8)&0x300f00f)^e<<4)&0x30c30c3)^e<<2)&0x9249249);return (s(i)<<2)+(s(t)<<1)+s(e)},i=this.getProp("x"),s=this.getProp("y"),r=this.getProp("z"),{min:a,max:n}=e(i),{min:o,max:l}=e(s),{min:h,max:c}=e(r),d=a===n?0:1024/(n-a),u=o===l?0:1024/(l-o),f=h===c?0:1024/(c-h),p=new Map;for(let e=0;ee-t),_=new Uint32Array(this.numSplats),g=0;for(let e=0;e{i.properties.forEach(i=>{i.storage&&(i.storage=(i=>{var s;let r=new i.constructor((e=>{if(t.has(e)){let i=t.get(e);return t.delete(e),i}return new ArrayBuffer(e)})(i.byteLength));for(let t=0;tthis._allocatedBoundsEntries){this.boundsBuffer?.destroy(),this._allocatedBoundsEntries=e,this.boundsBuffer=new Ee(this.device,e*EI*4,8);let a=new ArrayBuffer(e*EI*4);this._boundsFloatView=new Float32Array(a),this._boundsUintView=new Uint32Array(a),this._tmpSpheres=new Float32Array(e*4)}let s=this._boundsFloatView,i=this._boundsUintView,r=this._tmpSpheres;for(let a=0;athis._allocatedTransformCount&&(this.transformsBuffer?.destroy(),this._allocatedTransformCount=e,this.transformsBuffer=new Ee(this.device,e*12*4,8),this._transformsData=new Float32Array(e*12));let s=this._transformsData,i=0;for(let r=0;r0&&(this.splats.push(u),this._partialData.push(m,S))}}this._subDrawTexture.unlock()}else for(let o=0;o0&&(this.splats.push(l),this._partialData.push(0,0))}for(let o=0;o0}execute(){let{device:e,splats:s,cameraNode:i,_partialData:r}=this;e.setDrawStates();let a=i.getWorldTransform(),o=G6.copy(a).invert();e.scope.resolve("matrix_view").setValue(o.data);for(let l=0;l0?this.renderSplat(s[l],this._subDrawTexture,h,r[l*2]):this.renderSplat(s[l])}}renderSplat(e,s,i,r=0){let{device:a,resource:o}=e,l=a.scope,h=s??e.subDrawTexture,f=i??e.subDrawCount,u=e.getWorkBufferModifier?.()??null,d=o.format.hash,p=o.format.getInputDeclarations(),m=o.getWorkBufferRenderInfo(this.colorOnly,u,d,p,this.workBuffer.format);m.material.setParameters(a);let _=this.colorsByLod?.[e.lodIndex]??this.colorsByLod?.[0]??V6;l.resolve("uColorMultiply").setValue(_);let S=e.node.getWorldTransform();if(S.getScale(Gy),ru.setFromMat4(S),ru.w<0&&ru.mulScalar(-1),this._modelScaleData[0]=Gy.x,this._modelScaleData[1]=Gy.y,this._modelScaleData[2]=Gy.z,this._modelRotationData[0]=ru.x,this._modelRotationData[1]=ru.y,this._modelRotationData[2]=ru.z,this._modelRotationData[3]=ru.w,l.resolve("matrix_model").setValue(S.data),l.resolve("model_scale").setValue(this._modelScaleData),l.resolve("model_rotation").setValue(this._modelRotationData),l.resolve("uId").setValue(e.placementId),e.parameters)for(let C of e.parameters.values())C.scopeId.setValue(C.data);let g=e.getInstanceStreams?.();if(g){g.syncWithFormat(e.resource.format);for(let[C,v]of g.textures)l.resolve(C).setValue(v)}l.resolve("uSubDrawData").setValue(h),l.resolve("uSubDrawBase").setValue(r);let T=this.workBuffer.textureSize;this._textureSize[0]=T,this._textureSize[1]=T,l.resolve("uTextureSize").setValue(this._textureSize),m.quadRender.render(void 0,void 0,f)}};var dl=class{constructor(t,e=!1){n(this,"device");n(this,"format",null);n(this,"textures",new Map);n(this,"_textureDimensions",new B);n(this,"_isInstance",!1);n(this,"_formatVersion",-1);this.device=t,this._isInstance=e}get textureDimensions(){return this._textureDimensions}destroy(){for(let t of this.textures.values())t.destroy();this.textures.clear()}init(t,e){this.format=t,this._textureDimensions=gt.calcTextureSize(e,new B);let s=this._isInstance?t.instanceStreams:t.resourceStreams;for(let i of s){let r=this.createTexture(i.name,i.format,this._textureDimensions);this.textures.set(i.name,r)}this._formatVersion=t.extraStreamsVersion}getTexture(t){return this.syncWithFormat(this.format),this.textures.get(t)}getTexturesInOrder(){let t=[];if(this.format){let e=this._isInstance?this.format.instanceStreams:this.format.resourceStreams;for(let s of e){let i=this.textures.get(s.name);i&&t.push(i)}}return t}syncWithFormat(t){if(t){if(this.format===t&&this._formatVersion===t.extraStreamsVersion)return;this.format=t;let e=this._isInstance?t.instanceStreams:t.resourceStreams;for(let s of e)if(!this.textures.has(s.name)){let i=this.createTexture(s.name,s.format,this._textureDimensions);this.textures.set(s.name,i)}this._formatVersion=t.extraStreamsVersion}}resize(t,e){this._textureDimensions.set(t,e);for(let s of this.textures.values())s.resize(t,e)}createTexture(t,e,s,i){return Z.createDataTexture2D(this.device,t,s.x,s.y,e,i?[i]:void 0)}};var H6=0,Vy=class{constructor(t,e,s,i,r){n(this,"material");n(this,"quadRender");this.material=s;let a=new Map(s.defines),o=r.getStream("dataColor");o.format===Rs&&a.set("GSPLAT_COLOR_UINT",""),i&&a.set("GSPLAT_COLOR_ONLY",""),r.getStream("pcId")&&a.set("GSPLAT_ID","");let l=s.hasShaderChunks?t.isWebGPU?s.shaderChunks.wgsl:s.shaderChunks.glsl:void 0,h=i?[o]:[...r.streams,...r.extraStreams],f=[];for(let m of h){let _=An(m.format);f.push(_.returnType)}let u=a.has("GSPLAT_LOD"),d={uniqueName:`SplatCopyToWorkBuffer:${e}`,attributes:{vertex_position:ee},vertexDefines:a,fragmentDefines:a,fragmentGLSL:a2,fragmentWGSL:o2,fragmentIncludes:l,fragmentOutputTypes:f};u?(d.vertexGLSL=n2,d.vertexWGSL=l2):d.vertexChunk="fullscreenQuadVS";let p=Se.createShader(t,d);this.quadRender=new hs(p)}destroy(){this.material?.destroy(),this.quadRender?.destroy()}},AS=class{constructor(t,e){n(this,"device");n(this,"format");n(this,"id",H6++);n(this,"streams");n(this,"renderTarget");n(this,"colorRenderTarget");n(this,"orderTexture");n(this,"orderBuffer");n(this,"uploadStream");n(this,"renderPass");n(this,"colorRenderPass");n(this,"frustumCuller");this.device=t,this.format=e,this.frustumCuller=new zy(t),this.streams=new dl(t),this.streams.init(e,1),this._createRenderTargets(),this.uploadStream=new rm(t,!t.isWebGPU),t.isWebGPU?this.orderBuffer=new Ee(t,4,8):this.orderTexture=new Z(t,{name:"SplatGlobalOrder",width:1,height:1,format:zt,mipmaps:!1,addressU:1,addressV:1}),this.renderPass=new ES(t,this),this.renderPass.init(this.renderTarget),this.colorRenderPass=new ES(t,this,!0),this.colorRenderPass.init(this.colorRenderTarget)}_createRenderTargets(){this.renderTarget?.destroy(),this.colorRenderTarget?.destroy();let t=this.streams.getTexturesInOrder();this.renderTarget=new me({name:`GsplatWorkBuffer-MRT-${this.id}`,colorBuffers:t,depth:!1,flipY:!0});let e=this.streams.getTexture("dataColor");this.colorRenderTarget=new me({name:`GsplatWorkBuffer-Color-${this.id}`,colorBuffer:e,depth:!1,flipY:!0}),this.renderPass?.init(this.renderTarget),this.colorRenderPass?.init(this.colorRenderTarget)}syncWithFormat(){let t=this.streams._formatVersion;this.streams.syncWithFormat(this.format),t!==this.streams._formatVersion&&this._createRenderTargets()}getTexture(t){return this.streams.getTexture(t)}destroy(){this.renderPass?.destroy(),this.colorRenderPass?.destroy(),this.streams.destroy(),this.orderTexture?.destroy(),this.orderBuffer?.destroy(),this.renderTarget?.destroy(),this.colorRenderTarget?.destroy(),this.uploadStream.destroy(),this.frustumCuller.destroy()}get textureSize(){return this.streams.textureDimensions.x}setOrderData(t){let e=this.textureSize;this.device.isWebGPU?this.uploadStream.upload(t,this.orderBuffer,0,t.length):this.uploadStream.upload(t,this.orderTexture,0,t.length)}resize(t){if(this.renderTarget.resize(t,t),this.colorRenderTarget.resize(t,t),this.streams.resize(t,t),this.device.isWebGPU){let e=t*t*4;this.orderBuffer.byteSizenew CS)._pendingDestroy.add(e)}static process(t){let e=this._cache.get(t,()=>new CS)._pendingDestroy;for(let s of e)s.refCount===0&&(s._actualDestroy(),e.delete(s))}destroy(){this._pendingDestroy.clear()}};n(CS,"_cache",new et);var am=CS;var W6=0,om=new Map,rt=class c{constructor(t,e,s={}){n(this,"device");n(this,"gsplatData");n(this,"_centers",null);n(this,"centersVersion",0);n(this,"aabb");n(this,"mesh",null);n(this,"id",W6++);n(this,"workBufferRenderInfos",new Map);n(this,"_format",null);n(this,"streams");n(this,"parameters",new Map);n(this,"_refCount",0);n(this,"_meshRefCount",0);this.device=t,this.gsplatData=e,this.streams=new dl(t),s.prepareCenters!==!1?this._centers=e.getCenters():this._centers=null,this.aabb=new ge,e.calcAabb(this.aabb)}set centers(t){this._centers=t}get centers(){return this._centers}get hasCenters(){return this._centers!=null}destroy(){if(this.refCount>0){am.queueDestroy(this.device,this);return}this._actualDestroy()}_actualDestroy(){this.streams.destroy(),this.mesh?.destroy(),this.workBufferRenderInfos.forEach(t=>t.destroy()),this.workBufferRenderInfos.clear()}incRefCount(){this._refCount++}decRefCount(){this._refCount--}get refCount(){return this._refCount}ensureMesh(){this.mesh||(this.mesh=c.createMesh(this.device),this.mesh.aabb.copy(this.aabb)),this._meshRefCount++}releaseMesh(){this._meshRefCount--,this._meshRefCount<1&&(this.mesh=null)}getWorkBufferRenderInfo(t,e,s,i,r){this.configureMaterialDefines(om),om.set("GSPLAT_LOD",""),t&&om.set("GSPLAT_COLOR_ONLY","");let a="";for(let[h,f]of om)a&&(a+=";"),a+=`${h}=${f}`;let o=`${s};${r.hash};${e?.hash??0};${a}`,l=this.workBufferRenderInfos.get(o);if(!l){let h=new ct;this.configureMaterial(h,e,i);let f=this.device.isWebGPU?h.shaderChunks.wgsl:h.shaderChunks.glsl,u=t?[r.getStream("dataColor")]:[...r.streams,...r.extraStreams],d=r.getOutputDeclarations(u);t&&r.extraStreams.length>0&&(d+=` +${r.getOutputStubs(r.extraStreams)}`),f.set("gsplatWorkBufferOutputVS",d);let p=r.getWriteCode();p&&f.set("gsplatWriteVS",p),om.forEach((m,_)=>h.setDefine(_,m)),l=new Vy(this.device,o,h,t,r),this.workBufferRenderInfos.set(o,l)}return om.clear(),l}static createMesh(t){let e=c.instanceSize,s=new Float32Array(12*e),i=new Uint32Array(6*e);for(let a=0;a0&&t.setParameter("splatTextureSize",this.textureDimensions.x)}configureMaterialDefines(t){}instantiate(){}};var Hy=class extends rt{constructor(e,s,i){let r=new ge;super(e,{numSplats:s,getCenters:()=>null,calcAabb:o=>o.copy(r)},{prepareCenters:!1});n(this,"_maxSplats",0);n(this,"_numSplats",0);this._format=i,this._maxSplats=s,this._numSplats=s,this.streams.init(this._format,s)}set centers(e){this._centers=e}get centers(){return this._centers===null&&(this._centers=new Float32Array(this._maxSplats*3),this.centersVersion++),this._centers}get maxSplats(){return this._maxSplats}get numSplats(){return this._numSplats}update(e=this._numSplats,s=!0){this._numSplats=R.clamp(e,0,this._maxSplats),s&&this.centersVersion++}configureMaterialDefines(e){e.set("SH_BANDS","0")}configureMaterial(e,s=null,i){super.configureMaterial(e,s,i);let r=this.device.isWebGPU?e.shaderChunks.wgsl:e.shaderChunks.glsl;r.set("gsplatContainerDeclarationsVS",this.format.getInputDeclarations()),r.set("gsplatDeclarationsVS",'#include "gsplatContainerDeclVS"'),r.set("gsplatReadVS",this.format.getReadCode())}};var nm=new W,f2=new $,CI=new ge,u2=new ge,X6=new F(1,1,0,.4),PI=.28209479177387814,wI=class{constructor(t,e,s,i,r){let a=t.getProp("x"),o=t.getProp("y"),l=t.getProp("z"),h=t.getProp("rot_1"),f=t.getProp("rot_2"),u=t.getProp("rot_3"),d=t.getProp("rot_0"),p=t.getProp("scale_0"),m=t.getProp("scale_1"),_=t.getProp("scale_2"),S=t.getProp("f_dc_0"),g=t.getProp("f_dc_1"),T=t.getProp("f_dc_2"),C=t.getProp("opacity"),v=E=>{if(E>0)return 1/(1+Math.exp(-E));let y=Math.exp(E);return y/(1+y)};this.read=E=>{e&&(e.x=a[E],e.y=o[E],e.z=l[E]),s&&s.set(h[E],f[E],u[E],d[E]),i&&i.set(Math.exp(p[E]),Math.exp(m[E]),Math.exp(_[E])),r&&r.set(.5+S[E]*PI,.5+g[E]*PI,.5+T[E]*PI,v(C[E]))}}},d2=(c,t,e)=>{f2.set(e.x,e.y,e.z,e.w).normalize(),c.setTRS(t,f2,x.ONE)},Qa=class c{constructor(t,e=[]){n(this,"elements");n(this,"numSplats");n(this,"comments");this.elements=t,this.numSplats=this.getElement("vertex").count,this.comments=e}static calcSplatAabb(t,e,s,i){d2(nm,e,s),CI.center.set(0,0,0),CI.halfExtents.set(i.x*2,i.y*2,i.z*2),t.setFromTransformedAabb(CI,nm)}getProp(t,e="vertex"){return this.getElement(e)?.properties.find(s=>s.name===t)?.storage}getElement(t){return this.elements.find(e=>e.name===t)}addProp(t,e){this.getElement("vertex").properties.push({type:"float",name:t,storage:e,byteSize:4})}createIter(t,e,s,i){return new wI(this,t,e,s,i)}calcAabb(t,e){let s,i,r,a,o,l,h=!0,f=this.getProp("x"),u=this.getProp("y"),d=this.getProp("z"),p=this.getProp("scale_0"),m=this.getProp("scale_1"),_=this.getProp("scale_2");for(let S=0;S{for(let s=0;s<45;++s)if(!this.getProp(`f_rest_${s}`))return s;return 45})()]??0}calcMortonOrder(){let t=C=>{let v=C[0],E=C[0];for(let y=1;yE&&(E=C[y]);return{min:v,max:E}},e=(C,v,E)=>{let y=P=>(P&=1023,P=(P^P<<16)&4278190335,P=(P^P<<8)&50393103,P=(P^P<<4)&51130563,P=(P^P<<2)&153391689,P);return(y(E)<<2)+(y(v)<<1)+y(C)},s=this.getProp("x"),i=this.getProp("y"),r=this.getProp("z"),{min:a,max:o}=t(s),{min:l,max:h}=t(i),{min:f,max:u}=t(r),d=a===o?0:1024/(o-a),p=l===h?0:1024/(h-l),m=f===u?0:1024/(u-f),_=new Map;for(let C=0;CC-v),g=new Uint32Array(this.numSplats),T=0;for(let C=0;C{if(e.has(a)){let o=e.get(a);return e.delete(a),o}return new ArrayBuffer(a)},i=a=>{e.set(a.byteLength,a)},r=a=>{let o=new a.constructor(s(a.byteLength));for(let l=0;l{a.properties.forEach(o=>{o.storage&&(o.storage=r(o.storage))})})}reorderData(){this.reorder(this.calcMortonOrder())}};var Y6=` attribute vec2 vertex_position; void main(void) { gl_Position = vec4(vertex_position, 0.0, 1.0); } -`,u4=` +`,K6=` #include "gsplatEvalSHVS" vec4 packRgb(vec3 v) { uvec3 vb = uvec3(clamp(v, vec3(0.0), vec3(1.0)) * vec3(2047.0, 2047.0, 1023.0)); @@ -1733,7 +2157,7 @@ ${r.getOutputStubs(r.extraStreams)}`),a.set("gsplatWorkBufferOutputVS",h);let c= } gl_FragColor = packRgb(evalSH(coefficients, dir) * 0.25 + 0.5); } -`,u5=` +`,j6=` attribute vertex_position: vec2f; @vertex fn vertexMain(input: VertexInput) -> VertexOutput { @@ -1741,7 +2165,7 @@ ${r.getOutputStubs(r.extraStreams)}`),a.set("gsplatWorkBufferOutputVS",h);let c= output.position = vec4f(vertex_position, 0.0, 1.0); return output; } -`,u6=` +`,q6=` #include "gsplatEvalSHVS" fn packRgb(v: vec3f) -> vec4f { let vb = vec3u(clamp(v, vec3f(0.0), vec3f(1.0)) * vec3f(2047.0, 2047.0, 1023.0)); @@ -1764,7 +2188,7 @@ ${r.getOutputStubs(r.extraStreams)}`),a.set("gsplatWorkBufferOutputVS",h);let c= output.color = packRgb(evalSH(&coefficients, uniform.dir) * 0.25 + 0.5); return output; } -`,u8=` +`,$6=` uniform mediump sampler2D sh0; uniform highp sampler2D sh_labels; uniform mediump sampler2D sh_result; @@ -1786,7 +2210,7 @@ ${r.getOutputStubs(r.extraStreams)}`),a.set("gsplatWorkBufferOutputVS",h);let c= vec3 sh = (unpackRgb(shSample) - vec3(0.5)) * 4.0; return vec4(base.xyz + sh, base.w); } -`,u9=` +`,Z6=` var sh0: texture_2d; var sh_labels: texture_2d; var sh_result: texture_2d; @@ -1807,163 +2231,7 @@ ${r.getOutputStubs(r.extraStreams)}`),a.set("gsplatWorkBufferOutputVS",h);let c= let sh: vec3f = (unpackRgb(shSample) - vec3f(0.5)) * 4.0; return vec4f(base.xyz + sh, base.w); } -`;class u7 extends ah{execute(){this.executeCallback?.();}constructor(...e){super(...e),this.executeCallback=null;}}let fe=new ey,ft=new ed;class fi{destroy(){let{gsplatInstance:e}=this,{material:t}=e;t.setDefine("SH_BANDS",e.resource.gsplatData.shBands.toString());let{shaderChunks:i}=t;i.glsl.delete("gsplatSogColorVS"),i.wgsl.delete("gsplatSogColorVS"),t.update(),this.quadRender.destroy(),this.renderPass.destroy(),this.renderTarget.destroy(),this.texture.destroy(),this.shader.destroy();}render(e,t){let{prevDir:i,updateMode:s}=this;if("disable"===s||(fe.invert(t),fe.transformVector(e.forward,ft),ft.normalize(),"enable"===s&&ft.equalsApprox(i,.001)))return;i.copy(ft);let r=()=>{let{device:e}=this,{sh_centroids:t,meta:i}=this.gsplatInstance.resource.gsplatData;var s=e.scope,r={dir:ft.toArray(),centroids:t,shN_mins:i.shN.mins,shN_maxs:i.shN.maxs};for(let e in r)s.resolve(e).setValue(r[e]);e.setDrawStates(),this.quadRender.render();};this.renderPass.executeCallback=r,this.renderPass.render();}constructor(e,t){this.prevDir=new ed,this.updateMode="enable",this.device=e,this.gsplatInstance=t;let{resource:i}=t;this.shader=nJ.createShader(e,{uniqueName:"gsplatResolveSH",vertexGLSL:u3,fragmentGLSL:u4,vertexWGSL:u5,fragmentWGSL:u6,fragmentDefines:new Map([["SH_BANDS",i.gsplatData.shBands.toString()]]),attributes:{vertex_position:e8}}),this.texture=i.streams.createTexture("centroids",7,new ef(64,1024)),this.renderTarget=new iG({colorBuffer:this.texture,depth:false}),this.renderPass=new u7(e),this.renderPass.init(this.renderTarget,{}),this.renderPass.colorOps.clear=true,this.quadRender=new n4(this.shader);let{material:s}=t;s.setDefine("SH_BANDS","0");let{shaderChunks:r}=s;r.glsl.set("gsplatSogColorVS",u8),r.wgsl.set("gsplatSogColorVS",u9),s.update(),e.scope.resolve("sh_result").setValue(this.texture);}}function fs(){let e,t,i,s,r,a,n,o,l="u">typeof self&&self||require("node:worker_threads").parentPort,h=false,c={x:0,y:0,z:0},d={x:0,y:0,z:0},u={x:0,y:0,z:0},f={x:0,y:0,z:0},p=Array(32).fill(0),m=Array(32).fill(0),_=Array(32).fill(0);l.addEventListener("message",g=>{let v=g.data??g;if(v.order&&(e=new Uint32Array(v.order)),v.centers)if(t=new Float32Array(v.centers),h=true,v.chunks){let e=new Float32Array(v.chunks);i=new Float32Array(v.chunks,0,4*e.length/6),u.x=e[0],u.y=e[1],u.z=e[2],f.x=e[3],f.y=e[4],f.z=e[5];for(let t=0;tf.x&&(f.x=n),o>f.y&&(f.y=o),l>f.z&&(f.z=l);}}else {let e,s,r,a,n,o,l=t.length/3,h=Math.ceil(l/256);i=new Float32Array(4*h),u.x=u.y=u.z=1/0,f.x=f.y=f.z=-1/0;for(let c=0;ca&&(a=l),hn&&(n=h),co&&(o=c),lf.x&&(f.x=l),hf.y&&(f.y=h),cf.z&&(f.z=c));}i[4*c+0]=(e+a)*.5,i[4*c+1]=(s+n)*.5,i[4*c+2]=(r+o)*.5,i[4*c+3]=.5*Math.sqrt((a-e)**2+(n-s)**2+(o-r)**2);}}v.hasOwnProperty("mapping")&&(s=v.mapping?new Uint32Array(v.mapping):null,h=true),v.cameraPosition&&(r=v.cameraPosition),v.cameraDirection&&(a=v.cameraDirection),(()=>{let g,v,S;if(!e||!t||0===t.length||!r||!a)return;let y=performance.now(),x=r.x,T=r.y,E=r.z,w=a.x,b=a.y,C=a.z;if(!h&&.001>Math.abs(x-c.x)&&.001>Math.abs(T-c.y)&&.001>Math.abs(E-c.z)&&.001>Math.abs(w-d.x)&&.001>Math.abs(b-d.y)&&.001>Math.abs(C-d.z))return;h=false,c.x=x,c.y=T,c.z=E,d.x=w,d.y=b,d.z=C;for(let e=0;e<8;++e){let t=(1&e?u.x:f.x)*w+(2&e?u.y:f.y)*b+(4&e?u.z:f.z)*C;0===e?g=v=t:(g=Math.min(g,t),v=Math.max(v,t));}let A=t.length/3,P=Math.max(10,Math.min(20,Math.round(Math.log2(A/4)))),I=2**P+1;n?.length!==A&&(n=new Uint32Array(A)),o&&o.length===I?o.fill(0):o=new Uint32Array(I);let D=v-g;if(D<1e-6)for(let e=0;ee+t,0);for(let e=0;e<32;++e)_[e]=p[e]/s*I>>>0;for(let e=0;e<32;++e)m[e]=0===e?0:m[e-1]+_[e-1];let r=D/32,a=0;for(let e=0;e>>0,l=m[s]+_[s]*(i-s)>>>0;n[e]=l,o[l]++;}}for(let e=1;e{let s=3*e[i];return t[s++]*w+t[s++]*b+t[s]*C-R},M=L(A-1)>=0?(S=((e,t,i)=>{for(;e<=t;){let s=t+e>>1,r=i(s);if(r>0)e=s+1;else {if(!(r<0))return s;t=s-1;}}return ~e})(0,A-1,e=>-L(e)),Math.min(A,Math.abs(S))):A;if(s)for(let t=0;t{let t=e.data??e;this.scene&&void 0!==t.sortTime&&this.scene.fire("gsplat:sorted",t.sortTime);let i=t.order,s=this.orderData;this.worker.postMessage({order:s},[s]),this.orderData=i,this.pendingSorted={count:t.count,data:new Uint32Array(i)},this.fire("updated");},s=`(${fs.toString()})()`;"node"===k.environment?(this.worker=new Worker(s,{eval:true}),this.worker.on("message",i)):(this.worker=new Worker(URL.createObjectURL(new Blob([s],{type:"application/javascript"}))),this.worker.addEventListener("message",i));}}var fa=` -#include "gsplatPackingPS" -uniform highp sampler2D means_l; -uniform highp sampler2D means_u; -uniform highp sampler2D quats; -uniform highp sampler2D scales; -uniform highp sampler2D sh0; -uniform highp sampler2D sh_labels; -uniform highp uint numSplats; -#ifdef REORDER_V1 - float sigmoid(float x) { return 1.0 / (1.0 + exp(-x)); } - vec3 vmin(vec3 v) { return vec3(min(min(v.x, v.y), v.z)); } - vec3 vmax(vec3 v) { return vec3(max(max(v.x, v.y), v.z)); } - vec3 resolve(vec3 m, vec3 M, vec3 v) { return (mix(m, M, v) - vmin(m)) / (vmax(M) - vmin(m)); } - - uniform vec3 scalesMins; - uniform vec3 scalesMaxs; - uniform vec4 sh0Mins; - uniform vec4 sh0Maxs; -#else - uniform vec4 scales_codebook[64]; - uniform vec4 sh0_codebook[64]; -#endif -void main(void) { - int w = int(textureSize(means_l, 0).x); - ivec2 uv = ivec2(gl_FragCoord.xy); - if (uint(uv.x + uv.y * w) >= numSplats) { - discard; - } - vec3 meansLSample = texelFetch(means_l, uv, 0).xyz; - vec3 meansUSample = texelFetch(means_u, uv, 0).xyz; - vec4 quatsSample = texelFetch(quats, uv, 0); - vec3 scalesSample = texelFetch(scales, uv, 0).xyz; - vec4 sh0Sample = texelFetch(sh0, uv, 0); - vec2 shLabelsSample = texelFetch(sh_labels, uv, 0).xy; - #ifdef REORDER_V1 - uint scale = pack101010(resolve(scalesMins, scalesMaxs, scalesSample)); - uint sh0 = pack111110(resolve(sh0Mins.xyz, sh0Maxs.xyz, sh0Sample.xyz)); - float alpha = sigmoid(mix(sh0Mins.w, sh0Maxs.w, sh0Sample.w)); - #else - uint scale = pack101010(resolveCodebook(scalesSample, scales_codebook)); - uint sh0 = pack111110(resolveCodebook(sh0Sample.xyz, sh0_codebook)); - float alpha = sh0Sample.w; - #endif - uint qmode = uint(quatsSample.w * 255.0) - 252u; - pcFragColor0 = uvec4( - pack8888(vec4(meansLSample, shLabelsSample.x)), - pack8888(vec4(meansUSample, shLabelsSample.y)), - pack8888(vec4(quatsSample.xyz, alpha)), - (scale << 2u) | qmode - ); - pcFragColor1 = unpack8888(sh0); -} -`,fn=` -#include "gsplatPackingPS" -var means_l: texture_2d; -var means_u: texture_2d; -var quats: texture_2d; -var scales: texture_2d; -var sh0: texture_2d; -var sh_labels: texture_2d; -uniform numSplats: u32; -#ifdef REORDER_V1 - fn sigmoid(x: f32) -> f32 { return 1.0 / (1.0 + exp(-x)); } - fn vmin(v: vec3f) -> vec3f { return vec3f(min(min(v.x, v.y), v.z)); } - fn vmax(v: vec3f) -> vec3f { return vec3f(max(max(v.x, v.y), v.z)); } - fn resolve(m: vec3f, M: vec3f, v: vec3f) -> vec3f { return (mix(m, M, v) - vmin(m)) / (vmax(M) - vmin(m)); } - uniform scalesMins: vec3f; - uniform scalesMaxs: vec3f; - uniform sh0Mins: vec4f; - uniform sh0Maxs: vec4f; -#else - uniform scales_codebook: array; - uniform sh0_codebook: array; -#endif -@fragment -fn fragmentMain(input: FragmentInput) -> FragmentOutput { - var output: FragmentOutput; - let w: u32 = textureDimensions(means_l, 0).x; - let uv: vec2 = vec2(input.position.xy); - if (uv.x + uv.y * w >= uniform.numSplats) { - discard; - return output; - } - let meansLSample: vec3 = textureLoad(means_l, uv, 0).xyz; - let meansUSample: vec3 = textureLoad(means_u, uv, 0).xyz; - let quatsSample: vec4 = textureLoad(quats, uv, 0); - let scalesSample: vec3 = textureLoad(scales, uv, 0).xyz; - let sh0Sample: vec4f = textureLoad(sh0, uv, 0); - let shLabelsSample: vec2 = textureLoad(sh_labels, uv, 0).xy; - #ifdef REORDER_V1 - let scale = pack101010(resolve(uniform.scalesMins, uniform.scalesMaxs, scalesSample)); - let sh0 = pack111110(resolve(uniform.sh0Mins.xyz, uniform.sh0Maxs.xyz, sh0Sample.xyz)); - let alpha = sigmoid(mix(uniform.sh0Mins.w, uniform.sh0Maxs.w, sh0Sample.w)); - #else - let scalesIdx = vec3u(scalesSample * 255.0); - let scalesV = vec3f( - uniform.scales_codebook[scalesIdx.x >> 2u][scalesIdx.x & 3u], - uniform.scales_codebook[scalesIdx.y >> 2u][scalesIdx.y & 3u], - uniform.scales_codebook[scalesIdx.z >> 2u][scalesIdx.z & 3u] - ); - let scale = pack101010((scalesV - uniform.scales_codebook[0].x) / (uniform.scales_codebook[63].w - uniform.scales_codebook[0].x)); - let sh0Idx = vec3u(sh0Sample.xyz * 255.0); - let sh0V = vec3f( - uniform.sh0_codebook[sh0Idx.x >> 2u][sh0Idx.x & 3u], - uniform.sh0_codebook[sh0Idx.y >> 2u][sh0Idx.y & 3u], - uniform.sh0_codebook[sh0Idx.z >> 2u][sh0Idx.z & 3u] - ); - let sh0 = pack111110((sh0V - uniform.sh0_codebook[0].x) / (uniform.sh0_codebook[63].w - uniform.sh0_codebook[0].x)); - let alpha = sh0Sample.w; - #endif - let qmode = u32(quatsSample.w * 255.0) - 252u; - output.color = vec4u( - pack8888(vec4f(meansLSample, shLabelsSample.x)), - pack8888(vec4f(meansUSample, shLabelsSample.y)), - pack8888(vec4f(quatsSample.xyz, alpha)), - (scale << 2u) | qmode - ); - output.color1 = unpack8888(sh0); - return output; -} -`,fo=` -#include "gsplatPackingPS" -uniform highp sampler2D sh_centroids; -uniform vec4 shN_codebook[64]; -void main(void) { - ivec2 uv = ivec2(gl_FragCoord.xy); - vec3 shNSample = texelFetch(sh_centroids, uv, 0).xyz; -#ifdef REORDER_V1 - pcFragColor0 = unpack8888(pack111110(shNSample)); -#else - pcFragColor0 = unpack8888(pack111110(resolveCodebook(shNSample, shN_codebook))); -#endif -} -`,fl=` -#include "gsplatPackingPS" -var sh_centroids: texture_2d; -uniform shN_codebook: array; -@fragment -fn fragmentMain(input: FragmentInput) -> FragmentOutput { - var output: FragmentOutput; - var uv = vec2i(input.position.xy); - var shNSample = textureLoad(sh_centroids, uv, 0).xyz; -#ifdef REORDER_V1 - output.color = unpack8888(pack111110(shNSample)); -#else - let shNIdx = vec3u(shNSample * 255.0); - let shNV = vec3f( - uniform.shN_codebook[shNIdx.x >> 2u][shNIdx.x & 3u], - uniform.shN_codebook[shNIdx.y >> 2u][shNIdx.y & 3u], - uniform.shN_codebook[shNIdx.z >> 2u][shNIdx.z & 3u] - ); - output.color = unpack8888(pack111110((shNV - uniform.shN_codebook[0].x) / (uniform.shN_codebook[63].w - uniform.shN_codebook[0].x))); -#endif - return output; -} -`,fh=` +`,Q6=(c,t)=>{for(let e in t)c.resolve(e).setValue(t[e])},II=class extends yt{constructor(){super(...arguments);n(this,"executeCallback",null)}execute(){this.executeCallback?.()}},p2=new W,PS=new x,Wy=class{constructor(t,e){n(this,"prevDir",new x);n(this,"updateMode","enable");this.device=t,this.gsplatInstance=e;let{resource:s}=e;this.shader=Se.createShader(t,{uniqueName:"gsplatResolveSH",vertexGLSL:Y6,fragmentGLSL:K6,vertexWGSL:j6,fragmentWGSL:q6,fragmentDefines:new Map([["SH_BANDS",s.gsplatData.shBands.toString()]]),attributes:{vertex_position:ee}}),this.texture=s.streams.createTexture("centroids",ce,new B(64,1024)),this.renderTarget=new me({colorBuffer:this.texture,depth:!1}),this.renderPass=new II(t),this.renderPass.init(this.renderTarget,{}),this.renderPass.colorOps.clear=!0,this.quadRender=new hs(this.shader);let{material:i}=e;i.setDefine("SH_BANDS","0");let{shaderChunks:r}=i;r.glsl.set("gsplatSogColorVS",$6),r.wgsl.set("gsplatSogColorVS",Z6),i.update(),t.scope.resolve("sh_result").setValue(this.texture)}destroy(){let{gsplatInstance:t}=this,{material:e}=t;e.setDefine("SH_BANDS",t.resource.gsplatData.shBands.toString());let{shaderChunks:s}=e;s.glsl.delete("gsplatSogColorVS"),s.wgsl.delete("gsplatSogColorVS"),e.update(),this.quadRender.destroy(),this.renderPass.destroy(),this.renderTarget.destroy(),this.texture.destroy(),this.shader.destroy()}render(t,e){let{prevDir:s,updateMode:i}=this;if(i==="disable"||(p2.invert(e),p2.transformVector(t.forward,PS),PS.normalize(),i==="enable"&&PS.equalsApprox(s,.001)))return;s.copy(PS);let r=()=>{let{device:a}=this,{sh_centroids:o,meta:l}=this.gsplatInstance.resource.gsplatData;Q6(a.scope,{dir:PS.toArray(),centroids:o,shN_mins:l.shN.mins,shN_maxs:l.shN.maxs}),a.setDrawStates(),this.quadRender.render()};this.renderPass.executeCallback=r,this.renderPass.render()}};function m2(){let c=typeof self<"u"&&self||EC("node:worker_threads").parentPort,t,e,s,i,r,a,o=!1,l={x:0,y:0,z:0},h={x:0,y:0,z:0},f={x:0,y:0,z:0},u={x:0,y:0,z:0},d,p,m=32,_=new Array(m).fill(0),S=new Array(m).fill(0),g=new Array(m).fill(0),T=(v,E,y)=>{for(;v<=E;){let P=E+v>>1,A=y(P);if(A>0)v=P+1;else if(A<0)E=P-1;else return P}return~v},C=()=>{if(!t||!e||e.length===0||!r||!a)return;let v=performance.now(),E=r.x,y=r.y,P=r.z,A=a.x,w=a.y,I=a.z,D=.001;if(!o&&Math.abs(E-l.x)j+oe,0);for(let j=0;j>>0;for(let j=0;j>>0,Lt=S[Ve]+g[Ve]*(ot-Ve)>>>0;d[j]=Lt,p[Lt]++}}for(let V=1;V{let q=t[V]*3;return e[q++]*A+e[q++]*w+e[q]*I-b},k=()=>{let V=T(0,M-1,q=>-N(q));return Math.min(M,Math.abs(V))},z=N(M-1)>=0?k():M;if(i)for(let V=0;V{let E=v.data??v;if(E.order&&(t=new Uint32Array(E.order)),E.centers)if(e=new Float32Array(E.centers),o=!0,E.chunks){let y=new Float32Array(E.chunks);s=new Float32Array(E.chunks,0,y.length*4/6),f.x=y[0],f.y=y[1],f.z=y[2],u.x=y[3],u.y=y[4],u.z=y[5];for(let P=0;Pu.x&&(u.x=D),O>u.y&&(u.y=O),G>u.z&&(u.z=G)}}else{let y=e.length/3,P=Math.ceil(y/256);s=new Float32Array(P*4),f.x=f.y=f.z=1/0,u.x=u.y=u.z=-1/0;let A,w,I,D,O,G;for(let M=0;MD&&(D=b),NO&&(O=N),kG&&(G=k),bu.x&&(u.x=b),Nu.y&&(u.y=N),ku.z&&(u.z=k))}s[M*4+0]=(A+D)*.5,s[M*4+1]=(w+O)*.5,s[M*4+2]=(I+G)*.5,s[M*4+3]=Math.sqrt((D-A)**2+(O-w)**2+(G-I)**2)*.5}}E.hasOwnProperty("mapping")&&(i=E.mapping?new Uint32Array(E.mapping):null,o=!0),E.cameraPosition&&(r=E.cameraPosition),E.cameraDirection&&(a=E.cameraDirection),C()})}var Xy=class extends J{constructor(e,s){super();n(this,"worker");n(this,"target");n(this,"orderData");n(this,"centers");n(this,"scene");n(this,"uploadStream");n(this,"pendingSorted",null);this.scene=s??null,this.uploadStream=new rm(e,!e.isWebGPU);let i=a=>{let o=a.data??a;this.scene&&o.sortTime!==void 0&&this.scene.fire("gsplat:sorted",o.sortTime);let l=o.order,h=this.orderData;this.worker.postMessage({order:h},[h]),this.orderData=l,this.pendingSorted={count:o.count,data:new Uint32Array(l)},this.fire("updated")},r=`(${m2.toString()})()`;ue.environment==="node"?(this.worker=new Worker(r,{eval:!0}),this.worker.on("message",i)):(this.worker=new Worker(URL.createObjectURL(new Blob([r],{type:"application/javascript"}))),this.worker.addEventListener("message",i))}destroy(){this.worker.terminate(),this.worker=null,this.uploadStream.destroy(),this.uploadStream=null}init(e,s,i,r){this.target=e,this.centers=i.slice();let a=new Uint32Array(s);for(let h=0;h; var means_u: texture_2d; uniform numSplats: u32; @@ -2007,7 +2275,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { output.color = packed; return output; } -`;let fd=e=>e.device.isNull?new Promise(t=>{t(new Uint8Array(e.width*e.height*4));}):e.read(0,0,e.width,e.height,{mipLevel:0,face:0,immediate:true}),fu=(e,t)=>{for(let i in t)e.resolve(i).setValue(t[i]);};class ff{constructor(e,t,i,s,r,a){let n=(e,t,i)=>e*(1-i)+t*i,{meta:o,shBands:l}=e,{means:h,scales:c,sh0:d,shN:u}=o,f=t&&e.means_l._levels[0],p=t&&e.means_u._levels[0],m=i&&e.quats._levels[0],_=s&&e.scales._levels[0],g=r&&e.sh0._levels[0],v=a&&e.sh_labels._levels[0],S=a&&e.sh_centroids._levels[0],y=Math.SQRT2,x={1:3,2:8,3:15}[l]??0;this.read=l=>{if(t){let e=n(h.mins[0],h.maxs[0],((p[4*l+0]<<8)+f[4*l+0])/65535),i=n(h.mins[1],h.maxs[1],((p[4*l+1]<<8)+f[4*l+1])/65535),s=n(h.mins[2],h.maxs[2],((p[4*l+2]<<8)+f[4*l+2])/65535);t.x=Math.sign(e)*(Math.exp(Math.abs(e))-1),t.y=Math.sign(i)*(Math.exp(Math.abs(i))-1),t.z=Math.sign(s)*(Math.exp(Math.abs(s))-1);}if(i){let e=(m[4*l+0]/255-.5)*y,t=(m[4*l+1]/255-.5)*y,s=(m[4*l+2]/255-.5)*y,r=Math.sqrt(Math.max(0,1-(e*e+t*t+s*s)));switch(m[4*l+3]-252){case 0:i.set(e,t,s,r);break;case 1:i.set(r,t,s,e);break;case 2:i.set(t,r,s,e);break;case 3:i.set(t,s,r,e);}}if(s)if(2===o.version){let e=c.codebook[_[4*l+0]],t=c.codebook[_[4*l+1]],i=c.codebook[_[4*l+2]];s.set(e,t,i);}else {let e=n(c.mins[0],c.maxs[0],_[4*l+0]/255),t=n(c.mins[1],c.maxs[1],_[4*l+1]/255),i=n(c.mins[2],c.maxs[2],_[4*l+2]/255);s.set(e,t,i);}if(r)if(2===o.version){let e=d.codebook[g[4*l+0]],t=d.codebook[g[4*l+1]],i=d.codebook[g[4*l+2]],s=g[4*l+3]/255;r.set(.5+.28209479177387814*e,.5+.28209479177387814*t,.5+.28209479177387814*i,s);}else {let e=n(d.mins[0],d.maxs[0],g[4*l+0]/255),t=n(d.mins[1],d.maxs[1],g[4*l+1]/255),i=n(d.mins[2],d.maxs[2],g[4*l+2]/255),s=n(d.mins[3],d.maxs[3],g[4*l+3]/255);r.set(.5+.28209479177387814*e,.5+.28209479177387814*t,.5+.28209479177387814*i,1/(1+Math.exp(-s)));}if(a){let t=v[4*l+0]+(v[4*l+1]<<8),i=t%64*x,s=Math.floor(t/64);if(2===o.version)for(let t=0;t<3;++t)for(let r=0;rMath.sign(e)*(Math.exp(Math.abs(e))-1);e.center.set((s(t[0])+s(i[0]))*.5,(s(t[1])+s(i[1]))*.5,(s(t[2])+s(i[2]))*.5),e.halfExtents.set((s(i[0])-s(t[0]))*.5,(s(i[1])-s(t[1]))*.5,(s(i[2])-s(t[2]))*.5);}getCenters(){let e=this._centers;return this._centers=null,e}calcFocalPoint(e,t){let{mins:i,maxs:s}=this.meta.means,r=e=>Math.sign(e)*(Math.exp(Math.abs(e))-1);e.set((r(i[0])+r(s[0]))*.5,(r(i[1])+r(s[1]))*.5,(r(i[2])+r(s[2]))*.5);}get isSog(){return true}async decompress(){let e=["x","y","z","f_dc_0","f_dc_1","f_dc_2","opacity","scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3"],{shBands:t}=this,{means_l:i,means_u:s,quats:r,scales:a,sh0:n,sh_labels:o,sh_centroids:l}=this;if(i._levels[0]=await fd(i),s._levels[0]=await fd(s),r._levels[0]=await fd(r),a._levels[0]=await fd(a),n._levels[0]=await fd(n),t>0){o._levels[0]=await fd(o),l._levels[0]=await fd(l);let t=[];for(let e=0;e<45;++e)t.push(`f_rest_${e}`);e.splice(e.indexOf("f_dc_0")+1,0,...t);}let h={};e.forEach(e=>{h[e]=new Float32Array(this.numSplats);});let c=new ed,d=new ex,u=new ed,f=new ep,p=t>0?new Float32Array(45):null,m=this.createIter(c,d,u,f,p);for(let e=0;e=1?40:-Math.log(1/f.w-1),p)for(let t=0;t<45;++t)h[`f_rest_${t}`][e]=p[t];return new u2([{name:"vertex",count:this.numSplats,properties:e.map(e=>({name:e,type:"float",byteSize:4,storage:h[e]}))}])}async generateCenters(){let{device:e,width:t,height:i}=this.means_l,{scope:s}=e,r=new ic(e,{name:"sogCentersTexture",width:t,height:i,format:49,mipmaps:false}),a=nJ.createShader(e,{uniqueName:"GsplatSogCentersShader",attributes:{vertex_position:e8},vertexChunk:"fullscreenQuadVS",fragmentGLSL:fh,fragmentWGSL:fc,fragmentOutputTypes:["uvec4"]}),n=new iG({colorBuffer:r,depth:false,mipLevel:0});fu(s,{means_l:this.means_l,means_u:this.means_u,numSplats:this.numSplats,means_mins:this.meta.means.mins,means_maxs:this.meta.means.maxs});let o=new n4(a),l=new n5(e,o);l.name="SogGenerateCenters",l.init(n),l.colorOps.clear=false,l.depthStencilOps.clearDepth=false,l.render(),o.destroy(),n.destroy();let h=await fd(r);if(this.destroyed||e._destroyed)return void r.destroy();let c=new Float32Array(h.buffer),d=new Float32Array(3*this.numSplats);for(let e=0;e{this.packGpuMemory(),this.packedShN&&this.packShMemory();})),["scales","sh0","shN"].forEach(e=>{let t=this.meta[e]?.codebook;t?.[0]===null&&(t[0]=t[1]+(t[1]-t[255])/255);}),e=this.means_l?.device,!this.destroyed&&e&&!e._destroyed)&&(await this.generateCenters(),e=this.means_l?.device,!this.destroyed&&e&&!e._destroyed)){if(this.packGpuMemory(),this.packedShN){if(e=this.means_l?.device,this.destroyed||!e||e._destroyed)return;this.packShMemory();}this.minimalMemory&&(this.means_l?.destroy(),this.means_u?.destroy(),this.quats?.destroy(),this.scales?.destroy(),this.sh0?.destroy(),this.sh_centroids?.destroy(),this.sh_labels?.destroy(),this.means_l=null,this.means_u=null,this.quats=null,this.scales=null,this.sh0=null,this.sh_centroids=null,this.sh_labels=null);}}reorderData(){return this.prepareGpuData()}constructor(){this.url="",this.minimalMemory=false,this.deviceRestoredEvent=null,this._centers=null,this.destroyed=false,this.shBands=0;}}let fm=new ey,f_=new ed,fg=new ed;class fv{destroy(){this.resource?.releaseMesh(),this.orderTexture?.destroy(),this.orderBuffer?.destroy(),this.resolveSH?.destroy(),this.material?.destroy(),this.meshInstance?.destroy(),this.sorter?.destroy();}setMaterialOrderData(e){this.orderBuffer?e.setParameter("splatOrder",this.orderBuffer):(e.setParameter("splatOrder",this.orderTexture),e.setParameter("splatTextureSize",this.orderTexture.width));}set material(e){this._material!==e&&(this._material=e,this._material.setDefine("{GSPLAT_INSTANCE_SIZE}",String(uj.instanceSize)),this.setMaterialOrderData(this._material),this.meshInstance&&(this.meshInstance.material=e));}get material(){return this._material}configureMaterial(e,t={}){this.resource.configureMaterial(e,null,this.resource.format.getInputDeclarations()),e.setDefine("{GSPLAT_INSTANCE_SIZE}",uj.instanceSize),e.setParameter("numSplats",0),this.setMaterialOrderData(e),e.setParameter("alphaClip",.3),e.setParameter("minPixelSize",2),e.setDefine(`DITHER_${t.dither?"BLUENOISE":"NONE"}`,""),e.cull=0,e.blendType=t.dither?3:4,e.depthWrite=!!t.dither;}sort(e){if(this.sorter){let t=e.getWorldTransform();t.getTranslation(f_),t.getZ(fg);let i=this.meshInstance.node.getWorldTransform(),s=fm.invert(i);s.transformPoint(f_,f_),s.transformVector(fg,fg),f_.equalsApprox(this.lastCameraPosition)&&fg.equalsApprox(this.lastCameraDirection)||(this.lastCameraPosition.copy(f_),this.lastCameraDirection.copy(fg),this.sorter.setCamera(f_,fg));}}update(){let e=this.sorter?.applyPendingSorted()??-1;if(e>=0&&(this.meshInstance.instancingCount=Math.ceil(e/uj.instanceSize),this.material.setParameter("numSplats",e)),this.cameras.length>0){let e=this.cameras[0];this.sort(e._node),this.resolveSH?.render(e._node,this.meshInstance.node.getWorldTransform()),this.cameras.length=0;}}setHighQualitySH(e){let{resource:t}=this,{gsplatData:i}=t;i instanceof fp&&i.shBands>0&&!!this.resolveSH===e&&(this.resolveSH?(this.resolveSH.destroy(),this.resolveSH=null):this.resolveSH=new fi(t.device,this));}constructor(e,t={}){this.options={},this.sorter=null,this.lastCameraPosition=new ed,this.lastCameraDirection=new ed,this.resolveSH=null,this.cameras=[],this.resource=e;let i=e.device,s=e.streams.textureDimensions,r=s.x*s.y;i.isWebGPU?this.orderBuffer=new rO(i,4*r,8):this.orderTexture=e.streams.createTexture("splatOrder",37,s),t.material?(this._material=t.material,this._material.setDefine("{GSPLAT_INSTANCE_SIZE}",String(uj.instanceSize)),this.setMaterialOrderData(this._material)):(this._material=new cT({uniqueName:"SplatMaterial",vertexGLSL:'#include "gsplatVS"',fragmentGLSL:'#include "gsplatPS"',vertexWGSL:'#include "gsplatVS"',fragmentWGSL:'#include "gsplatPS"',attributes:{vertex_position:e8}}),this.configureMaterial(this._material),this._material.update()),e.ensureMesh(),this.meshInstance=new oS(e.mesh,this._material),this.meshInstance.setInstancing(true,true),this.meshInstance.gsplatInstance=this,this.meshInstance.instancingCount=0;let a=e.centers.slice(),n=e.chunks?.slice(),o=this.orderBuffer??this.orderTexture;this.sorter=new fr(i,t.scene),this.sorter.init(o,r,a,n),this.setHighQualitySH(t.highQualitySH??false);}}var fS=` +`;var pl=.28209479177387814,Kc=c=>c.device.isNull?new Promise(t=>{t(new Uint8Array(c.width*c.height*4))}):c.read(0,0,c.width,c.height,{mipLevel:0,face:0,immediate:!0}),J6=(c,t)=>{for(let e in t)c.resolve(e).setValue(t[e])},RI=class{constructor(t,e,s,i,r,a){let o=(P,A,w)=>P*(1-w)+A*w,{meta:l,shBands:h}=t,{means:f,scales:u,sh0:d,shN:p}=l,m=e&&t.means_l._levels[0],_=e&&t.means_u._levels[0],S=s&&t.quats._levels[0],g=i&&t.scales._levels[0],T=r&&t.sh0._levels[0],C=a&&t.sh_labels._levels[0],v=a&&t.sh_centroids._levels[0],E=Math.SQRT2,y={1:3,2:8,3:15}[h]??0;this.read=P=>{if(e){let A=o(f.mins[0],f.maxs[0],((_[P*4+0]<<8)+m[P*4+0])/65535),w=o(f.mins[1],f.maxs[1],((_[P*4+1]<<8)+m[P*4+1])/65535),I=o(f.mins[2],f.maxs[2],((_[P*4+2]<<8)+m[P*4+2])/65535);e.x=Math.sign(A)*(Math.exp(Math.abs(A))-1),e.y=Math.sign(w)*(Math.exp(Math.abs(w))-1),e.z=Math.sign(I)*(Math.exp(Math.abs(I))-1)}if(s){let A=(S[P*4+0]/255-.5)*E,w=(S[P*4+1]/255-.5)*E,I=(S[P*4+2]/255-.5)*E,D=Math.sqrt(Math.max(0,1-(A*A+w*w+I*I)));switch(S[P*4+3]-252){case 0:s.set(A,w,I,D);break;case 1:s.set(D,w,I,A);break;case 2:s.set(w,D,I,A);break;case 3:s.set(w,I,D,A);break}}if(i)if(l.version===2){let A=u.codebook[g[P*4+0]],w=u.codebook[g[P*4+1]],I=u.codebook[g[P*4+2]];i.set(A,w,I)}else{let A=o(u.mins[0],u.maxs[0],g[P*4+0]/255),w=o(u.mins[1],u.maxs[1],g[P*4+1]/255),I=o(u.mins[2],u.maxs[2],g[P*4+2]/255);i.set(A,w,I)}if(r)if(l.version===2){let A=d.codebook[T[P*4+0]],w=d.codebook[T[P*4+1]],I=d.codebook[T[P*4+2]],D=T[P*4+3]/255;r.set(.5+A*pl,.5+w*pl,.5+I*pl,D)}else{let A=o(d.mins[0],d.maxs[0],T[P*4+0]/255),w=o(d.mins[1],d.maxs[1],T[P*4+1]/255),I=o(d.mins[2],d.maxs[2],T[P*4+2]/255),D=o(d.mins[3],d.maxs[3],T[P*4+3]/255);r.set(.5+A*pl,.5+w*pl,.5+I*pl,1/(1+Math.exp(-D)))}if(a){let A=C[P*4+0]+(C[P*4+1]<<8),w=A%64*y,I=Math.floor(A/64);if(l.version===2)for(let D=0;D<3;++D)for(let O=0;OMath.sign(r)*(Math.exp(Math.abs(r))-1);t.center.set((i(e[0])+i(s[0]))*.5,(i(e[1])+i(s[1]))*.5,(i(e[2])+i(s[2]))*.5),t.halfExtents.set((i(s[0])-i(e[0]))*.5,(i(s[1])-i(e[1]))*.5,(i(s[2])-i(e[2]))*.5)}getCenters(){let t=this._centers;return this._centers=null,t}calcFocalPoint(t,e){let{mins:s,maxs:i}=this.meta.means,r=a=>Math.sign(a)*(Math.exp(Math.abs(a))-1);t.set((r(s[0])+r(i[0]))*.5,(r(s[1])+r(i[1]))*.5,(r(s[2])+r(i[2]))*.5)}get isSog(){return!0}async decompress(){let t=["x","y","z","f_dc_0","f_dc_1","f_dc_2","opacity","scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3"];this._patchCodebooks();let{shBands:e}=this,{means_l:s,means_u:i,quats:r,scales:a,sh0:o,sh_labels:l,sh_centroids:h}=this;if(s._levels[0]=await Kc(s),i._levels[0]=await Kc(i),r._levels[0]=await Kc(r),a._levels[0]=await Kc(a),o._levels[0]=await Kc(o),e>0){l._levels[0]=await Kc(l),h._levels[0]=await Kc(h);let g=[];for(let T=0;T<45;++T)g.push(`f_rest_${T}`);t.splice(t.indexOf("f_dc_0")+1,0,...g)}let f={};t.forEach(g=>{f[g]=new Float32Array(this.numSplats)});let u=new x,d=new $,p=new x,m=new Q,_=e>0?new Float32Array(45):null,S=this.createIter(u,d,p,m,_);for(let g=0;g=1?40:-Math.log(1/m.w-1),_)for(let T=0;T<45;++T)f[`f_rest_${T}`][g]=_[T];return new Qa([{name:"vertex",count:this.numSplats,properties:t.map(g=>({name:g,type:"float",byteSize:4,storage:f[g]}))}])}async generateCenters(){let{device:t,width:e,height:s}=this.means_l,{scope:i}=t,r=new Z(t,{name:"sogCentersTexture",width:e,height:s,format:At,mipmaps:!1}),a=Se.createShader(t,{uniqueName:"GsplatSogCentersShader",attributes:{vertex_position:ee},vertexChunk:"fullscreenQuadVS",fragmentGLSL:_2,fragmentWGSL:g2,fragmentOutputTypes:["uvec4"]}),o=new me({colorBuffer:r,depth:!1,mipLevel:0});J6(i,{means_l:this.means_l,means_u:this.means_u,numSplats:this.numSplats,means_mins:this.meta.means.mins,means_maxs:this.meta.means.maxs});let l=new hs(a),h=new Cp(t,l);h.name="SogGenerateCenters",h.init(o),h.colorOps.clear=!1,h.depthStencilOps.clearDepth=!1,h.render(),l.destroy(),o.destroy();let f=await Kc(r);if(this.destroyed||t._destroyed){r.destroy();return}let u=new Float32Array(f.buffer),d=new Float32Array(this.numSplats*3);for(let p=0;p{let e=this.meta[t]?.codebook;e?.[0]===null&&(e[0]=e[1]+(e[1]-e[255])/255)})}prepareCodebook(){let t=this.means_l?.device;this.destroyed||!t||t._destroyed||(this._patchCodebooks(),this.meta.version===2&&this._createCodebookTexture())}async prepareGpuData(){let t=this.means_l?.device;this.destroyed||!t||t._destroyed||await this.generateCenters()}};var e8=new W,lm=new x,cm=new x,hm=class{constructor(t,e={}){n(this,"resource");n(this,"orderTexture");n(this,"orderBuffer");n(this,"_material");n(this,"meshInstance");n(this,"options",{});n(this,"sorter",null);n(this,"lastCameraPosition",new x);n(this,"lastCameraDirection",new x);n(this,"resolveSH",null);n(this,"cameras",[]);this.resource=t;let s=t.device,i=t.streams.textureDimensions,r=i.x*i.y;if(s.isWebGPU?this.orderBuffer=new Ee(s,r*4,8):this.orderTexture=t.streams.createTexture("splatOrder",zt,i),e.material?(this._material=e.material,this._material.setDefine("{GSPLAT_INSTANCE_SIZE}",String(rt.instanceSize)),this.setMaterialOrderData(this._material),this._material.setParameter("alphaClipForward",1/255)):(this._material=new ct({uniqueName:"SplatMaterial",vertexGLSL:'#include "gsplatVS"',fragmentGLSL:'#include "gsplatPS"',vertexWGSL:'#include "gsplatVS"',fragmentWGSL:'#include "gsplatPS"',attributes:{vertex_position:ee}}),this.configureMaterial(this._material),this._material.update()),t.ensureMesh(),this.meshInstance=new we(t.mesh,this._material),this.meshInstance.setInstancing(!0,!0),this.meshInstance.gsplatInstance=this,this.meshInstance.instancingCount=0,t.hasCenters){let a=t.centers.slice(),o=t.chunks?.slice(),l=this.orderBuffer??this.orderTexture;this.sorter=new Xy(s,e.scene),this.sorter.init(l,r,a,o)}this.setHighQualitySH(e.highQualitySH??!1)}destroy(){this.resource?.releaseMesh(),this.orderTexture?.destroy(),this.orderBuffer?.destroy(),this.resolveSH?.destroy(),this.material?.destroy(),this.meshInstance?.destroy(),this.sorter?.destroy()}setMaterialOrderData(t){this.orderBuffer?t.setParameter("splatOrder",this.orderBuffer):(t.setParameter("splatOrder",this.orderTexture),t.setParameter("splatTextureSize",this.orderTexture.width))}set material(t){this._material!==t&&(this._material=t,this._material.setDefine("{GSPLAT_INSTANCE_SIZE}",String(rt.instanceSize)),this.setMaterialOrderData(this._material),this._material.setParameter("alphaClipForward",1/255),this.meshInstance&&(this.meshInstance.material=t))}get material(){return this._material}configureMaterial(t,e={}){this.resource.configureMaterial(t,null,this.resource.format.getInputDeclarations()),t.setDefine("{GSPLAT_INSTANCE_SIZE}",rt.instanceSize),t.setParameter("numSplats",0),this.setMaterialOrderData(t),t.setParameter("alphaClip",.3),t.setParameter("alphaClipForward",1/255),t.setParameter("minPixelSize",2),t.setDefine(`DITHER_${e.dither?"BLUENOISE":"NONE"}`,""),t.cull=0,t.blendType=e.dither?wt:Ms,t.depthWrite=!!e.dither}sort(t){if(this.sorter){let e=t.getWorldTransform();e.getTranslation(lm),e.getZ(cm);let s=this.meshInstance.node.getWorldTransform(),i=e8.invert(s);i.transformPoint(lm,lm),i.transformVector(cm,cm),(!lm.equalsApprox(this.lastCameraPosition)||!cm.equalsApprox(this.lastCameraDirection))&&(this.lastCameraPosition.copy(lm),this.lastCameraDirection.copy(cm),this.sorter.setCamera(lm,cm))}}update(){let t=this.sorter?.applyPendingSorted()??-1;if(t>=0&&(this.meshInstance.instancingCount=Math.ceil(t/rt.instanceSize),this.material.setParameter("numSplats",t)),this.cameras.length>0){let e=this.cameras[0];this.sort(e._node),this.resolveSH?.render(e._node,this.meshInstance.node.getWorldTransform()),this.cameras.length=0}}setHighQualitySH(t){let{resource:e}=this,{gsplatData:s}=e;s instanceof ca&&s.shBands>0&&t===!!this.resolveSH&&(this.resolveSH?(this.resolveSH.destroy(),this.resolveSH=null):this.resolveSH=new Wy(e.device,this))}};var S2=` uniform uint splatTextureSize; uniform uint dstTextureSize; uniform uint srcNumSplats; @@ -2028,7 +2296,7 @@ void main(void) { process(); } -`,fy=` +`;var x2=` uniform splatTextureSize: u32; uniform dstTextureSize: u32; uniform srcNumSplats: u32; @@ -2055,12 +2323,12 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return processOutput; } -`;class fx extends uj{configureMaterialDefines(e){e.set("SH_BANDS",this.shBands);}updateColorData(e){let t=this.streams.getTexture("splatColor");if(!t)return;let i=eh.float2Half,s=t.lock(),r=e.getProp("f_dc_0"),a=e.getProp("f_dc_1"),n=e.getProp("f_dc_2"),o=e.getProp("opacity");for(let e=0;e{let i=[];for(let s=0;s1&&(n[4*t+0]=f[9]<<21|f[10]<<11|f[11],n[4*t+1]=f[12]<<21|f[13]<<11|f[14],n[4*t+2]=f[15]<<21|f[16]<<11|f[17],n[4*t+3]=f[18]<<21|f[19]<<11|f[20],this.shBands>2?(o[4*t+0]=f[21]<<21|f[22]<<11|f[23],o[4*t+1]=f[24]<<21|f[25]<<11|f[26],o[4*t+2]=f[27]<<21|f[28]<<11|f[29],o[4*t+3]=f[30]<<21|f[31]<<11|f[32],l[4*t+0]=f[33]<<21|f[34]<<11|f[35],l[4*t+1]=f[36]<<21|f[37]<<11|f[38],l[4*t+2]=f[39]<<21|f[40]<<11|f[41],l[4*t+3]=f[42]<<21|f[43]<<11|f[44]):o[t]=f[21]<<21|f[22]<<11|f[23]);}}t.unlock(),i?.unlock(),s?.unlock(),r?.unlock();}constructor(e,t){super(e,t);let i=t.numSplats;this.shBands=t.shBands;let s=[{name:"splatColor",format:12},{name:"transformA",format:49},{name:"transformB",format:12}];this.shBands>0&&(s.push({name:"splatSH_1to3",format:49}),this.shBands>1&&(s.push({name:"splatSH_4to7",format:49}),this.shBands>2?(s.push({name:"splatSH_8to11",format:49}),s.push({name:"splatSH_12to15",format:49})):s.push({name:"splatSH_8to11",format:37}))),this._format=new cG(e,s,{readGLSL:'#include "gsplatUncompressedVS"',readWGSL:'#include "gsplatUncompressedVS"'}),this.streams.init(this.format,i),this.updateColorData(t),this.updateTransformData(t),this.shBands>0&&this.updateSHData(t);}}class fT extends uj{_actualDestroy(){this.streams.textures.delete("packedTexture"),this.streams.textures.delete("packedSh0"),this.streams.textures.delete("packedShN"),this.gsplatData.destroy(),super._actualDestroy();}_populateParameters(){let{meta:e}=this.gsplatData;e.means&&(this.parameters.set("means_mins",e.means.mins),this.parameters.set("means_maxs",e.means.maxs)),2===e.version?["scales","sh0","shN"].forEach(t=>{let i=e[t];i&&(this.parameters.set(`${t}_mins`,i.codebook[0]),this.parameters.set(`${t}_maxs`,i.codebook[255]));}):(["scales","sh0"].forEach(t=>{let i=e[t];i&&(this.parameters.set(`${t}_mins`,Math.min(...i.mins.slice(0,3))),this.parameters.set(`${t}_maxs`,Math.max(...i.maxs.slice(0,3))));}),["shN"].forEach(t=>{let i=e[t];i&&(this.parameters.set(`${t}_mins`,i.mins),this.parameters.set(`${t}_maxs`,i.maxs));}));}configureMaterialDefines(e){e.set("SH_BANDS",this.gsplatData.shBands);}constructor(e,t){super(e,t);let i=t.means_l||t.packedTexture;i&&this.streams.textureDimensions.set(i.width,i.height),t.packedTexture&&this.streams.textures.set("packedTexture",t.packedTexture),t.packedSh0&&this.streams.textures.set("packedSh0",t.packedSh0),t.packedShN&&this.streams.textures.set("packedShN",t.packedShN),this._format=new cG(e,[{name:"packedTexture",format:49}],{readGLSL:'#include "gsplatSogVS"',readWGSL:'#include "gsplatSogVS"'}),this._populateParameters();}}let fE="FILL_WINDOW",fw="KEEP_ASPECT",fb="AUTO",fC="FIXED",fA=false,fP={app:null,createLoadingScreen(e){fA||(fA=true,e(r));}};class fI{addRenderPass(e){e.frameUpdate();let t=e.beforePasses;for(let e=0;ee.clear)||i.afterPasses.length>0||r.beforePasses.length>0||(i._skipEnd=true,r._skipStart=true);}let i=null,s=null;for(let e=0;enew fD(t,t===i?null:i)),e.scope.resolve("areaLightsLutTex1").setValue(t),e.scope.resolve("areaLightsLutTex2").setValue(i);}static createPlaceholder(e){let t=fL.createTexture(e,12,2,"placeholder");t.lock().fill(0),t.unlock(),fL.applyTextures(e,t,t);}static set(e,t,i){function s(e,t,i){let s=fL.createTexture(e,i,64);return s.lock().set(t),s.unlock(),s}function r(e){let t=e.length,i=new Uint16Array(t),s=eh.float2Half;for(let r=0;r0),fN(["fa","hi"],e=>e>=0&&e<=1?0:1),fN(["fr","pt"],e=>e>=0&&e<2?0:1),fN(["da"],e=>1===e||!Number.isInteger(e)&&e>=0&&e<=1?0:1),fN(["de","en","it","el","es","tr","fi","sv","nb","no","ur"],e=>+(1!==e)),fN(["ru","uk"],e=>{if(Number.isInteger(e)){let t=e%10,i=e%100;if(1===t&&11!==i)return 0;if(t>=2&&t<=4&&(i<12||i>14))return 1;if(0===t||t>=5&&t<=9||i>=11&&i<=14)return 2}return 3}),fN(["pl"],e=>{if(Number.isInteger(e)){if(1===e)return 0;let t=e%10,i=e%100;if(t>=2&&t<=4&&(i<12||i>14))return 1;if(t>=0&&t<=1||t>=5&&t<=9||i>=12&&i<=14)return 2}return 3}),fN(["ar"],e=>{if(0===e)return 0;if(1===e)return 1;if(2===e)return 2;if(Number.isInteger(e)){let t=e%100;if(t>=3&&t<=10)return 3;if(t>=11&&t<=99)return 4}return 5});let fU=fF[fB(fM)],fz=RegExp("^\\s*(?:(?:[a-z]+[a-z0-9\\-+.]*:)?//|data:|blob:)","i");class fV{equals(e){return this.url===e.url&&this.filename===e.filename&&this.hash===e.hash&&this.size===e.size&&this.opt===e.opt&&this.contents===e.contents}constructor(e="",t="",i=null,s=null,r=null,a=null){this.url=e,this.filename=t,this.hash=i,this.size=s,this.opt=r,this.contents=a;}}let fG=-1,fH={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1",basis:"canvas"},fW=["pvr","dxt","etc2","etc1","basis"];class fX extends X{set name(e){if(this._name===e)return;let t=this._name;this._name=e,this.fire("name",this,this._name,t);}get name(){return this._name}set file(e){if(e&&e.variants&&-1!==["texture","textureatlas","bundle"].indexOf(this.type)){let t=this.registry?._loader?._app||r,i=t?.graphicsDevice;if(i)for(let s=0,r=fW.length;se?.file?.variants[r]))break}}}let t=this._file,i=e?new fV(e.url,e.filename,e.hash,e.size,e.opt,e.contents):null;(!!i!=!!t||i&&!i.equals(t))&&(this._file=i,this.fire("change",this,"file",i,t),this.reload());}get file(){return this._file}set data(e){let t=this._data;this._data=e,e!==t&&(this.fire("change",this,"data",e,t),this.loaded&&this.registry._loader.patch(this,this.registry));}get data(){return this._data}set resource(e){let t=this._resources[0];this._resources[0]=e,this.fire("change",this,"resource",e,t);}get resource(){return this._resources[0]}set resources(e){let t=this._resources;this._resources=e,this.fire("change",this,"resources",e,t);}get resources(){return this._resources}set preload(e){e=!!e,this._preload!==e&&(this._preload=e,this._preload&&!this.loaded&&!this.loading&&this.registry&&this.registry.load(this));}get preload(){return this._preload}set loadFaces(e){e=!!e,(!this.hasOwnProperty("_loadFaces")||e!==this._loadFaces)&&(this._loadFaces=e,this.loaded&&this.registry._loader.patch(this,this.registry));}get loadFaces(){return this._loadFaces}getFileUrl(){let e=this.file;if(!e||!e.url)return null;let t=e.url;if(this.registry&&this.registry.prefix&&!fz.test(t)&&(t=this.registry.prefix+t),"script"!==this.type&&e.hash){let i=-1!==t.indexOf("?")?"&":"?";t+=`${i}t=${e.hash}`;}return t}getAbsoluteUrl(e){if(e.startsWith("blob:")||e.startsWith("data:"))return e;let t=P.getDirectory(this.file.url);return P.join(t,e)}getLocalizedAssetId(e){return e=fk(e,this._i18n),this._i18n[e]||null}addLocalizedAssetId(e,t){this._i18n[e]=t,this.fire("add:localized",e,t);}removeLocalizedAssetId(e){let t=this._i18n[e];t&&(delete this._i18n[e],this.fire("remove:localized",e,t));}ready(e,t){t=t||this,this.loaded?e.call(t,this):this.once("load",i=>{e.call(t,i);});}reload(){this.loaded&&(this.loaded=false,this.registry.load(this));}unload(){if(!this.loaded&&0===this._resources.length)return;this.fire("unload",this),this.registry.fire(`unload:${this.id}`,this);let e=this._resources;this.urlObject&&(URL.revokeObjectURL(this.urlObject),this.urlObject=null),this.resources=[],this.loaded=false,this.file&&this.registry._loader.clearCache(this.getFileUrl(),this.type);for(let t=0;t{t(null,i.file.contents);}):a0.get(e,{cache:true,responseType:"arraybuffer",retry:s>0,maxRetries:s,progress:i},t);}constructor(e,t,i,s={},r={}){super(),this._file=null,this._i18n={},this._preload=false,this._resources=[],this.id=fG--,this.loaded=false,this.loading=false,this.options={},this.registry=null,this.tags=new Z(this),this.urlObject=null,this._name=e||"",this.type=t,this._data=s||{},this.options=r||{},i&&(this.file=i);}}fX.EVENT_LOAD="load",fX.EVENT_UNLOAD="unload",fX.EVENT_REMOVE="remove",fX.EVENT_ERROR="error",fX.EVENT_CHANGE="change",fX.EVENT_PROGRESS="progress",fX.EVENT_ADDLOCALIZED="add:localized",fX.EVENT_REMOVELOCALIZED="remove:localized";class fY{addItem(e){for(let t of e.tags._list)this.add(t,e);}removeItem(e){for(let t of e.tags._list)this.remove(t,e);}add(e,t){(!this._index[e]||-1===this._index[e].list.indexOf(t))&&(!this._index[e]&&(this._index[e]={list:[]},this._key&&(this._index[e].keys={})),this._index[e].list.push(t),this._key&&(this._index[e].keys[t[this._key]]=t));}remove(e,t){if(!this._index[e]||this._key&&!this._index[e].keys[t[this._key]])return;let i=this._index[e].list.indexOf(t);-1!==i&&(this._index[e].list.splice(i,1),this._key&&delete this._index[e].keys[t[this._key]],0===this._index[e].list.length&&delete this._index[e]);}find(e){let t,i,s,r,a,n={},o=[],l=(e,t)=>this._index[e].list.length-this._index[t].list.length;for(let h=0;ht.preload===e.preload):t}add(e){!this._assets.has(e)&&(this._assets.add(e),this._idToAsset.set(e.id,e),e.file?.url&&this._urlToAsset.set(e.file.url,e),this._nameToAsset.has(e.name)||this._nameToAsset.set(e.name,new Set),this._nameToAsset.get(e.name).add(e),e.on("name",this._onNameChange,this),e.registry=this,this._tags.addItem(e),e.tags.on("add",this._onTagAdd,this),e.tags.on("remove",this._onTagRemove,this),this.fire("add",e),this.fire(`add:${e.id}`,e),e.file?.url&&this.fire(`add:url:${e.file.url}`,e),e.preload&&this.load(e));}remove(e){if(!this._assets.has(e))return false;if(this._assets.delete(e),this._idToAsset.delete(e.id),e.file?.url&&this._urlToAsset.delete(e.file.url),e.off("name",this._onNameChange,this),this._nameToAsset.has(e.name)){let t=this._nameToAsset.get(e.name);t.delete(e),0===t.size&&this._nameToAsset.delete(e.name);}return this._tags.removeItem(e),e.tags.off("add",this._onTagAdd,this),e.tags.off("remove",this._onTagRemove,this),e.fire("remove",e),this.fire("remove",e),this.fire(`remove:${e.id}`,e),e.file?.url&&this.fire(`remove:url:${e.file.url}`,e),true}get(e){return this._idToAsset.get(Number(e))}getByUrl(e){return this._urlToAsset.get(e)}load(e,t){if((e.loading||e.loaded)&&!t?.force)return;let i=e.file,s=()=>{this.fire("load",e),this.fire(`load:${e.id}`,e),i&&i.url&&this.fire(`load:url:${i.url}`,e),e.fire("load",e);},r=t=>{if(t instanceof Array?e.resources=t:e.resource=t,this._loader.patch(e,this),"bundle"===e.type){let t=e.data.assets;for(let e=0;e{if(e.loaded=true,e.loading=false,t)this.fire("error",t,e),this.fire(`error:${e.id}`,t,e),e.fire("error",t,e);else {if("script"===e.type){let t=this._loader.getHandler("script");t._cache[e.id]&&t._cache[e.id].parentNode===document.head&&document.head.removeChild(t._cache[e.id]),s&&(t._cache[e.id]=s);}r(i);}};if(i||"cubemap"===e.type){this.fire("load:start",e),this.fire(`load:${e.id}:start`,e),e.loading=true;let i=e.getFileUrl();if("bundle"===e.type){let t=e.data.assets;for(let e=0;e{e.once("load",e=>{"material"===i?this._loadTextures(e,(t,i)=>{s(t,e);}):s(null,e);}),e.once("error",t=>{t&&(this.loadFromUrlError=t),s(t,e);}),this.load(e);};a.resource?s(null,a):"model"===i?this._loadModel(a,n):n(a);}_loadModel(e,t){let i=e.getFileUrl(),s=P.getExtension(i);if(".json"===s||".glb"===s){let r=P.getDirectory(i),a=P.getBasename(i),n=P.join(r,a.replace(s,".mapping.json"));this._loader.load(n,"json",(i,s)=>{i?(e.data={mapping:[]},t(e)):this._loadMaterials(e,s,(i,r)=>{e.data=s,t(e);});});}else t(e);}_loadMaterials(e,t,i){let s=[],r=0,a=(e,t)=>{this._loadTextures(t,(e,a)=>{s.push(t),s.length===r&&i(null,s);});};for(let i=0;i{i.push(r),i.length===s&&t(null,i);};for(let t=0;te(t))}find(e,t){let i=this._nameToAsset.get(e);if(!i)return null;for(let e of i)if(!t||e.type===t)return e;return null}findAll(e,t){let i=this._nameToAsset.get(e);if(!i)return [];let s=Array.from(i);return t?s.filter(e=>e.type===t):s}log(){}constructor(e){super(),this._assets=new Set,this._idToAsset=new Map,this._urlToAsset=new Map,this._nameToAsset=new Map,this._tags=new fY("id"),this.prefix=null,this.bundles=null,this._loader=e;}}fq.EVENT_LOAD="load",fq.EVENT_ADD="add",fq.EVENT_REMOVE="remove",fq.EVENT_ERROR="error";class fj{_onAssetAdd(e){if("bundle"===e.type){this._idToBundle.set(e.id,e),this._assets.on(`load:start:${e.id}`,this._onBundleLoadStart,this),this._assets.on(`load:${e.id}`,this._onBundleLoad,this),this._assets.on(`error:${e.id}`,this._onBundleError,this);let t=e.data.assets;for(let i=0;i{let i=this._fileRequests.get(e);if(i){for(let e=0;e{this.pump(e.done,e.value);}).catch(e=>{this.fire("error",e);})}readFile(){if(!this.headerRead&&this.bytesReceived>this.bytesRead+this.headerSize){this.headerRead=true;let e=new DataView(this.data.buffer,this.bytesRead,this.headerSize);this.decoder??(this.decoder=new TextDecoder("windows-1252"));let t=this.decoder.decode(e);if(this.fileName=t.substring(0,100).replace(/\0/g,""),this.fileSize=parseInt(t.substring(124,136),8),this.fileType=t.substring(156,157),this.ustarFormat=t.substring(257,263),-1!==this.ustarFormat.indexOf("ustar")){let e=t.substring(345,500).replace(/\0/g,"");e.length>0&&(this.fileName=e.trim()+this.fileName.trim());}this.bytesRead+=512;}if(this.headerRead){if(this.bytesReceived{this.pump(e.done,e.value);}).catch(e=>{this.fire("error",e);});}}class fQ{set maxRetries(e){this._maxRetries=e;}get maxRetries(){return this._maxRetries}load(e,t,i){}open(e,t,i){return t}patch(e,t){}constructor(e,t){this.handlerType="",this._maxRetries=0,this._app=e,this.handlerType=t;}}class fJ extends fQ{_fetchRetries(e,t,i=0){return new Promise((s,r)=>{let a=()=>{fetch(e,t).then(s).catch(e=>{++i{let i=new f$;t(null,i);let s=new fZ(e,this._assets.prefix);s.on("file",e=>{i.addFile(e.name,e.data);}),s.on("done",()=>{i.loaded=true;}),s.on("error",e=>{t(e);});}).catch(e=>{t(e);});}open(e,t){return t}constructor(e){super(e,"bundle"),this._assets=e.assets;}}class f0{addHandler(e,t){this._handlers[e]=t,t._loader=this;}removeHandler(e){delete this._handlers[e];}getHandler(e){return this._handlers[e]}static makeKey(e,t){return `${e}-${t}`}load(e,t,i,s,r){let a=this._handlers[t];if(!a)return void i(`No resource handler for asset type: '${t}' when loading [${e}]`);if(!e)return void this._loadNull(a,i,s);let n=f0.makeKey(e,t);if(void 0!==this._cache[n])i(null,this._cache[n]);else if(this._requests[n])this._requests[n].push(i);else {this._requests[n]=[i];let t=this,o=function(e,i){if(e)return void t._onFailure(n,e);if(i.load instanceof DataView){if(a.openBinary){if(!t._requests[n])return;try{let e=a.openBinary(i.load);t._onSuccess(n,e);}catch(e){t._onFailure(n,e);}return}i.load=URL.createObjectURL(new Blob([i.load])),s&&(s.urlObject&&URL.revokeObjectURL(s.urlObject),s.urlObject=i.load);}a.load(i,(e,r,o)=>{if(t._requests[n]){if(e)return void t._onFailure(n,e);try{t._onSuccess(n,a.open(i.original,r,s),o);}catch(e){t._onFailure(n,e);}}},s);},l=e.split("?")[0];if(this._app.enableBundles&&this._app.bundles.hasUrl(l)&&!(r&&r.bundlesIgnore)){if(!this._app.bundles.urlIsLoadedOrLoading(l)){let e,t=this._app.bundles.listBundlesForAsset(s);r&&r.bundlesFilter&&(e=r.bundlesFilter(t)),e||(t?.sort((e,t)=>e.file.size-t.file.size),e=t?.[0]),e&&this._app.assets?.load(e);}this._app.bundles.loadUrl(l,(e,t)=>{o(e,{load:t,original:l});});}else o(null,{load:e,original:s&&s.file.filename||e});}}_loadNull(e,t,i){e.load(null,function(s,r,a){if(s)t(s);else try{t(null,e.open(null,r,i),a);}catch(e){t(e);}},i);}_onSuccess(e,t,i){null!==t?this._cache[e]=t:delete this._cache[e];for(let s=0;s{if(e.prototype.swap){let i=this._scripts[t],s=this._list.indexOf(i);this._list[s]=e,this._scripts[t]=e,this.fire("swap",t,e),this.fire(`swap:${t}`,e);}}),false):(this._scripts[t]=e,this._list.push(e),this.fire("add",t,e),this.fire(`add:${t}`,e),setTimeout(()=>{let e;if(!this._scripts.hasOwnProperty(t)||!this.app||!this.app.systems||!this.app.systems.script)return;let i=this.app.systems.script._components,s=[],r=[];for(i.loopIndex=0;i.loopIndexe.constructor.order-t.constructor.order,f5=[],f6=[],f8=e=>{e.length=0,f6.push(e);};class f9 extends oJ{addComponent(e,t){let i=this._app.systems[e];return !i||this.c[e]?null:i.addComponent(this,t)}removeComponent(e){let t=this._app.systems[e];!t||this.c[e]&&t.removeComponent(this);}findComponent(e){let t=this.findOne(t=>t.c?.[e]);return t&&t.c[e]}findComponents(e){return this.find(t=>t.c?.[e]).map(t=>t.c[e])}findScript(e){let t=this.findOne(t=>t.c?.script?.has(e));return t?.c.script.get(e)}findScripts(e){return this.find(t=>t.c?.script?.has(e)).map(t=>t.c.script.get(e))}getGuid(){return this._guid||this.setGuid(A.create()),this._guid}setGuid(e){let t=this._app._entityIndex;this._guid&&delete t[this._guid],this._guid=e,t[this._guid]=this;}_notifyHierarchyStateChanged(e,t){let i=false;e===this&&0===f5.length&&(i=true),e._beingEnabled=true,e._onHierarchyStateChanged(t),e._onHierarchyStatePostChanged&&f5.push(e);let s=e._children;for(let e=0,i=s.length;ee instanceof f9),o=s.children.filter(e=>e instanceof f9);for(let i=0,s=n.length;i1&&t.sort(f4),t}_cloneRecursively(e){let t=new this.constructor(void 0,this._app);for(let e in super._cloneInternal(t),this.c)this.c[e].system.cloneComponent(this,t);for(let i=0;i{e.data=s,e._loading=false;for(let t=0;t{if(e){i&&i(e);return}t&&t(s);let r=this._app;r._preloadScripts(s.data,()=>{let e=r.loader.getHandler("hierarchy");r.systems.script.preloading=true;let t=e.open(s.url,s.data);r.systems.script.preloading=false,r.loader.clearCache(s.url,"hierarchy"),r.root.addChild(t),r.systems.fire("initialize",t),r.systems.fire("postInitialize",t),r.systems.fire("postPostInitialize",t),i&&i(null,t);});});}loadSceneHierarchy(e,t){this._loadSceneHierarchy(e,null,t);}loadSceneSettings(e,t){this._loadSceneData(e,false,(e,i)=>{e?t&&t(e):(this._app.applySceneSettings(i.data.settings),t&&t(null));});}changeScene(e,t){let i=this._app;this._loadSceneHierarchy(e,e=>{let{children:t}=i.root;for(;t.length;)t[0].destroy();i.applySceneSettings(e.data.settings);},t);}loadScene(e,t){let i=this._app,s=i.loader.getHandler("scene");i.assets&&i.assets.prefix&&!fz.test(e)&&(e=P.join(i.assets.prefix,e)),s.load(e,(r,a)=>{if(r)t&&t(r);else {let r=()=>{i.systems.script.preloading=true;let r=s.open(e,a),n=this.findByUrl(e);n&&!n.loaded&&(n.data=a),i.systems.script.preloading=false,i.loader.clearCache(e,"scene"),i.loader.patch({resource:r,type:"scene"},i.assets),i.root.addChild(r.root),i.systems.rigidbody&&"u">typeof Ammo&&i.systems.rigidbody.gravity.set(r._gravity.x,r._gravity.y,r._gravity.z),t&&t(null,r);};i._preloadScripts(a,r);}});}constructor(e){this._list=[],this._index={},this._urlIndex={},this._app=e;}}class pt{get scene(){return r.scene._stats}get lightmapper(){return r.lightmapper?.stats}get batcher(){let e=r._batcher;return e?e._stats:null}frameEnd(){this.frame.gsplatSort=0;}constructor(e){this.frame={fps:0,ms:0,dt:0,updateStart:0,updateTime:0,renderStart:0,renderTime:0,physicsStart:0,physicsTime:0,scriptUpdateStart:0,scriptUpdate:0,scriptPostUpdateStart:0,scriptPostUpdate:0,animUpdateStart:0,animUpdate:0,cullTime:0,sortTime:0,skinTime:0,morphTime:0,instancingTime:0,triangles:0,gsplats:0,gsplatSort:0,gsplatBufferCopy:0,otherPrimitives:0,shaders:0,materials:0,cameras:0,shadowMapUpdates:0,shadowMapTime:0,depthMapTime:0,forwardTime:0,lightClustersTime:0,lightClusters:0,_timeToCountFrames:0,_fpsAccum:0},this.drawCalls={forward:0,depth:0,shadow:0,immediate:0,misc:0,total:0,skinned:0,instanced:0,removedByInstancing:0},this.misc={renderTargetCreationTime:0},this.particles={updatesPerFrame:0,_updatesPerFrame:0,frameTime:0,_frameTime:0},this.shaders=e._shaderStats,this.vram=e._vram,this.gpu=e.gpuProfiler?.passTimings??new Map,Object.defineProperty(this.vram,"totalUsed",{get:function(){return this.tex+this.vb+this.ib+this.ub+this.sb}}),Object.defineProperty(this.vram,"geom",{get:function(){return this.vb+this.ib}}),Object.defineProperty(this.vram,"buffers",{get:function(){return this.ub+this.sb}});}}let pi={alphaTestPS:` +`;var Yy=class{constructor(t,e,s,i){n(this,"_device");n(this,"_source");n(this,"_destination");n(this,"_srcResource");n(this,"_dstResource");n(this,"_dstStreamDescriptors");n(this,"_dstStreamNames");n(this,"_useAllInputStreams");n(this,"_srcTextures",[]);n(this,"_renderTarget",null);n(this,"_quadRender",null);n(this,"_renderPass",null);n(this,"_parameters",new Map);n(this,"blendState",Oe.NOBLEND);this._device=t,this._source=e,this._destination=s,this._srcResource=e.resource??e.component?.resource,this._dstResource=s.resource??s.component?.resource,this._dstStreamDescriptors=[],this._dstStreamNames=new Set;for(let o of s.streams){let l=this._dstResource.format.getStream(o);l&&(this._dstStreamDescriptors.push(l),this._dstStreamNames.add(l.name))}this._useAllInputStreams=!e.streams?.length;let r=this._srcResource.format,a=this._useAllInputStreams?[...r.streams,...r.extraStreams]:e.streams.map(o=>({name:o}));for(let o of a){let l=this._resolveTexture(e,o.name,this._srcResource);this._srcTextures.push({name:o.name,texture:l})}this._createRenderTarget(),this._createShader(i),this._renderPass=new Ut(t),this._renderPass.quadRender=this._quadRender,this._renderPass.init(this._renderTarget),this._renderPass.colorOps.clear=!1,this._renderPass.depthStencilOps.clearDepth=!1}destroy(){this._renderTarget?.destroy(),this._renderTarget=null,this._quadRender?.destroy(),this._quadRender=null,this._renderPass?.destroy(),this._renderPass=null,this._parameters.clear()}_resolveTexture(t,e,s){if(t.component&&s.format.getStream(e)?.storage===Vf){let a=t.component.getInstanceTexture(e);if(a)return a}let i=s.getTexture(e);return i}_createRenderTarget(){let t=[];for(let e of this._dstStreamDescriptors){let s=this._resolveTexture(this._destination,e.name,this._dstResource);s&&t.push(s)}t.length>0&&(this._renderTarget=new me({name:"GSplatProcessor-MRT",colorBuffers:t,depth:!1,flipY:!0}))}_createShader(t){let{processGLSL:e="",processWGSL:s=""}=t,i=this._device,r=this._srcResource.format,a=this._dstResource.format,o="",l="";if(this._useAllInputStreams){let g=[...r.streams,...r.extraStreams],T=this._srcResource===this._dstResource,C=g.filter(v=>!T||!this._dstStreamNames.has(v.name)).map(v=>v.name);o=r.getInputDeclarations(C),l=r.getReadCode()}else o=r.getInputDeclarations(this._source.streams);let h=a.getOutputDeclarations(this._dstStreamDescriptors),f=this._dstStreamDescriptors.map(g=>An(g.format).returnType),u=new Map;this._srcResource.configureMaterialDefines(u),u.set("SH_BANDS","0");let d=i.isWebGPU,p=new Map;p.set("gsplatProcessInputVS",o),p.set("gsplatProcessOutputVS",h),p.set("gsplatProcessReadVS",l),p.set("gsplatProcessChunk",d?s:e);let m=xt([d?s:e,this._useAllInputStreams?"1":"0"].join("|")),_=this._dstStreamDescriptors.map(g=>g.name).join(","),S=Se.createShader(i,{uniqueName:`GSplatProcessor:${r.hash};${m};out=${_}`,attributes:{vertex_position:ee},vertexDefines:u,fragmentDefines:u,vertexChunk:"fullscreenQuadVS",fragmentGLSL:S2,fragmentWGSL:x2,fragmentIncludes:p,fragmentOutputTypes:f});this._quadRender=new hs(S)}setParameter(t,e){let s=this._device.scope.resolve(t);this._parameters.set(t,{scopeId:s,data:e})}getParameter(t){return this._parameters.get(t)?.data}deleteParameter(t){this._parameters.delete(t)}process(){if(!this._renderPass)return;let t=this._device;for(let{name:e,texture:s}of this._srcTextures)t.scope.resolve(e).setValue(s);t.scope.resolve("splatTextureSize").setValue(this._srcResource.textureDimensions.x),t.scope.resolve("dstTextureSize").setValue(this._dstResource.textureDimensions.x),t.scope.resolve("srcNumSplats").setValue(this._srcResource.numSplats),t.scope.resolve("dstNumSplats").setValue(this._dstResource.numSplats);for(let[e,s]of this._srcResource.parameters)t.scope.resolve(e).setValue(s);for(let[,e]of this._parameters)e.scopeId.setValue(e.data);this._renderPass.blendState=this.blendState,this._renderPass.render()}};var t8=(c,t)=>{let e=[];for(let s=0;s0&&(a.push({name:"splatSH_1to3",format:At}),this.shBands>1&&(a.push({name:"splatSH_4to7",format:At}),this.shBands>2?(a.push({name:"splatSH_8to11",format:At}),a.push({name:"splatSH_12to15",format:At})):a.push({name:"splatSH_8to11",format:zt}))),this._format=new Pr(e,a,{readGLSL:'#include "gsplatUncompressedVS"',readWGSL:'#include "gsplatUncompressedVS"'}),this.streams.init(this.format,r),this.updateColorData(s),this.updateTransformData(s),this.shBands>0&&this.updateSHData(s)}configureMaterialDefines(e){e.set("SH_BANDS",this.shBands)}updateColorData(e){let s=this.streams.getTexture("splatColor");if(!s)return;let i=Hs.float2Half,r=s.lock(),a=e.getProp("f_dc_0"),o=e.getProp("f_dc_1"),l=e.getProp("f_dc_2"),h=e.getProp("opacity"),f=.28209479177387814;for(let u=0;u1&&(l[T*4+0]=g[9]<<21|g[10]<<11|g[11],l[T*4+1]=g[12]<<21|g[13]<<11|g[14],l[T*4+2]=g[15]<<21|g[16]<<11|g[17],l[T*4+3]=g[18]<<21|g[19]<<11|g[20],this.shBands>2?(h[T*4+0]=g[21]<<21|g[22]<<11|g[23],h[T*4+1]=g[24]<<21|g[25]<<11|g[26],h[T*4+2]=g[27]<<21|g[28]<<11|g[29],h[T*4+3]=g[30]<<21|g[31]<<11|g[32],f[T*4+0]=g[33]<<21|g[34]<<11|g[35],f[T*4+1]=g[36]<<21|g[37]<<11|g[38],f[T*4+2]=g[39]<<21|g[40]<<11|g[41],f[T*4+3]=g[42]<<21|g[43]<<11|g[44]):h[T]=g[21]<<21|g[22]<<11|g[23])}}s.unlock(),i?.unlock(),r?.unlock(),a?.unlock()}};var jc=class extends rt{constructor(t,e,s={}){super(t,e,s);let{meta:i,means_l:r}=e,a=i.version===2,o=e.shBands>0;r&&this.streams.textureDimensions.set(r.width,r.height),this.streams.textures.set("means_l",e.means_l),this.streams.textures.set("means_u",e.means_u),this.streams.textures.set("quats",e.quats),this.streams.textures.set("scales",e.scales),this.streams.textures.set("sh0",e.sh0),o&&(this.streams.textures.set("sh_labels",e.sh_labels),this.streams.textures.set("sh_centroids",e.sh_centroids)),a&&this.streams.textures.set("sogCodebook",e.codebookTexture);let l=[{name:"means_l",format:ce},{name:"means_u",format:ce},{name:"quats",format:ce},{name:"scales",format:ce},{name:"sh0",format:ce}];o&&(l.push({name:"sh_labels",format:ce}),l.push({name:"sh_centroids",format:ce})),a&&l.push({name:"sogCodebook",format:ke}),this._format=new Pr(t,l,{readGLSL:'#include "gsplatSogVS"',readWGSL:'#include "gsplatSogVS"'}),this._populateParameters()}releaseTextureSources(){let t=this.gsplatData;t.means_l?.setReleaseSourceAfterUpload(),t.means_u?.setReleaseSourceAfterUpload(),t.quats?.setReleaseSourceAfterUpload(),t.scales?.setReleaseSourceAfterUpload(),t.sh0?.setReleaseSourceAfterUpload(),t.sh_centroids?.setReleaseSourceAfterUpload(),t.sh_labels?.setReleaseSourceAfterUpload()}_actualDestroy(){this.streams.textures.delete("means_l"),this.streams.textures.delete("means_u"),this.streams.textures.delete("quats"),this.streams.textures.delete("scales"),this.streams.textures.delete("sh0"),this.streams.textures.delete("sh_labels"),this.streams.textures.delete("sh_centroids"),this.streams.textures.delete("sogCodebook"),this.gsplatData.destroy(),super._actualDestroy()}_populateParameters(){let{meta:t}=this.gsplatData;t.means&&(this.parameters.set("means_mins",t.means.mins),this.parameters.set("means_maxs",t.means.maxs)),t.version!==2&&(t.scales&&(this.parameters.set("scales_mins",t.scales.mins),this.parameters.set("scales_maxs",t.scales.maxs)),t.sh0&&(this.parameters.set("sh0_mins",t.sh0.mins),this.parameters.set("sh0_maxs",t.sh0.maxs)),t.shN&&(this.parameters.set("shN_mins",t.shN.mins),this.parameters.set("shN_maxs",t.shN.maxs)))}configureMaterialDefines(t){let e=this.gsplatData;t.set("SH_BANDS",e.shBands),e.meta.version===2&&t.set("SOG_V2","")}};var s8="NONE",bI="FILL_WINDOW",Ky="KEEP_ASPECT",jy="AUTO",DI="FIXED";var v2;function ys(){return v2}function qy(c){v2=c}var T2=!1,fm={app:null,createLoadingScreen(c){if(T2)return;T2=!0;let t=ys();c(t)}};var $y=class{constructor(){n(this,"renderPasses",[]);n(this,"renderTargetMap",new Map);n(this,"multiview",null)}beginMultiView(t){this.multiview=new Zf(t)}endMultiView(){let t=this.multiview;this.multiview=null,t?.children.length&&this.renderPasses.push(t)}addRenderPass(t){t.frameUpdate();let e=t.beforePasses;for(let i=0;if.clear)||a.afterPasses.length>0||l.beforePasses.length>0||(a._skipEnd=!0,l._skipStart=!0)}let s=null,i=null;for(let r=0;rnew LI(e,e===s?null:s)),t.scope.resolve("areaLightsLutTex1").setValue(e),t.scope.resolve("areaLightsLutTex2").setValue(s)}static createPlaceholder(t){let e=c.createTexture(t,Me,2,"placeholder");e.lock().fill(0),e.unlock(),c.applyTextures(t,e,e)}static set(t,e,s){function i(d,p,m){let _=c.createTexture(d,m,64);return _.lock().set(p),_.unlock(),_}function r(d){let p=d.length,m=new Uint16Array(p),_=Hs.float2Half;for(let S=0;S0);qc(["fa","hi"],c=>c>=0&&c<=1?0:1);qc(["fr","pt"],c=>c>=0&&c<2?0:1);qc(["da"],c=>c===1||!Number.isInteger(c)&&c>=0&&c<=1?0:1);qc(["de","en","it","el","es","tr","fi","sv","nb","no","ur"],c=>c===1?0:1);qc(["ru","uk"],c=>{if(Number.isInteger(c)){let t=c%10,e=c%100;if(t===1&&e!==11)return 0;if(t>=2&&t<=4&&(e<12||e>14))return 1;if(t===0||t>=5&&t<=9||e>=11&&e<=14)return 2}return 3});qc(["pl"],c=>{if(Number.isInteger(c)){if(c===1)return 0;let t=c%10,e=c%100;if(t>=2&&t<=4&&(e<12||e>14))return 1;if(t>=0&&t<=1||t>=5&&t<=9||e>=12&&e<=14)return 2}return 3});qc(["ar"],c=>{if(c===0)return 0;if(c===1)return 1;if(c===2)return 2;if(Number.isInteger(c)){let t=c%100;if(t>=3&&t<=10)return 3;if(t>=11&&t<=99)return 4}return 5});var i8=MI[Zo(um)];function Qy(c){return MI[c]||i8}var Ja=new RegExp("^\\s*(?:(?:[a-z]+[a-z0-9\\-+.]*:)?//|data:|blob:)","i"),r8="animation",a8="audio",o8="image",n8="json",l8="model",c8="material",h8="text",f8="texture",u8="textureatlas",d8="cubemap",p8="shader",m8="css",_8="html",g8="script",S8="container";var Jy=class{constructor(t="",e="",s=null,i=null,r=null,a=null){this.url=t,this.filename=e,this.hash=s,this.size=i,this.opt=r,this.contents=a}equals(t){return this.url===t.url&&this.filename===t.filename&&this.hash===t.hash&&this.size===t.size&&this.opt===t.opt&&this.contents===t.contents}};var x8=-1,v8={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1",basis:"canvas"},A2=["pvr","dxt","etc2","etc1","basis"],ae=class extends J{constructor(e,s,i,r={},a={}){super();n(this,"_file",null);n(this,"_i18n",{});n(this,"_preload",!1);n(this,"_resources",[]);n(this,"id",x8--);n(this,"loaded",!1);n(this,"loading",!1);n(this,"options",{});n(this,"registry",null);n(this,"tags",new va(this));n(this,"type");n(this,"urlObject",null);this._name=e||"",this.type=s,this._data=r||{},this.options=a||{},i&&(this.file=i)}set name(e){if(this._name===e)return;let s=this._name;this._name=e,this.fire("name",this,this._name,s)}get name(){return this._name}set file(e){if(e&&e.variants&&["texture","textureatlas","bundle"].indexOf(this.type)!==-1){let r=this.registry?._loader?._app||ys(),a=r?.graphicsDevice;if(a)for(let o=0,l=A2.length;ou?.file?.variants[h]))break}}}let s=this._file,i=e?new Jy(e.url,e.filename,e.hash,e.size,e.opt,e.contents):null;(!!i!=!!s||i&&!i.equals(s))&&(this._file=i,this.fire("change",this,"file",i,s),this.reload())}get file(){return this._file}set data(e){let s=this._data;this._data=e,e!==s&&(this.fire("change",this,"data",e,s),this.loaded&&this.registry._loader.patch(this,this.registry))}get data(){return this._data}set resource(e){let s=this._resources[0];this._resources[0]=e,this.fire("change",this,"resource",e,s)}get resource(){return this._resources[0]}set resources(e){let s=this._resources;this._resources=e,this.fire("change",this,"resources",e,s)}get resources(){return this._resources}set preload(e){e=!!e,this._preload!==e&&(this._preload=e,this._preload&&!this.loaded&&!this.loading&&this.registry&&this.registry.load(this))}get preload(){return this._preload}set loadFaces(e){e=!!e,(!this.hasOwnProperty("_loadFaces")||e!==this._loadFaces)&&(this._loadFaces=e,this.loaded&&this.registry._loader.patch(this,this.registry))}get loadFaces(){return this._loadFaces}getFileUrl(){let e=this.file;if(!e||!e.url)return null;let s=e.url;if(this.registry&&this.registry.prefix&&!Ja.test(s)&&(s=this.registry.prefix+s),this.type!=="script"&&e.hash){let i=s.indexOf("?")!==-1?"&":"?";s+=`${i}t=${e.hash}`}return s}getAbsoluteUrl(e){if(e.startsWith("blob:")||e.startsWith("data:"))return e;let s=xe.getDirectory(this.file.url);return xe.join(s,e)}getLocalizedAssetId(e){return e=Zy(e,this._i18n),this._i18n[e]||null}addLocalizedAssetId(e,s){this._i18n[e]=s,this.fire("add:localized",e,s)}removeLocalizedAssetId(e){let s=this._i18n[e];s&&(delete this._i18n[e],this.fire("remove:localized",e,s))}ready(e,s){s=s||this,this.loaded?e.call(s,this):this.once("load",i=>{e.call(s,i)})}reload(){this.loaded&&(this.loaded=!1,this.registry.load(this))}unload(){if(!this.loaded&&this._resources.length===0)return;this.fire("unload",this),this.registry.fire(`unload:${this.id}`,this);let e=this._resources;this.urlObject&&(URL.revokeObjectURL(this.urlObject),this.urlObject=null),this.resources=[],this.loaded=!1,this.file&&this.registry._loader.clearCache(this.getFileUrl(),this.type);for(let s=0;s{s(null,i.file.contents)}):Le.get(e,{cache:!0,responseType:"arraybuffer",retry:r>0,maxRetries:r,progress:i},s)}};n(ae,"EVENT_LOAD","load"),n(ae,"EVENT_UNLOAD","unload"),n(ae,"EVENT_REMOVE","remove"),n(ae,"EVENT_ERROR","error"),n(ae,"EVENT_CHANGE","change"),n(ae,"EVENT_PROGRESS","progress"),n(ae,"EVENT_ADDLOCALIZED","add:localized"),n(ae,"EVENT_REMOVELOCALIZED","remove:localized");var e0=class{constructor(t=null){n(this,"_index",{});n(this,"_key");this._key=t}addItem(t){let e=t.tags._list;for(let s of e)this.add(s,t)}removeItem(t){let e=t.tags._list;for(let s of e)this.remove(s,t)}add(t,e){this._index[t]&&this._index[t].list.indexOf(e)!==-1||(this._index[t]||(this._index[t]={list:[]},this._key&&(this._index[t].keys={})),this._index[t].list.push(e),this._key&&(this._index[t].keys[e[this._key]]=e))}remove(t,e){if(!this._index[t]||this._key&&!this._index[t].keys[e[this._key]])return;let s=this._index[t].list.indexOf(e);s!==-1&&(this._index[t].list.splice(s,1),this._key&&delete this._index[t].keys[e[this._key]],this._index[t].list.length===0&&delete this._index[t])}find(t){let e={},s=[],i,r,a,o,l,h=(f,u)=>this._index[f].list.length-this._index[u].list.length;for(let f=0;fi.preload===e.preload):s}add(e){this._assets.has(e)||(this._assets.add(e),this._idToAsset.set(e.id,e),e.file?.url&&this._urlToAsset.set(e.file.url,e),this._nameToAsset.has(e.name)||this._nameToAsset.set(e.name,new Set),this._nameToAsset.get(e.name).add(e),e.on("name",this._onNameChange,this),e.registry=this,this._tags.addItem(e),e.tags.on("add",this._onTagAdd,this),e.tags.on("remove",this._onTagRemove,this),this.fire("add",e),this.fire(`add:${e.id}`,e),e.file?.url&&this.fire(`add:url:${e.file.url}`,e),e.preload&&this.load(e))}remove(e){if(!this._assets.has(e))return!1;if(this._assets.delete(e),this._idToAsset.delete(e.id),e.file?.url&&this._urlToAsset.delete(e.file.url),e.off("name",this._onNameChange,this),this._nameToAsset.has(e.name)){let s=this._nameToAsset.get(e.name);s.delete(e),s.size===0&&this._nameToAsset.delete(e.name)}return this._tags.removeItem(e),e.tags.off("add",this._onTagAdd,this),e.tags.off("remove",this._onTagRemove,this),e.fire("remove",e),this.fire("remove",e),this.fire(`remove:${e.id}`,e),e.file?.url&&this.fire(`remove:url:${e.file.url}`,e),!0}get(e){return this._idToAsset.get(Number(e))}getByUrl(e){return this._urlToAsset.get(e)}load(e,s){if((e.loading||e.loaded)&&!s?.force)return;let i=e.file,r=()=>{this.fire("load",e),this.fire(`load:${e.id}`,e),i&&i.url&&this.fire(`load:url:${i.url}`,e),e.fire("load",e)},a=l=>{if(l instanceof Array?e.resources=l:e.resource=l,this._loader.patch(e,this),e.type==="bundle"){let h=e.data.assets;for(let f=0;f{if(e.loaded=!0,e.loading=!1,l)this.fire("error",l,e),this.fire(`error:${e.id}`,l,e),e.fire("error",l,e);else{if(e.type==="script"){let u=this._loader.getHandler("script");u._cache[e.id]&&u._cache[e.id].parentNode===document.head&&document.head.removeChild(u._cache[e.id]),f&&(u._cache[e.id]=f)}a(h)}};if(i||e.type==="cubemap"){this.fire("load:start",e),this.fire(`load:${e.id}:start`,e),e.loading=!0;let l=e.getFileUrl();if(e.type==="bundle"){let h=e.data.assets;for(let f=0;f{f.once("load",u=>{i==="material"?this._loadTextures(u,(d,p)=>{r(d,u)}):r(null,u)}),f.once("error",u=>{u&&(this.loadFromUrlError=u),r(u,f)}),this.load(f)};l.resource?r(null,l):i==="model"?this._loadModel(l,h):h(l)}_loadModel(e,s){let i=e.getFileUrl(),r=xe.getExtension(i);if(r===".json"||r===".glb"){let a=xe.getDirectory(i),o=xe.getBasename(i),l=xe.join(a,o.replace(r,".mapping.json"));this._loader.load(l,"json",(h,f)=>{h?(e.data={mapping:[]},s(e)):this._loadMaterials(e,f,(u,d)=>{e.data=f,s(e)})})}else s(e)}_loadMaterials(e,s,i){let r=[],a=0,o=(l,h)=>{this._loadTextures(h,(f,u)=>{r.push(h),r.length===a&&i(null,r)})};for(let l=0;l{i.push(f),i.length===r&&s(null,i)},l=qf;for(let h=0;he(s))}find(e,s){let i=this._nameToAsset.get(e);if(!i)return null;for(let r of i)if(!s||r.type===s)return r;return null}findAll(e,s){let i=this._nameToAsset.get(e);if(!i)return[];let r=Array.from(i);return s?r.filter(a=>a.type===s):r}log(){}};n(ha,"EVENT_LOAD","load"),n(ha,"EVENT_ADD","add"),n(ha,"EVENT_REMOVE","remove"),n(ha,"EVENT_ERROR","error");var pm=class{constructor(t){n(this,"_idToBundle",new Map);n(this,"_assetToBundles",new Map);n(this,"_urlsToBundles",new Map);n(this,"_fileRequests",new Map);this._assets=t,this._assets.bundles=this,this._assets.on("add",this._onAssetAdd,this),this._assets.on("remove",this._onAssetRemove,this)}_onAssetAdd(t){if(t.type==="bundle"){this._idToBundle.set(t.id,t),this._assets.on(`load:start:${t.id}`,this._onBundleLoadStart,this),this._assets.on(`load:${t.id}`,this._onBundleLoad,this),this._assets.on(`error:${t.id}`,this._onBundleError,this);let e=t.data.assets;for(let s=0;s{let i=this._fileRequests.get(e);if(i){for(let r=0;r{this.pump(i.done,i.value)}).catch(i=>{this.fire("error",i)})}pump(e,s){if(e)return this.fire("done"),null;this.bytesReceived+=s.byteLength;let i=new Uint8Array(this.data.length+s.length);for(i.set(this.data),i.set(s,this.data.length),this.data=i;this.readFile(););return this.reader.read().then(r=>{this.pump(r.done,r.value)}).catch(r=>{this.fire("error",r)})}readFile(){if(!this.headerRead&&this.bytesReceived>this.bytesRead+this.headerSize){this.headerRead=!0;let e=new DataView(this.data.buffer,this.bytesRead,this.headerSize);this.decoder??(this.decoder=new TextDecoder("windows-1252"));let s=this.decoder.decode(e);if(this.fileName=s.substring(0,100).replace(/\0/g,""),this.fileSize=parseInt(s.substring(124,136),8),this.fileType=s.substring(156,157),this.ustarFormat=s.substring(257,263),this.ustarFormat.indexOf("ustar")!==-1){let i=s.substring(345,500).replace(/\0/g,"");i.length>0&&(this.fileName=i.trim()+this.fileName.trim())}this.bytesRead+=512}if(this.headerRead){if(this.bytesReceived{let a=()=>{fetch(t,e).then(i).catch(o=>{s++,s{let i=new $c;e(null,i);let r=new t0(s,this._assets.prefix);r.on("file",a=>{i.addFile(a.name,a.data)}),r.on("done",()=>{i.loaded=!0}),r.on("error",a=>{e(a)})}).catch(s=>{e(s)})}open(t,e){return e}};var Zc=class c{constructor(t){this._handlers={},this._requests={},this._cache={},this._app=t}addHandler(t,e){this._handlers[t]=e,e._loader=this}removeHandler(t){delete this._handlers[t]}getHandler(t){return this._handlers[t]}static makeKey(t,e){return`${t}-${e}`}load(t,e,s,i,r){let a=this._handlers[e];if(!a){let l=`No resource handler for asset type: '${e}' when loading [${t}]`;s(l);return}if(!t){this._loadNull(a,s,i);return}let o=c.makeKey(t,e);if(this._cache[o]!==void 0)s(null,this._cache[o]);else if(this._requests[o])this._requests[o].push(s);else{this._requests[o]=[s];let l=this,h=function(u,d){if(u){l._onFailure(o,u);return}if(d.load instanceof DataView){if(a.openBinary){if(!l._requests[o])return;try{let p=a.openBinary(d.load);l._onSuccess(o,p)}catch(p){l._onFailure(o,p)}return}d.load=URL.createObjectURL(new Blob([d.load])),i&&(i.urlObject&&URL.revokeObjectURL(i.urlObject),i.urlObject=d.load)}a.load(d,(p,m,_)=>{if(l._requests[o]){if(p){l._onFailure(o,p);return}try{l._onSuccess(o,a.open(d.original,m,i),_)}catch(S){l._onFailure(o,S)}}},i)},f=t.split("?")[0];if(this._app.enableBundles&&this._app.bundles.hasUrl(f)&&!(r&&r.bundlesIgnore)){if(!this._app.bundles.urlIsLoadedOrLoading(f)){let u=this._app.bundles.listBundlesForAsset(i),d;r&&r.bundlesFilter&&(d=r.bundlesFilter(u)),d||(u?.sort((p,m)=>p.file.size-m.file.size),d=u?.[0]),d&&this._app.assets?.load(d)}this._app.bundles.loadUrl(f,(u,d)=>{h(u,{load:d,original:f})})}else h(null,{load:t,original:i&&i.file.filename||t})}}_loadNull(t,e,s){let i=function(r,a,o){if(r)e(r);else try{e(null,t.open(null,a,s),o)}catch(l){e(l)}};t.load(null,i,s)}_onSuccess(t,e,s){e!==null?this._cache[t]=e:delete this._cache[t];for(let i=0;ic&&c[0].toLowerCase()+c.substring(1);function r0(c){if(typeof c!="function")return;if(Object.prototype.hasOwnProperty.call(c,"scriptName")&&c.scriptName)return c.scriptName;if("name"in Function.prototype)return c.name;if(c===Function||c===Function.prototype.constructor)return"Function";let t=`${c}`.match(T8);return t?t[1]:void 0}function Qc(c){if(typeof c!="function")return;if(Object.prototype.hasOwnProperty.call(c,"__name")&&c.__name)return c.__name;if(Object.prototype.hasOwnProperty.call(c,"scriptName")&&c.scriptName)return c.scriptName;let t=r0(c);return t?y8(t):void 0}var Sm=class extends J{constructor(e){super();n(this,"_scripts",new Map);n(this,"_list",[]);n(this,"_scriptSchemas",new Map);this.app=e}destroy(){this.app=null,this.off()}addSchema(e,s){s&&this._scriptSchemas.set(e,s)}getSchema(e){return this._scriptSchemas.get(e)}add(e){let s=Qc(e);return!s||gm.has(s)?!1:(e.__name=s,this._scripts.has(s)?(setTimeout(()=>{if(e.prototype.swap){let i=this._scripts.get(s),r=this._list.indexOf(i);this._list[r]=e,this._scripts.set(s,e),this.fire("swap",s,e),this.fire(`swap:${s}`,e)}}),!1):(this._scripts.set(s,e),this._list.push(e),this.fire("add",s,e),this.fire(`add:${s}`,e),setTimeout(()=>{if(!this._scripts.has(s)||!this.app||!this.app.systems||!this.app.systems.script)return;let i=this.app.systems.script._components,r,a=[],o=[];for(i.loopIndex=0;i.loopIndexc.constructor.order-t.constructor.order,A8=c=>c.sort(E8),bS=[],R2=[],C8=()=>R2.pop()??[],I2=c=>{c.length=0,R2.push(c)},a0=class a0 extends Pe{constructor(e,s=ys()){super(e);n(this,"anim");n(this,"animation");n(this,"audiolistener");n(this,"button");n(this,"camera");n(this,"collision");n(this,"element");n(this,"gsplat");n(this,"layoutchild");n(this,"layoutgroup");n(this,"light");n(this,"model");n(this,"particlesystem");n(this,"render");n(this,"rigidbody");n(this,"screen");n(this,"script");n(this,"scrollbar");n(this,"scrollview");n(this,"sound");n(this,"sprite");n(this,"c",{});n(this,"_app");n(this,"_destroying",!1);n(this,"_guid",null);n(this,"_template",!1);this._app=s}addComponent(e,s){let i=this._app.systems[e];return!i||this.c[e]?null:i.addComponent(this,s)}removeComponent(e){let s=this._app.systems[e];s&&this.c[e]&&s.removeComponent(this)}findComponent(e){let s=this.findOne(i=>i.c?.[e]);return s&&s.c[e]}findComponents(e){return this.find(s=>s.c?.[e]).map(s=>s.c[e])}findScript(e){return this.findOne(i=>i.c?.script?.has(e))?.c.script.get(e)}findScripts(e){return this.find(i=>i.c?.script?.has(e)).map(i=>i.c.script.get(e))}set guid(e){let s=this._app._entityIndex;this._guid&&delete s[this._guid],this._guid=e,s[this._guid]=this}get guid(){return this._guid||(this.guid=bx.create()),this._guid}getGuid(){return this.guid}setGuid(e){this.guid=e}_notifyHierarchyStateChanged(e,s){let i=!1;e===this&&bS.length===0&&(i=!0),e._beingEnabled=!0,e._onHierarchyStateChanged(s),e._onHierarchyStatePostChanged&&bS.push(e);let r=e._children;for(let a=0,o=r.length;a1&&A8(s),s}_cloneRecursively(e){let s=new this.constructor(void 0,this._app);super._cloneInternal(s);for(let i in this.c)this.c[i].system.cloneComponent(this,s);for(let i=0;io instanceof Ne),a=e.children.filter(o=>o instanceof Ne);for(let o=0,l=r.length;o{t.data=l,t._loading=!1;for(let h=0;h{if(i){s&&s(i);return}e&&e(r);let a=this._app,o=()=>{let l=a.loader.getHandler("hierarchy");a.systems.script.preloading=!0;let h=l.open(r.url,r.data);a.systems.script.preloading=!1,a.loader.clearCache(r.url,"hierarchy"),a.root.addChild(h),a.systems.fire("initialize",h),a.systems.fire("postInitialize",h),a.systems.fire("postPostInitialize",h),s&&s(null,h)};a._preloadScripts(r.data,o)})}loadSceneHierarchy(t,e){this._loadSceneHierarchy(t,null,e)}loadSceneSettings(t,e){this._loadSceneData(t,!1,(s,i)=>{s?e&&e(s):(this._app.applySceneSettings(i.data.settings),e&&e(null))})}changeScene(t,e){let s=this._app,i=r=>{let{children:a}=s.root;for(;a.length;)a[0].destroy();s.applySceneSettings(r.data.settings)};this._loadSceneHierarchy(t,i,e)}loadScene(t,e){let s=this._app,i=s.loader.getHandler("scene");s.assets&&s.assets.prefix&&!Ja.test(t)&&(t=xe.join(s.assets.prefix,t)),i.load(t,(r,a)=>{if(r)e&&e(r);else{let o=()=>{s.systems.script.preloading=!0;let l=i.open(t,a),h=this.findByUrl(t);h&&!h.loaded&&(h.data=a),s.systems.script.preloading=!1,s.loader.clearCache(t,"scene"),s.loader.patch({resource:l,type:"scene"},s.assets),s.root.addChild(l.root),s.systems.rigidbody&&typeof Ammo<"u"&&s.systems.rigidbody.gravity.set(l._gravity.x,l._gravity.y,l._gravity.z),e&&e(null,l)};s._preloadScripts(a,o)}})}};var o0=class{constructor(t){this.frame={fps:0,ms:0,dt:0,updateStart:0,updateTime:0,renderStart:0,renderTime:0,physicsStart:0,physicsTime:0,scriptUpdateStart:0,scriptUpdate:0,scriptPostUpdateStart:0,scriptPostUpdate:0,animUpdateStart:0,animUpdate:0,cullTime:0,sortTime:0,skinTime:0,morphTime:0,instancingTime:0,triangles:0,gsplats:0,gsplatSort:0,gsplatBufferCopy:0,otherPrimitives:0,shaders:0,materials:0,cameras:0,shadowMapUpdates:0,shadowMapTime:0,depthMapTime:0,forwardTime:0,lightClustersTime:0,lightClusters:0,_timeToCountFrames:0,_fpsAccum:0},this.drawCalls={forward:0,depth:0,shadow:0,immediate:0,misc:0,total:0,skinned:0,instanced:0,removedByInstancing:0},this.misc={renderTargetCreationTime:0},this.particles={updatesPerFrame:0,_updatesPerFrame:0,frameTime:0,_frameTime:0},this.shaders=t._shaderStats,this.vram=t._vram,this.gpu=t.gpuProfiler?.passTimings??new Map,Object.defineProperty(this.vram,"totalUsed",{get:function(){return this.tex+this.vb+this.ib+this.ub+this.sb}}),Object.defineProperty(this.vram,"geom",{get:function(){return this.vb+this.ib}}),Object.defineProperty(this.vram,"buffers",{get:function(){return this.ub+this.sb}})}get scene(){return ys().scene._stats}get lightmapper(){return ys().lightmapper?.stats}get batcher(){let t=ys()._batcher;return t?t._stats:null}updateBasic(t,e,s,i,r){let a=this.frame;a.dt=e,a.ms=s,t>a._timeToCountFrames?(a.fps=a._fpsAccum,a._fpsAccum=0,a._timeToCountFrames=t+1e3):a._fpsAccum++,this.drawCalls.total=r._drawCallsPerFrame,r._drawCallsPerFrame=0,a.gsplats=i._gsplatCount,a.gsplatBufferCopy=i._gsplatBufferCopy??0}updateDetailed(t,e){let s=this.frame;s.cameras=t._camerasRendered,s.materials=t._materialSwitches,s.shaders=e._shaderSwitchesPerFrame,s.shadowMapUpdates=t._shadowMapUpdates,s.shadowMapTime=t._shadowMapTime,s.depthMapTime=t._depthMapTime,s.forwardTime=t._forwardTime;let i=e._primsPerFrame;s.triangles=i[Yt]/3+Math.max(i[Ks]-2,0)+Math.max(i[dr]-2,0),s.cullTime=t._cullTime,s.sortTime=t._sortTime,s.skinTime=t._skinTime,s.morphTime=t._morphTime,s.lightClusters=t._lightClusters,s.lightClustersTime=t._lightClustersTime,s.otherPrimitives=0;for(let r=0;r 0.5) { if (dAtten > 0.00001) { @@ -2193,7 +2461,7 @@ void occludeSpecular(float gloss, float ao, vec3 worldNormal, vec3 viewDir) { gl_FragColor.rgb = dirLm.xyz; gl_FragColor.a = max(dirLm.w, dAtten > 0.00001 ? (1.0/255.0) : 0.0); } -`,bakeLmEndPS:` +`;var U2=` #ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT dDiffuseLight = ((dDiffuseLight - 0.5) * max(ambientBakeOcclusionContrast + 1.0, 0.0)) + 0.5; dDiffuseLight += vec3(ambientBakeOcclusionBrightness); @@ -2210,7 +2478,7 @@ void occludeSpecular(float gloss, float ao, vec3 worldNormal, vec3 viewDir) { #else gl_FragColor = vec4(dDiffuseLight, 1.0); #endif -`,basePS:` +`;var k2=` uniform vec3 view_position; uniform vec3 light_globalAmbient; float square(float x) { @@ -2222,7 +2490,7 @@ float saturate(float x) { vec3 saturate(vec3 x) { return clamp(x, vec3(0.0), vec3(1.0)); } -`,baseNineSlicedPS:` +`;var z2=` #define NINESLICED varying vec2 vMask; varying vec2 vTiledUv; @@ -2230,7 +2498,7 @@ uniform mediump vec4 innerOffset; uniform mediump vec2 outerScale; uniform mediump vec4 atlasRect; vec2 nineSlicedUv; -`,baseNineSlicedTiledPS:` +`;var G2=` #define NINESLICED #define NINESLICETILED varying vec2 vMask; @@ -2239,7 +2507,7 @@ uniform mediump vec4 innerOffset; uniform mediump vec2 outerScale; uniform mediump vec4 atlasRect; vec2 nineSlicedUv; -`,bayerPS:` +`;var V2=` float bayer2(vec2 p) { return mod(2.0 * p.y + p.x + 1.0, 4.0); } @@ -2254,7 +2522,7 @@ float bayer8(vec2 p) { vec2 p4 = floor(0.25 * mod(p, 8.0)); return 4.0 * (4.0 * bayer2(p1) + bayer2(p2)) + bayer2(p4); } -`,blurVSMPS:` +`;var H2=` varying vec2 vUv0; uniform sampler2D source; uniform vec2 pixelOffset; @@ -2277,7 +2545,7 @@ void main(void) { #endif gl_FragColor = vec4(moments.x, moments.y, moments.z, 1.0); } -`,clearCoatPS:` +`;var W2=` uniform float material_clearCoat; void getClearCoat() { ccSpecularity = material_clearCoat; @@ -2288,7 +2556,7 @@ void getClearCoat() { ccSpecularity *= saturate(vVertexColor.{STD_CLEARCOAT_VERTEX_CHANNEL}); #endif } -`,clearCoatGlossPS:` +`;var X2=` uniform float material_clearCoatGloss; void getClearCoatGlossiness() { ccGlossiness = material_clearCoatGloss; @@ -2303,7 +2571,7 @@ void getClearCoatGlossiness() { #endif ccGlossiness += 0.0000001; } -`,clearCoatNormalPS:` +`;var Y2=` #ifdef STD_CLEARCOATNORMAL_TEXTURE uniform float material_clearCoatBumpiness; #endif @@ -2316,7 +2584,47 @@ void getClearCoatNormal() { ccNormalW = dVertexNormalW; #endif } -`,clusteredLightCookiesPS:` +`;var K2=` +vec2 getCubemapFaceCoordinates(const vec3 dir, out float faceIndex, out vec2 tileOffset) +{ + vec3 vAbs = abs(dir); + float ma; + vec2 uv; + if (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) { + faceIndex = dir.z < 0.0 ? 5.0 : 4.0; + ma = 0.5 / vAbs.z; + uv = vec2(dir.z < 0.0 ? -dir.x : dir.x, -dir.y); + tileOffset.x = 2.0; + tileOffset.y = dir.z < 0.0 ? 1.0 : 0.0; + } else if(vAbs.y >= vAbs.x) { + faceIndex = dir.y < 0.0 ? 3.0 : 2.0; + ma = 0.5 / vAbs.y; + uv = vec2(dir.x, dir.y < 0.0 ? -dir.z : dir.z); + tileOffset.x = 1.0; + tileOffset.y = dir.y < 0.0 ? 1.0 : 0.0; + } else { + faceIndex = dir.x < 0.0 ? 1.0 : 0.0; + ma = 0.5 / vAbs.x; + uv = vec2(dir.x < 0.0 ? dir.z : -dir.z, -dir.y); + tileOffset.x = 0.0; + tileOffset.y = dir.x < 0.0 ? 1.0 : 0.0; + } + return uv * ma + 0.5; +} +vec2 getCubemapAtlasCoordinates(const vec3 omniAtlasViewport, float shadowEdgePixels, float shadowTextureResolution, const vec3 dir) { + float faceIndex; + vec2 tileOffset; + vec2 uv = getCubemapFaceCoordinates(dir, faceIndex, tileOffset); + float atlasFaceSize = omniAtlasViewport.z; + float tileSize = shadowTextureResolution * atlasFaceSize; + float offset = shadowEdgePixels / tileSize; + uv = uv * vec2(1.0 - offset * 2.0) + vec2(offset * 1.0); + uv *= atlasFaceSize; + uv += tileOffset * atlasFaceSize; + uv += omniAtlasViewport.xy; + return uv; +} +`;var j2=` vec3 _getCookieClustered(TEXTURE_ACCEPT(tex), vec2 uv, float intensity, vec4 cookieChannel) { vec4 pixel = mix(vec4(1.0), texture2DLod(tex, uv, 0.0), intensity); bool isRgb = dot(cookieChannel.rgb, vec3(1.0)) == 3.0; @@ -2330,7 +2638,7 @@ vec3 getCookieCubeClustered(TEXTURE_ACCEPT(tex), vec3 dir, float intensity, vec4 vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir); return _getCookieClustered(TEXTURE_PASS(tex), uv, intensity, cookieChannel); } -`,clusteredLightShadowsPS:` +`;var q2=` vec3 _getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) { vec4 projPos = shadowMatrix * vec4(wPos, 1.0); projPos.xyz /= projPos.w; @@ -2387,47 +2695,7 @@ float getShadowSpotClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, return getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams); } #endif -`,clusteredLightUtilsPS:` -vec2 getCubemapFaceCoordinates(const vec3 dir, out float faceIndex, out vec2 tileOffset) -{ - vec3 vAbs = abs(dir); - float ma; - vec2 uv; - if (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) { - faceIndex = dir.z < 0.0 ? 5.0 : 4.0; - ma = 0.5 / vAbs.z; - uv = vec2(dir.z < 0.0 ? -dir.x : dir.x, -dir.y); - tileOffset.x = 2.0; - tileOffset.y = dir.z < 0.0 ? 1.0 : 0.0; - } else if(vAbs.y >= vAbs.x) { - faceIndex = dir.y < 0.0 ? 3.0 : 2.0; - ma = 0.5 / vAbs.y; - uv = vec2(dir.x, dir.y < 0.0 ? -dir.z : dir.z); - tileOffset.x = 1.0; - tileOffset.y = dir.y < 0.0 ? 1.0 : 0.0; - } else { - faceIndex = dir.x < 0.0 ? 1.0 : 0.0; - ma = 0.5 / vAbs.x; - uv = vec2(dir.x < 0.0 ? dir.z : -dir.z, -dir.y); - tileOffset.x = 0.0; - tileOffset.y = dir.x < 0.0 ? 1.0 : 0.0; - } - return uv * ma + 0.5; -} -vec2 getCubemapAtlasCoordinates(const vec3 omniAtlasViewport, float shadowEdgePixels, float shadowTextureResolution, const vec3 dir) { - float faceIndex; - vec2 tileOffset; - vec2 uv = getCubemapFaceCoordinates(dir, faceIndex, tileOffset); - float atlasFaceSize = omniAtlasViewport.z; - float tileSize = shadowTextureResolution * atlasFaceSize; - float offset = shadowEdgePixels / tileSize; - uv = uv * vec2(1.0 - offset * 2.0) + vec2(offset * 1.0); - uv *= atlasFaceSize; - uv += tileOffset * atlasFaceSize; - uv += omniAtlasViewport.xy; - return uv; -} -`,clusteredLightPS:` +`;var $2=` #include "lightBufferDefinesPS" #include "clusteredLightUtilsPS" #ifdef CLUSTER_COOKIES @@ -2454,48 +2722,53 @@ uniform ivec3 clusterCellsDot; uniform ivec3 clusterCellsMax; uniform vec2 shadowAtlasParams; struct ClusterLightData { - vec3 halfWidth; - bool isSpot; - vec3 halfHeight; - int lightIndex; vec3 position; - uint shape; + int lightIndex; vec3 direction; - bool falloffModeLinear; + uint shape; vec3 color; float shadowIntensity; - vec3 omniAtlasViewport; float range; - vec4 cookieChannelMask; float biasesData; - float shadowBias; - float shadowNormalBias; - float innerConeAngleCos; - float outerConeAngleCos; float cookieIntensity; + bool isSpot; + bool falloffModeLinear; bool isDynamic; bool isLightmapped; }; +struct ClusterLightSpotData { + float innerConeAngleCos; + float outerConeAngleCos; +}; +struct ClusterLightAreaData { + vec3 halfWidth; + vec3 halfHeight; +}; +struct ClusterLightShadowData { + float shadowBias; + float shadowNormalBias; +}; mat4 lightProjectionMatrix; uint clusterLightData_flags; float clusterLightData_anglesData; uint clusterLightData_colorBFlagsData; -vec4 sampleLightTextureF(const ClusterLightData clusterLightData, int index) { - return texelFetch(lightsTexture, ivec2(index, clusterLightData.lightIndex), 0); +vec4 sampleLightTextureF(int lightIndex, int index) { + return texelFetch(lightsTexture, ivec2(index, lightIndex), 0); } -void decodeClusterLightCore(inout ClusterLightData clusterLightData, int lightIndex) { +ClusterLightData decodeClusterLightCore(int lightIndex) { + ClusterLightData clusterLightData; clusterLightData.lightIndex = lightIndex; - vec4 halfData = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_COLOR_ANGLES_BIAS}); + vec4 halfData = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_COLOR_ANGLES_BIAS}); clusterLightData_anglesData = halfData.z; clusterLightData.biasesData = halfData.w; clusterLightData_colorBFlagsData = floatBitsToUint(halfData.y); vec2 colorRG = unpackHalf2x16(floatBitsToUint(halfData.x)); vec2 colorB_flags = unpackHalf2x16(clusterLightData_colorBFlagsData); clusterLightData.color = vec3(colorRG, colorB_flags.x) * {LIGHT_COLOR_DIVIDER}; - vec4 lightPosRange = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_POSITION_RANGE}); + vec4 lightPosRange = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_POSITION_RANGE}); clusterLightData.position = lightPosRange.xyz; clusterLightData.range = lightPosRange.w; - vec4 lightDir_Flags = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_DIRECTION_FLAGS}); + vec4 lightDir_Flags = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_DIRECTION_FLAGS}); clusterLightData.direction = lightDir_Flags.xyz; clusterLightData_flags = floatBitsToUint(lightDir_Flags.w); clusterLightData.isSpot = (clusterLightData_flags & (1u << 30u)) != 0u; @@ -2505,42 +2778,44 @@ void decodeClusterLightCore(inout ClusterLightData clusterLightData, int lightIn clusterLightData.cookieIntensity = float((clusterLightData_flags >> 8u) & 0xFFu) / 255.0; clusterLightData.isDynamic = (clusterLightData_flags & (1u << 22u)) != 0u; clusterLightData.isLightmapped = (clusterLightData_flags & (1u << 21u)) != 0u; + return clusterLightData; } -void decodeClusterLightSpot(inout ClusterLightData clusterLightData) { +ClusterLightSpotData decodeClusterLightSpot() { uint angleFlags = (clusterLightData_colorBFlagsData >> 16u) & 0xFFFFu; vec2 angleValues = unpackHalf2x16(floatBitsToUint(clusterLightData_anglesData)); float innerVal = angleValues.x; float outerVal = angleValues.y; float innerIsVersine = float(angleFlags & 1u); float outerIsVersine = float((angleFlags >> 1u) & 1u); - clusterLightData.innerConeAngleCos = mix(innerVal, 1.0 - innerVal, innerIsVersine); - clusterLightData.outerConeAngleCos = mix(outerVal, 1.0 - outerVal, outerIsVersine); + return ClusterLightSpotData( + mix(innerVal, 1.0 - innerVal, innerIsVersine), + mix(outerVal, 1.0 - outerVal, outerIsVersine) + ); } -void decodeClusterLightOmniAtlasViewport(inout ClusterLightData clusterLightData) { - clusterLightData.omniAtlasViewport = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_0}).xyz; +vec3 decodeClusterLightOmniAtlasViewport(int lightIndex) { + return sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}).xyz; } -void decodeClusterLightAreaData(inout ClusterLightData clusterLightData) { - clusterLightData.halfWidth = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_AREA_DATA_WIDTH}).xyz; - clusterLightData.halfHeight = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_AREA_DATA_HEIGHT}).xyz; +ClusterLightAreaData decodeClusterLightAreaData(int lightIndex) { + return ClusterLightAreaData( + sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_AREA_DATA_WIDTH}).xyz, + sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_AREA_DATA_HEIGHT}).xyz + ); } -void decodeClusterLightProjectionMatrixData(inout ClusterLightData clusterLightData) { - - vec4 m0 = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_0}); - vec4 m1 = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_1}); - vec4 m2 = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_2}); - vec4 m3 = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_3}); - lightProjectionMatrix = mat4(m0, m1, m2, m3); +mat4 decodeClusterLightProjectionMatrixData(int lightIndex) { + vec4 m0 = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}); + vec4 m1 = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_1}); + vec4 m2 = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_2}); + vec4 m3 = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_3}); + return mat4(m0, m1, m2, m3); } -void decodeClusterLightShadowData(inout ClusterLightData clusterLightData) { - - vec2 biases = unpackHalf2x16(floatBitsToUint(clusterLightData.biasesData)); - clusterLightData.shadowBias = biases.x; - clusterLightData.shadowNormalBias = biases.y; +ClusterLightShadowData decodeClusterLightShadowData(float biasesData) { + vec2 biases = unpackHalf2x16(floatBitsToUint(biasesData)); + return ClusterLightShadowData(biases.x, biases.y); } -void decodeClusterLightCookieData(inout ClusterLightData clusterLightData) { +vec4 decodeClusterLightCookieData() { uint cookieFlags = (clusterLightData_flags >> 23u) & 0x0Fu; - clusterLightData.cookieChannelMask = vec4(uvec4(cookieFlags) & uvec4(1u, 2u, 4u, 8u)); - clusterLightData.cookieChannelMask = step(1.0, clusterLightData.cookieChannelMask); + vec4 mask = vec4(uvec4(cookieFlags) & uvec4(1u, 2u, 4u, 8u)); + return step(1.0, mask); } void evaluateLight( ClusterLightData light, @@ -2569,13 +2844,13 @@ void evaluateLight( vec3 lightDirNormW = normalize(lightDirW); #ifdef CLUSTER_AREALIGHTS if (light.shape != {LIGHTSHAPE_PUNCTUAL}) { - decodeClusterLightAreaData(light); + ClusterLightAreaData areaData = decodeClusterLightAreaData(light.lightIndex); if (light.shape == {LIGHTSHAPE_RECT}) { - calcRectLightValues(light.position, light.halfWidth, light.halfHeight); + calcRectLightValues(light.position, areaData.halfWidth, areaData.halfHeight); } else if (light.shape == {LIGHTSHAPE_DISK}) { - calcDiskLightValues(light.position, light.halfWidth, light.halfHeight); + calcDiskLightValues(light.position, areaData.halfWidth, areaData.halfHeight); } else { - calcSphereLightValues(light.position, light.halfWidth, light.halfHeight); + calcSphereLightValues(light.position, areaData.halfWidth, areaData.halfHeight); } falloffAttenuation = getFalloffWindow(light.range, lightDirW); } else @@ -2602,33 +2877,34 @@ void evaluateLight( falloffAttenuation *= getLightDiffuse(worldNormal, viewDir, lightDirNormW); } if (light.isSpot) { - decodeClusterLightSpot(light); - falloffAttenuation *= getSpotEffect(light.direction, light.innerConeAngleCos, light.outerConeAngleCos, lightDirNormW); + ClusterLightSpotData spotData = decodeClusterLightSpot(); + falloffAttenuation *= getSpotEffect(light.direction, spotData.innerConeAngleCos, spotData.outerConeAngleCos, lightDirNormW); } #if defined(CLUSTER_COOKIES) || defined(CLUSTER_SHADOWS) if (falloffAttenuation > 0.00001) { if (light.shadowIntensity > 0.0 || light.cookieIntensity > 0.0) { + vec3 omniAtlasViewport = vec3(0.0); if (light.isSpot) { - decodeClusterLightProjectionMatrixData(light); + lightProjectionMatrix = decodeClusterLightProjectionMatrixData(light.lightIndex); } else { - decodeClusterLightOmniAtlasViewport(light); + omniAtlasViewport = decodeClusterLightOmniAtlasViewport(light.lightIndex); } float shadowTextureResolution = shadowAtlasParams.x; float shadowEdgePixels = shadowAtlasParams.y; #ifdef CLUSTER_COOKIES if (light.cookieIntensity > 0.0) { - decodeClusterLightCookieData(light); + vec4 cookieChannelMask = decodeClusterLightCookieData(); if (light.isSpot) { - cookieAttenuation = getCookie2DClustered(TEXTURE_PASS(cookieAtlasTexture), lightProjectionMatrix, vPositionW, light.cookieIntensity, light.cookieChannelMask); + cookieAttenuation = getCookie2DClustered(TEXTURE_PASS(cookieAtlasTexture), lightProjectionMatrix, vPositionW, light.cookieIntensity, cookieChannelMask); } else { - cookieAttenuation = getCookieCubeClustered(TEXTURE_PASS(cookieAtlasTexture), lightDirW, light.cookieIntensity, light.cookieChannelMask, shadowTextureResolution, shadowEdgePixels, light.omniAtlasViewport); + cookieAttenuation = getCookieCubeClustered(TEXTURE_PASS(cookieAtlasTexture), lightDirW, light.cookieIntensity, cookieChannelMask, shadowTextureResolution, shadowEdgePixels, omniAtlasViewport); } } #endif #ifdef CLUSTER_SHADOWS if (light.shadowIntensity > 0.0) { - decodeClusterLightShadowData(light); - vec4 shadowParams = vec4(shadowTextureResolution, light.shadowNormalBias, light.shadowBias, 1.0 / light.range); + ClusterLightShadowData shadowData = decodeClusterLightShadowData(light.biasesData); + vec4 shadowParams = vec4(shadowTextureResolution, shadowData.shadowNormalBias, shadowData.shadowBias, 1.0 / light.range); if (light.isSpot) { vec3 shadowCoord = getShadowCoordPerspZbufferNormalOffset(lightProjectionMatrix, shadowParams, geometricNormal); @@ -2645,11 +2921,11 @@ void evaluateLight( } else { vec3 dir = normalOffsetPointShadow(shadowParams, light.position, lightDirW, lightDirNormW, geometricNormal); #if defined(CLUSTER_SHADOW_TYPE_PCF1) - float shadow = getShadowOmniClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir); + float shadow = getShadowOmniClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, omniAtlasViewport, shadowEdgePixels, dir); #elif defined(CLUSTER_SHADOW_TYPE_PCF3) - float shadow = getShadowOmniClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir); + float shadow = getShadowOmniClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, omniAtlasViewport, shadowEdgePixels, dir); #elif defined(CLUSTER_SHADOW_TYPE_PCF5) - float shadow = getShadowOmniClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir); + float shadow = getShadowOmniClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, omniAtlasViewport, shadowEdgePixels, dir); #endif falloffAttenuation *= mix(1.0, shadow, light.shadowIntensity); } @@ -2701,7 +2977,7 @@ void evaluateLight( #endif dDiffuseLight += punctualDiffuse; } - + #ifdef LIT_SPECULAR vec3 halfDir = normalize(-lightDirNormW + viewDir); @@ -2756,8 +3032,7 @@ void evaluateClusterLight( float sheen_gloss, float iridescence_intensity ) { - ClusterLightData clusterLightData; - decodeClusterLightCore(clusterLightData, lightIndex); + ClusterLightData clusterLightData = decodeClusterLightCore(lightIndex); #ifdef CLUSTER_MESH_DYNAMIC_LIGHTS bool acceptLightMask = clusterLightData.isDynamic; #else @@ -2838,7 +3113,7 @@ void addClusteredLights( } } } -`,combinePS:` +`;var Z2=` vec3 combineColor(vec3 albedo, vec3 sheenSpecularity, float clearcoatSpecularity) { vec3 ret = vec3(0); #ifdef LIT_OLD_AMBIENT @@ -2862,13 +3137,13 @@ vec3 combineColor(vec3 albedo, vec3 sheenSpecularity, float clearcoatSpecularity #endif return ret; } -`,cookieBlit2DPS:` +`;var Q2=` varying vec2 uv0; uniform sampler2D blitTexture; void main(void) { gl_FragColor = texture2D(blitTexture, uv0); } -`,cookieBlitCubePS:` +`;var J2=` varying vec2 uv0; uniform samplerCube blitTexture; uniform mat4 invViewProj; @@ -2877,7 +3152,7 @@ vec3 combineColor(vec3 albedo, vec3 sheenSpecularity, float clearcoatSpecularity vec4 worldPos = invViewProj * projPos; gl_FragColor = textureCube(blitTexture, worldPos.xyz); } -`,cookieBlitVS:` +`;var e1=` attribute vec2 vertex_position; varying vec2 uv0; void main(void) { @@ -2887,7 +3162,7 @@ vec3 combineColor(vec3 albedo, vec3 sheenSpecularity, float clearcoatSpecularity uv0.y = 1.0 - uv0.y; #endif } -`,cookiePS:` +`;var t1=` vec4 getCookie2D(sampler2D tex, mat4 transform, float intensity) { vec4 projPos = transform * vec4(vPositionW, 1.0); projPos.xy /= projPos.w; @@ -2917,7 +3192,7 @@ vec4 getCookie2DClipXform(sampler2D tex, mat4 transform, float intensity, vec4 c vec4 getCookieCube(samplerCube tex, mat4 transform, float intensity) { return mix(vec4(1.0), textureCube(tex, dLightDirNormW * mat3(transform)), intensity); } -`,cubeMapProjectPS:` +`;var s1=` #if LIT_CUBEMAP_PROJECTION == BOX uniform vec3 envBoxMin; uniform vec3 envBoxMax; @@ -2937,7 +3212,7 @@ vec3 cubeMapProject(vec3 nrdir) { return normalize(posonbox - envBoxPos); #endif } -`,cubeMapRotatePS:` +`;var i1=` #ifdef CUBEMAP_ROTATION uniform mat3 cubeMapRotationMatrix; #endif @@ -2948,7 +3223,7 @@ vec3 cubeMapRotate(vec3 refDir) { return refDir; #endif } -`,debugOutputPS:` +`;var r1=` #ifdef DEBUG_ALBEDO_PASS gl_FragColor = vec4(gammaCorrectOutput(dAlbedo), 1.0); #endif @@ -2976,7 +3251,7 @@ gl_FragColor = vec4(vec3(litArgs_ao) , 1.0); #ifdef DEBUG_EMISSION_PASS gl_FragColor = vec4(gammaCorrectOutput(litArgs_emission), 1.0); #endif -`,debugProcessFrontendPS:` +`;var a1=` #ifdef DEBUG_LIGHTING_PASS litArgs_albedo = vec3(0.5); #endif @@ -2987,48 +3262,7 @@ litArgs_albedo = vec3(vUv0, 0); litArgs_albedo = vec3(0); #endif #endif -`,detailModesPS:` -#ifndef _DETAILMODES_INCLUDED_ -#define _DETAILMODES_INCLUDED_ -vec3 detailMode_mul(vec3 c1, vec3 c2) { - return c1 * c2; -} -vec3 detailMode_add(vec3 c1, vec3 c2) { - return c1 + c2; -} -vec3 detailMode_screen(vec3 c1, vec3 c2) { - return 1.0 - (1.0 - c1)*(1.0 - c2); -} -vec3 detailMode_overlay(vec3 c1, vec3 c2) { - return mix(1.0 - 2.0 * (1.0 - c1)*(1.0 - c2), 2.0 * c1 * c2, step(c1, vec3(0.5))); -} -vec3 detailMode_min(vec3 c1, vec3 c2) { - return min(c1, c2); -} -vec3 detailMode_max(vec3 c1, vec3 c2) { - return max(c1, c2); -} -#endif -`,diffusePS:` -uniform vec3 material_diffuse; -#ifdef STD_DIFFUSEDETAIL_TEXTURE - #include "detailModesPS" -#endif -void getAlbedo() { - dAlbedo = material_diffuse.rgb; - #ifdef STD_DIFFUSE_TEXTURE - vec3 albedoTexture = {STD_DIFFUSE_TEXTURE_DECODE}(texture2DBias({STD_DIFFUSE_TEXTURE_NAME}, {STD_DIFFUSE_TEXTURE_UV}, textureBias)).{STD_DIFFUSE_TEXTURE_CHANNEL}; - #ifdef STD_DIFFUSEDETAIL_TEXTURE - vec3 albedoDetail = {STD_DIFFUSEDETAIL_TEXTURE_DECODE}(texture2DBias({STD_DIFFUSEDETAIL_TEXTURE_NAME}, {STD_DIFFUSEDETAIL_TEXTURE_UV}, textureBias)).{STD_DIFFUSEDETAIL_TEXTURE_CHANNEL}; - albedoTexture = detailMode_{STD_DIFFUSEDETAIL_DETAILMODE}(albedoTexture, albedoDetail); - #endif - dAlbedo *= albedoTexture; - #endif - #ifdef STD_DIFFUSE_VERTEX - dAlbedo *= saturate(vVertexColor.{STD_DIFFUSE_VERTEX_CHANNEL}); - #endif -} -`,decodePS:` +`;var o1=` #ifndef _DECODE_INCLUDED_ #define _DECODE_INCLUDED_ vec3 decodeLinear(vec4 raw) { @@ -3071,7 +3305,48 @@ vec3 unpackNormalXY(vec4 nmap) { return normal; } #endif -`,emissivePS:` +`;var n1=` +#ifndef _DETAILMODES_INCLUDED_ +#define _DETAILMODES_INCLUDED_ +vec3 detailMode_mul(vec3 c1, vec3 c2) { + return c1 * c2; +} +vec3 detailMode_add(vec3 c1, vec3 c2) { + return c1 + c2; +} +vec3 detailMode_screen(vec3 c1, vec3 c2) { + return 1.0 - (1.0 - c1)*(1.0 - c2); +} +vec3 detailMode_overlay(vec3 c1, vec3 c2) { + return mix(1.0 - 2.0 * (1.0 - c1)*(1.0 - c2), 2.0 * c1 * c2, step(c1, vec3(0.5))); +} +vec3 detailMode_min(vec3 c1, vec3 c2) { + return min(c1, c2); +} +vec3 detailMode_max(vec3 c1, vec3 c2) { + return max(c1, c2); +} +#endif +`;var l1=` +uniform vec3 material_diffuse; +#ifdef STD_DIFFUSEDETAIL_TEXTURE + #include "detailModesPS" +#endif +void getAlbedo() { + dAlbedo = material_diffuse.rgb; + #ifdef STD_DIFFUSE_TEXTURE + vec3 albedoTexture = {STD_DIFFUSE_TEXTURE_DECODE}(texture2DBias({STD_DIFFUSE_TEXTURE_NAME}, {STD_DIFFUSE_TEXTURE_UV}, textureBias)).{STD_DIFFUSE_TEXTURE_CHANNEL}; + #ifdef STD_DIFFUSEDETAIL_TEXTURE + vec3 albedoDetail = {STD_DIFFUSEDETAIL_TEXTURE_DECODE}(texture2DBias({STD_DIFFUSEDETAIL_TEXTURE_NAME}, {STD_DIFFUSEDETAIL_TEXTURE_UV}, textureBias)).{STD_DIFFUSEDETAIL_TEXTURE_CHANNEL}; + albedoTexture = detailMode_{STD_DIFFUSEDETAIL_DETAILMODE}(albedoTexture, albedoDetail); + #endif + dAlbedo *= albedoTexture; + #endif + #ifdef STD_DIFFUSE_VERTEX + dAlbedo *= saturate(vVertexColor.{STD_DIFFUSE_VERTEX_CHANNEL}); + #endif +} +`;var c1=` uniform vec3 material_emissive; uniform float material_emissiveIntensity; void getEmission() { @@ -3083,7 +3358,7 @@ void getEmission() { dEmission *= saturate(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL}); #endif } -`,encodePS:` +`;var h1=` vec4 encodeLinear(vec3 source) { return vec4(source, 1.0); } @@ -3115,13 +3390,13 @@ vec4 encodeRGBE(vec3 source) { return vec4(source / pow(2.0, e), (e + 128.0) / 255.0); } } -`,endPS:` +`;var f1=` gl_FragColor.rgb = combineColor(litArgs_albedo, litArgs_sheen_specularity, litArgs_clearcoat_specularity); gl_FragColor.rgb += litArgs_emission; gl_FragColor.rgb = addFog(gl_FragColor.rgb); gl_FragColor.rgb = toneMap(gl_FragColor.rgb); gl_FragColor.rgb = gammaCorrectOutput(gl_FragColor.rgb); -`,envAtlasPS:` +`;var u1=` #ifndef _ENVATLAS_INCLUDED_ #define _ENVATLAS_INCLUDED_ const float atlasSize = 512.0; @@ -3139,7 +3414,7 @@ vec2 mapShinyUv(vec2 uv, float level) { return mapUv(uv, vec4(1.0 - t, 1.0 - t, t, t * 0.5)); } #endif -`,envProcPS:` +`;var d1=` #ifdef LIT_SKYBOX_INTENSITY uniform float skyboxIntensity; #endif @@ -3150,7 +3425,7 @@ vec3 processEnvironment(vec3 color) { return color; #endif } -`,falloffInvSquaredPS:` +`;var p1=` float getFalloffWindow(float lightRadius, vec3 lightDir) { float sqrDist = dot(lightDir, lightDir); float invRadius = 1.0 / lightRadius; @@ -3164,12 +3439,12 @@ float getFalloffInvSquared(float lightRadius, vec3 lightDir) { falloff *= square(saturate(1.0 - square(sqrDist * square(invRadius)))); return falloff; } -`,falloffLinearPS:` +`;var m1=` float getFalloffLinear(float lightRadius, vec3 lightDir) { float d = length(lightDir); return max(((lightRadius - d) / lightRadius), 0.0); } -`,floatAsUintPS:` +`;var _1=` #ifndef FLOAT_AS_UINT #define FLOAT_AS_UINT vec4 float2uint(float value) { @@ -3197,7 +3472,7 @@ vec4 float2vec4(float value) { #endif } #endif -`,fogPS:` +`;var g1=` float dBlendModeFogFactor = 1.0; #if (FOG != NONE) uniform vec3 fog_color; @@ -3239,7 +3514,11 @@ float dBlendModeFogFactor = 1.0; return color; } #endif -`,fresnelSchlickPS:` +`;var S1=` +float pow5(float x) { + float x2 = x * x; + return x2 * x2 * x; +} vec3 getFresnel( float cosTheta, float gloss, @@ -3249,7 +3528,7 @@ vec3 getFresnel( float iridescenceIntensity #endif ) { - float fresnel = pow(1.0 - saturate(cosTheta), 5.0); + float fresnel = pow5(1.0 - saturate(cosTheta)); float glossSq = gloss * gloss; float specIntensity = max(specularity.r, max(specularity.g, specularity.b)); vec3 ret = specularity + (max(vec3(glossSq * specIntensity), specularity) - specularity) * fresnel; @@ -3260,10 +3539,10 @@ vec3 getFresnel( #endif } float getFresnelCC(float cosTheta) { - float fresnel = pow(1.0 - saturate(cosTheta), 5.0); + float fresnel = pow5(1.0 - saturate(cosTheta)); return 0.04 + (1.0 - 0.04) * fresnel; } -`,frontendCodePS:"",frontendDeclPS:"",fullscreenQuadVS:` +`;var x1=` attribute vec2 vertex_position; varying vec2 vUv0; void main(void) @@ -3271,7 +3550,7 @@ void main(void) gl_Position = vec4(vertex_position, 0.5, 1.0); vUv0 = vertex_position.xy * 0.5 + 0.5; } -`,gammaPS:` +`;var v1=` #include "decodePS" #if (GAMMA == SRGB) float gammaCorrectInput(float color) { @@ -3300,7 +3579,7 @@ void main(void) return color; } #endif -`,gles3PS:rr,gles3VS:ra,glossPS:` +`;var T1=` #ifdef STD_GLOSS_CONSTANT uniform float material_gloss; #endif @@ -3320,7 +3599,7 @@ void getGlossiness() { #endif dGlossiness += 0.0000001; } -`,quadVS:` +`;var y1=` attribute vec2 aPosition; varying vec2 uv0; void main(void) @@ -3328,13 +3607,13 @@ void getGlossiness() { gl_Position = vec4(aPosition, 0.0, 1.0); uv0 = getImageEffectUV((aPosition.xy + 1.0) * 0.5); } -`,immediateLinePS:` +`;var E1=` #include "gammaPS" varying vec4 color; void main(void) { gl_FragColor = vec4(gammaCorrectOutput(decodeGamma(color.rgb)), color.a); } -`,immediateLineVS:` +`;var A1=` attribute vec4 vertex_position; attribute vec4 vertex_color; uniform mat4 matrix_model; @@ -3344,7 +3623,7 @@ void getGlossiness() { color = vertex_color; gl_Position = matrix_viewProjection * matrix_model * vertex_position; } -`,iridescenceDiffractionPS:` +`;var C1=` uniform float material_iridescenceRefractionIndex; float iridescence_iorToFresnel(float transmittedIor, float incidentIor) { return pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0); @@ -3424,7 +3703,7 @@ vec3 calcIridescence(float outsideIor, float cosTheta, vec3 base_f0, float iride vec3 getIridescence(float cosTheta, vec3 specularity, float iridescenceThickness) { return calcIridescence(1.0, cosTheta, specularity, iridescenceThickness); } -`,iridescencePS:` +`;var P1=` #ifdef STD_IRIDESCENCE_CONSTANT uniform float material_iridescence; #endif @@ -3438,7 +3717,7 @@ void getIridescence() { #endif dIridescence = iridescence; } -`,iridescenceThicknessPS:` +`;var w1=` uniform float material_iridescenceThicknessMax; #ifdef STD_IRIDESCENCETHICKNESS_TEXTURE uniform float material_iridescenceThicknessMin; @@ -3452,7 +3731,7 @@ void getIridescenceThickness() { #endif dIridescenceThickness = iridescenceThickness; } -`,iorPS:` +`;var I1=` #ifdef STD_IOR_CONSTANT uniform float material_refractionIndex; #endif @@ -3463,7 +3742,7 @@ void getIor() { dIor = 1.0 / 1.5; #endif } -`,lightDeclarationPS:` +`;var R1=` #if defined(LIGHT{i}) uniform vec3 light{i}_color; #if LIGHT{i}TYPE == DIRECTIONAL @@ -3547,15 +3826,15 @@ void getIor() { #endif #endif #endif -`,lightDiffuseLambertPS:` +`;var b1=` float getLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm) { return max(dot(worldNormal, -lightDirNorm), 0.0); } -`,lightDirPointPS:` +`;var D1=` vec3 evalOmniLight(vec3 lightPosW) { return vPositionW - lightPosW; } -`,lightEvaluationPS:` +`;var L1=` #if defined(LIGHT{i}) evaluateLight{i}( #if defined(LIT_IRIDESCENCE) @@ -3563,7 +3842,7 @@ vec3 evalOmniLight(vec3 lightPosW) { #endif ); #endif -`,lightFunctionLightPS:` +`;var M1=` #if defined(LIGHT{i}) void evaluateLight{i}( #if defined(LIT_IRIDESCENCE) @@ -3726,7 +4005,7 @@ void evaluateLight{i}( #endif } #endif -`,lightFunctionShadowPS:` +`;var O1=` #ifdef LIGHT{i}CASTSHADOW #ifdef LIGHT{i}_SHADOW_SAMPLE_POINT vec3 getShadowSampleCoordOmni{i}(vec4 shadowParams, vec3 worldPosition, vec3 lightPos, inout vec3 lightDir, vec3 lightDirNorm, vec3 normal) { @@ -3859,7 +4138,7 @@ void evaluateLight{i}( #endif } #endif -`,lightingPS:` +`;var F1=` #ifdef LIT_CLUSTERED_LIGHTS #define LIT_CODE_FALLOFF_LINEAR #define LIT_CODE_FALLOFF_SQUARED @@ -3918,7 +4197,7 @@ void evaluateLight{i}( #include "lightFunctionShadowPS, LIGHT_COUNT" #include "lightFunctionLightPS, LIGHT_COUNT" #endif -`,lightmapAddPS:` +`;var N1=` void addLightMap( vec3 lightmap, vec3 dir, @@ -3961,7 +4240,7 @@ void addLightMap( dDiffuseLight += lightmap; #endif } -`,lightmapPS:` +`;var B1=` #ifdef STD_LIGHTMAP_DIR vec3 dLightmapDir; uniform sampler2D texture_dirLightMap; @@ -3980,7 +4259,7 @@ void getLightMap() { dLightmap *= saturate(vVertexColor.{STD_LIGHT_VERTEX_CHANNEL}); #endif } -`,lightSpecularAnisoGGXPS:` +`;var U1=` float calcLightSpecular(float gloss, vec3 worldNormal, vec3 viewDir, vec3 h, vec3 lightDirNorm, mat3 tbn) { float PI = 3.141592653589793; float roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001); @@ -4013,7 +4292,7 @@ float calcLightSpecular(float gloss, vec3 worldNormal, vec3 viewDir, vec3 h, vec float getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) { return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm, tbn); } -`,lightSpecularGGXPS:` +`;var k1=` float calcLightSpecular(float gloss, vec3 worldNormal, vec3 viewDir, vec3 h, vec3 lightDirNorm) { const float PI = 3.141592653589793; float roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001); @@ -4033,7 +4312,7 @@ float calcLightSpecular(float gloss, vec3 worldNormal, vec3 viewDir, vec3 h, vec float getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) { return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm); } -`,lightSpecularBlinnPS:` +`;var z1=` float calcLightSpecular(float gloss, vec3 worldNormal, vec3 h) { float nh = max( dot( h, worldNormal ), 0.0 ); float specPow = exp2(gloss * 11.0); @@ -4043,7 +4322,7 @@ float calcLightSpecular(float gloss, vec3 worldNormal, vec3 h) { float getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) { return calcLightSpecular(gloss, worldNormal, h); } -`,lightSheenPS:` +`;var G1=` float sheenD(vec3 normal, vec3 h, float roughness) { const float PI = 3.141592653589793; float invR = 1.0 / (roughness * roughness); @@ -4062,7 +4341,7 @@ float getLightSpecularSheen(vec3 h, vec3 worldNormal, vec3 viewDir, vec3 lightDi float V = sheenV(worldNormal, viewDir, -lightDirNorm); return D * V; } -`,linearizeDepthPS:` +`;var V1=` #ifndef LINEARIZE_DEPTH #define LINEARIZE_DEPTH float linearizeDepthWithParams(float z, vec4 cameraParams) { @@ -4079,7 +4358,7 @@ float linearizeDepth(float z) { return linearizeDepthWithParams(z, camera_params); } #endif -`,litForwardBackendPS:` +`;var H1=` void evaluateBackend() { #ifdef LIT_SSAO litArgs_ao *= texture2DLod(ssaoTexture, gl_FragCoord.xy * ssaoTextureSizeInv, 0.0).r; @@ -4262,7 +4541,7 @@ void evaluateBackend() { gl_FragColor.rgb = vec3(dShadowCatcher); #endif } -`,litForwardDeclarationPS:` +`;var W1=` vec3 sReflection; vec3 dVertexNormalW; vec3 dTangentW; @@ -4309,7 +4588,7 @@ vec3 sSpecularLight; uniform float ambientBakeOcclusionContrast; uniform float ambientBakeOcclusionBrightness; #endif -`,litForwardMainPS:` +`;var X1=` void main(void) { #include "litUserMainStartPS" dReflection = vec4(0); @@ -4343,7 +4622,7 @@ void main(void) { evaluateBackend(); #include "litUserMainEndPS" } -`,litForwardPostCodePS:` +`;var Y1=` #ifdef LIT_NEEDS_NORMAL #include "cubeMapRotatePS" #include "cubeMapProjectPS" @@ -4430,7 +4709,7 @@ uniform vec3 material_ambient; #endif #endif #include "lightingPS" -`,litForwardPreCodePS:` +`;var K1=` #include "basePS" #include "sphericalPS" #include "decodePS" @@ -4448,7 +4727,7 @@ uniform vec3 material_ambient; #include "twoSidedLightingPS" #endif #endif -`,litMainPS:` +`;var j1=` #include "varyingsPS" #include "litUserDeclarationPS" #include "frontendDeclPS" @@ -4469,7 +4748,7 @@ uniform vec3 material_ambient; #include "litUserCodePS" #include "litForwardMainPS" #endif -`,litMainVS:` +`;var q1=` #include "varyingsVS" #include "litUserDeclarationVS" #ifdef VERTEX_COLOR @@ -4562,7 +4841,7 @@ void main(void) { #endif #include "litUserMainEndVS" } -`,litOtherMainPS:` +`;var $1=` #ifdef PICK_PASS #include "pickPS" #endif @@ -4583,7 +4862,7 @@ void main(void) { #endif #include "litUserMainEndPS" } -`,litShaderArgsPS:` +`;var Z1=` vec3 litArgs_albedo; float litArgs_opacity; vec3 litArgs_emission; @@ -4606,14 +4885,14 @@ float litArgs_iridescence_thickness; vec3 litArgs_clearcoat_worldNormal; float litArgs_clearcoat_specularity; float litArgs_clearcoat_gloss; -`,litShaderCorePS:` +`;var Q1=` #if LIT_NONE_SLICE_MODE == TILED const float textureBias = -1000.0; #else uniform float textureBias; #endif #include "litShaderArgsPS" -`,litShadowMainPS:` +`;var J1=` #if LIGHT_TYPE != DIRECTIONAL uniform vec3 view_position; uniform float light_radius; @@ -4656,7 +4935,7 @@ void main(void) { #endif #include "litUserMainEndPS" } -`,litUserDeclarationPS:"",litUserDeclarationVS:"",litUserCodePS:"",litUserCodeVS:"",litUserMainStartPS:"",litUserMainStartVS:"",litUserMainEndPS:"",litUserMainEndVS:"",ltcPS:` +`;var e3=` mat3 transposeMat3( const in mat3 m ) { mat3 tmp; tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); @@ -4955,7 +5234,7 @@ float getDiskLightSpecular(vec3 worldNormal, vec3 viewDir) { float getSphereLightSpecular(vec3 worldNormal, vec3 viewDir) { return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV); } -`,metalnessPS:` +`;var t3=` #ifdef STD_METALNESS_CONSTANT uniform float material_metalness; #endif @@ -4972,48 +5251,7 @@ void getMetalness() { #endif dMetalness = metalness; } -`,metalnessModulatePS:` -vec3 getSpecularModulate(in vec3 specularity, in vec3 albedo, in float metalness, in float f0, in float specularityFactor) { - vec3 dielectricF0 = f0 * specularity * specularityFactor; - return mix(dielectricF0, albedo, metalness); -} -vec3 getAlbedoModulate(in vec3 albedo, in float metalness) { - return albedo * (1.0 - metalness); -} -`,morphPS:` - varying vec2 uv0; - uniform sampler2DArray morphTexture; - uniform highp float morphFactor[{MORPH_TEXTURE_MAX_COUNT}]; - uniform highp uint morphIndex[{MORPH_TEXTURE_MAX_COUNT}]; - uniform int count; - #ifdef MORPH_INT - uniform vec3 aabbSize; - uniform vec3 aabbMin; - #endif - void main (void) { - highp vec3 color = vec3(0, 0, 0); - ivec2 pixelCoords = ivec2(uv0 * vec2(textureSize(morphTexture, 0).xy)); - - for (int i = 0; i < count; i++) { - uint textureIndex = morphIndex[i]; - vec3 delta = texelFetch(morphTexture, ivec3(pixelCoords, int(textureIndex)), 0).xyz; - color += morphFactor[i] * delta; - } - #ifdef MORPH_INT - color = (color - aabbMin) / aabbSize * 65535.0; - gl_FragColor = uvec4(color, 1u); - #else - gl_FragColor = vec4(color, 1.0); - #endif - } -`,morphVS:` - attribute vec2 vertex_position; - varying vec2 uv0; - void main(void) { - gl_Position = vec4(vertex_position, 0.5, 1.0); - uv0 = vertex_position.xy * 0.5 + 0.5; - } -`,msdfPS:` +`;var s3=` uniform sampler2D texture_msdfMap; float median(float r, float g, float b) { return max(min(r, g), min(max(r, g), b)); @@ -5062,7 +5300,48 @@ vec4 applyMsdf(vec4 color) { return tcolor; } -`,msdfVS:` +`;var i3=` +vec3 getSpecularModulate(in vec3 specularity, in vec3 albedo, in float metalness, in float f0, in float specularityFactor) { + vec3 dielectricF0 = f0 * specularity * specularityFactor; + return mix(dielectricF0, albedo, metalness); +} +vec3 getAlbedoModulate(in vec3 albedo, in float metalness) { + return albedo * (1.0 - metalness); +} +`;var r3=` + varying vec2 uv0; + uniform sampler2DArray morphTexture; + uniform highp float morphFactor[{MORPH_TEXTURE_MAX_COUNT}]; + uniform highp uint morphIndex[{MORPH_TEXTURE_MAX_COUNT}]; + uniform int count; + #ifdef MORPH_INT + uniform vec3 aabbSize; + uniform vec3 aabbMin; + #endif + void main (void) { + highp vec3 color = vec3(0, 0, 0); + ivec2 pixelCoords = ivec2(uv0 * vec2(textureSize(morphTexture, 0).xy)); + + for (int i = 0; i < count; i++) { + uint textureIndex = morphIndex[i]; + vec3 delta = texelFetch(morphTexture, ivec3(pixelCoords, int(textureIndex)), 0).xyz; + color += morphFactor[i] * delta; + } + #ifdef MORPH_INT + color = (color - aabbMin) / aabbSize * 65535.0; + gl_FragColor = uvec4(color, 1u); + #else + gl_FragColor = vec4(color, 1.0); + #endif + } +`;var a3=` + attribute vec2 vertex_position; + varying vec2 uv0; + void main(void) { + gl_Position = vec4(vertex_position, 0.5, 1.0); + uv0 = vertex_position.xy * 0.5 + 0.5; + } +`;var o3=` attribute vec3 vertex_outlineParameters; attribute vec3 vertex_shadowParameters; varying vec4 outline_color; @@ -5081,14 +5360,14 @@ void unpackMsdfParams() { shadow_color.ga = big.xy / 255.; shadow_offset = (vec2(little.z, big.z) / 127. - 1.) * 0.005; } -`,normalVS:` +`;var n3=` mat3 dNormalMatrix; vec3 getNormal() { dNormalMatrix = getNormalMatrix(dModelMatrix); vec3 localNormal = getLocalNormal(vertex_normal); return normalize(dNormalMatrix * localNormal); } -`,normalCoreVS:` +`;var l3=` attribute vec3 vertex_normal; uniform mat3 matrix_normal; #ifdef MORPHING_NORMAL @@ -5124,7 +5403,7 @@ vec3 getLocalNormal(vec3 vertexNormal) { return matrix_normal; } #endif -`,normalMapPS:` +`;var c3=` #ifdef STD_NORMAL_TEXTURE uniform float material_bumpiness; #endif @@ -5150,8 +5429,9 @@ void getNormal() { dNormalW = dVertexNormalW; #endif } -`,opacityPS:` +`;var h3=` uniform float material_opacity; +uniform float material_alphaDitherScale; void getOpacity() { dAlpha = material_opacity; #ifdef STD_OPACITY_TEXTURE @@ -5161,7 +5441,7 @@ void getOpacity() { dAlpha *= clamp(vVertexColor.{STD_OPACITY_VERTEX_CHANNEL}, 0.0, 1.0); #endif } -`,opacityDitherPS:` +`;var f3=` #if STD_OPACITY_DITHER == BAYER8 #include "bayerPS" #endif @@ -5170,6 +5450,10 @@ uniform vec4 blueNoiseJitter; uniform sampler2D blueNoiseTex32; #endif void opacityDither(float alpha, float id) { + if (alpha <= 0.0) + discard; + if (alpha >= 1.0) + return; #if STD_OPACITY_DITHER == BAYER8 float noise = bayer8(floor(mod(gl_FragCoord.xy + blueNoiseJitter.xy + id, 8.0))) / 64.0; #else @@ -5186,8 +5470,8 @@ void opacityDither(float alpha, float id) { if (alpha < noise) discard; } -`,outputPS:` -`,outputAlphaPS:` +`;var u3=` +`;var d3=` #if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == ADDITIVEALPHA || defined(LIT_ALPHA_TO_COVERAGE) gl_FragColor.a = litArgs_opacity; #elif LIT_BLEND_TYPE == PREMULTIPLIED @@ -5196,13 +5480,13 @@ void opacityDither(float alpha, float id) { #else gl_FragColor.a = 1.0; #endif -`,outputTex2DPS:` +`;var p3=` varying vec2 vUv0; uniform sampler2D source; void main(void) { gl_FragColor = texture2D(source, vUv0); } -`,sheenPS:` +`;var m3=` uniform vec3 material_sheen; void getSheen() { vec3 sheenColor = material_sheen; @@ -5214,7 +5498,7 @@ void getSheen() { #endif sSpecularity = sheenColor; } -`,sheenGlossPS:` +`;var _3=` uniform float material_sheenGloss; void getSheenGlossiness() { float sheenGlossiness = material_sheenGloss; @@ -5229,7 +5513,7 @@ void getSheenGlossiness() { #endif sGlossiness = sheenGlossiness + 0.0000001; } -`,parallaxPS:` +`;var g3=` uniform float material_heightMapFactor; void getParallax() { float parallaxScale = material_heightMapFactor; @@ -5239,7 +5523,7 @@ void getParallax() { viewDirT.z += 0.42; dUvOffset = height * (viewDirT.xy / viewDirT.z); } -`,pickPS:` +`;var S3=` vec4 encodePickOutput(uint id) { const vec4 inv = vec4(1.0 / 255.0); const uvec4 shifts = uvec4(16, 8, 0, 24); @@ -5254,7 +5538,10 @@ vec4 encodePickOutput(uint id) { #endif #ifdef DEPTH_PICK_PASS #include "floatAsUintPS" - uniform vec4 camera_params; + #ifndef CAMERAPLANES + #define CAMERAPLANES + uniform vec4 camera_params; + #endif vec4 getPickDepth() { float linearDepth; if (camera_params.w > 0.5) { @@ -5266,11 +5553,11 @@ vec4 encodePickOutput(uint id) { return float2uint(linearDepth); } #endif -`,reflDirPS:` +`;var x3=` void getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) { dReflDirW = normalize(-reflect(viewDir, worldNormal)); } -`,reflDirAnisoPS:` +`;var v3=` void getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) { float roughness = sqrt(1.0 - min(gloss, 1.0)); vec2 direction = dAnisotropyRotation; @@ -5285,13 +5572,13 @@ void getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) { vec3 bentNormal = normalize(mix(normalize(anisotropicNormal), normalize(worldNormal), bendFactor4)); dReflDirW = reflect(-viewDir, bentNormal); } -`,reflectionCCPS:` +`;var T3=` #ifdef LIT_CLEARCOAT void addReflectionCC(vec3 reflDir, float gloss) { ccReflection += calcReflection(reflDir, gloss); } #endif -`,reflectionCubePS:` +`;var y3=` uniform samplerCube texture_cubeMap; uniform float material_reflectivity; vec3 calcReflection(vec3 reflDir, float gloss) { @@ -5302,7 +5589,7 @@ vec3 calcReflection(vec3 reflDir, float gloss) { void addReflection(vec3 reflDir, float gloss) { dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity); } -`,reflectionEnvHQPS:` +`;var E3=` #ifndef ENV_ATLAS #define ENV_ATLAS uniform sampler2D texture_envAtlas; @@ -5323,7 +5610,7 @@ vec3 calcReflection(vec3 reflDir, float gloss) { void addReflection(vec3 reflDir, float gloss) { dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity); } -`,reflectionEnvPS:` +`;var A3=` #ifndef ENV_ATLAS #define ENV_ATLAS uniform sampler2D texture_envAtlas; @@ -5364,7 +5651,7 @@ vec3 calcReflection(vec3 reflDir, float gloss) { void addReflection(vec3 reflDir, float gloss) { dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity); } -`,reflectionSpherePS:` +`;var C3=` #ifndef VIEWMATRIX #define VIEWMATRIX uniform mat4 matrix_view; @@ -5380,7 +5667,7 @@ vec3 calcReflection(vec3 reflDir, float gloss) { void addReflection(vec3 reflDir, float gloss) { dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity); } -`,reflectionSheenPS:` +`;var P3=` void addReflectionSheen(vec3 worldNormal, vec3 viewDir, float gloss) { float NoV = dot(worldNormal, viewDir); float alphaG = gloss * gloss; @@ -5389,7 +5676,7 @@ void addReflectionSheen(vec3 worldNormal, vec3 viewDir, float gloss) { float DG = exp( a * NoV + b ) + ( gloss < 0.25 ? 0.0 : 0.1 * ( gloss - 0.25 ) ); sReflection += calcReflection(worldNormal, 0.0) * saturate(DG); } -`,refractionCubePS:` +`;var w3=` vec3 refract2(vec3 viewVec, vec3 normal, float IOR) { float vn = dot(viewVec, normal); float k = 1.0 - IOR * IOR * (1.0 - vn * vn); @@ -5418,7 +5705,7 @@ void addRefraction( dDiffuseLight = mix(dDiffuseLight, dReflection.rgb * albedo, transmission); dReflection = tmpRefl; } -`,refractionDynamicPS:` +`;var I3=` uniform float material_invAttenuationDistance; uniform vec3 material_attenuation; vec3 evalRefractionColor(vec3 refractionVector, float gloss, float refractionIndex) { @@ -5486,7 +5773,7 @@ void addRefraction( ); dDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, transmission); } -`,reprojectPS:` +`;var R3=` varying vec2 vUv0; #ifdef CUBEMAP_SOURCE uniform samplerCube sourceCube; @@ -5686,7 +5973,7 @@ vec4 unpackFloat = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0); void main(void) { gl_FragColor = {PROCESS_FUNC}(); } -`,reprojectVS:` +`;var b3=` attribute vec2 vertex_position; uniform vec4 uvMod; varying vec2 vUv0; @@ -5694,7 +5981,7 @@ void main(void) { gl_Position = vec4(vertex_position, 0.5, 1.0); vUv0 = getImageEffectUV((vertex_position.xy * 0.5 + 0.5) * uvMod.xy + uvMod.zw); } -`,screenDepthPS:` +`;var D3=` uniform highp sampler2D uSceneDepthMap; #ifndef SCREENSIZE #define SCREENSIZE @@ -5753,7 +6040,7 @@ float getLinearScreenDepth(vec2 uv) { float getLinearDepth(vec3 pos) { return -(matrix_view * vec4(pos, 1.0)).z; } -`,shadowCascadesPS:` +`;var L3=` int getShadowCascadeIndex(vec4 shadowCascadeDistances, int shadowCascadeCount) { float depth = 1.0 / gl_FragCoord.w; vec4 comparisons = step(shadowCascadeDistances, vec4(depth)); @@ -5783,12 +6070,12 @@ vec3 fadeShadow(vec3 shadowCoord, vec4 shadowCascadeDistances) { } return shadowCoord; } -`,shadowEVSMPS:` +`;var M3=` float linstep(float a, float b, float v) { return saturate((v - a) / (b - a)); } float reduceLightBleeding(float pMax, float amount) { - return linstep(amount, 1.0, pMax); + return linstep(amount, 1.0, pMax); } float chebyshevUpperBound(vec2 moments, float mean, float minVariance, float lightBleedingReduction) { float variance = moments.y - (moments.x * moments.x); @@ -5841,7 +6128,7 @@ float getShadowSpotVSM32(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shado float Z = length(lightDir) * shadowParams.w + shadowParams.z; return VSM32(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent); } -`,shadowPCF1PS:` +`;var O3=` float getShadowPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) { return textureShadow(shadowMap, shadowCoord); } @@ -5854,7 +6141,7 @@ float getShadowOmniPCF1x1(samplerCubeShadow shadowMap, vec3 shadowCoord, vec4 sh return texture(shadowMap, vec4(lightDir, shadowZ)); } #endif -`,shadowPCF3PS:` +`;var F3=` float _getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) { float z = shadowCoord.z; vec2 uv = shadowCoord.xy * shadowParams.x; @@ -5907,7 +6194,7 @@ float getShadowOmniPCF3x3(samplerCubeShadow shadowMap, vec3 shadowCoord, vec4 sh return getShadowOmniPCF3x3(shadowMap, shadowParams, lightDir); } #endif -`,shadowPCF5PS:` +`;var N3=` float _getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) { float z = shadowCoord.z; vec2 uv = shadowCoord.xy * shadowParams.x; @@ -5955,7 +6242,7 @@ float getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadow float getShadowSpotPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) { return _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz); } -`,shadowPCSSPS:` +`;var B3=` #define PCSS_SAMPLE_COUNT 16 uniform float pcssDiskSamples[PCSS_SAMPLE_COUNT]; uniform float pcssSphereSamples[PCSS_SAMPLE_COUNT]; @@ -6075,7 +6362,7 @@ float getShadowOmniPCSS(samplerCube shadowMap, vec3 shadowCoord, vec4 shadowPara float getShadowSpotPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) { return PCSS(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, shadowSearchArea); } -`,shadowSoftPS:` +`;var U3=` highp float fractSinRand(const in vec2 uv) { const float PI = 3.141592653589793; const highp float a = 12.9898, b = 78.233, c = 43758.5453; @@ -6162,7 +6449,7 @@ float PCSSDirectional(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoords, vec4 cameraP float getShadowPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec4 softShadowParams, vec3 lightDir) { return PCSSDirectional(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, softShadowParams); } -`,skinBatchVS:` +`;var k3=` attribute float vertex_boneIndices; uniform highp sampler2D texture_poseMap; mat4 getBoneMatrix(const in float indexFloat) { @@ -6180,7 +6467,7 @@ mat4 getBoneMatrix(const in float indexFloat) { v1.w, v2.w, v3.w, 1 ); } -`,skinVS:` +`;var z3=` attribute vec4 vertex_boneWeights; attribute vec4 vertex_boneIndices; uniform highp sampler2D texture_poseMap; @@ -6213,7 +6500,7 @@ mat4 getSkinMatrix(const in vec4 indicesFloat, const in vec4 weights) { v1.w, v2.w, v3.w, one ); } -`,skyboxPS:` +`;var G3=` #define LIT_SKYBOX_INTENSITY #include "envProcPS" #include "gammaPS" @@ -6283,7 +6570,7 @@ mat4 getSkinMatrix(const in vec4 indicesFloat, const in vec4 weights) { gl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0); #endif } -`,skyboxVS:` +`;var V3=` attribute vec4 aPosition; uniform mat4 matrix_view; uniform mat4 matrix_projectionSkybox; @@ -6324,7 +6611,7 @@ void main(void) { #endif gl_Position.z = gl_Position.w - 1.0e-7; } -`,specularPS:` +`;var H3=` #ifdef STD_SPECULAR_CONSTANT uniform vec3 material_specular; #endif @@ -6341,7 +6628,7 @@ void getSpecularity() { #endif dSpecularity = specularColor; } -`,sphericalPS:` +`;var W3=` vec2 toSpherical(vec3 dir) { return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y)); } @@ -6350,7 +6637,7 @@ vec2 toSphericalUv(vec3 dir) { vec2 uv = toSpherical(dir) / vec2(PI * 2.0, PI) + 0.5; return vec2(uv.x, 1.0 - uv.y); } -`,specularityFactorPS:` +`;var X3=` #ifdef STD_SPECULARITYFACTOR_CONSTANT uniform float material_specularityFactor; #endif @@ -6367,14 +6654,14 @@ void getSpecularityFactor() { #endif dSpecularityFactor = specularityFactor; } -`,spotPS:` +`;var Y3=` float getSpotEffect(vec3 lightSpotDir, float lightInnerConeAngle, float lightOuterConeAngle, vec3 lightDirNorm) { float cosAngle = dot(lightDirNorm, lightSpotDir); return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle); } -`,startNineSlicedPS:` +`;var K3=` nineSlicedUv = vec2(vUv0.x, 1.0 - vUv0.y); -`,startNineSlicedTiledPS:` +`;var j3=` vec2 tileMask = step(vMask, vec2(0.99999)); vec2 tileSize = 0.5 * (innerOffset.xy + innerOffset.zw); vec2 tileScale = vec2(1.0) / (vec2(1.0) - tileSize); @@ -6383,7 +6670,7 @@ float getSpotEffect(vec3 lightSpotDir, float lightInnerConeAngle, float lightOut nineSlicedUv = vUv0 * tileMask + clampedUv * (vec2(1.0) - tileMask); nineSlicedUv.y = 1.0 - nineSlicedUv.y; -`,stdDeclarationPS:` +`;var q3=` float dAlpha = 1.0; #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE #ifdef STD_OPACITY_TEXTURE_ALLOCATE @@ -6523,7 +6810,7 @@ float getSpotEffect(vec3 lightSpotDir, float lightInnerConeAngle, float lightOut #endif #endif #include "litShaderCorePS" -`,stdFrontEndPS:` +`;var $3=` #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE #include "opacityPS" #if defined(LIT_ALPHA_TEST) @@ -6593,7 +6880,7 @@ float getSpotEffect(vec3 lightSpotDir, float lightInnerConeAngle, float lightOut alphaTest(dAlpha); #endif #if STD_OPACITY_DITHER != NONE - opacityDither(dAlpha, 0.0); + opacityDither(dAlpha * material_alphaDitherScale, 0.0); #endif litArgs_opacity = dAlpha; #endif @@ -6670,7 +6957,7 @@ float getSpotEffect(vec3 lightSpotDir, float lightInnerConeAngle, float lightOut #endif #endif } -`,TBNPS:` +`;var Z3=` #ifdef LIT_TANGENTS #define TBN_TANGENTS #else @@ -6722,7 +7009,7 @@ void getTBN(vec3 tangent, vec3 binormal, vec3 normal) { dTBN = mat3(normalize(T), normalize(B), normalize(normal)); #endif } -`,thicknessPS:` +`;var Q3=` #ifdef STD_THICKNESS_CONSTANT uniform float material_thickness; #endif @@ -6738,7 +7025,7 @@ void getThickness() { dThickness *= saturate(vVertexColor.{STD_THICKNESS_VERTEX_CHANNEL}); #endif } -`,tonemappingPS:` +`;var J3=` #ifndef TONEMAP_NO_EXPOSURE_UNIFORM #if TONEMAP != NONE uniform float exposure; @@ -6762,7 +7049,7 @@ void getThickness() { #elif TONEMAP == NEUTRAL #include "tonemappingNeutralPS" #endif -`,tonemappingAcesPS:` +`;var eO=` vec3 toneMap(vec3 color) { float tA = 2.51; float tB = 0.03; @@ -6772,7 +7059,7 @@ vec3 toneMap(vec3 color) { vec3 x = color * getExposure(); return (x*(tA*x+tB))/(x*(tC*x+tD)+tE); } -`,tonemappingAces2PS:` +`;var tO=` const mat3 ACESInputMat = mat3( 0.59719, 0.35458, 0.04823, 0.07600, 0.90834, 0.01566, @@ -6796,7 +7083,7 @@ vec3 toneMap(vec3 color) { color = clamp(color, 0.0, 1.0); return color; } -`,tonemappingFilmicPS:` +`;var sO=` const float A = 0.15; const float B = 0.50; const float C = 0.10; @@ -6805,7 +7092,7 @@ const float E = 0.02; const float F = 0.30; const float W = 11.2; vec3 uncharted2Tonemap(vec3 x) { - return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F; + return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F; } vec3 toneMap(vec3 color) { color = uncharted2Tonemap(color * getExposure()); @@ -6813,7 +7100,7 @@ vec3 toneMap(vec3 color) { color = color * whiteScale; return color; } -`,tonemappingHejlPS:` +`;var iO=` vec3 toneMap(vec3 color) { color *= getExposure(); const float A = 0.22, B = 0.3, C = .1, D = 0.2, E = .01, F = 0.3; @@ -6821,11 +7108,11 @@ vec3 toneMap(vec3 color) { vec3 h = max( vec3(0.0), color - vec3(0.004) ); return (h*((Scl*A)*h+Scl*vec3(C*B,C*B,C*B))+Scl*vec3(D*E,D*E,D*E)) / (h*(A*h+vec3(B,B,B))+vec3(D*F,D*F,D*F)) - Scl*vec3(E/F,E/F,E/F); } -`,tonemappingLinearPS:` +`;var rO=` vec3 toneMap(vec3 color) { return color * getExposure(); } -`,tonemappingNeutralPS:` +`;var aO=` vec3 toneMap(vec3 color) { color *= getExposure(); float startCompression = 0.8 - 0.04; @@ -6841,11 +7128,11 @@ vec3 toneMap(vec3 color) { float g = 1. - 1. / (desaturation * (peak - newPeak) + 1.); return mix(color, newPeak * vec3(1, 1, 1), g); } -`,tonemappingNonePS:` +`;var oO=` vec3 toneMap(vec3 color) { return color; } -`,transformVS:` +`;var nO=` #ifdef PIXELSNAP uniform vec4 uScreenSize; #endif @@ -6899,7 +7186,7 @@ vec4 getPosition() { vec3 getWorldPosition() { return dPositionW; } -`,transformCoreVS:` +`;var lO=` attribute vec4 vertex_position; uniform mat4 matrix_viewProjection; uniform mat4 matrix_model; @@ -6955,7 +7242,7 @@ vec3 getLocalPosition(vec3 vertexPosition) { #endif return localPos; } -`,transformInstancingVS:` +`;var cO=` attribute vec4 instance_line1; attribute vec4 instance_line2; attribute vec4 instance_line3; @@ -6963,7 +7250,7 @@ attribute vec4 instance_line4; mat4 getModelMatrix() { return matrix_model * mat4(instance_line1, instance_line2, instance_line3, instance_line4); } -`,transmissionPS:` +`;var hO=` #ifdef STD_REFRACTION_CONSTANT uniform float material_refraction; #endif @@ -6980,11 +7267,11 @@ void getRefraction() { #endif dTransmission = refraction; } -`,twoSidedLightingPS:` +`;var fO=` void handleTwoSidedLighting() { if (!gl_FrontFacing) dTBN[2] = -dTBN[2]; } -`,uv0VS:` +`;var uO=` #ifdef NINESLICED vec2 getUv0() { vec2 uv = vertex_position.xz; @@ -7001,45 +7288,30 @@ void handleTwoSidedLighting() { return vertex_texCoord0; } #endif -`,uv1VS:` +`;var dO=` vec2 getUv1() { return vertex_texCoord1; } -`,uvTransformVS:` +`;var pO=` vUV{TRANSFORM_UV_{i}}_{TRANSFORM_ID_{i}} = vec2( dot(vec3(uv{TRANSFORM_UV_{i}}, 1), {TRANSFORM_NAME_{i}}0), dot(vec3(uv{TRANSFORM_UV_{i}}, 1), {TRANSFORM_NAME_{i}}1) ); -`,uvTransformUniformsPS:` +`;var mO=` uniform vec3 {TRANSFORM_NAME_{i}}0; uniform vec3 {TRANSFORM_NAME_{i}}1; -`,viewDirPS:` +`;var _O=` void getViewDir() { dViewDirW = normalize(view_position - vPositionW); } -`,webgpuPS:rn,webgpuVS:ro};var ps=` -struct DrawIndexedIndirectArgs { - indexCount: u32, - instanceCount: u32, - firstIndex: u32, - baseVertex: i32, - firstInstance: u32 -}; -struct DrawIndirectArgs { - vertexCount: u32, - instanceCount: u32, - firstVertex: u32, - firstInstance: u32, - _pad: u32 -}; -`;let pr={alphaTestPS:` +`;var gO={alphaTestPS:D2,ambientPS:L2,anisotropyPS:M2,aoPS:O2,aoDiffuseOccPS:F2,aoSpecOccPS:N2,bakeDirLmEndPS:B2,bakeLmEndPS:U2,basePS:k2,baseNineSlicedPS:z2,baseNineSlicedTiledPS:G2,bayerPS:V2,blurVSMPS:H2,clearCoatPS:W2,clearCoatGlossPS:X2,clearCoatNormalPS:Y2,clusteredLightCookiesPS:j2,clusteredLightShadowsPS:q2,clusteredLightUtilsPS:K2,clusteredLightPS:$2,combinePS:Z2,cookieBlit2DPS:Q2,cookieBlitCubePS:J2,cookieBlitVS:e1,cookiePS:t1,cubeMapProjectPS:s1,cubeMapRotatePS:i1,debugOutputPS:r1,debugProcessFrontendPS:a1,detailModesPS:n1,diffusePS:l1,decodePS:o1,emissivePS:c1,encodePS:h1,endPS:f1,envAtlasPS:u1,envProcPS:d1,falloffInvSquaredPS:p1,falloffLinearPS:m1,floatAsUintPS:_1,fogPS:g1,fresnelSchlickPS:S1,frontendCodePS:"",frontendDeclPS:"",fullscreenQuadVS:x1,gammaPS:v1,gles3PS:mv,gles3VS:_v,glossPS:T1,quadVS:y1,immediateLinePS:E1,immediateLineVS:A1,iridescenceDiffractionPS:C1,iridescencePS:P1,iridescenceThicknessPS:w1,iorPS:I1,lightDeclarationPS:R1,lightDiffuseLambertPS:b1,lightDirPointPS:D1,lightEvaluationPS:L1,lightFunctionLightPS:M1,lightFunctionShadowPS:O1,lightingPS:F1,lightmapAddPS:N1,lightmapPS:B1,lightSpecularAnisoGGXPS:U1,lightSpecularGGXPS:k1,lightSpecularBlinnPS:z1,lightSheenPS:G1,linearizeDepthPS:V1,litForwardBackendPS:H1,litForwardDeclarationPS:W1,litForwardMainPS:X1,litForwardPostCodePS:Y1,litForwardPreCodePS:K1,litMainPS:j1,litMainVS:q1,litOtherMainPS:$1,litShaderArgsPS:Z1,litShaderCorePS:Q1,litShadowMainPS:J1,litUserDeclarationPS:"",litUserDeclarationVS:"",litUserCodePS:"",litUserCodeVS:"",litUserMainStartPS:"",litUserMainStartVS:"",litUserMainEndPS:"",litUserMainEndVS:"",ltcPS:e3,metalnessPS:t3,metalnessModulatePS:i3,morphPS:r3,morphVS:a3,msdfPS:s3,msdfVS:o3,normalVS:n3,normalCoreVS:l3,normalMapPS:c3,opacityPS:h3,opacityDitherPS:f3,outputPS:u3,outputAlphaPS:d3,outputTex2DPS:p3,sheenPS:m3,sheenGlossPS:_3,parallaxPS:g3,pickPS:S3,reflDirPS:x3,reflDirAnisoPS:v3,reflectionCCPS:T3,reflectionCubePS:y3,reflectionEnvHQPS:E3,reflectionEnvPS:A3,reflectionSpherePS:C3,reflectionSheenPS:P3,refractionCubePS:w3,refractionDynamicPS:I3,reprojectPS:R3,reprojectVS:b3,screenDepthPS:D3,shadowCascadesPS:L3,shadowEVSMPS:M3,shadowPCF1PS:O3,shadowPCF3PS:F3,shadowPCF5PS:N3,shadowPCSSPS:B3,shadowSoftPS:U3,skinBatchVS:k3,skinVS:z3,skyboxPS:G3,skyboxVS:V3,specularPS:H3,sphericalPS:W3,specularityFactorPS:X3,spotPS:Y3,startNineSlicedPS:K3,startNineSlicedTiledPS:j3,stdDeclarationPS:q3,stdFrontEndPS:$3,TBNPS:Z3,thicknessPS:Q3,tonemappingPS:J3,tonemappingAcesPS:eO,tonemappingAces2PS:tO,tonemappingFilmicPS:sO,tonemappingHejlPS:iO,tonemappingLinearPS:rO,tonemappingNeutralPS:aO,tonemappingNonePS:oO,transformVS:nO,transformCoreVS:lO,transformInstancingVS:cO,transmissionPS:hO,twoSidedLightingPS:fO,uv0VS:uO,uv1VS:dO,uvTransformVS:pO,uvTransformUniformsPS:mO,viewDirPS:_O,webgpuPS:gv,webgpuVS:Sv};var SO=` uniform alpha_ref: f32; fn alphaTest(a: f32) { if (a < uniform.alpha_ref) { discard; } } -`,ambientPS:` +`;var xO=` #if LIT_AMBIENT_SOURCE == AMBIENTSH uniform ambientSH: array; #endif @@ -7077,7 +7349,7 @@ fn addAmbient(worldNormal: vec3f) { dDiffuseLight += uniform.light_globalAmbient; #endif } -`,anisotropyPS:` +`;var vO=` #ifdef LIT_GGX_SPECULAR uniform material_anisotropyIntensity: f32; uniform material_anisotropyRotation: vec2f; @@ -7098,7 +7370,7 @@ fn getAnisotropy() { #endif dAnisotropy = clamp(dAnisotropy, 0.0, 1.0); } -`,aoPS:` +`;var TO=` #if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX) uniform material_aoIntensity: f32; #endif @@ -7122,11 +7394,11 @@ fn getAO() { dAo = mix(1.0, dAo, uniform.material_aoIntensity); #endif } -`,aoDiffuseOccPS:` +`;var yO=` fn occludeDiffuse(ao: f32) { dDiffuseLight = dDiffuseLight * ao; } -`,aoSpecOccPS:` +`;var EO=` #if LIT_OCCLUDE_SPECULAR != NONE #ifdef LIT_OCCLUDE_SPECULAR_FLOAT uniform material_occludeSpecularIntensity: f32; @@ -7156,7 +7428,7 @@ fn occludeSpecular(gloss: f32, ao: f32, worldNormal: vec3f, viewDir: vec3f) { #endif #endif } -`,bakeDirLmEndPS:` +`;var AO=` let dirLm = textureSample(texture_dirLightMap, texture_dirLightMapSampler, vUv1); if (uniform.bakeDir > 0.5) { if (dAtten > 0.00001) { @@ -7174,7 +7446,7 @@ fn occludeSpecular(gloss: f32, ao: f32, worldNormal: vec3f, viewDir: vec3f) { let finalA = max(dirLm.w, alpha_min); output.color = vec4f(dirLm.rgb, finalA); } -`,bakeLmEndPS:` +`;var CO=` #ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT dDiffuseLight = ((dDiffuseLight - 0.5) * max(uniform.ambientBakeOcclusionContrast + 1.0, 0.0)) + 0.5; dDiffuseLight = dDiffuseLight + vec3f(uniform.ambientBakeOcclusionBrightness); @@ -7194,7 +7466,7 @@ fn occludeSpecular(gloss: f32, ao: f32, worldNormal: vec3f, viewDir: vec3f) { #else output.color = vec4f(dDiffuseLight, 1.0); #endif -`,basePS:` +`;var PO=` uniform view_position: vec3f; uniform light_globalAmbient: vec3f; fn square(x: f32) -> f32 { @@ -7206,7 +7478,7 @@ fn saturate(x: f32) -> f32 { fn saturate3(x: vec3f) -> vec3f { return clamp(x, vec3f(0.0), vec3f(1.0)); } -`,baseNineSlicedPS:` +`;var wO=` #define NINESLICED varying vMask: vec2f; varying vTiledUv: vec2f; @@ -7214,7 +7486,7 @@ uniform innerOffset: vec4f; uniform outerScale: vec2f; uniform atlasRect: vec4f; var nineSlicedUv: vec2f; -`,baseNineSlicedTiledPS:` +`;var IO=` #define NINESLICED #define NINESLICETILED varying vMask: vec2f; @@ -7223,7 +7495,7 @@ uniform innerOffset: vec4f; uniform outerScale: vec2f; uniform atlasRect: vec4f; var nineSlicedUv: vec2f; -`,bayerPS:` +`;var RO=` fn bayer2(p: vec2f) -> f32 { return (2.0 * p.y + p.x + 1.0) % 4.0; } @@ -7238,7 +7510,7 @@ fn bayer8(p: vec2f) -> f32 { let p4: vec2f = floor(0.25 * (p % vec2f(8.0))); return 4.0 * (4.0 * bayer2(p1) + bayer2(p2)) + bayer2(p4); } -`,blurVSMPS:` +`;var bO=` varying vUv0: vec2f; var source: texture_2d; var sourceSampler: sampler; @@ -7265,7 +7537,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { output.color = vec4f(moments, 1.0); return output; } -`,clearCoatPS:` +`;var DO=` uniform material_clearCoat: f32; fn getClearCoat() { ccSpecularity = uniform.material_clearCoat; @@ -7276,7 +7548,7 @@ fn getClearCoat() { ccSpecularity = ccSpecularity * saturate(vVertexColor.{STD_CLEARCOAT_VERTEX_CHANNEL}); #endif } -`,clearCoatGlossPS:` +`;var LO=` uniform material_clearCoatGloss: f32; fn getClearCoatGlossiness() { ccGlossiness = uniform.material_clearCoatGloss; @@ -7291,7 +7563,7 @@ fn getClearCoatGlossiness() { #endif ccGlossiness += 0.0000001; } -`,clearCoatNormalPS:` +`;var MO=` #ifdef STD_CLEARCOATNORMAL_TEXTURE uniform material_clearCoatBumpiness: f32; #endif @@ -7304,7 +7576,54 @@ fn getClearCoatNormal() { ccNormalW = dVertexNormalW; #endif } -`,clusteredLightCookiesPS:` +`;var OO=` +struct FaceCoords { + uv: vec2f, + faceIndex: f32, + tileOffset: vec2f, +} +fn getCubemapFaceCoordinates(dir: vec3f) -> FaceCoords { + var faceIndex: f32; + var tileOffset: vec2f; + var uv: vec2f; + let vAbs: vec3f = abs(dir); + var ma: f32; + if (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) { + let is_neg_z = dir.z < 0.0; + faceIndex = select(4.0, 5.0, is_neg_z); + ma = 0.5 / vAbs.z; + uv = vec2f(select(dir.x, -dir.x, is_neg_z), -dir.y); + tileOffset = vec2f(2.0, select(0.0, 1.0, is_neg_z)); + } else if (vAbs.y >= vAbs.x) { + let is_neg_y = dir.y < 0.0; + faceIndex = select(2.0, 3.0, is_neg_y); + ma = 0.5 / vAbs.y; + uv = vec2f(dir.x, select(dir.z, -dir.z, is_neg_y)); + tileOffset = vec2f(1.0, select(0.0, 1.0, is_neg_y)); + } else { + let is_neg_x = dir.x < 0.0; + faceIndex = select(0.0, 1.0, is_neg_x); + ma = 0.5 / vAbs.x; + uv = vec2f(select(-dir.z, dir.z, is_neg_x), -dir.y); + tileOffset = vec2f(0.0, select(0.0, 1.0, is_neg_x)); + } + uv = uv * ma + 0.5; + return FaceCoords(uv, faceIndex, tileOffset); +} +fn getCubemapAtlasCoordinates(omniAtlasViewport: vec3f, shadowEdgePixels: f32, shadowTextureResolution: f32, dir: vec3f) -> vec2f { + let faceData: FaceCoords = getCubemapFaceCoordinates(dir); + var uv: vec2f = faceData.uv; + let tileOffset: vec2f = faceData.tileOffset; + let atlasFaceSize: f32 = omniAtlasViewport.z; + let tileSize: f32 = shadowTextureResolution * atlasFaceSize; + var offset: f32 = shadowEdgePixels / tileSize; + uv = uv * (1.0 - offset * 2.0) + offset; + uv = uv * atlasFaceSize; + uv = uv + tileOffset * atlasFaceSize; + uv = uv + omniAtlasViewport.xy; + return uv; +} +`;var FO=` fn _getCookieClustered(tex: texture_2d, texSampler: sampler, uv: vec2f, intensity: f32, cookieChannel: vec4f) -> vec3f { let pixel: vec4f = mix(vec4f(1.0), textureSampleLevel(tex, texSampler, uv, 0.0), intensity); let isRgb: bool = dot(cookieChannel.rgb, vec3f(1.0)) == 3.0; @@ -7318,7 +7637,7 @@ fn getCookieCubeClustered(tex: texture_2d, texSampler: sampler, dir: vec3f, let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir); return _getCookieClustered(tex, texSampler, uv, intensity, cookieChannel); } -`,clusteredLightShadowsPS:` +`;var NO=` fn _getShadowCoordPerspZbuffer(shadowMatrix: mat4x4f, shadowParams: vec4f, wPos: vec3f) -> vec3f { var projPos = shadowMatrix * vec4f(wPos, 1.0); return projPos.xyz / projPos.w; @@ -7374,54 +7693,7 @@ fn normalOffsetPointShadow(shadowParams: vec4f, lightPos: vec3f, lightDir: vec3f return getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams); } #endif -`,clusteredLightUtilsPS:` -struct FaceCoords { - uv: vec2f, - faceIndex: f32, - tileOffset: vec2f, -} -fn getCubemapFaceCoordinates(dir: vec3f) -> FaceCoords { - var faceIndex: f32; - var tileOffset: vec2f; - var uv: vec2f; - let vAbs: vec3f = abs(dir); - var ma: f32; - if (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) { - let is_neg_z = dir.z < 0.0; - faceIndex = select(4.0, 5.0, is_neg_z); - ma = 0.5 / vAbs.z; - uv = vec2f(select(dir.x, -dir.x, is_neg_z), -dir.y); - tileOffset = vec2f(2.0, select(0.0, 1.0, is_neg_z)); - } else if (vAbs.y >= vAbs.x) { - let is_neg_y = dir.y < 0.0; - faceIndex = select(2.0, 3.0, is_neg_y); - ma = 0.5 / vAbs.y; - uv = vec2f(dir.x, select(dir.z, -dir.z, is_neg_y)); - tileOffset = vec2f(1.0, select(0.0, 1.0, is_neg_y)); - } else { - let is_neg_x = dir.x < 0.0; - faceIndex = select(0.0, 1.0, is_neg_x); - ma = 0.5 / vAbs.x; - uv = vec2f(select(-dir.z, dir.z, is_neg_x), -dir.y); - tileOffset = vec2f(0.0, select(0.0, 1.0, is_neg_x)); - } - uv = uv * ma + 0.5; - return FaceCoords(uv, faceIndex, tileOffset); -} -fn getCubemapAtlasCoordinates(omniAtlasViewport: vec3f, shadowEdgePixels: f32, shadowTextureResolution: f32, dir: vec3f) -> vec2f { - let faceData: FaceCoords = getCubemapFaceCoordinates(dir); - var uv: vec2f = faceData.uv; - let tileOffset: vec2f = faceData.tileOffset; - let atlasFaceSize: f32 = omniAtlasViewport.z; - let tileSize: f32 = shadowTextureResolution * atlasFaceSize; - var offset: f32 = shadowEdgePixels / tileSize; - uv = uv * (1.0 - offset * 2.0) + offset; - uv = uv * atlasFaceSize; - uv = uv + tileOffset * atlasFaceSize; - uv = uv + omniAtlasViewport.xy; - return uv; -} -`,clusteredLightPS:` +`;var BO=` #include "lightBufferDefinesPS" #include "clusteredLightUtilsPS" #ifdef CLUSTER_COOKIES @@ -7450,95 +7722,103 @@ uniform clusterCellsDot: vec3i; uniform clusterCellsMax: vec3i; uniform shadowAtlasParams: vec2f; struct ClusterLightData { - flags: u32, - halfWidth: vec3f, - isSpot: bool, - halfHeight: vec3f, - lightIndex: i32, position: vec3f, - shape: u32, + lightIndex: i32, direction: vec3f, - falloffModeLinear: bool, + shape: u32, color: vec3f, shadowIntensity: f32, - omniAtlasViewport: vec3f, range: f32, - cookieChannelMask: vec4f, biasesData: f32, - colorBFlagsData: u32, - shadowBias: f32, - shadowNormalBias: f32, - anglesData: f32, - innerConeAngleCos: f32, - outerConeAngleCos: f32, cookieIntensity: f32, + isSpot: bool, + falloffModeLinear: bool, isDynamic: bool, isLightmapped: bool } +struct ClusterLightSpotData { + innerConeAngleCos: f32, + outerConeAngleCos: f32 +} +struct ClusterLightAreaData { + halfWidth: vec3f, + halfHeight: vec3f +} +struct ClusterLightShadowData { + shadowBias: f32, + shadowNormalBias: f32 +} var lightProjectionMatrix: mat4x4f; +var clusterLightData_flags: u32; +var clusterLightData_anglesData: f32; +var clusterLightData_colorBFlagsData: u32; fn sampleLightTextureF(lightIndex: i32, index: i32) -> vec4f { return textureLoad(lightsTexture, vec2(index, lightIndex), 0); } -fn decodeClusterLightCore(clusterLightData: ptr, lightIndex: i32) { +fn decodeClusterLightCore(lightIndex: i32) -> ClusterLightData { + var clusterLightData: ClusterLightData; clusterLightData.lightIndex = lightIndex; - let halfData: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_COLOR_ANGLES_BIAS}); - clusterLightData.anglesData = halfData.z; + let halfData: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_COLOR_ANGLES_BIAS}); + clusterLightData_anglesData = halfData.z; clusterLightData.biasesData = halfData.w; - clusterLightData.colorBFlagsData = bitcast(halfData.y); + clusterLightData_colorBFlagsData = bitcast(halfData.y); let colorRG: vec2f = unpack2x16float(bitcast(halfData.x)); - let colorB_flags: vec2f = unpack2x16float(clusterLightData.colorBFlagsData); + let colorB_flags: vec2f = unpack2x16float(clusterLightData_colorBFlagsData); clusterLightData.color = vec3f(colorRG, colorB_flags.x) * {LIGHT_COLOR_DIVIDER}; - let lightPosRange: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_POSITION_RANGE}); + let lightPosRange: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_POSITION_RANGE}); clusterLightData.position = lightPosRange.xyz; clusterLightData.range = lightPosRange.w; - let lightDir_Flags: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_DIRECTION_FLAGS}); + let lightDir_Flags: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_DIRECTION_FLAGS}); clusterLightData.direction = lightDir_Flags.xyz; - let flags_uint: u32 = bitcast(lightDir_Flags.w); - clusterLightData.flags = flags_uint; - clusterLightData.isSpot = (flags_uint & (1u << 30u)) != 0u; - clusterLightData.shape = (flags_uint >> 28u) & 0x3u; - clusterLightData.falloffModeLinear = (flags_uint & (1u << 27u)) == 0u; - clusterLightData.shadowIntensity = f32((flags_uint >> 0u) & 0xFFu) / 255.0; - clusterLightData.cookieIntensity = f32((flags_uint >> 8u) & 0xFFu) / 255.0; - clusterLightData.isDynamic = (flags_uint & (1u << 22u)) != 0u; - clusterLightData.isLightmapped = (flags_uint & (1u << 21u)) != 0u; + clusterLightData_flags = bitcast(lightDir_Flags.w); + clusterLightData.isSpot = (clusterLightData_flags & (1u << 30u)) != 0u; + clusterLightData.shape = (clusterLightData_flags >> 28u) & 0x3u; + clusterLightData.falloffModeLinear = (clusterLightData_flags & (1u << 27u)) == 0u; + clusterLightData.shadowIntensity = f32((clusterLightData_flags >> 0u) & 0xFFu) / 255.0; + clusterLightData.cookieIntensity = f32((clusterLightData_flags >> 8u) & 0xFFu) / 255.0; + clusterLightData.isDynamic = (clusterLightData_flags & (1u << 22u)) != 0u; + clusterLightData.isLightmapped = (clusterLightData_flags & (1u << 21u)) != 0u; + return clusterLightData; } -fn decodeClusterLightSpot(clusterLightData: ptr) { - let angleFlags: u32 = (clusterLightData.colorBFlagsData >> 16u) & 0xFFFFu; - let angleValues: vec2f = unpack2x16float(bitcast(clusterLightData.anglesData)); +fn decodeClusterLightSpot() -> ClusterLightSpotData { + let angleFlags: u32 = (clusterLightData_colorBFlagsData >> 16u) & 0xFFFFu; + let angleValues: vec2f = unpack2x16float(bitcast(clusterLightData_anglesData)); let innerVal: f32 = angleValues.x; let outerVal: f32 = angleValues.y; let innerIsVersine: bool = (angleFlags & 1u) != 0u; let outerIsVersine: bool = ((angleFlags >> 1u) & 1u) != 0u; - clusterLightData.innerConeAngleCos = select(innerVal, 1.0 - innerVal, innerIsVersine); - clusterLightData.outerConeAngleCos = select(outerVal, 1.0 - outerVal, outerIsVersine); + return ClusterLightSpotData( + select(innerVal, 1.0 - innerVal, innerIsVersine), + select(outerVal, 1.0 - outerVal, outerIsVersine) + ); } -fn decodeClusterLightOmniAtlasViewport(clusterLightData: ptr) { - clusterLightData.omniAtlasViewport = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}).xyz; +fn decodeClusterLightOmniAtlasViewport(lightIndex: i32) -> vec3f { + return sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}).xyz; } -fn decodeClusterLightAreaData(clusterLightData: ptr) { - clusterLightData.halfWidth = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_AREA_DATA_WIDTH}).xyz; - clusterLightData.halfHeight = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_AREA_DATA_HEIGHT}).xyz; +fn decodeClusterLightAreaData(lightIndex: i32) -> ClusterLightAreaData { + return ClusterLightAreaData( + sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_AREA_DATA_WIDTH}).xyz, + sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_AREA_DATA_HEIGHT}).xyz + ); } -fn decodeClusterLightProjectionMatrixData(clusterLightData: ptr) { - let m0: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}); - let m1: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_1}); - let m2: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_2}); - let m3: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_3}); - lightProjectionMatrix = mat4x4f(m0, m1, m2, m3); +fn decodeClusterLightProjectionMatrixData(lightIndex: i32) -> mat4x4f { + let m0: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}); + let m1: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_1}); + let m2: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_2}); + let m3: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_3}); + return mat4x4f(m0, m1, m2, m3); } -fn decodeClusterLightShadowData(clusterLightData: ptr) { - let biases: vec2f = unpack2x16float(bitcast(clusterLightData.biasesData)); - clusterLightData.shadowBias = biases.x; - clusterLightData.shadowNormalBias = biases.y; +fn decodeClusterLightShadowData(biasesData: f32) -> ClusterLightShadowData { + let biases: vec2f = unpack2x16float(bitcast(biasesData)); + return ClusterLightShadowData(biases.x, biases.y); } -fn decodeClusterLightCookieData(clusterLightData: ptr) { - let cookieFlags: u32 = (clusterLightData.flags >> 23u) & 0x0Fu; +fn decodeClusterLightCookieData() -> vec4f { + let cookieFlags: u32 = (clusterLightData_flags >> 23u) & 0x0Fu; let mask_uvec: vec4 = vec4(cookieFlags) & vec4(1u, 2u, 4u, 8u); - clusterLightData.cookieChannelMask = step(vec4f(1.0), vec4f(mask_uvec)); + return step(vec4f(1.0), vec4f(mask_uvec)); } fn evaluateLight( - light: ptr, + light: ClusterLightData, worldNormal: vec3f, viewDir: vec3f, reflectionDir: vec3f, @@ -7564,13 +7844,13 @@ fn evaluateLight( let lightDirNormW: vec3f = normalize(lightDirW); #ifdef CLUSTER_AREALIGHTS if (light.shape != {LIGHTSHAPE_PUNCTUAL}) { - decodeClusterLightAreaData(light); + let areaData: ClusterLightAreaData = decodeClusterLightAreaData(light.lightIndex); if (light.shape == {LIGHTSHAPE_RECT}) { - calcRectLightValues(light.position, light.halfWidth, light.halfHeight); + calcRectLightValues(light.position, areaData.halfWidth, areaData.halfHeight); } else if (light.shape == {LIGHTSHAPE_DISK}) { - calcDiskLightValues(light.position, light.halfWidth, light.halfHeight); + calcDiskLightValues(light.position, areaData.halfWidth, areaData.halfHeight); } else { - calcSphereLightValues(light.position, light.halfWidth, light.halfHeight); + calcSphereLightValues(light.position, areaData.halfWidth, areaData.halfHeight); } falloffAttenuation = getFalloffWindow(light.range, lightDirW); } else @@ -7598,33 +7878,34 @@ fn evaluateLight( falloffAttenuation = falloffAttenuation * getLightDiffuse(worldNormal, viewDir, lightDirNormW); } if (light.isSpot) { - decodeClusterLightSpot(light); - falloffAttenuation = falloffAttenuation * getSpotEffect(light.direction, light.innerConeAngleCos, light.outerConeAngleCos, lightDirNormW); + let spotData: ClusterLightSpotData = decodeClusterLightSpot(); + falloffAttenuation = falloffAttenuation * getSpotEffect(light.direction, spotData.innerConeAngleCos, spotData.outerConeAngleCos, lightDirNormW); } #if defined(CLUSTER_COOKIES) || defined(CLUSTER_SHADOWS) if (falloffAttenuation > 0.00001) { if (light.shadowIntensity > 0.0 || light.cookieIntensity > 0.0) { + var omniAtlasViewport: vec3f = vec3f(0.0); if (light.isSpot) { - decodeClusterLightProjectionMatrixData(light); + lightProjectionMatrix = decodeClusterLightProjectionMatrixData(light.lightIndex); } else { - decodeClusterLightOmniAtlasViewport(light); + omniAtlasViewport = decodeClusterLightOmniAtlasViewport(light.lightIndex); } let shadowTextureResolution: f32 = uniform.shadowAtlasParams.x; let shadowEdgePixels: f32 = uniform.shadowAtlasParams.y; #ifdef CLUSTER_COOKIES if (light.cookieIntensity > 0.0) { - decodeClusterLightCookieData(light); + let cookieChannelMask: vec4f = decodeClusterLightCookieData(); if (light.isSpot) { - cookieAttenuation = getCookie2DClustered(cookieAtlasTexture, cookieAtlasTextureSampler, lightProjectionMatrix, vPositionW, light.cookieIntensity, light.cookieChannelMask); + cookieAttenuation = getCookie2DClustered(cookieAtlasTexture, cookieAtlasTextureSampler, lightProjectionMatrix, vPositionW, light.cookieIntensity, cookieChannelMask); } else { - cookieAttenuation = getCookieCubeClustered(cookieAtlasTexture, cookieAtlasTextureSampler, lightDirW, light.cookieIntensity, light.cookieChannelMask, shadowTextureResolution, shadowEdgePixels, light.omniAtlasViewport); + cookieAttenuation = getCookieCubeClustered(cookieAtlasTexture, cookieAtlasTextureSampler, lightDirW, light.cookieIntensity, cookieChannelMask, shadowTextureResolution, shadowEdgePixels, omniAtlasViewport); } } #endif #ifdef CLUSTER_SHADOWS if (light.shadowIntensity > 0.0) { - decodeClusterLightShadowData(light); - let shadowParams: vec4f = vec4f(shadowTextureResolution, light.shadowNormalBias, light.shadowBias, 1.0 / light.range); + let shadowData: ClusterLightShadowData = decodeClusterLightShadowData(light.biasesData); + let shadowParams: vec4f = vec4f(shadowTextureResolution, shadowData.shadowNormalBias, shadowData.shadowBias, 1.0 / light.range); if (light.isSpot) { let shadowCoord: vec3f = getShadowCoordPerspZbufferNormalOffset(lightProjectionMatrix, shadowParams, geometricNormal); #if defined(CLUSTER_SHADOW_TYPE_PCF1) @@ -7640,11 +7921,11 @@ fn evaluateLight( } else { let dir: vec3f = normalOffsetPointShadow(shadowParams, light.position, lightDirW, lightDirNormW, geometricNormal); #if defined(CLUSTER_SHADOW_TYPE_PCF1) - let shadow: f32 = getShadowOmniClusteredPCF1(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir); + let shadow: f32 = getShadowOmniClusteredPCF1(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, omniAtlasViewport, shadowEdgePixels, dir); #elif defined(CLUSTER_SHADOW_TYPE_PCF3) - let shadow: f32 = getShadowOmniClusteredPCF3(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir); + let shadow: f32 = getShadowOmniClusteredPCF3(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, omniAtlasViewport, shadowEdgePixels, dir); #elif defined(CLUSTER_SHADOW_TYPE_PCF5) - let shadow: f32 = getShadowOmniClusteredPCF5(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir); + let shadow: f32 = getShadowOmniClusteredPCF5(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, omniAtlasViewport, shadowEdgePixels, dir); #endif falloffAttenuation = falloffAttenuation * mix(1.0, shadow, light.shadowIntensity); } @@ -7749,8 +8030,7 @@ fn evaluateClusterLight( sheen_gloss: f32, iridescence_intensity: f32 ) { - var clusterLightData: ClusterLightData; - decodeClusterLightCore(&clusterLightData, lightIndex); + let clusterLightData: ClusterLightData = decodeClusterLightCore(lightIndex); #ifdef CLUSTER_MESH_DYNAMIC_LIGHTS let acceptLightMask: bool = clusterLightData.isDynamic; #else @@ -7758,7 +8038,7 @@ fn evaluateClusterLight( #endif if (acceptLightMask) { evaluateLight( - &clusterLightData, + clusterLightData, worldNormal, viewDir, reflectionDir, @@ -7833,7 +8113,7 @@ fn addClusteredLights( ); } } -}`,combinePS:` +}`;var UO=` fn combineColor(albedo: vec3f, sheenSpecularity: vec3f, clearcoatSpecularity: f32) -> vec3f { var ret: vec3f = vec3f(0.0); #ifdef LIT_OLD_AMBIENT @@ -7857,7 +8137,7 @@ fn combineColor(albedo: vec3f, sheenSpecularity: vec3f, clearcoatSpecularity: f3 #endif return ret; } -`,cookieBlit2DPS:` +`;var kO=` varying uv0: vec2f; var blitTexture: texture_2d; var blitTextureSampler : sampler; @@ -7867,7 +8147,7 @@ fn combineColor(albedo: vec3f, sheenSpecularity: vec3f, clearcoatSpecularity: f3 output.color = textureSample(blitTexture, blitTextureSampler, input.uv0); return output; } -`,cookieBlitCubePS:` +`;var zO=` varying uv0: vec2f; uniform invViewProj: mat4x4; var blitTexture: texture_cube; @@ -7880,7 +8160,7 @@ fn combineColor(albedo: vec3f, sheenSpecularity: vec3f, clearcoatSpecularity: f3 output.color = textureSample(blitTexture, blitTextureSampler, worldPos.xyz); return output; } -`,cookieBlitVS:` +`;var GO=` attribute vertex_position: vec2f; varying uv0: vec2f; @vertex @@ -7891,7 +8171,7 @@ fn combineColor(albedo: vec3f, sheenSpecularity: vec3f, clearcoatSpecularity: f3 output.uv0.y = 1.0 - output.uv0.y; return output; } -`,cubeMapProjectPS:` +`;var VO=` #if LIT_CUBEMAP_PROJECTION == BOX uniform envBoxMin: vec3f; uniform envBoxMax: vec3f; @@ -7911,7 +8191,7 @@ fn cubeMapProject(nrdir: vec3f) -> vec3f { return normalize(posonbox - envBoxPos); #endif } -`,cubeMapRotatePS:` +`;var HO=` #ifdef CUBEMAP_ROTATION uniform cubeMapRotationMatrix: mat3x3f; #endif @@ -7922,7 +8202,7 @@ fn cubeMapRotate(refDir: vec3f) -> vec3f { return refDir; #endif } -`,debugOutputPS:` +`;var WO=` #ifdef DEBUG_ALBEDO_PASS output.color = vec4(gammaCorrectOutput(dAlbedo), 1.0); #endif @@ -7950,7 +8230,7 @@ output.color = vec4f(vec3f(litArgs_ao) , 1.0); #ifdef DEBUG_EMISSION_PASS output.color = vec4f(gammaCorrectOutput(litArgs_emission), 1.0); #endif -`,debugProcessFrontendPS:` +`;var XO=` #ifdef DEBUG_LIGHTING_PASS litArgs_albedo = vec3f(0.5); #endif @@ -7961,48 +8241,7 @@ output.color = vec4f(gammaCorrectOutput(litArgs_emission), 1.0); litArgs_albedo = vec3f(0.0); #endif #endif -`,detailModesPS:` -#ifndef _DETAILMODES_INCLUDED_ -#define _DETAILMODES_INCLUDED_ -fn detailMode_mul(c1: vec3f, c2: vec3f) -> vec3f { - return c1 * c2; -} -fn detailMode_add(c1: vec3f, c2: vec3f) -> vec3f { - return c1 + c2; -} -fn detailMode_screen(c1: vec3f, c2: vec3f) -> vec3f { - return 1.0 - (1.0 - c1)*(1.0 - c2); -} -fn detailMode_overlay(c1: vec3f, c2: vec3f) -> vec3f { - return mix(1.0 - 2.0 * (1.0 - c1)*(1.0 - c2), 2.0 * c1 * c2, step(c1, vec3f(0.5))); -} -fn detailMode_min(c1: vec3f, c2: vec3f) -> vec3f { - return min(c1, c2); -} -fn detailMode_max(c1: vec3f, c2: vec3f) -> vec3f { - return max(c1, c2); -} -#endif -`,diffusePS:` -uniform material_diffuse: vec3f; -#ifdef STD_DIFFUSEDETAIL_TEXTURE - #include "detailModesPS" -#endif -fn getAlbedo() { - dAlbedo = uniform.material_diffuse.rgb; - #ifdef STD_DIFFUSE_TEXTURE - var albedoTexture: vec3f = {STD_DIFFUSE_TEXTURE_DECODE}(textureSampleBias({STD_DIFFUSE_TEXTURE_NAME}, {STD_DIFFUSE_TEXTURE_NAME}Sampler, {STD_DIFFUSE_TEXTURE_UV}, uniform.textureBias)).{STD_DIFFUSE_TEXTURE_CHANNEL}; - #ifdef STD_DIFFUSEDETAIL_TEXTURE - var albedoDetail: vec3f = {STD_DIFFUSEDETAIL_TEXTURE_DECODE}(textureSampleBias({STD_DIFFUSEDETAIL_TEXTURE_NAME}, {STD_DIFFUSEDETAIL_TEXTURE_NAME}Sampler, {STD_DIFFUSEDETAIL_TEXTURE_UV}, uniform.textureBias)).{STD_DIFFUSEDETAIL_TEXTURE_CHANNEL}; - albedoTexture = detailMode_{STD_DIFFUSEDETAIL_DETAILMODE}(albedoTexture, albedoDetail); - #endif - dAlbedo = dAlbedo * albedoTexture; - #endif - #ifdef STD_DIFFUSE_VERTEX - dAlbedo = dAlbedo * saturate3(vVertexColor.{STD_DIFFUSE_VERTEX_CHANNEL}); - #endif -} -`,decodePS:` +`;var YO=` #ifndef _DECODE_INCLUDED_ #define _DECODE_INCLUDED_ fn decodeLinear(raw: vec4f) -> vec3f { @@ -8039,7 +8278,48 @@ fn unpackNormalXY(nmap: vec4f) -> vec3f { return vec3f(xy, sqrt(1.0 - clamp(dot(xy, xy), 0.0, 1.0))); } #endif -`,emissivePS:` +`;var KO=` +#ifndef _DETAILMODES_INCLUDED_ +#define _DETAILMODES_INCLUDED_ +fn detailMode_mul(c1: vec3f, c2: vec3f) -> vec3f { + return c1 * c2; +} +fn detailMode_add(c1: vec3f, c2: vec3f) -> vec3f { + return c1 + c2; +} +fn detailMode_screen(c1: vec3f, c2: vec3f) -> vec3f { + return 1.0 - (1.0 - c1)*(1.0 - c2); +} +fn detailMode_overlay(c1: vec3f, c2: vec3f) -> vec3f { + return mix(1.0 - 2.0 * (1.0 - c1)*(1.0 - c2), 2.0 * c1 * c2, step(c1, vec3f(0.5))); +} +fn detailMode_min(c1: vec3f, c2: vec3f) -> vec3f { + return min(c1, c2); +} +fn detailMode_max(c1: vec3f, c2: vec3f) -> vec3f { + return max(c1, c2); +} +#endif +`;var jO=` +uniform material_diffuse: vec3f; +#ifdef STD_DIFFUSEDETAIL_TEXTURE + #include "detailModesPS" +#endif +fn getAlbedo() { + dAlbedo = uniform.material_diffuse.rgb; + #ifdef STD_DIFFUSE_TEXTURE + var albedoTexture: vec3f = {STD_DIFFUSE_TEXTURE_DECODE}(textureSampleBias({STD_DIFFUSE_TEXTURE_NAME}, {STD_DIFFUSE_TEXTURE_NAME}Sampler, {STD_DIFFUSE_TEXTURE_UV}, uniform.textureBias)).{STD_DIFFUSE_TEXTURE_CHANNEL}; + #ifdef STD_DIFFUSEDETAIL_TEXTURE + var albedoDetail: vec3f = {STD_DIFFUSEDETAIL_TEXTURE_DECODE}(textureSampleBias({STD_DIFFUSEDETAIL_TEXTURE_NAME}, {STD_DIFFUSEDETAIL_TEXTURE_NAME}Sampler, {STD_DIFFUSEDETAIL_TEXTURE_UV}, uniform.textureBias)).{STD_DIFFUSEDETAIL_TEXTURE_CHANNEL}; + albedoTexture = detailMode_{STD_DIFFUSEDETAIL_DETAILMODE}(albedoTexture, albedoDetail); + #endif + dAlbedo = dAlbedo * albedoTexture; + #endif + #ifdef STD_DIFFUSE_VERTEX + dAlbedo = dAlbedo * saturate3(vVertexColor.{STD_DIFFUSE_VERTEX_CHANNEL}); + #endif +} +`;var qO=` uniform material_emissive: vec3f; uniform material_emissiveIntensity: f32; fn getEmission() { @@ -8051,7 +8331,7 @@ fn getEmission() { dEmission = dEmission * saturate3(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL}); #endif } -`,encodePS:` +`;var $O=` fn encodeLinear(source: vec3f) -> vec4f { return vec4f(source, 1.0); } @@ -8082,14 +8362,14 @@ fn encodeRGBE(source: vec3f) -> vec4f { return vec4f(source / pow(2.0, e), (e + 128.0) / 255.0); } } -`,endPS:` +`;var ZO=` var finalRgb: vec3f = combineColor(litArgs_albedo, litArgs_sheen_specularity, litArgs_clearcoat_specularity); finalRgb = finalRgb + litArgs_emission; finalRgb = addFog(finalRgb); finalRgb = toneMap(finalRgb); finalRgb = gammaCorrectOutput(finalRgb); output.color = vec4f(finalRgb, output.color.a); -`,envAtlasPS:` +`;var QO=` #ifndef _ENVATLAS_INCLUDED_ #define _ENVATLAS_INCLUDED_ const atlasSize : f32 = 512.0; @@ -8107,7 +8387,7 @@ fn mapShinyUv(uv : vec2f, level : f32) -> vec2f { return mapUv(uv, vec4f(1.0 - t, 1.0 - t, t, t * 0.5)); } #endif -`,envProcPS:` +`;var JO=` #ifdef LIT_SKYBOX_INTENSITY uniform skyboxIntensity : f32; #endif @@ -8118,7 +8398,7 @@ fn processEnvironment(color : vec3f) -> vec3f { return color; #endif } -`,falloffInvSquaredPS:` +`;var eF=` fn getFalloffWindow(lightRadius: f32, lightDir: vec3f) -> f32 { let sqrDist: f32 = dot(lightDir, lightDir); let invRadius: f32 = 1.0 / lightRadius; @@ -8132,12 +8412,12 @@ fn getFalloffInvSquared(lightRadius: f32, lightDir: vec3f) -> f32 { falloff = falloff * square(saturate(1.0 - square(sqrDist * square(invRadius)))); return falloff; } -`,falloffLinearPS:` +`;var tF=` fn getFalloffLinear(lightRadius: f32, lightDir: vec3f) -> f32 { let d: f32 = length(lightDir); return max(((lightRadius - d) / lightRadius), 0.0); } -`,floatAsUintPS:` +`;var sF=` #ifndef FLOAT_AS_UINT #define FLOAT_AS_UINT fn float2uint(value: f32) -> vec4f { @@ -8166,7 +8446,7 @@ fn float2vec4(value: f32) -> vec4f { #endif } #endif -`,fogPS:` +`;var iF=` #include "fogMathPS" var dBlendModeFogFactor : f32 = 1.0; #if (FOG != NONE) @@ -8212,7 +8492,7 @@ var dBlendModeFogFactor : f32 = 1.0; #endif } #endif -`,fogMathPS:` +`;var rF=` fn evaluateFogFactorLinear(depth: f32, fogStart: f32, fogEnd: f32) -> f32 { return clamp((fogEnd - depth) / (fogEnd - fogStart), 0.0, 1.0); } @@ -8222,7 +8502,11 @@ fn evaluateFogFactorExp(depth: f32, fogDensity: f32) -> f32 { fn evaluateFogFactorExp2(depth: f32, fogDensity: f32) -> f32 { return clamp(exp(-depth * depth * fogDensity * fogDensity), 0.0, 1.0); } -`,fresnelSchlickPS:` +`;var aF=` +fn pow5(x: f32) -> f32 { + let x2: f32 = x * x; + return x2 * x2 * x; +} fn getFresnel( cosTheta: f32, gloss: f32, @@ -8232,7 +8516,7 @@ fn getFresnel( iridescenceIntensity: f32 #endif ) -> vec3f { - let fresnel: f32 = pow(1.0 - saturate(cosTheta), 5.0); + let fresnel: f32 = pow5(1.0 - saturate(cosTheta)); let glossSq: f32 = gloss * gloss; let specIntensity: f32 = max(specularity.r, max(specularity.g, specularity.b)); let ret: vec3f = specularity + (max(vec3f(glossSq * specIntensity), specularity) - specularity) * fresnel; @@ -8243,9 +8527,9 @@ fn getFresnel( #endif } fn getFresnelCC(cosTheta: f32) -> f32 { - let fresnel: f32 = pow(1.0 - saturate(cosTheta), 5.0); + let fresnel: f32 = pow5(1.0 - saturate(cosTheta)); return 0.04 + (1.0 - 0.04) * fresnel; -}`,frontendCodePS:"",frontendDeclPS:"",fullscreenQuadVS:` +}`;var oF=` attribute vertex_position: vec2f; varying vUv0: vec2f; @vertex @@ -8255,7 +8539,7 @@ fn vertexMain(input: VertexInput) -> VertexOutput { output.vUv0 = input.vertex_position.xy * 0.5 + vec2f(0.5); return output; } -`,gammaPS:` +`;var nF=` #include "decodePS" #if (GAMMA == SRGB) fn gammaCorrectInput(color: f32) -> f32 { @@ -8284,7 +8568,7 @@ fn vertexMain(input: VertexInput) -> VertexOutput { return color; } #endif -`,glossPS:` +`;var lF=` #ifdef STD_GLOSS_CONSTANT uniform material_gloss: f32; #endif @@ -8304,7 +8588,7 @@ fn getGlossiness() { #endif dGlossiness = dGlossiness + 0.0000001; } -`,quadVS:` +`;var cF=` attribute aPosition: vec2f; varying uv0: vec2f; @vertex fn vertexMain(input: VertexInput) -> VertexOutput { @@ -8313,7 +8597,22 @@ fn getGlossiness() { output.uv0 = getImageEffectUV((input.aPosition + 1.0) * 0.5); return output; } -`,indirectCoreCS:ps,immediateLinePS:` +`;var Jc=` +struct DrawIndexedIndirectArgs { + indexCount: u32, + instanceCount: u32, + firstIndex: u32, + baseVertex: i32, + firstInstance: u32 +}; +struct DrawIndirectArgs { + vertexCount: u32, + instanceCount: u32, + firstVertex: u32, + firstInstance: u32, + _pad: u32 +}; +`;var hF=` #include "gammaPS" varying color: vec4f; @fragment @@ -8322,7 +8621,7 @@ fn getGlossiness() { output.color = vec4f(gammaCorrectOutput(decodeGamma3(input.color.rgb)), input.color.a); return output; } -`,immediateLineVS:` +`;var fF=` attribute vertex_position: vec4f; attribute vertex_color: vec4f; uniform matrix_model: mat4x4f; @@ -8335,7 +8634,7 @@ fn getGlossiness() { output.position = uniform.matrix_viewProjection * uniform.matrix_model * input.vertex_position; return output; } -`,iridescenceDiffractionPS:` +`;var uF=` uniform material_iridescenceRefractionIndex: f32; fn iridescence_iorToFresnelScalar(transmittedIor: f32, incidentIor: f32) -> f32 { return pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0); @@ -8413,7 +8712,7 @@ fn calcIridescence(outsideIor: f32, cosTheta: f32, base_f0: vec3f, iridescenceTh fn getIridescenceDiffraction(cosTheta: f32, specularity: vec3f, iridescenceThickness: f32) -> vec3f { return calcIridescence(1.0, cosTheta, specularity, iridescenceThickness); } -`,iridescencePS:` +`;var dF=` #ifdef STD_IRIDESCENCE_CONSTANT uniform material_iridescence: f32; #endif @@ -8427,7 +8726,7 @@ fn getIridescence() { #endif dIridescence = iridescence; } -`,iridescenceThicknessPS:` +`;var pF=` uniform material_iridescenceThicknessMax: f32; #ifdef STD_IRIDESCENCETHICKNESS_TEXTURE uniform material_iridescenceThicknessMin: f32; @@ -8441,7 +8740,7 @@ fn getIridescenceThickness() { #endif dIridescenceThickness = iridescenceThickness; } -`,iorPS:` +`;var mF=` #ifdef STD_IOR_CONSTANT uniform material_refractionIndex: f32; #endif @@ -8452,7 +8751,7 @@ fn getIor() { dIor = 1.0 / 1.5; #endif } -`,lightDeclarationPS:` +`;var _F=` #if defined(LIGHT{i}) uniform light{i}_color: vec3f; #if LIGHT{i}TYPE == DIRECTIONAL @@ -8504,7 +8803,6 @@ fn getIor() { #endif #if LIGHT{i}TYPE == OMNI NOT SUPPORTED - #else #if defined(LIGHT{i}SHADOW_PCF) var light{i}_shadowMap: texture_depth_2d; @@ -8525,15 +8823,15 @@ fn getIor() { #endif #endif #endif -`,lightDiffuseLambertPS:` +`;var gF=` fn getLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f) -> f32 { return max(dot(worldNormal, -lightDirNorm), 0.0); } -`,lightDirPointPS:` +`;var SF=` fn evalOmniLight(lightPosW: vec3f) -> vec3f { return vPositionW - lightPosW; } -`,lightEvaluationPS:` +`;var xF=` #if defined(LIGHT{i}) evaluateLight{i}( #if defined(LIT_IRIDESCENCE) @@ -8541,7 +8839,7 @@ fn evalOmniLight(lightPosW: vec3f) -> vec3f { #endif ); #endif -`,lightFunctionLightPS:` +`;var vF=` #if defined(LIGHT{i}) fn evaluateLight{i}( #if defined(LIT_IRIDESCENCE) @@ -8703,7 +9001,7 @@ fn evaluateLight{i}( #endif } #endif -`,lightFunctionShadowPS:` +`;var TF=` #ifdef LIGHT{i}CASTSHADOW #ifdef LIGHT{i}_SHADOW_SAMPLE_POINT fn getShadowSampleCoordOmni{i}(shadowParams: vec4f, worldPosition: vec3f, lightPos: vec3f, lightDir: ptr, lightDirNorm: vec3f, normal: vec3f) -> vec3f { @@ -8838,7 +9136,7 @@ fn evaluateLight{i}( #endif } #endif -`,lightingPS:` +`;var yF=` #ifdef LIT_CLUSTERED_LIGHTS #define LIT_CODE_FALLOFF_LINEAR #define LIT_CODE_FALLOFF_SQUARED @@ -8898,7 +9196,7 @@ fn evaluateLight{i}( #include "lightFunctionShadowPS, LIGHT_COUNT" #include "lightFunctionLightPS, LIGHT_COUNT" #endif -`,lightmapAddPS:` +`;var EF=` fn addLightMap( lightmap: vec3f, dir: vec3f, @@ -8941,7 +9239,7 @@ fn addLightMap( dDiffuseLight = dDiffuseLight + lightmap; #endif } -`,lightmapPS:` +`;var AF=` #ifdef STD_LIGHTMAP_DIR var dLightmapDir: vec3f; var texture_dirLightMap: texture_2d; @@ -8961,7 +9259,7 @@ fn getLightMap() { dLightmap = dLightmap * saturate(vVertexColor.{STD_LIGHT_VERTEX_CHANNEL}); #endif } -`,lightSpecularAnisoGGXPS:` +`;var CF=` fn calcLightSpecular(gloss: f32, worldNormal: vec3f, viewDir: vec3f, h: vec3f, lightDirNorm: vec3f, tbn: mat3x3f) -> f32 { let PI: f32 = 3.141592653589793; let roughness: f32 = max((1.0 - gloss) * (1.0 - gloss), 0.001); @@ -8994,7 +9292,7 @@ fn calcLightSpecular(gloss: f32, worldNormal: vec3f, viewDir: vec3f, h: vec3f, l fn getLightSpecular(h: vec3f, reflDir: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, gloss: f32, tbn: mat3x3f) -> f32 { return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm, tbn); } -`,lightSpecularGGXPS:` +`;var PF=` fn calcLightSpecular(gloss: f32, worldNormal: vec3f, viewDir: vec3f, h: vec3f, lightDirNorm: vec3f) -> f32 { const PI: f32 = 3.141592653589793; let roughness: f32 = max((1.0 - gloss) * (1.0 - gloss), 0.001); @@ -9014,7 +9312,7 @@ fn calcLightSpecular(gloss: f32, worldNormal: vec3f, viewDir: vec3f, h: vec3f, l fn getLightSpecular(h: vec3f, reflDir: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, gloss: f32, tbn: mat3x3f) -> f32 { return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm); } -`,lightSpecularBlinnPS:` +`;var wF=` fn calcLightSpecular(gloss: f32, worldNormal: vec3f, h: vec3f) -> f32 { let nh: f32 = max( dot( h, worldNormal ), 0.0 ); var specPow: f32 = exp2(gloss * 11.0); @@ -9024,7 +9322,7 @@ fn calcLightSpecular(gloss: f32, worldNormal: vec3f, h: vec3f) -> f32 { fn getLightSpecular(h: vec3f, reflDir: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, gloss: f32, tbn: mat3x3f) -> f32 { return calcLightSpecular(gloss, worldNormal, h); } -`,lightSheenPS:` +`;var IF=` fn sheenD(normal: vec3f, h: vec3f, roughness: f32) -> f32 { let PI: f32 = 3.141592653589793; let invR: f32 = 1.0 / (roughness * roughness); @@ -9042,7 +9340,7 @@ fn getLightSpecularSheen(h: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirN let D: f32 = sheenD(worldNormal, h, sheenGloss); let V: f32 = sheenV(worldNormal, viewDir, -lightDirNorm); return D * V; -}`,linearizeDepthPS:` +}`;var RF=` #ifndef LINEARIZE_DEPTH #define LINEARIZE_DEPTH fn linearizeDepthWithParams(z: f32, cameraParams: vec4f) -> f32 { @@ -9060,7 +9358,7 @@ fn linearizeDepth(z: f32) -> f32 { return linearizeDepthWithParams(z, uniform.camera_params); } #endif -`,litForwardBackendPS:` +`;var bF=` fn evaluateBackend() -> FragmentOutput { var output: FragmentOutput; #ifdef LIT_SSAO @@ -9248,7 +9546,7 @@ fn evaluateBackend() -> FragmentOutput { #endif return output; } -`,litForwardDeclarationPS:` +`;var DF=` var sReflection: vec3f; var dVertexNormalW: vec3f; var dTangentW: vec3f; @@ -9296,7 +9594,7 @@ var sSpecularLight: vec3f; uniform ambientBakeOcclusionContrast: f32; uniform ambientBakeOcclusionBrightness: f32; #endif -`,litForwardMainPS:` +`;var LF=` @fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput { #include "litUserMainStartPS" @@ -9332,7 +9630,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { #include "litUserMainEndPS" return output; } -`,litForwardPostCodePS:` +`;var MF=` #ifdef LIT_NEEDS_NORMAL #include "cubeMapRotatePS" #include "cubeMapProjectPS" @@ -9419,7 +9717,7 @@ uniform material_ambient: vec3f; #endif #endif #include "lightingPS" -`,litForwardPreCodePS:` +`;var OF=` #include "basePS" #include "sphericalPS" #include "decodePS" @@ -9437,7 +9735,7 @@ uniform material_ambient: vec3f; #include "twoSidedLightingPS" #endif #endif -`,litMainPS:` +`;var FF=` #include "varyingsPS" #include "litUserDeclarationPS" #include "frontendDeclPS" @@ -9458,7 +9756,7 @@ uniform material_ambient: vec3f; #include "litUserCodePS" #include "litForwardMainPS" #endif -`,litMainVS:` +`;var NF=` #include "varyingsVS" #include "litUserDeclarationVS" #ifdef VERTEX_COLOR @@ -9563,7 +9861,7 @@ fn vertexMain(input : VertexInput) -> VertexOutput { #include "litUserMainEndVS" return output; } -`,litOtherMainPS:` +`;var BF=` #ifdef PICK_PASS #include "pickPS" #endif @@ -9588,7 +9886,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { #include "litUserMainEndPS" return output; } -`,litShaderArgsPS:` +`;var UF=` var litArgs_albedo: vec3f; var litArgs_opacity: f32; var litArgs_emission: vec3f; @@ -9611,14 +9909,14 @@ var litArgs_iridescence_thickness: f32; var litArgs_clearcoat_worldNormal: vec3f; var litArgs_clearcoat_specularity: f32; var litArgs_clearcoat_gloss: f32; -`,litShaderCorePS:` +`;var kF=` #if LIT_NONE_SLICE_MODE == TILED var textureBias: f32 = -1000.0; #else uniform textureBias: f32; #endif #include "litShaderArgsPS" -`,litShadowMainPS:` +`;var zF=` #if LIGHT_TYPE != DIRECTIONAL uniform view_position: vec3f; uniform light_radius: f32; @@ -9665,7 +9963,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return output; } -`,litUserDeclarationPS:"",litUserDeclarationVS:"",litUserCodePS:"",litUserCodeVS:"",litUserMainStartPS:"",litUserMainStartVS:"",litUserMainEndPS:"",litUserMainEndVS:"",ltcPS:` +`;var GF=` fn LTC_Uv(N: vec3f, V: vec3f, roughness: f32) -> vec2f { const LUT_SIZE: f32 = 64.0; const LUT_SCALE: f32 = (LUT_SIZE - 1.0) / LUT_SIZE; @@ -9942,7 +10240,7 @@ fn getDiskLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 { fn getSphereLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 { return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV); } -`,metalnessPS:` +`;var VF=` #ifdef STD_METALNESS_CONSTANT uniform material_metalness: f32; #endif @@ -9959,46 +10257,7 @@ fn getMetalness() { #endif dMetalness = metalness; } -`,metalnessModulatePS:` -fn getSpecularModulate(specularity: vec3f, albedo: vec3f, metalness: f32, f0: f32, specularityFactor: f32) -> vec3f { - let dielectricF0: vec3f = f0 * specularity * specularityFactor; - return mix(dielectricF0, albedo, metalness); -} -fn getAlbedoModulate(albedo: vec3f, metalness: f32) -> vec3f { - return albedo * (1.0 - metalness); -} -`,morphPS:` - varying uv0: vec2f; - var morphTexture: texture_2d_array; - uniform morphFactor: array; - uniform morphIndex: array; - uniform count: u32; - @fragment - fn fragmentMain(input : FragmentInput) -> FragmentOutput { - var color = vec3f(0, 0, 0); - let textureDims = textureDimensions(morphTexture); - let pixelCoords = vec2i(input.uv0 * vec2f(textureDims)); - - for (var i: u32 = 0; i < uniform.count; i = i + 1) { - var textureIndex: u32 = uniform.morphIndex[i].element; - var delta = textureLoad(morphTexture, pixelCoords, textureIndex, 0).xyz; - color += uniform.morphFactor[i].element * delta; - } - var output: FragmentOutput; - output.color = vec4f(color, 1.0); - return output; - } -`,morphVS:` - attribute vertex_position: vec2f; - varying uv0: vec2f; - @vertex - fn vertexMain(input: VertexInput) -> VertexOutput { - var output: VertexOutput; - output.position = vec4f(input.vertex_position, 0.5, 1.0); - output.uv0 = input.vertex_position * 0.5 + vec2f(0.5, 0.5); - return output; - } -`,msdfPS:` +`;var HF=` var texture_msdfMap: texture_2d; var texture_msdfMapSampler: sampler; fn median(r: f32, g: f32, b: f32) -> f32 { @@ -10060,7 +10319,46 @@ fn applyMsdf(color_in: vec4f) -> vec4f { tcolor = vec4f(gammaCorrectOutput(tcolor.rgb), tcolor.a); return tcolor; } -`,msdfVS:` +`;var WF=` +fn getSpecularModulate(specularity: vec3f, albedo: vec3f, metalness: f32, f0: f32, specularityFactor: f32) -> vec3f { + let dielectricF0: vec3f = f0 * specularity * specularityFactor; + return mix(dielectricF0, albedo, metalness); +} +fn getAlbedoModulate(albedo: vec3f, metalness: f32) -> vec3f { + return albedo * (1.0 - metalness); +} +`;var XF=` + varying uv0: vec2f; + var morphTexture: texture_2d_array; + uniform morphFactor: array; + uniform morphIndex: array; + uniform count: u32; + @fragment + fn fragmentMain(input : FragmentInput) -> FragmentOutput { + var color = vec3f(0, 0, 0); + let textureDims = textureDimensions(morphTexture); + let pixelCoords = vec2i(input.uv0 * vec2f(textureDims)); + + for (var i: u32 = 0; i < uniform.count; i = i + 1) { + var textureIndex: u32 = uniform.morphIndex[i].element; + var delta = textureLoad(morphTexture, pixelCoords, textureIndex, 0).xyz; + color += uniform.morphFactor[i].element * delta; + } + var output: FragmentOutput; + output.color = vec4f(color, 1.0); + return output; + } +`;var YF=` + attribute vertex_position: vec2f; + varying uv0: vec2f; + @vertex + fn vertexMain(input: VertexInput) -> VertexOutput { + var output: VertexOutput; + output.position = vec4f(input.vertex_position, 0.5, 1.0); + output.uv0 = input.vertex_position * 0.5 + vec2f(0.5, 0.5); + return output; + } +`;var KF=` attribute vertex_outlineParameters: vec3f; attribute vertex_shadowParameters: vec3f; varying outline_color: vec4f; @@ -10081,13 +10379,13 @@ fn unpackMsdfParams() { dShadowColor = vec4f(little_shadow.x, big_shadow.x, little_shadow.y, big_shadow.y) / 255.0; dShadowOffset = (vec2f(little_shadow.z, big_shadow.z) / 127.0 - 1.0) * 0.005; } -`,normalVS:` +`;var jF=` var dNormalMatrix: mat3x3f; fn getNormal() -> vec3f { dNormalMatrix = getNormalMatrix(dModelMatrix); let localNormal: vec3f = getLocalNormal(vertex_normal); return normalize(dNormalMatrix * localNormal); -}`,normalCoreVS:` +}`;var qF=` attribute vertex_normal: vec3f; uniform matrix_normal: mat3x3f; #ifdef MORPHING_NORMAL @@ -10127,7 +10425,7 @@ fn getLocalNormal(vertexNormal: vec3f) -> vec3f { return uniform.matrix_normal; } #endif -`,normalMapPS:` +`;var $F=` #ifdef STD_NORMAL_TEXTURE uniform material_bumpiness: f32; #endif @@ -10153,8 +10451,9 @@ fn getNormal() { dNormalW = dVertexNormalW; #endif } -`,opacityPS:` +`;var ZF=` uniform material_opacity: f32; +uniform material_alphaDitherScale: f32; fn getOpacity() { dAlpha = uniform.material_opacity; #ifdef STD_OPACITY_TEXTURE @@ -10164,7 +10463,7 @@ fn getOpacity() { dAlpha = dAlpha * clamp(vVertexColor.{STD_OPACITY_VERTEX_CHANNEL}, 0.0, 1.0); #endif } -`,opacityDitherPS:` +`;var QF=` #if STD_OPACITY_DITHER == BAYER8 #include "bayerPS" #endif @@ -10174,6 +10473,12 @@ uniform blueNoiseJitter: vec4f; var blueNoiseTex32Sampler : sampler; #endif fn opacityDither(alpha: f32, id: f32) { + if (alpha <= 0.0) { + discard; + } + if (alpha >= 1.0) { + return; + } #if STD_OPACITY_DITHER == BAYER8 var noise: f32 = bayer8(floor((pcPosition.xy + uniform.blueNoiseJitter.xy + id) % vec2f(8.0))) / 64.0; #else @@ -10191,8 +10496,8 @@ fn opacityDither(alpha: f32, id: f32) { discard; } } -`,outputPS:` -`,outputAlphaPS:` +`;var JF=` +`;var eN=` #if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == ADDITIVEALPHA || defined(LIT_ALPHA_TO_COVERAGE) output.color = vec4f(output.color.rgb, litArgs_opacity); #elif LIT_BLEND_TYPE == PREMULTIPLIED @@ -10200,7 +10505,7 @@ fn opacityDither(alpha: f32, id: f32) { #else output.color = vec4f(output.color.rgb, 1.0); #endif -`,outputTex2DPS:` +`;var tN=` varying vUv0: vec2f; var source: texture_2d; var sourceSampler: sampler; @@ -10209,7 +10514,7 @@ var sourceSampler: sampler; output.color = textureSample(source, sourceSampler, input.vUv0); return output; } -`,sheenPS:` +`;var sN=` uniform material_sheen: vec3f; fn getSheen() { var sheenColor = uniform.material_sheen; @@ -10221,7 +10526,7 @@ fn getSheen() { #endif sSpecularity = sheenColor; } -`,sheenGlossPS:` +`;var iN=` uniform material_sheenGloss: f32; fn getSheenGlossiness() { var sheenGlossiness = uniform.material_sheenGloss; @@ -10236,7 +10541,7 @@ fn getSheenGlossiness() { #endif sGlossiness = sheenGlossiness + 0.0000001; } -`,parallaxPS:` +`;var rN=` uniform material_heightMapFactor: f32; fn getParallax() { var parallaxScale = uniform.material_heightMapFactor; @@ -10246,7 +10551,7 @@ fn getParallax() { viewDirT.z = viewDirT.z + 0.42; dUvOffset = height * (viewDirT.xy / viewDirT.z); } -`,pickPS:` +`;var aN=` fn encodePickOutput(id: u32) -> vec4f { let inv: vec4f = vec4f(1.0 / 255.0); let shifts: vec4u = vec4u(16u, 8u, 0u, 24u); @@ -10261,7 +10566,10 @@ fn encodePickOutput(id: u32) -> vec4f { #endif #ifdef DEPTH_PICK_PASS #include "floatAsUintPS" - uniform camera_params: vec4f; + #ifndef CAMERAPLANES + #define CAMERAPLANES + uniform camera_params: vec4f; + #endif fn getPickDepth() -> vec4f { var linearDepth: f32; if (uniform.camera_params.w > 0.5) { @@ -10273,11 +10581,11 @@ fn encodePickOutput(id: u32) -> vec4f { return float2uint(linearDepth); } #endif -`,reflDirPS:` +`;var oN=` fn getReflDir(worldNormal: vec3f, viewDir: vec3f, gloss: f32, tbn: mat3x3f) { dReflDirW = normalize(-reflect(viewDir, worldNormal)); } -`,reflDirAnisoPS:` +`;var nN=` fn getReflDir(worldNormal: vec3f, viewDir: vec3f, gloss: f32, tbn: mat3x3f) { let roughness: f32 = sqrt(1.0 - min(gloss, 1.0)); let direction: vec2f = dAnisotropyRotation; @@ -10291,13 +10599,13 @@ fn getReflDir(worldNormal: vec3f, viewDir: vec3f, gloss: f32, tbn: mat3x3f) { let bendFactor4: f32 = bendFactor * bendFactor * bendFactor * bendFactor; let bentNormal: vec3f = normalize(mix(normalize(anisotropicNormal), normalize(worldNormal), bendFactor4)); dReflDirW = reflect(-viewDir, bentNormal); -}`,reflectionCCPS:` +}`;var lN=` #ifdef LIT_CLEARCOAT fn addReflectionCC(reflDir: vec3f, gloss: f32) { ccReflection = ccReflection + calcReflection(reflDir, gloss); } #endif -`,reflectionCubePS:` +`;var cN=` var texture_cubeMap: texture_cube; var texture_cubeMapSampler: sampler; uniform material_reflectivity: f32; @@ -10309,7 +10617,7 @@ fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f { fn addReflection(reflDir: vec3f, gloss: f32) { dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity); } -`,reflectionEnvHQPS:` +`;var hN=` #ifndef ENV_ATLAS #define ENV_ATLAS var texture_envAtlas: texture_2d; @@ -10332,7 +10640,7 @@ fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f { fn addReflection(reflDir: vec3f, gloss: f32) { dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity); } -`,reflectionEnvPS:` +`;var fN=` #ifndef ENV_ATLAS #define ENV_ATLAS var texture_envAtlas: texture_2d; @@ -10376,7 +10684,7 @@ fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f { fn addReflection(reflDir: vec3f, gloss: f32) { dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity); } -`,reflectionSpherePS:` +`;var uN=` #ifndef VIEWMATRIX #define VIEWMATRIX uniform matrix_view: mat4x4f; @@ -10394,7 +10702,7 @@ fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f { fn addReflection(reflDir: vec3f, gloss: f32) { dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity); } -`,reflectionSheenPS:` +`;var dN=` fn addReflectionSheen(worldNormal: vec3f, viewDir: vec3f, gloss: f32) { let NoV: f32 = dot(worldNormal, viewDir); let alphaG: f32 = gloss * gloss; @@ -10415,7 +10723,7 @@ fn addReflectionSheen(worldNormal: vec3f, viewDir: vec3f, gloss: f32) { ); let dg: f32 = exp( a * NoV + b ) + dg_add; sReflection = sReflection + (calcReflection(worldNormal, 0.0) * saturate(dg)); -}`,refractionCubePS:` +}`;var pN=` fn refract2(viewVec: vec3f, normal: vec3f, IOR: f32) -> vec3f { let vn: f32 = dot(viewVec, normal); let k: f32 = 1.0 - IOR * IOR * (1.0 - vn * vn); @@ -10444,7 +10752,7 @@ fn addRefraction( dDiffuseLight = mix(dDiffuseLight, dReflection.rgb * albedo, transmission); dReflection = tmpRefl; } -`,refractionDynamicPS:` +`;var mN=` uniform material_invAttenuationDistance: f32; uniform material_attenuation: vec3f; fn evalRefractionColor(refractionVector: vec3f, gloss: f32, refractionIndex: f32) -> vec3f { @@ -10512,7 +10820,7 @@ fn addRefraction( ); dDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, transmission); } -`,reprojectPS:` +`;var _N=` varying vUv0: vec2f; #ifdef CUBEMAP_SOURCE var sourceCube: texture_cube; @@ -10719,18 +11027,18 @@ fn fragmentMain(input : FragmentInput) -> FragmentOutput { output.color = {PROCESS_FUNC}(input.vUv0); return output; } -`,reprojectVS:` +`;var gN=` attribute vertex_position: vec2f; uniform uvMod: vec4f; varying vUv0: vec2f; @vertex fn vertexMain(input: VertexInput) -> VertexOutput { - var output: VertexOutput; - output.position = vec4f(input.vertex_position, 0.5, 1.0); - output.vUv0 = getImageEffectUV((input.vertex_position * 0.5 + vec2f(0.5, 0.5)) * uniform.uvMod.xy + uniform.uvMod.zw); - return output; + var output: VertexOutput; + output.position = vec4f(input.vertex_position, 0.5, 1.0); + output.vUv0 = getImageEffectUV((input.vertex_position * 0.5 + vec2f(0.5, 0.5)) * uniform.uvMod.xy + uniform.uvMod.zw); + return output; } -`,screenDepthPS:` +`;var SN=` var uSceneDepthMap: texture_2d; #ifndef SCREENSIZE #define SCREENSIZE @@ -10779,7 +11087,7 @@ fn getLinearScreenDepth(uv: vec2f) -> f32 { fn getLinearDepth(pos: vec3f) -> f32 { return -(uniform.matrix_view * vec4f(pos, 1.0)).z; } -`,shadowCascadesPS:` +`;var xN=` fn getShadowCascadeIndex(shadowCascadeDistances: vec4f, shadowCascadeCount: i32) -> i32 { let depth: f32 = 1.0 / pcPosition.w; let comparisons: vec4f = step(shadowCascadeDistances, vec4f(depth)); @@ -10810,12 +11118,12 @@ fn fadeShadow(shadowCoord_in: vec3f, shadowCascadeDistances: vec4f) -> vec3f { } return shadowCoord; } -`,shadowEVSMPS:` +`;var vN=` fn linstep(a: f32, b: f32, v: f32) -> f32 { return clamp((v - a) / (b - a), 0.0, 1.0); } fn reduceLightBleeding(pMax: f32, amount: f32) -> f32 { - return linstep(amount, 1.0, pMax); + return linstep(amount, 1.0, pMax); } fn chebyshevUpperBound(moments: vec2f, mean: f32, minVariance: f32, lightBleedingReduction: f32) -> f32 { var variance: f32 = moments.y - (moments.x * moments.x); @@ -10869,14 +11177,14 @@ fn getShadowSpotVSM32(shadowMap: texture_2d, shadowMapSampler: sampler, sha let Z: f32 = length(lightDir) * shadowParams.w + shadowParams.z; return VSM32(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent); } -`,shadowPCF1PS:` +`;var TN=` fn getShadowPCF1x1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 { return textureSampleCompareLevel(shadowMap, shadowMapSampler, shadowCoord.xy, shadowCoord.z); } fn getShadowSpotPCF1x1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 { return textureSampleCompareLevel(shadowMap, shadowMapSampler, shadowCoord.xy, shadowCoord.z); } -`,shadowPCF3PS:` +`;var yN=` fn _getShadowPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec3f) -> f32 { let z: f32 = shadowCoord.z; let uv: vec2f = shadowCoord.xy * shadowParams.x; @@ -10911,7 +11219,7 @@ fn getShadowPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_compar fn getShadowSpotPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 { return _getShadowPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz); } -`,shadowPCF5PS:` +`;var EN=` fn _getShadowPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec3f) -> f32 { let z: f32 = shadowCoord.z; let uv: vec2f = shadowCoord.xy * shadowParams.x; @@ -10958,7 +11266,7 @@ fn getShadowPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_compar fn getShadowSpotPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 { return _getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz); } -`,shadowSoftPS:` +`;var AN=` fn fractSinRand(uv: vec2f) -> f32 { let PI: f32 = 3.141592653589793; let a: f32 = 12.9898; let b: f32 = 78.233; let c: f32 = 43758.5453; @@ -11048,7 +11356,7 @@ fn PCSSDirectional(shadowMap: texture_2d, shadowMapSampler: sampler, shadow fn getShadowPCSS(shadowMap: texture_2d, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, cameraParams: vec4f, softShadowParams: vec4f, lightDir: vec3f) -> f32 { return PCSSDirectional(shadowMap, shadowMapSampler, shadowCoord, cameraParams, softShadowParams); } -`,skinBatchVS:` +`;var CN=` attribute vertex_boneIndices: f32; var texture_poseMap: texture_2d; fn getBoneMatrix(indexFloat: f32) -> mat4x4f { @@ -11066,7 +11374,7 @@ fn getBoneMatrix(indexFloat: f32) -> mat4x4f { v1.w, v2.w, v3.w, 1.0 ); } -`,skinVS:` +`;var PN=` attribute vertex_boneWeights: vec4f; attribute vertex_boneIndices: vec4f; var texture_poseMap: texture_2d; @@ -11102,7 +11410,7 @@ fn getSkinMatrix(indicesFloat: vec4f, weights: vec4f) -> mat4x4f { v1.w, v2.w, v3.w, one ); } -`,skyboxPS:` +`;var wN=` #define LIT_SKYBOX_INTENSITY #include "envProcPS" #include "gammaPS" @@ -11188,7 +11496,7 @@ fn getSkinMatrix(indicesFloat: vec4f, weights: vec4f) -> mat4x4f { #endif return output; } -`,skyboxVS:` +`;var IN=` attribute aPosition : vec4f; uniform matrix_view : mat4x4f; uniform matrix_projectionSkybox : mat4x4f; @@ -11234,7 +11542,39 @@ fn getSkinMatrix(indicesFloat: vec4f, weights: vec4f) -> mat4x4f { output.position.z = output.position.w - 1.0e-7; return output; } -`,specularPS:` +`;var vm=` +fn writeSortIndirectArgs( + baseSlot: u32, + count: u32, + slotInfo: vec4 +) { + let n = slotInfo.x; + if (n >= 1u) { + let g = slotInfo.y; + let wc = (count + g - 1u) / g; + let off = baseSlot * 3u; + indirectDispatchArgs[off + 0u] = wc; + indirectDispatchArgs[off + 1u] = 1u; + indirectDispatchArgs[off + 2u] = 1u; + } + if (n >= 2u) { + let g = slotInfo.z; + let wc = (count + g - 1u) / g; + let off = (baseSlot + 1u) * 3u; + indirectDispatchArgs[off + 0u] = wc; + indirectDispatchArgs[off + 1u] = 1u; + indirectDispatchArgs[off + 2u] = 1u; + } + if (n >= 3u) { + let g = slotInfo.w; + let wc = (count + g - 1u) / g; + let off = (baseSlot + 2u) * 3u; + indirectDispatchArgs[off + 0u] = wc; + indirectDispatchArgs[off + 1u] = 1u; + indirectDispatchArgs[off + 2u] = 1u; + } +} +`;var RN=` #ifdef STD_SPECULAR_CONSTANT uniform material_specular: vec3f; #endif @@ -11251,7 +11591,7 @@ fn getSpecularity() { #endif dSpecularity = specularColor; } -`,sphericalPS:` +`;var bN=` fn toSpherical(dir: vec3f) -> vec2f { let angle_xz = select(0.0, atan2(dir.x, dir.z), any(dir.xz != vec2f(0.0))); return vec2f(angle_xz, asin(dir.y)); @@ -11261,7 +11601,7 @@ fn toSphericalUv(dir : vec3f) -> vec2f { let uv : vec2f = toSpherical(dir) / vec2f(PI * 2.0, PI) + vec2f(0.5, 0.5); return vec2f(uv.x, 1.0 - uv.y); } -`,specularityFactorPS:` +`;var DN=` #ifdef STD_SPECULARITYFACTOR_CONSTANT uniform material_specularityFactor: f32; #endif @@ -11278,13 +11618,13 @@ fn getSpecularityFactor() { #endif dSpecularityFactor = specularityFactor; } -`,spotPS:` +`;var LN=` fn getSpotEffect(lightSpotDir: vec3f, lightInnerConeAngle: f32, lightOuterConeAngle: f32, lightDirNorm: vec3f) -> f32 { let cosAngle: f32 = dot(lightDirNorm, lightSpotDir); return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle); -}`,startNineSlicedPS:` +}`;var MN=` nineSlicedUv = vec2f(vUv0.x, 1.0 - vUv0.y); -`,startNineSlicedTiledPS:` +`;var ON=` let tileMask: vec2f = step(vMask, vec2f(0.99999)); let tileSize: vec2f = 0.5 * (innerOffset.xy + innerOffset.zw); let tileScale: vec2f = vec2f(1.0) / (vec2f(1.0) - tileSize); @@ -11292,7 +11632,7 @@ fn getSpotEffect(lightSpotDir: vec3f, lightInnerConeAngle: f32, lightOuterConeAn clampedUv = clampedUv * atlasRect.zw + atlasRect.xy; var nineSlicedUv: vec2f = vUv0 * tileMask + clampedUv * (vec2f(1.0) - tileMask); nineSlicedUv.y = 1.0 - nineSlicedUv.y; -`,stdDeclarationPS:` +`;var FN=` var dAlpha: f32 = 1.0; #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE #ifdef STD_OPACITY_TEXTURE_ALLOCATE @@ -11456,7 +11796,7 @@ fn getSpotEffect(lightSpotDir: vec3f, lightInnerConeAngle: f32, lightOuterConeAn #endif #endif #include "litShaderCorePS" -`,stdFrontEndPS:` +`;var NN=` #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE #include "opacityPS" #if defined(LIT_ALPHA_TEST) @@ -11526,7 +11866,7 @@ fn getSpotEffect(lightSpotDir: vec3f, lightInnerConeAngle: f32, lightOuterConeAn alphaTest(dAlpha); #endif #if STD_OPACITY_DITHER != NONE - opacityDither(dAlpha, 0.0); + opacityDither(dAlpha * uniform.material_alphaDitherScale, 0.0); #endif litArgs_opacity = dAlpha; #endif @@ -11603,7 +11943,7 @@ fn getSpotEffect(lightSpotDir: vec3f, lightInnerConeAngle: f32, lightOuterConeAn #endif #endif } -`,TBNPS:` +`;var BN=` #ifdef LIT_TANGENTS #define TBN_TANGENTS #else @@ -11654,7 +11994,7 @@ fn getTBN(tangent: vec3f, binormal: vec3f, normal: vec3f) { } dTBN = mat3x3f(normalize(T), normalize(B), normalize(normal)); #endif -}`,thicknessPS:` +}`;var UN=` #ifdef STD_THICKNESS_CONSTANT uniform material_thickness: f32; #endif @@ -11670,7 +12010,7 @@ fn getThickness() { dThickness = dThickness * saturate(vVertexColor.{STD_THICKNESS_VERTEX_CHANNEL}); #endif } -`,tonemappingPS:` +`;var kN=` #ifndef TONEMAP_NO_EXPOSURE_UNIFORM #if TONEMAP != NONE uniform exposure: f32; @@ -11700,7 +12040,7 @@ fn getThickness() { #elif TONEMAP == NEUTRAL #include "tonemappingNeutralPS" #endif -`,tonemappingAcesPS:` +`;var zN=` fn toneMap(color: vec3f) -> vec3f { let tA: f32 = 2.51; let tB: f32 = 0.03; @@ -11710,7 +12050,7 @@ fn toneMap(color: vec3f) -> vec3f { let x: vec3f = color * getExposure(); return (x * (tA * x + tB)) / (x * (tC * x + tD) + tE); } -`,tonemappingAces2PS:` +`;var GN=` const ACESInputMat: mat3x3f = mat3x3f( vec3f(0.59719, 0.35458, 0.04823), vec3f(0.07600, 0.90834, 0.01566), @@ -11733,7 +12073,7 @@ fn toneMap(color: vec3f) -> vec3f { c = c * ACESOutputMat; return clamp(c, vec3f(0.0), vec3f(1.0)); } -`,tonemappingFilmicPS:` +`;var VN=` const A: f32 = 0.15; const B: f32 = 0.50; const C: f32 = 0.10; @@ -11750,7 +12090,7 @@ fn toneMap(color: vec3f) -> vec3f { c *= whiteScale; return c; } -`,tonemappingHejlPS:` +`;var HN=` fn toneMap(color: vec3f) -> vec3f { let A: f32 = 0.22; let B: f32 = 0.3; @@ -11765,11 +12105,11 @@ fn toneMap(color: vec3f) -> vec3f { (h * (A * h + vec3f(B)) + vec3f(D * F)) - Scl * vec3f(E / F); } -`,tonemappingLinearPS:` +`;var WN=` fn toneMap(color: vec3f) -> vec3f { return color * getExposure(); } -`,tonemappingNeutralPS:` +`;var XN=` fn toneMap(col: vec3f) -> vec3f { var color = col * getExposure(); let startCompression = 0.8 - 0.04; @@ -11787,11 +12127,11 @@ fn toneMap(col: vec3f) -> vec3f { let g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0); return mix(color, vec3f(newPeak), vec3f(g)); } -`,tonemappingNonePS:` +`;var YN=` fn toneMap(color: vec3f) -> vec3f { return color; } -`,transformVS:` +`;var KN=` #ifdef PIXELSNAP uniform uScreenSize: vec4f; #endif @@ -11844,7 +12184,7 @@ fn getPosition() -> vec4f { fn getWorldPosition() -> vec3f { return dPositionW; } -`,transformCoreVS:` +`;var jN=` attribute vertex_position: vec4f; uniform matrix_viewProjection: mat4x4f; uniform matrix_model: mat4x4f; @@ -11899,7 +12239,7 @@ fn getWorldPosition() -> vec3f { #endif return localPos; } -`,transformInstancingVS:` +`;var qN=` attribute instance_line1: vec4f; attribute instance_line2: vec4f; attribute instance_line3: vec4f; @@ -11907,7 +12247,7 @@ attribute instance_line4: vec4f; fn getModelMatrix() -> mat4x4f { return uniform.matrix_model * mat4x4f(instance_line1, instance_line2, instance_line3, instance_line4); } -`,transmissionPS:` +`;var $N=` #ifdef STD_REFRACTION_CONSTANT uniform material_refraction: f32; #endif @@ -11924,11 +12264,11 @@ fn getRefraction() { #endif dTransmission = refraction; } -`,twoSidedLightingPS:` +`;var ZN=` fn handleTwoSidedLighting() { if (!pcFrontFacing) { dTBN[2] = -dTBN[2]; } } -`,uv0VS:` +`;var QN=` #ifdef NINESLICED fn getUv0() -> vec2f { var uv = vertex_position.xz; @@ -11945,23 +12285,23 @@ fn handleTwoSidedLighting() { return vertex_texCoord0; } #endif -`,uv1VS:` +`;var JN=` fn getUv1() -> vec2f { return vertex_texCoord1; } -`,uvTransformVS:` +`;var eB=` output.vUV{TRANSFORM_UV_{i}}_{TRANSFORM_ID_{i}} = vec2f( dot(vec3f(uv{TRANSFORM_UV_{i}}, 1), uniform.{TRANSFORM_NAME_{i}}0), dot(vec3f(uv{TRANSFORM_UV_{i}}, 1), uniform.{TRANSFORM_NAME_{i}}1) ); -`,uvTransformUniformsPS:` +`;var tB=` uniform {TRANSFORM_NAME_{i}}0: vec3f; uniform {TRANSFORM_NAME_{i}}1: vec3f; -`,viewDirPS:` +`;var sB=` fn getViewDir() { dViewDirW = normalize(uniform.view_position - vPositionW); } -`,webgpuPS:rl,webgpuVS:rh};e.app=null;class pa extends X{init(e){let{assetPrefix:t,batchManager:i,componentSystems:s,elementInput:r,gamepads:a,graphicsDevice:n,keyboard:o,lightmapper:l,mouse:h,resourceHandlers:c,scriptsOrder:d,scriptPrefix:u,soundManager:f,touch:p,xr:m}=e;this.graphicsDevice=n,n$.get(n,tz).add(pi),n$.get(n,tV).add(pr),this._initDefaultMaterial(),this._initProgramLibrary(),this.stats=new pt(n),this._soundManager=f,this.scene=new dw(n),this._registerSceneImmediate(this.scene),this.assets=new fq(this.loader),t&&(this.assets.prefix=t),this.bundles=new fj(this.assets),this.scriptsOrder=d||[],this.defaultLayerWorld=new hy({name:"World",id:0}),this.defaultLayerDepth=new hy({name:"Depth",id:1,enabled:false,opaqueSortMode:0}),this.defaultLayerSkybox=new hy({name:"Skybox",id:2,opaqueSortMode:0}),this.defaultLayerUi=new hy({name:"UI",id:4,transparentSortMode:1}),this.defaultLayerImmediate=new hy({name:"Immediate",id:3,opaqueSortMode:0});let _=new hT("default");_.pushOpaque(this.defaultLayerWorld),_.pushOpaque(this.defaultLayerDepth),_.pushOpaque(this.defaultLayerSkybox),_.pushTransparent(this.defaultLayerWorld),_.pushOpaque(this.defaultLayerImmediate),_.pushTransparent(this.defaultLayerImmediate),_.pushTransparent(this.defaultLayerUi),this.scene.layers=_,fL.createPlaceholder(n),this.renderer=new hp(n,this.scene),l&&(this.lightmapper=new l(n,this.root,this.scene,this.renderer,this.assets),this.once("prerender",this._firstBake,this)),i&&(this._batcher=new i(n,this.root,this.scene),this.once("prerender",this._firstBatch,this)),this.keyboard=o||null,this.mouse=h||null,this.touch=p||null,this.gamepads=a||null,r&&(this.elementInput=r,this.elementInput.app=this),this.xr=m?new m(this):null,this.elementInput&&this.elementInput.attachSelectEvents(),this._scriptPrefix=u||"",this.enableBundles&&this.loader.addHandler("bundle",new fJ(this)),c.forEach(e=>{let t=new e(this);this.loader.addHandler(t.handlerType,t);}),s.forEach(e=>{this.systems.add(new e(this));}),this._visibilityChangeHandler=this.onVisibilityChange.bind(this),"u">typeof document&&(void 0!==document.hidden?(this._hiddenAttr="hidden",document.addEventListener("visibilitychange",this._visibilityChangeHandler,false)):void 0!==document.mozHidden?(this._hiddenAttr="mozHidden",document.addEventListener("mozvisibilitychange",this._visibilityChangeHandler,false)):void 0!==document.msHidden?(this._hiddenAttr="msHidden",document.addEventListener("msvisibilitychange",this._visibilityChangeHandler,false)):void 0!==document.webkitHidden&&(this._hiddenAttr="webkitHidden",document.addEventListener("webkitvisibilitychange",this._visibilityChangeHandler,false))),this.tick=pn(this);}static getApplication(e){return e?pa._applications[e]:r}_initDefaultMaterial(){var e;let t=new ud;t.name="Default Material",e=this.graphicsDevice,oo.get(e,()=>t);}_initProgramLibrary(){var e;let t=new uC(this.graphicsDevice,new ud);e=this.graphicsDevice,nG.get(e,()=>t);}get soundManager(){return this._soundManager}get batcher(){return this._batcher}get fillMode(){return this._fillMode}get resolutionMode(){return this._resolutionMode}configure(e,t){a0.get(e,(e,i)=>{if(e)return void t(e);let s=i.application_properties,r=i.scenes,a=i.assets;this._parseApplicationProperties(s,e=>{this._parseScenes(r),this._parseAssets(a),e?t(e):t(null);});});}preload(e){this.fire("preload:start");let t=this.assets.list({preload:true});if(0===t.length){this.fire("preload:end"),e();return}let i=0,s=()=>{i++,this.fire("preload:progress",i/t.length),i===t.length&&(this.fire("preload:end"),e());};t.forEach(e=>{e.loaded?s():(e.once("load",s),e.once("error",s),this.assets.load(e));});}_preloadScripts(e,t){t();}_parseApplicationProperties(e,t){if("number"==typeof e.maxAssetRetries&&e.maxAssetRetries>0&&this.loader.enableRetry(e.maxAssetRetries),e.useDevicePixelRatio||(e.useDevicePixelRatio=e.use_device_pixel_ratio),e.resolutionMode||(e.resolutionMode=e.resolution_mode),e.fillMode||(e.fillMode=e.fill_mode),this._width=e.width,this._height=e.height,e.useDevicePixelRatio&&(this.graphicsDevice.maxPixelRatio=window.devicePixelRatio),this.setCanvasResolution(e.resolutionMode,this._width,this._height),this.setCanvasFillMode(e.fillMode,this._width,this._height),e.layers&&e.layerOrder){let t=new hT("application"),i={};for(let t in e.layers){let s=e.layers[t];s.id=parseInt(t,10),s.enabled=1!==s.id,i[t]=new hy(s);}for(let s=0,r=e.layerOrder.length;s{s--,e?t(e):0===s&&(this.onLibrariesLoaded(),t(null));};for(let t=0;t0,s.tags.add(i.tags),i.i18n)for(let e in i.i18n)s.addLocalizedAssetId(e,i.i18n[e]);this.assets.add(s);}}start(){this.frame=0,this.fire("start",{timestamp:Q(),target:this}),this._librariesLoaded||this.onLibrariesLoaded(),this.systems.fire("initialize",this.root),this.fire("initialize"),this.systems.fire("postInitialize",this.root),this.systems.fire("postPostInitialize",this.root),this.fire("postinitialize"),this.requestAnimationFrame();}requestAnimationFrame(){this.xr?.session?this.frameRequestId=this.xr.session.requestAnimationFrame(this.tick):this.frameRequestId=k.browser||k.worker?requestAnimationFrame(this.tick):null;}inputUpdate(e){this.controller&&this.controller.update(e),this.mouse&&this.mouse.update(),this.keyboard&&this.keyboard.update(),this.gamepads&&this.gamepads.update();}update(e){this.frame++,this.graphicsDevice.update(),this.stats.frame.scriptUpdateStart=Q(),this.systems.fire(this._inTools?"toolsUpdate":"update",e),this.stats.frame.scriptUpdate=Q()-this.stats.frame.scriptUpdateStart,this.stats.frame.animUpdateStart=Q(),this.systems.fire("animationUpdate",e),this.stats.frame.animUpdate=Q()-this.stats.frame.animUpdateStart,this.stats.frame.scriptPostUpdateStart=Q(),this.systems.fire("postUpdate",e),this.stats.frame.scriptPostUpdate=Q()-this.stats.frame.scriptPostUpdateStart,this.fire("update",e),this.inputUpdate(e);}render(){this.updateCanvasSize(),this.graphicsDevice.frameStart(),this.fire("prerender"),this.root.syncHierarchy(),this._batcher&&this._batcher.updateAll(),this.renderComposition(this.scene.layers),this.fire("postrender"),this.stats.frame.renderTime=Q()-this.stats.frame.renderStart,this.graphicsDevice.frameEnd();}renderComposition(e){this.renderer.update(e),this.renderer.buildFrameGraph(this.frameGraph,e),this.frameGraph.render(this.graphicsDevice);}_fillFrameStatsBasic(e,t,i){let s=this.stats.frame;s.dt=t,s.ms=i,e>s._timeToCountFrames?(s.fps=s._fpsAccum,s._fpsAccum=0,s._timeToCountFrames=e+1e3):s._fpsAccum++,this.stats.drawCalls.total=this.graphicsDevice._drawCallsPerFrame,this.graphicsDevice._drawCallsPerFrame=0,s.gsplats=this.renderer._gsplatCount,s.gsplatBufferCopy=this.renderer._gsplatBufferCopy??0;}_fillFrameStats(){let e=this.stats.frame;e.cameras=this.renderer._camerasRendered,e.materials=this.renderer._materialSwitches,e.shaders=this.graphicsDevice._shaderSwitchesPerFrame,e.shadowMapUpdates=this.renderer._shadowMapUpdates,e.shadowMapTime=this.renderer._shadowMapTime,e.depthMapTime=this.renderer._depthMapTime,e.forwardTime=this.renderer._forwardTime;let t=this.graphicsDevice._primsPerFrame;e.triangles=t[4]/3+Math.max(t[5]-2,0)+Math.max(t[6]-2,0),e.cullTime=this.renderer._cullTime,e.sortTime=this.renderer._sortTime,e.skinTime=this.renderer._skinTime,e.morphTime=this.renderer._morphTime,e.lightClusters=this.renderer._lightClusters,e.lightClustersTime=this.renderer._lightClustersTime,e.otherPrimitives=0;for(let i=0;ii/s?t=(e=i)/r:e=(t=s)*r;}else this._fillMode===fE&&(e=i,t=s);return this.graphicsDevice.canvas.style.width=`${e}px`,this.graphicsDevice.canvas.style.height=`${t}px`,this.updateCanvasSize(),{width:e,height:t}}updateCanvasSize(){if(!(!this._allowResize||this.xr?.active)&&this._resolutionMode===fb){let e=this.graphicsDevice.canvas;this.graphicsDevice.resizeCanvas(e.clientWidth,e.clientHeight);}}onLibrariesLoaded(){this._librariesLoaded=true,this.systems.rigidbody&&this.systems.rigidbody.onLibraryLoaded();}applySceneSettings(e){let t;if(this.systems.rigidbody&&"u">typeof Ammo){let[t,i,s]=e.physics.gravity;this.systems.rigidbody.gravity.set(t,i,s);}this.scene.applySettings(e),e.render.hasOwnProperty("skybox")&&(e.render.skybox?(t=this.assets.get(e.render.skybox))?this.setSkybox(t):this.assets.once(`add:${e.render.skybox}`,this.setSkybox,this):this.setSkybox(null));}setAreaLightLuts(e,t){e&&t&&fL.set(this.graphicsDevice,e,t);}setSkybox(e){if(e!==this._skyboxAsset){let t=()=>{this.setSkybox(null);},i=()=>{this.scene.setSkybox(this._skyboxAsset?this._skyboxAsset.resources:null);};this._skyboxAsset&&(this.assets.off(`load:${this._skyboxAsset.id}`,i,this),this.assets.off(`remove:${this._skyboxAsset.id}`,t,this),this._skyboxAsset.off("change",i,this)),this._skyboxAsset=e,this._skyboxAsset&&(this.assets.on(`load:${this._skyboxAsset.id}`,i,this),this.assets.once(`remove:${this._skyboxAsset.id}`,t,this),this._skyboxAsset.on("change",i,this),0!==this.scene.skyboxMip||this._skyboxAsset.loadFaces||(this._skyboxAsset.loadFaces=true),this.assets.load(this._skyboxAsset)),i();}}_firstBake(){this.lightmapper?.bake(null,this.scene.lightmapMode);}_firstBatch(){this.batcher?.generate();}_processTimestamp(e){return e}drawLine(e,t,i,s,r){this.scene.drawLine(e,t,i,s,r);}drawLines(e,t,i=true,s=this.scene.defaultDrawLayer){this.scene.drawLines(e,t,i,s);}drawLineArrays(e,t,i=true,s=this.scene.defaultDrawLayer){this.scene.drawLineArrays(e,t,i,s);}drawWireSphere(e,t,i=es.WHITE,s=20,r=true,a=this.scene.defaultDrawLayer){this.scene.immediate.drawWireSphere(e,t,i,s,r,a);}drawWireAlignedBox(e,t,i=es.WHITE,s=true,r=this.scene.defaultDrawLayer,a){this.scene.immediate.drawWireAlignedBox(e,t,i,s,r,a);}drawMeshInstance(e,t=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(null,null,null,e,t);}drawMesh(e,t,i,s=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(t,i,e,null,s);}drawQuad(e,t,i=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(t,e,this.scene.immediate.getQuadMesh(),null,i);}drawTexture(e,t,i,s,r,a,n=this.scene.defaultDrawLayer,o=true){if(false===o&&!this.graphicsDevice.isWebGPU)return;let l=new ey;l.setTRS(new ed(e,t,0),ex.IDENTITY,new ed(i,-s,0)),a||((a=new cT).cull=0,a.setParameter("colorMap",r),a.shaderDesc=o?this.scene.immediate.getTextureShaderDesc(r.encoding):this.scene.immediate.getUnfilterableTextureShaderDesc(),a.update()),this.drawQuad(l,a,n);}drawDepthTexture(e,t,i,s,r=this.scene.defaultDrawLayer){let a=new cT;a.cull=0,a.shaderDesc=this.scene.immediate.getDepthTextureShaderDesc(),a.update(),this.drawTexture(e,t,i,s,null,a,r);}destroy(){if(this._inFrameUpdate){this._destroyRequested=true;return}let e=this.graphicsDevice.canvas.id;this.fire("destroy",this),this.off("librariesloaded"),this._gsplatSortedEvt?.off(),this._gsplatSortedEvt=null,"u">typeof document&&(document.removeEventListener("visibilitychange",this._visibilityChangeHandler,false),document.removeEventListener("mozvisibilitychange",this._visibilityChangeHandler,false),document.removeEventListener("msvisibilitychange",this._visibilityChangeHandler,false),document.removeEventListener("webkitvisibilitychange",this._visibilityChangeHandler,false)),this._visibilityChangeHandler=null,this.root.destroy(),this.root=null,this.mouse&&(this.mouse.off(),this.mouse.detach(),this.mouse=null),this.keyboard&&(this.keyboard.off(),this.keyboard.detach(),this.keyboard=null),this.touch&&(this.touch.off(),this.touch.detach(),this.touch=null),this.elementInput&&(this.elementInput.detach(),this.elementInput=null),this.gamepads&&(this.gamepads.destroy(),this.gamepads=null),this.controller&&(this.controller=null),this.systems.destroy(),this.scene.layers&&this.scene.layers.destroy(),this.bundles.destroy(),this.bundles=null,this.i18n.destroy(),this.i18n=null;let t=this.loader.getHandler("script");t?.clearCache(),this.loader.destroy(),this.loader=null,this.systems=null,this.context=null,this.scripts.destroy(),this.scripts=null,this.scenes.destroy(),this.scenes=null,this.lightmapper?.destroy(),this.lightmapper=null,this._batcher&&(this._batcher.destroy(),this._batcher=null),this._entityIndex={},this.defaultLayerDepth.onDisable=null,this.defaultLayerDepth.onEnable=null,this.defaultLayerDepth=null,this.defaultLayerWorld=null,this.xr?.end(),this.xr?.destroy(),this.renderer.destroy(),this.renderer=null;let i=this.assets.list();for(let e=0;e{this.stats.frame.gsplatSort+=e;});}constructor(t){super(),this._batcher=null,this._destroyRequested=false,this._inFrameUpdate=false,this._librariesLoaded=false,this._fillMode=fw,this._resolutionMode=fC,this._allowResize=true,this._skyboxAsset=null,this._entityIndex={},this._inTools=false,this._scriptPrefix="",this._time=0,this.enableBundles="u">typeof TextDecoder,this.timeScale=1,this.maxDeltaTime=.1,this.frame=0,this.frameGraph=new fI,this.scriptsOrder=[],this.autoRender=true,this.renderNextFrame=false,this.lightmapper=null,this.loader=new f0(this),this.scenes=new pe(this),this.scripts=new f3(this),this.systems=new fK,this.i18n=new f2(this),this.keyboard=null,this.mouse=null,this.touch=null,this.gamepads=null,this.elementInput=null,this.xr=null,pa._applications[t.id]=this,r=this,e.app=this,this.root=new f9,this.root._enabledInHierarchy=true;}}pa._applications={};let pn=function(t){return function(i,s){if(!t.graphicsDevice)return;t.frameRequestId&&(t.xr?.session?.cancelAnimationFrame(t.frameRequestId),cancelAnimationFrame(t.frameRequestId),t.frameRequestId=null),t._inFrameUpdate=true,r=t,e.app=t;let a=t._processTimestamp(i)||Q(),n=a-(t._time||a),o=n/1e3;if(o=ei.clamp(o,0,t.maxDeltaTime)*t.timeScale,t._time=a,t.requestAnimationFrame(),t.graphicsDevice.contextLost)return;t._fillFrameStatsBasic(a,o,n),t.fire("frameupdate",n);let l=false;s?(l=!t.xr?.update(s),t.graphicsDevice.defaultFramebuffer=s.session.renderState.baseLayer.framebuffer):t.graphicsDevice.defaultFramebuffer=null,l||(t.update(o),t.fire("framerender"),(t.autoRender||t.renderNextFrame)&&(t.render(),t.renderNextFrame=false),t.fire("frameend"),t.stats.frameEnd()),t._inFrameUpdate=false,t._destroyRequested&&t.destroy();}};class po{constructor(){this.componentSystems=[],this.resourceHandlers=[];}}let pl=new eD;class ph{store(){this.mask=this.light.mask,this.shadowUpdateMode=this.light.shadowUpdateMode,this.enabled=this.light.enabled,this.intensity=this.light.intensity,this.rotation=this.light._node.getLocalRotation().clone(),this.numCascades=this.light.numCascades,this.castShadows=this.light._castShadows;}restore(){let e=this.light;e.mask=this.mask,e.shadowUpdateMode=this.shadowUpdateMode,e.enabled=this.enabled,e.intensity=this.intensity,e._node.setLocalRotation(this.rotation),e.numCascades=this.numCascades,e._castShadows=this.castShadows;}startBake(){this.light.enabled=true,this.light._destroyShadowMap(),this.light.beginFrame();}endBake(e){let t=this.light;t.enabled=false,t.shadowMap&&(t.shadowMap.cached&&e.add(t,t.shadowMap),t.shadowMap=null);}constructor(e,t,i){this.scene=e,this.light=t,this.store(),t.numCascades=1,this.scene.clusteredLightingEnabled&&!i.shadowsEnabled&&(t.castShadows=false),0!==t.type&&(t._node.getWorldTransform(),t.getBoundingSphere(pl),this.lightBounds=new eA,this.lightBounds.center.copy(pl.center),this.lightBounds.halfExtents.set(pl.radius,pl.radius,pl.radius));}}let pc=new ef;class pd extends ph{get numVirtualLights(){return 0===this.light.type?this.light.bakeNumSamples:1}prepareVirtualLight(e,t){let i=this.light;if(i._node.setLocalRotation(this.rotation),e>0){let s=i.bakeArea;dl.circlePointDeterministic(pc,e,t),pc.mulScalar(.5*s),i._node.rotateLocal(pc.x,0,pc.y);}i._node.getWorldTransform(),i.intensity=Math.pow(Math.pow(this.intensity,2.2)/t,.45454545454545453);}constructor(e,t){super(e.scene,t,e.lightingParams);}}let pu=new ed;class pf extends ph{get numVirtualLights(){return this.light.bakeNumSamples}prepareVirtualLight(e,t){dl.spherePointDeterministic(pu,e,t,0,this.scene.ambientBakeSpherePart),this.light._node.lookAt(pu.mulScalar(-1)),this.light._node.rotateLocal(90,0,0);let i=Math.pow(2*Math.PI*this.scene.ambientBakeSpherePart,2.2);this.light.intensity=Math.pow(i/t,.45454545454545453);}constructor(e){let t=e.scene,i=new f9("AmbientLight");i.addComponent("light",{type:"directional",affectDynamic:true,affectLightmapped:false,bake:true,bakeNumSamples:t.ambientBakeNumSamples,castShadows:true,normalOffsetBias:.05,shadowBias:.2,shadowDistance:1,shadowResolution:2048,shadowType:0,color:es.WHITE,intensity:1,bakeDir:false}),super(t,i.light.light,e.lightingParams);}}class pp{store(){this.castShadows=this.component.castShadows;}restore(){this.component.castShadows=this.castShadows;}constructor(e,t=null){this.node=e,this.component=e.render||e.model,t=t||this.component.meshInstances,this.store(),this.meshInstances=t,this.bounds=null,this.renderTargets=[];}}let pm={glslBilateralDeNoisePS:` +`;var eh={alphaTestPS:SO,ambientPS:xO,anisotropyPS:vO,aoPS:TO,aoDiffuseOccPS:yO,aoSpecOccPS:EO,bakeDirLmEndPS:AO,bakeLmEndPS:CO,basePS:PO,baseNineSlicedPS:wO,baseNineSlicedTiledPS:IO,bayerPS:RO,blurVSMPS:bO,clearCoatPS:DO,clearCoatGlossPS:LO,clearCoatNormalPS:MO,clusteredLightCookiesPS:FO,clusteredLightShadowsPS:NO,clusteredLightUtilsPS:OO,clusteredLightPS:BO,combinePS:UO,cookieBlit2DPS:kO,cookieBlitCubePS:zO,cookieBlitVS:GO,cubeMapProjectPS:VO,cubeMapRotatePS:HO,debugOutputPS:WO,debugProcessFrontendPS:XO,detailModesPS:KO,diffusePS:jO,decodePS:YO,emissivePS:qO,encodePS:$O,endPS:ZO,envAtlasPS:QO,envProcPS:JO,falloffInvSquaredPS:eF,falloffLinearPS:tF,floatAsUintPS:sF,fogPS:iF,fogMathPS:rF,fresnelSchlickPS:aF,frontendCodePS:"",frontendDeclPS:"",fullscreenQuadVS:oF,gammaPS:nF,glossPS:lF,quadVS:cF,indirectCoreCS:Jc,immediateLinePS:hF,immediateLineVS:fF,iridescenceDiffractionPS:uF,iridescencePS:dF,iridescenceThicknessPS:pF,iorPS:mF,lightDeclarationPS:_F,lightDiffuseLambertPS:gF,lightDirPointPS:SF,lightEvaluationPS:xF,lightFunctionLightPS:vF,lightFunctionShadowPS:TF,lightingPS:yF,lightmapAddPS:EF,lightmapPS:AF,lightSpecularAnisoGGXPS:CF,lightSpecularGGXPS:PF,lightSpecularBlinnPS:wF,lightSheenPS:IF,linearizeDepthPS:RF,litForwardBackendPS:bF,litForwardDeclarationPS:DF,litForwardMainPS:LF,litForwardPostCodePS:MF,litForwardPreCodePS:OF,litMainPS:FF,litMainVS:NF,litOtherMainPS:BF,litShaderArgsPS:UF,litShaderCorePS:kF,litShadowMainPS:zF,litUserDeclarationPS:"",litUserDeclarationVS:"",litUserCodePS:"",litUserCodeVS:"",litUserMainStartPS:"",litUserMainStartVS:"",litUserMainEndPS:"",litUserMainEndVS:"",ltcPS:GF,metalnessPS:VF,metalnessModulatePS:WF,morphPS:XF,morphVS:YF,msdfPS:HF,msdfVS:KF,normalVS:jF,normalCoreVS:qF,normalMapPS:$F,opacityPS:ZF,opacityDitherPS:QF,outputPS:JF,outputAlphaPS:eN,outputTex2DPS:tN,sheenPS:sN,sheenGlossPS:iN,parallaxPS:rN,pickPS:aN,reflDirPS:oN,reflDirAnisoPS:nN,reflectionCCPS:lN,reflectionCubePS:cN,reflectionEnvHQPS:hN,reflectionEnvPS:fN,reflectionSpherePS:uN,reflectionSheenPS:dN,refractionCubePS:pN,refractionDynamicPS:mN,reprojectPS:_N,reprojectVS:gN,screenDepthPS:SN,shadowCascadesPS:xN,shadowEVSMPS:vN,shadowPCF1PS:TN,shadowPCF3PS:yN,shadowPCF5PS:EN,shadowSoftPS:AN,skinBatchVS:CN,skinVS:PN,skyboxPS:wN,skyboxVS:IN,sortIndirectArgsCS:vm,specularPS:RN,sphericalPS:bN,specularityFactorPS:DN,spotPS:LN,startNineSlicedPS:MN,startNineSlicedTiledPS:ON,stdDeclarationPS:FN,stdFrontEndPS:NN,TBNPS:BN,thicknessPS:UN,tonemappingPS:kN,tonemappingAcesPS:zN,tonemappingAces2PS:GN,tonemappingFilmicPS:VN,tonemappingHejlPS:HN,tonemappingLinearPS:WN,tonemappingNeutralPS:XN,tonemappingNonePS:YN,transformVS:KN,transformCoreVS:jN,transformInstancingVS:qN,transmissionPS:$N,twoSidedLightingPS:ZN,uv0VS:QN,uv1VS:JN,uvTransformVS:eB,uvTransformUniformsPS:tB,viewDirPS:sB,webgpuPS:xv,webgpuVS:vv};var n0=null,ou=class ou extends J{constructor(e){super();n(this,"_batcher",null);n(this,"_destroyRequested",!1);n(this,"_inFrameUpdate",!1);n(this,"_librariesLoaded",!1);n(this,"_fillMode",Ky);n(this,"_resolutionMode",DI);n(this,"_allowResize",!0);n(this,"_skyboxAsset",null);n(this,"_soundManager");n(this,"_visibilityChangeHandler");n(this,"_entityIndex",{});n(this,"_inTools",!1);n(this,"_scriptPrefix","");n(this,"_time",0);n(this,"enableBundles",typeof TextDecoder<"u");n(this,"frameRequestId");n(this,"tick",(e,s)=>{if(!this.graphicsDevice)return;this.frameRequestId&&(this.xr?.session?.cancelAnimationFrame(this.frameRequestId),cancelAnimationFrame(this.frameRequestId),this.frameRequestId=null),this._inFrameUpdate=!0,qy(this),n0=this;let i=this._processTimestamp(e)||Tt(),r=i-(this._time||i),a=r/1e3;if(a=R.clamp(a,0,this.maxDeltaTime),a*=this.timeScale,this._time=i,this.requestAnimationFrame(),this.graphicsDevice.contextLost)return;this.stats.updateBasic(i,a,r,this.renderer,this.graphicsDevice),this.fire("frameupdate",r);let o=!1;s&&(o=!this.xr?.update(s)),o||(this.update(a),this.fire("framerender"),(this.autoRender||this.renderNextFrame)&&(this.render(),this.renderNextFrame=!1),this.fire("frameend"),this.stats.frameEnd()),this._inFrameUpdate=!1,this._destroyRequested&&this.destroy()});n(this,"timeScale",1);n(this,"maxDeltaTime",.1);n(this,"frame",0);n(this,"frameGraph",new $y);n(this,"renderer");n(this,"scriptsOrder",[]);n(this,"stats");n(this,"autoRender",!0);n(this,"renderNextFrame",!1);n(this,"graphicsDevice");n(this,"root");n(this,"scene");n(this,"lightmapper",null);n(this,"loader",new Zc(this));n(this,"assets");n(this,"bundles");n(this,"scenes",new xm(this));n(this,"scripts",new Sm(this));n(this,"systems",new mm);n(this,"i18n",new fa(this));n(this,"keyboard",null);n(this,"mouse",null);n(this,"touch",null);n(this,"gamepads",null);n(this,"elementInput",null);n(this,"xr",null);ou._applications[e.id]=this,qy(this),n0=this,this.root=new Ne,this.root._enabledInHierarchy=!0}init(e){let{assetPrefix:s,batchManager:i,componentSystems:r,elementInput:a,gamepads:o,graphicsDevice:l,keyboard:h,lightmapper:f,mouse:u,resourceHandlers:d,scriptsOrder:p,scriptPrefix:m,soundManager:_,touch:S,xr:g}=e;this.graphicsDevice=l,ne.get(l,fe).add(gO),ne.get(l,se).add(eh),this._initDefaultMaterial(),this._initProgramLibrary(),this.stats=new o0(l),this._soundManager=_,this.scene=new Bt(l),this._registerSceneImmediate(this.scene),this.assets=new ha(this.loader),s&&(this.assets.prefix=s),this.bundles=new pm(this.assets),this.scriptsOrder=p||[],this.defaultLayerWorld=new Dt({name:"World",id:Os}),this.defaultLayerDepth=new Dt({name:"Depth",id:Zt,enabled:!1,opaqueSortMode:Ho}),this.defaultLayerSkybox=new Dt({name:"Skybox",id:$n,opaqueSortMode:Ho}),this.defaultLayerUi=new Dt({name:"UI",id:Va,transparentSortMode:gw}),this.defaultLayerImmediate=new Dt({name:"Immediate",id:Zn,opaqueSortMode:Ho});let T=new ol("default");T.pushOpaque(this.defaultLayerWorld),T.pushOpaque(this.defaultLayerDepth),T.pushOpaque(this.defaultLayerSkybox),T.pushTransparent(this.defaultLayerWorld),T.pushOpaque(this.defaultLayerImmediate),T.pushTransparent(this.defaultLayerImmediate),T.pushTransparent(this.defaultLayerUi),this.scene.layers=T,wS.createPlaceholder(l),this.renderer=new Bc(l,this.scene),f&&(this.lightmapper=new f(l,this.root,this.scene,this.renderer,this.assets),this.once("prerender",this._firstBake,this)),i&&(this._batcher=new i(l,this.root,this.scene),this.once("prerender",this._firstBatch,this)),this.keyboard=h||null,this.mouse=u||null,this.touch=S||null,this.gamepads=o||null,a&&(this.elementInput=a,this.elementInput.app=this),this.xr=g?new g(this):null,this.elementInput&&this.elementInput.attachSelectEvents(),this._scriptPrefix=m||"",this.enableBundles&&this.loader.addHandler("bundle",new _m(this)),d.forEach(C=>{let v=new C(this);this.loader.addHandler(v.handlerType,v)}),this.loader.enableRetry(),r.forEach(C=>{this.systems.add(new C(this))}),this._visibilityChangeHandler=this.onVisibilityChange.bind(this),typeof document<"u"&&document.addEventListener("visibilitychange",this._visibilityChangeHandler,!1)}static getApplication(e){return e?ou._applications[e]:ys()}_initDefaultMaterial(){let e=new it;e.name="Default Material",RL(this.graphicsDevice,e)}_initProgramLibrary(){let e=new im(this.graphicsDevice,new it);gL(this.graphicsDevice,e)}get soundManager(){return this._soundManager}get batcher(){return this._batcher}get fillMode(){return this._fillMode}get resolutionMode(){return this._resolutionMode}configure(e,s){Le.get(e,(i,r)=>{if(i){s(i);return}let a=r.application_properties,o=r.scenes,l=r.assets;this._parseApplicationProperties(a,h=>{this._parseScenes(o),this._parseAssets(l),s(h||null)})})}preload(e){this.fire("preload:start");let s=this.assets.list({preload:!0});if(s.length===0){this.fire("preload:end"),e();return}let i=0,r=()=>{i++,this.fire("preload:progress",i/s.length),i===s.length&&(this.fire("preload:end"),e())};s.forEach(a=>{a.loaded?r():(a.once("load",r),a.once("error",r),this.assets.load(a))})}_preloadScripts(e,s){s()}_parseApplicationProperties(e,s){if(typeof e.maxAssetRetries=="number"&&e.maxAssetRetries>0&&this.loader.enableRetry(e.maxAssetRetries),e.useDevicePixelRatio||(e.useDevicePixelRatio=e.use_device_pixel_ratio),e.resolutionMode||(e.resolutionMode=e.resolution_mode),e.fillMode||(e.fillMode=e.fill_mode),this._width=e.width,this._height=e.height,e.useDevicePixelRatio&&(this.graphicsDevice.maxPixelRatio=window.devicePixelRatio),this.setCanvasResolution(e.resolutionMode,this._width,this._height),this.setCanvasFillMode(e.fillMode,this._width,this._height),e.layers&&e.layerOrder){let i=new ol("application"),r={};for(let a in e.layers){let o=e.layers[a];o.id=parseInt(a,10),o.enabled=o.id!==Zt,r[a]=new Dt(o)}for(let a=0,o=e.layerOrder.length;a{r--,l?s(l):r===0&&(this.onLibrariesLoaded(),s(null))};for(let l=0;l0,l.tags.add(o.tags),o.i18n)for(let h in o.i18n)l.addLocalizedAssetId(h,o.i18n[h]);this.assets.add(l)}}start(){this.frame=0,this.fire("start",{timestamp:Tt(),target:this}),this._librariesLoaded||this.onLibrariesLoaded(),this.systems.fire("initialize",this.root),this.fire("initialize"),this.systems.fire("postInitialize",this.root),this.systems.fire("postPostInitialize",this.root),this.fire("postinitialize"),this.requestAnimationFrame()}requestAnimationFrame(){this.xr?.session?this.frameRequestId=this.xr.session.requestAnimationFrame(this.tick):this.frameRequestId=ue.browser||ue.worker?requestAnimationFrame(this.tick):null}inputUpdate(e){this.mouse&&this.mouse.update(),this.keyboard&&this.keyboard.update(),this.gamepads&&this.gamepads.update()}update(e){this.frame++,this.graphicsDevice.update(),this.stats.frame.scriptUpdateStart=Tt(),this.systems.fire(this._inTools?"toolsUpdate":"update",e),this.stats.frame.scriptUpdate=Tt()-this.stats.frame.scriptUpdateStart,this.stats.frame.animUpdateStart=Tt(),this.systems.fire("animationUpdate",e),this.stats.frame.animUpdate=Tt()-this.stats.frame.animUpdateStart,this.stats.frame.scriptPostUpdateStart=Tt(),this.systems.fire("postUpdate",e),this.stats.frame.scriptPostUpdate=Tt()-this.stats.frame.scriptPostUpdateStart,this.fire("update",e),this.inputUpdate(e)}render(){this.updateCanvasSize(),this.graphicsDevice.frameStart(),this.fire("prerender"),this.root.syncHierarchy(),this._batcher&&this._batcher.updateAll(),this.renderComposition(this.scene.layers),this.fire("postrender"),this.stats.frame.renderTime=Tt()-this.stats.frame.renderStart,this.graphicsDevice.frameEnd()}renderComposition(e){this.renderer.update(e),this.renderer.buildFrameGraph(this.frameGraph,e),this.frameGraph.render(this.graphicsDevice)}setCanvasFillMode(e,s,i){this._fillMode=e,this.resizeCanvas(s,i)}setCanvasResolution(e,s,i){this._resolutionMode=e,e===jy&&s===void 0&&(s=this.graphicsDevice.canvas.clientWidth,i=this.graphicsDevice.canvas.clientHeight),this.graphicsDevice.resizeCanvas(s,i)}isHidden(){return document.hidden}onVisibilityChange(){this.isHidden()?this._soundManager&&this._soundManager.suspend():this._soundManager&&this._soundManager.resume()}resizeCanvas(e,s){if(!this._allowResize||this.xr&&this.xr.session)return;let i=window.innerWidth,r=window.innerHeight;if(this._fillMode===Ky){let a=this.graphicsDevice.canvas.width/this.graphicsDevice.canvas.height,o=i/r;a>o?(e=i,s=e/a):(s=r,e=s*a)}else this._fillMode===bI&&(e=i,s=r);return this.graphicsDevice.canvas.style.width=`${e}px`,this.graphicsDevice.canvas.style.height=`${s}px`,this.updateCanvasSize(),{width:e,height:s}}updateCanvasSize(){if(!(!this._allowResize||this.xr?.active)&&this._resolutionMode===jy){let e=this.graphicsDevice.canvas;this.graphicsDevice.resizeCanvas(e.clientWidth,e.clientHeight)}}onLibrariesLoaded(){this._librariesLoaded=!0,this.systems.rigidbody&&this.systems.rigidbody.onLibraryLoaded()}applySceneSettings(e){let s;if(this.systems.rigidbody&&typeof Ammo<"u"){let[i,r,a]=e.physics.gravity;this.systems.rigidbody.gravity.set(i,r,a)}this.scene.applySettings(e),e.render.hasOwnProperty("skybox")&&(e.render.skybox?(s=this.assets.get(e.render.skybox),s?this.setSkybox(s):this.assets.once(`add:${e.render.skybox}`,this.setSkybox,this)):this.setSkybox(null))}setAreaLightLuts(e,s){e&&s&&wS.set(this.graphicsDevice,e,s)}setSkybox(e){if(e!==this._skyboxAsset){let s=()=>{this.setSkybox(null)},i=()=>{this.scene.setSkybox(this._skyboxAsset?this._skyboxAsset.resources:null)};this._skyboxAsset&&(this.assets.off(`load:${this._skyboxAsset.id}`,i,this),this.assets.off(`remove:${this._skyboxAsset.id}`,s,this),this._skyboxAsset.off("change",i,this)),this._skyboxAsset=e,this._skyboxAsset&&(this.assets.on(`load:${this._skyboxAsset.id}`,i,this),this.assets.once(`remove:${this._skyboxAsset.id}`,s,this),this._skyboxAsset.on("change",i,this),this.scene.skyboxMip===0&&!this._skyboxAsset.loadFaces&&(this._skyboxAsset.loadFaces=!0),this.assets.load(this._skyboxAsset)),i()}}_firstBake(){this.lightmapper?.bake(null,this.scene.lightmapMode)}_firstBatch(){this.batcher?.generate()}_processTimestamp(e){return e}drawLine(e,s,i,r,a){this.scene.drawLine(e,s,i,r,a)}drawLines(e,s,i=!0,r=this.scene.defaultDrawLayer){this.scene.drawLines(e,s,i,r)}drawLineArrays(e,s,i=!0,r=this.scene.defaultDrawLayer){this.scene.drawLineArrays(e,s,i,r)}drawWireSphere(e,s,i=F.WHITE,r=20,a=!0,o=this.scene.defaultDrawLayer){this.scene.immediate.drawWireSphere(e,s,i,r,a,o)}drawWireAlignedBox(e,s,i=F.WHITE,r=!0,a=this.scene.defaultDrawLayer,o){this.scene.immediate.drawWireAlignedBox(e,s,i,r,a,o)}drawMeshInstance(e,s=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(null,null,null,e,s)}drawMesh(e,s,i,r=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(s,i,e,null,r)}drawQuad(e,s,i=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(s,e,this.scene.immediate.getQuadMesh(),null,i)}drawTexture(e,s,i,r,a,o,l=this.scene.defaultDrawLayer,h=!0){if(h===!1&&!this.graphicsDevice.isWebGPU)return;let f=new W;f.setTRS(new x(e,s,0),$.IDENTITY,new x(i,-r,0)),o||(o=new ct,o.cull=0,o.setParameter("colorMap",a),o.shaderDesc=h?this.scene.immediate.getTextureShaderDesc(a.encoding):this.scene.immediate.getUnfilterableTextureShaderDesc(),o.update()),this.drawQuad(f,o,l)}drawDepthTexture(e,s,i,r,a=this.scene.defaultDrawLayer){let o=new ct;o.cull=0,o.shaderDesc=this.scene.immediate.getDepthTextureShaderDesc(),o.update(),this.drawTexture(e,s,i,r,null,o,a)}destroy(){if(this._inFrameUpdate){this._destroyRequested=!0;return}let e=this.graphicsDevice.canvas.id;this.fire("destroy",this),this.off("librariesloaded"),this._gsplatSortedEvt?.off(),this._gsplatSortedEvt=null,typeof document<"u"&&document.removeEventListener("visibilitychange",this._visibilityChangeHandler,!1),this._visibilityChangeHandler=null,this.root.destroy(),this.root=null,this.mouse&&(this.mouse.off(),this.mouse.detach(),this.mouse=null),this.keyboard&&(this.keyboard.off(),this.keyboard.detach(),this.keyboard=null),this.touch&&(this.touch.off(),this.touch.detach(),this.touch=null),this.elementInput&&(this.elementInput.detach(),this.elementInput=null),this.gamepads&&(this.gamepads.destroy(),this.gamepads=null),this.systems.destroy(),this.scene.layers&&this.scene.layers.destroy(),this.bundles.destroy(),this.bundles=null,this.i18n.destroy(),this.i18n=null,this.loader.getHandler("script")?.clearCache(),this.loader.destroy(),this.loader=null,this.systems=null,this.context=null,this.scripts.destroy(),this.scripts=null,this.scenes.destroy(),this.scenes=null,this.lightmapper?.destroy(),this.lightmapper=null,this._batcher&&(this._batcher.destroy(),this._batcher=null),this._entityIndex={},this.defaultLayerDepth.onDisable=null,this.defaultLayerDepth.onEnable=null,this.defaultLayerDepth=null,this.defaultLayerWorld=null,this.xr?.end(),this.xr?.destroy(),this.renderer.destroy(),this.renderer=null;let i=this.assets.list();for(let r=0;r{this.stats.frame.gsplatSort+=s})}};n(ou,"_applications",{});var Pi=ou;var Tm=class{constructor(){n(this,"elementInput");n(this,"keyboard");n(this,"mouse");n(this,"touch");n(this,"gamepads");n(this,"scriptPrefix");n(this,"assetPrefix");n(this,"scriptsOrder");n(this,"soundManager");n(this,"graphicsDevice");n(this,"lightmapper");n(this,"batchManager");n(this,"xr");n(this,"componentSystems",[]);n(this,"resourceHandlers",[])}};var DS=new Br,ym=class{constructor(t,e,s){this.scene=t,this.light=e,this.store(),e.numCascades=1,this.scene.clusteredLightingEnabled&&!s.shadowsEnabled&&(e.castShadows=!1),e.type!==Ce&&(e._node.getWorldTransform(),e.getBoundingSphere(DS),this.lightBounds=new ge,this.lightBounds.center.copy(DS.center),this.lightBounds.halfExtents.set(DS.radius,DS.radius,DS.radius))}store(){this.mask=this.light.mask,this.shadowUpdateMode=this.light.shadowUpdateMode,this.enabled=this.light.enabled,this.intensity=this.light.intensity,this.rotation=this.light._node.getLocalRotation().clone(),this.numCascades=this.light.numCascades,this.castShadows=this.light._castShadows}restore(){let t=this.light;t.mask=this.mask,t.shadowUpdateMode=this.shadowUpdateMode,t.enabled=this.enabled,t.intensity=this.intensity,t._node.setLocalRotation(this.rotation),t.numCascades=this.numCascades,t._castShadows=this.castShadows}startBake(){this.light.enabled=!0,this.light._destroyShadowMap(),this.light.beginFrame()}endBake(t){let e=this.light;e.enabled=!1,e.shadowMap&&(e.shadowMap.cached&&t.add(e,e.shadowMap),e.shadowMap=null)}};var l0=new B,c0=class extends ym{constructor(t,e){super(t.scene,e,t.lightingParams)}get numVirtualLights(){return this.light.type===Ce?this.light.bakeNumSamples:1}prepareVirtualLight(t,e){let s=this.light;if(s._node.setLocalRotation(this.rotation),t>0){let a=s.bakeArea;Rc.circlePointDeterministic(l0,t,e),l0.mulScalar(a*.5),s._node.rotateLocal(l0.x,0,l0.y)}s._node.getWorldTransform();let i=2.2,r=Math.pow(this.intensity,i);s.intensity=Math.pow(r/e,1/i)}};var iB=new x,LS=class extends ym{constructor(t){let e=t.scene,s=new Ne("AmbientLight");s.addComponent("light",{type:"directional",affectDynamic:!0,affectLightmapped:!1,bake:!0,bakeNumSamples:e.ambientBakeNumSamples,castShadows:!0,normalOffsetBias:.05,shadowBias:.2,shadowDistance:1,shadowResolution:2048,shadowType:Oi,color:F.WHITE,intensity:1,bakeDir:!1}),super(e,s.light.light,t.lightingParams)}get numVirtualLights(){return this.light.bakeNumSamples}prepareVirtualLight(t,e){Rc.spherePointDeterministic(iB,t,e,0,this.scene.ambientBakeSpherePart),this.light._node.lookAt(iB.mulScalar(-1)),this.light._node.rotateLocal(90,0,0);let s=2.2,i=2*Math.PI*this.scene.ambientBakeSpherePart,r=Math.pow(i,s);this.light.intensity=Math.pow(r/e,1/s)}};var nu=class{constructor(t,e=null){this.node=t,this.component=t.render||t.model,e=e||this.component.meshInstances,this.store(),this.meshInstances=e,this.bounds=null,this.renderTargets=[]}store(){this.castShadows=this.component.castShadows}restore(){this.component.castShadows=this.castShadows}};var rB=` float normpdf3(in vec3 v, in float sigma) { return 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma; } @@ -12035,7 +12375,7 @@ void main(void) { gl_FragColor = encodeRGBM(finalHDR); #endif } -`,glslDilatePS:` +`;var aB=` varying vec2 vUv0; uniform sampler2D source; uniform vec2 pixelOffset; @@ -12058,7 +12398,7 @@ void main(void) { c = isUsed(c) ? c : texture2DLod(source, vUv0 + pixelOffset, 0.0); gl_FragColor = c; } -`},p_={wgslBilateralDeNoisePS:` +`;var oB=` fn normpdf3(v: vec3f, sigma: f32) -> f32 { return 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma; } @@ -12136,7 +12476,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { #endif return output; } -`,wgslDilatePS:` +`;var nB=` varying vUv0: vec2f; var source: texture_2d; var sourceSampler: sampler; @@ -12163,7 +12503,11 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { output.color = c; return output; } -`};class pg{setSourceTexture(e){this.constantTexSource.setValue(e);}prepare(e,t){this.pixelOffset[0]=1/e,this.pixelOffset[1]=1/t,this.constantPixelOffset.setValue(this.pixelOffset);}prepareDenoise(e,t,i){let s=+!i;if(!this.shaderDenoise[s]){let e=new Map;e.set("{MSIZE}",15),i&&e.set("HDR",""),this.shaderDenoise[s]=nJ.createShader(this.device,{uniqueName:`lmBilateralDeNoise-${i?"hdr":"rgbm"}`,attributes:{vertex_position:e8},vertexGLSL:n$.get(this.device,tz).get("fullscreenQuadVS"),vertexWGSL:n$.get(this.device,tV).get("fullscreenQuadVS"),fragmentGLSL:n$.get(this.device,tz).get("glslBilateralDeNoisePS"),fragmentWGSL:n$.get(this.device,tV).get("wgslBilateralDeNoisePS"),fragmentDefines:e}),this.sigmas=new Float32Array(2),this.constantSigmas=this.device.scope.resolve("sigmas"),this.constantKernel=this.device.scope.resolve("kernel[0]"),this.bZnorm=this.device.scope.resolve("bZnorm");}this.sigmas[0]=e,this.sigmas[1]=t,this.constantSigmas.setValue(this.sigmas),this.evaluateDenoiseUniforms(e,t);}getDenoise(e){return this.shaderDenoise[+!e]}getDilate(e,t){let i=+!t;if(!this.shaderDilate[i]){let s=t?"#define HDR\n":"";this.shaderDilate[i]=nJ.createShader(e,{uniqueName:`lmDilate-${t?"hdr":"rgbm"}`,attributes:{vertex_position:e8},vertexGLSL:n$.get(this.device,tz).get("fullscreenQuadVS"),vertexWGSL:n$.get(this.device,tV).get("fullscreenQuadVS"),fragmentGLSL:s+n$.get(this.device,tz).get("glslDilatePS"),fragmentWGSL:s+n$.get(this.device,tV).get("wgslDilatePS")});}return this.shaderDilate[i]}evaluateDenoiseUniforms(e,t){function i(e,t){return .39894*Math.exp(-0.5*e*e/(t*t))/t}this.kernel=this.kernel||new Float32Array(15);let s=this.kernel,r=Math.floor(7);for(let t=0;t<=r;++t){let a=i(t,e);s[r+t]=a,s[r-t]=a;}this.constantKernel.setValue(this.kernel);let a=1/i(0,t);this.bZnorm.setValue(a);}constructor(e){this.shaderDilate=[],this.shaderDenoise=[],this.device=e,n$.get(this.device,tz).add(pm),n$.get(this.device,tV).add(p_),this.constantTexSource=e.scope.resolve("source"),this.constantPixelOffset=e.scope.resolve("pixelOffset"),this.pixelOffset=new Float32Array(2),this.sigmas=null,this.constantSigmas=null,this.kernel=null;}}class pv extends ah{destroy(){this.viewBindGroups.forEach(e=>{e.defaultUniformBuffer.destroy(),e.destroy();}),this.viewBindGroups.length=0;}execute(){let e=this.device,{renderer:t,camera:i,receivers:s,renderTarget:r,worldClusters:a,lightArray:n}=this;e.supportsUniformBuffers&&!t.viewUniformFormat&&t.initViewBindGroupFormat(t.scene.clusteredLightingEnabled),t.renderForwardLayer(i,r,null,void 0,0,this.viewBindGroups,{meshInstances:s,splitLights:n,lightClusters:a});}constructor(e,t,i,s,r,a){super(e),this.viewBindGroups=[],this.renderer=t,this.camera=i,this.worldClusters=s,this.receivers=r,this.lightArray=a;}}let pS=new ed;class py{destroy(){oh.decRef(this.blackTex),this.blackTex=null,oh.destroy(),this.device=null,this.root=null,this.scene=null,this.renderer=null,this.assets=null,this.camera?.destroy(),this.camera=null;}initBake(e){if(this.bakeHDR=7!==this.scene.lightmapPixelFormat,!this._initCalled){this._initCalled=true,this.lightmapFilters=new pg(e),this.constantBakeDir=e.scope.resolve("bakeDir"),this.materials=[],this.blackTex=new ic(this.device,{width:4,height:4,format:7,type:tI,name:"lightmapBlack"}),oh.incRef(this.blackTex);let t=new oN;t.clearColor.set(0,0,0,0),t.clearColorBuffer=true,t.clearDepthBuffer=false,t.clearStencilBuffer=false,t.frustumCulling=false,t.projection=1,t.aspectRatio=1,t.node=new oJ,this.camera=t,this.camera.shaderParams.gammaCorrection=0,this.camera.shaderParams.toneMapping=0;}if(this.scene.clusteredLightingEnabled){let t=new hM(e.supportsAreaLights,e.maxTextureSize,()=>{});this.lightingParams=t;let i=this.scene.lighting;t.shadowsEnabled=i.shadowsEnabled,t.shadowAtlasResolution=i.shadowAtlasResolution,t.cookiesEnabled=i.cookiesEnabled,t.cookieAtlasResolution=i.cookieAtlasResolution,t.areaLightsEnabled=i.areaLightsEnabled,t.cells=new ed(3,3,3),t.maxLightsPerCell=4,this.worldClusters=new ll(e),this.worldClusters.name="ClusterLightmapper",this.shadowLocalClusteredPass=new lq(e,this.renderer.shadowRenderer,this.renderer._shadowRendererLocal);}}finishBake(e){function t(e){oh.decRef(e.colorBuffer),e.destroy();}this.materials=[],this.renderTargets.forEach(e=>{t(e);}),this.renderTargets.clear(),e.forEach(e=>{e.renderTargets.forEach(e=>{t(e);}),e.renderTargets.length=0;}),this.ambientAOMaterial=null,this.worldClusters&&(this.worldClusters.destroy(),this.worldClusters=null);}createMaterialForPass(e,t,i){let s=new ud;return s.name=`lmMaterial-pass:${t}-ambient:${i}`,s.setDefine("UV1LAYOUT",""),s.setDefine("LIT_LIGHTMAP_BAKING",""),0===t?(s.setDefine("LIT_LIGHTMAP_BAKING_COLOR",""),i?s.setDefine("LIT_LIGHTMAP_BAKING_ADD_AMBIENT",""):s.ambient=new es(0,0,0),this.bakeHDR||s.setDefine("LIGHTMAP_RGBM",""),s.lightMap=this.blackTex):(s.setDefine("LIT_LIGHTMAP_BAKING_DIR",""),s.setDefine("STD_LIGHTMAP_DIR","")),s.cull=0,s.forceUv1=true,s.update(),s}createMaterials(e,t,i){for(let e=0;e0&&t.push(new pp(e,i));}}for(let s=0;s0){this.renderer.shadowRenderer.frameUpdate();let e=1===t?2:1;this.setLightmapping(o,false,e),this.initBake(i),this.bakeInternal(e,o,l);let s=64;1===t&&(s|=128),this.scene.ambientBake&&(s|=4096),this.setLightmapping(o,true,e,s),this.finishBake(o);}let h=Q();this.stats.totalRenderTime=h-s,this.stats.shadersLinked=i._shaderStats.linked-r,this.stats.compileTime=i._shaderStats.compileTime-n,this.stats.fboTime=i._renderTargetCreationTime-a,this.stats.lightmapCount=o.length;}allocateTextures(e,t){for(let i=0;i0){t.copy(e[0].aabb);for(let i=1;i1&&y>1&&i.light.bakeDir&&(y=1);for(let s=0;s1&&i.prepareVirtualLight(s,y),i.startBake();let p=false,x=this.lightCameraPrepare(d,i);for(l=0;l0)||!(s>0))&&(!f||!(o>0));o++){let e=T.renderTargets[o],t=T.renderTargets[o].colorBuffer.width,l=this.renderTargets.get(t),c=l.colorBuffer;0===o?v=h.updateShaders:v&&(h.updateShaders=true);let p=this.passMaterials[o];for(f&&s+1===y&&0===o&&(p=this.ambientAOMaterial),r=0;r{let i="object"==typeof t?t.name:t;Object.defineProperty(e,i,{get:function(){return this.data[i]},set:function(e){let t=this.data,s=t[i];t[i]=e,this.fire("set",i,s,e);},configurable:true});}),e._accessorsBuilt=true;}buildAccessors(e){px._buildAccessors(this,e);}onSetEnabled(e,t,i){t!==i&&this.entity.enabled&&(i?this.onEnable():this.onDisable());}onEnable(){}onDisable(){}onPostStateChange(){}get data(){let e=this.system.store[this.entity.getGuid()];return e?e.data:null}set enabled(e){}get enabled(){return true}constructor(e,t){super(),this.system=e,this.entity=t,this.system.schema&&!this._accessorsBuilt&&this.buildAccessors(this.system.schema),this.on("set",function(e,t,i){this.fire(`set_${e}`,e,t,i);}),this.on("set_enabled",this.onSetEnabled,this);}}px.order=0;class pT extends X{addComponent(e,t={}){let i=new this.ComponentType(this,e),s=new this.DataType;return this.store[e.getGuid()]={entity:e,data:s},e[this.id]=i,e.c[this.id]=i,this.initializeComponentData(i,t,[]),this.fire("add",e,i),i}removeComponent(e){let t=this.id,i=this.store[e.getGuid()],s=e.c[t];s.fire("beforeremove"),this.fire("beforeremove",e,s),delete this.store[e.getGuid()],e[t]=void 0,delete e.c[t],this.fire("remove",e,i.data);}cloneComponent(e,t){let i=this.store[e.getGuid()];return this.addComponent(t,i.data)}initializeComponentData(e,t={},i){for(let s=0,r=i.length;s{i&&"object"==typeof i&&i.type===e&&t.push(i);}),t}destroy(){this.off();}constructor(e){super(),this.app=e,this.store={},this.schema=[];}}class pE{update(e,t){if(e=this._right){let i=t.length;if(i)if(e=t[i-1])this._left=t[i-1],this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=i-1;else {let i=this._findKey(e,t);this._left=t[i],this._right=t[i+1],this._len=this._right-this._left;let s=1/this._len;this._recip=isFinite(s)?s:0,this._p0=i,this._p1=i+1;}else this._left=-1/0,this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=0;}this._t=0===this._recip?0:(e-this._left)*this._recip,this._hermite.valid=false;}_findKey(e,t){let i=0;for(;e>=t[i+1];)i++;return i}eval(e,t,i){let s=i._data,r=i._components,a=this._p0*r;if(0===t)for(let t=0;t=e)}nextEventBehindTime(e){return !!this.nextEvent&&(e===this.track.duration?this.isReverse?this.nextEvent.time>=e:this.nextEvent.time<=e:this.isReverse?this.nextEvent.time>e:this.nextEvent.time=this.track.events.length?this._eventCursor=0:this._eventCursor<0&&(this._eventCursor=this.track.events.length-1);}clipFrameTime(e){let t=pb.eventFrame;t.start=0,t.end=e,t.residual=0,this.isReverse?e<0&&(t.start=this.track.duration,t.end=0,t.residual=e+this.track.duration):e>this.track.duration&&(t.start=0,t.end=this.track.duration,t.residual=e-this.track.duration);}alignCursorToCurrentTime(){for(this.resetEventCursor();this.nextEventBehindTime(this._time)&&this._eventCursor!==this.eventCursorEnd;)this.moveEventCursor();}fireNextEvent(){this._eventHandler.fire(this.nextEvent.name,{track:this.track,...this.nextEvent}),this.moveEventCursor();}fireNextEventInFrame(e,t){return !!(this.nextEventAheadOfTime(e)&&this.nextEventBehindTime(t))&&(this.fireNextEvent(),true)}activeEventsForFrame(e,t){let i=pb.eventFrame;this.clipFrameTime(t);let s=this.eventCursor;for(;this.fireNextEventInFrame(e,i.end)&&s!==this.eventCursor;);this.loop&&Math.abs(i.residual)>0&&this.activeEventsForFrame(i.start,i.residual);}progressForTime(e){return e*this._speed/this._track.duration}_update(e){if(this._playing){let t=this._time,i=this._track.duration,s=this._speed,r=this._loop;this._track.events.length>0&&i>0&&this.activeEventsForFrame(t,t+s*e),t+=s*e,s>=0?t>i&&(r?t=t%i||0:(t=this._track.duration,this.pause())):t<0&&(r?t=i+(t%i||0):(t=0,this.pause())),this._time=t;}this._time!==this._snapshot._time&&this._track.eval(this._time,this._snapshot);}play(){this._playing=true,this._time=0;}stop(){this._playing=false,this._time=0;}pause(){this._playing=false;}resume(){this._playing=true;}reset(){this._time=0;}constructor(e,t,i,s,r,a){this._name=e.name,this._track=e,this._snapshot=new pw(e),this._playing=s,this._time=t,this._speed=i,this._loop=r,this._blendWeight=1,this._blendOrder=0,this._eventHandler=a,this.alignCursorToCurrentTime();}}pb.eventFrame={start:0,end:0,residual:0};let pC="NONE",pA="PREV_STATE",pP="NEXT_STATE",pI="PREV_STATE_NEXT_STATE",pD="NEXT_STATE_PREV_STATE",pR="GREATER_THAN",pL="LESS_THAN",pM="GREATER_THAN_EQUAL_TO",pO="LESS_THAN_EQUAL_TO",pF="EQUAL_TO",pN="NOT_EQUAL_TO",pB="INTEGER",pk="FLOAT",pU="BOOLEAN",pz="TRIGGER",pV="2D_DIRECTIONAL",pG="2D_CARTESIAN",pH="DIRECT",pW="START",pX=[pW,"END","ANY"],pY="OVERWRITE",pq="ADDITIVE";class pj{static dot(e,t){let i=e.length,s=0;for(let r=0;r0){t=1/Math.sqrt(t);let i=e.length;for(let s=0;s0&&(i=1/Math.sqrt(i));for(let r=0;rpj.dot(e,t)&&(i=-i);for(let s=0;s0;)this.removeClip(0);}updateClipTrack(e,t){this._clips.forEach(i=>{i.name.includes(e)&&(i.track=t);}),this.rebind();}findClip(e){let t=this._clips;for(let i=0;i{this.addClip(e);});}assignMask(e){return this._binder.assignMask(e)}update(e,t=true){let i=this._clips,s=i.map((e,t)=>t);pj.stableSort(s,(e,t)=>i[e].blendOrder0&&h._update(e),!t)break;if(u>=1)for(let e=0;e0)for(let e=0;ee.time-t.time);}}class pQ{get name(){return this._name}get duration(){return this._duration}get inputs(){return this._inputs}get outputs(){return this._outputs}get curves(){return this._curves}set events(e){this._animEvents=e;}get events(){return this._animEvents.events}eval(e,t){t._time=e;let i=this._inputs,s=this._outputs,r=this._curves,a=t._cache,n=t._results;for(let t=0;t0&&i.push(s),i}static encode(e,t,i){return `${Array.isArray(e)?e.join("/"):e}/${t}/${Array.isArray(i)?i.join("/"):i}`}resolve(e){return null}unresolve(e){}update(e){}}class p0{get set(){return this._set}get get(){return this._get}get type(){return this._type}get components(){return this._components}get targetPath(){return this._targetPath}get isTransform(){return this._isTransform}get isWeight(){return this._isWeight}get usesLayerBlending(){return this._isTransform||this._isWeight}constructor(e,t,i,s){e.set?(this._set=e.set,this._get=e.get):this._set=e,this._type=t,this._components=i,this._targetPath=s,this._isTransform="localRotation"===this._targetPath.substring(this._targetPath.length-13)||"localPosition"===this._targetPath.substring(this._targetPath.length-13)||"localScale"===this._targetPath.substring(this._targetPath.length-10),this._isWeight=-1!==this._targetPath.indexOf("weight.");}}class p1{_isPathActive(e){if(!this._mask)return true;let t=[e.entityPath[0],this.graph.name];for(let i=0;i{let i=this._mask[e];if(i&&(i.children||t&&false!==i.value))return true;return false},this.graph=e,!e)return;this._mask=null;let t={},i=function(e){t[e.name]=e;for(let t=0;t0?p1.createAnimTarget({set:e=>{for(let i=0;i[r[0].getWeight(t)]},"number",1,e,`weight.${t}`):null},materialTexture:(e,t)=>{let i=s(e);if(i){let s;for(let t=0;t{let i=this.animComponent.system.app.assets.get(e[0]);i&&i.resource&&"texture"===i.type&&(s.material[t]=i.resource,s.material.update());};return p1.createAnimTarget(i,"vector",1,e,"materialTexture","material")}}return null}};}}class p2 extends px{set animations(e){this._animations=e,this.onSetAnimations();}get animations(){return this._animations}set assets(e){let t=this._assets;if(t&&t.length){for(let e=0;ee instanceof fX?e.id:e);this.loadAnimationAssets(i);}get assets(){return this._assets}set currentTime(e){if(this.skeleton&&(this.skeleton.currentTime=e,this.skeleton.addTime(0),this.skeleton.updateGraph()),this.animEvaluator){let t=this.animEvaluator.clips;for(let i=0;i0)return e[e.length-1].time}return 0}get duration(){return this.currAnim?this.animations[this.currAnim].duration:0}set loop(e){if(this._loop=e,this.skeleton&&(this.skeleton.looping=e),this.animEvaluator)for(let t=0;t0&&!!this.prevAnim,this.blending&&(this.blend=0,this.blendSpeed=1/t),this.skeleton&&(this.blending?(this.fromSkel.animation=e,this.fromSkel.addTime(this.skeleton._time),this.toSkel.animation=i):this.skeleton.animation=i),this.animEvaluator){let e=this.animEvaluator;if(this.blending)for(;e.clips.length>1;)e.removeClip(0);else this.animEvaluator.removeClips();let t=new pb(this.animations[this.currAnim],0,1,true,this.loop);t.name=this.currAnim,t.blendWeight=+!this.blending,t.reset(),this.animEvaluator.addClip(t);}}this.playing=true;}}getAnimation(e){return this.animations[e]}setModel(e){e!==this.model&&(this._resetAnimationController(),this.model=e,this.animations&&this.currAnim&&this.animations[this.currAnim]&&this.play(this.currAnim));}onSetAnimations(){let e=this.entity.model;if(e){let t=e.model;t&&t!==this.model&&this.setModel(t);}if(!this.currAnim&&this.activate&&this.enabled&&this.entity.enabled){let e=Object.keys(this._animations);e.length>0&&this.play(e[0]);}}_resetAnimationController(){this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null;}_createAnimationController(){let e=this.model,t=this.animations,i=false,s=false;for(let e in t)t.hasOwnProperty(e)&&(t[e].constructor===pQ?s=true:i=true);let r=e.getGraph();i?(this.fromSkel=new dO(r),this.toSkel=new dO(r),this.skeleton=new dO(r),this.skeleton.looping=this.loop,this.skeleton.setGraph(r)):s&&(this.animEvaluator=new p$(new p1(this.entity)));}loadAnimationAssets(e){if(!e||!e.length)return;let t=this.system.app.assets,i=e=>{if(e.resources.length>1)for(let t=0;t{e.off("change",this.onAssetChanged,this),e.on("change",this.onAssetChanged,this),e.off("remove",this.onAssetRemoved,this),e.on("remove",this.onAssetRemoved,this),e.resource?i(e):(e.once("load",i,this),this.enabled&&this.entity.enabled&&t.load(e));};for(let i=0,r=e.length;i1){if(s&&s.length>1)for(let e=0;e1)for(let e=0;e1)for(let e=0;e1)for(let t=0;t0&&this.play(e[0]);}}onBeforeRemove(){for(let e=0;e=1&&(this.blend=1)),this.playing){let t=this.skeleton;if(null!==t&&null!==this.model){if(this.blending)t.blend(this.fromSkel,this.toSkel,this.blend);else {let i=e*this.speed;t.addTime(i),this.speed>0&&t._time===t.animation.duration&&!this.loop?this.playing=false:this.speed<0&&0===t._time&&!this.loop&&(this.playing=false);}this.blending&&1===this.blend&&(t.animation=this.toSkel.animation),t.updateGraph();}}let t=this.animEvaluator;if(t){for(let e=0;e1&&(t.clips[1].blendWeight=this.blend),t.update(e);}this.blending&&1===this.blend&&(this.blending=false);}constructor(...e){super(...e),this._animations={},this._assets=[],this._loop=true,this.animEvaluator=null,this.model=null,this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animationsIndex={},this.prevAnim=null,this.currAnim=null,this.blend=0,this.blending=false,this.blendSpeed=0,this.activate=true,this.speed=1;}}class p3{constructor(){this.enabled=true;}}let p4=["enabled"];class p5 extends pT{initializeComponentData(e,t,i){for(let i of ["activate","enabled","loop","speed","assets"])t.hasOwnProperty(i)&&(e[i]=t[i]);super.initializeComponentData(e,t,p4);}cloneComponent(e,t){this.addComponent(t,{}),t.animation.assets=e.animation.assets.slice(),t.animation.speed=e.animation.speed,t.animation.loop=e.animation.loop,t.animation.activate=e.animation.activate,t.animation.enabled=e.animation.enabled;let i={},s=e.animation.animations;for(let e in s)s.hasOwnProperty(e)&&(i[e]=s[e]);t.animation.animations=i;let r={},a=e.animation.animationsIndex;for(let e in a)a.hasOwnProperty(e)&&(r[e]=a[e]);return t.animation.animationsIndex=r,t.animation}onBeforeRemove(e,t){t.onBeforeRemove();}onUpdate(e){let t=this.store;for(let i in t)if(t.hasOwnProperty(i)){let s=t[i];s.data.enabled&&s.entity.enabled&&s.entity.animation.update(e);}}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this);}constructor(e){super(e),this.id="animation",this.ComponentType=p2,this.DataType=p3,this.schema=p4,this.on("beforeremove",this.onBeforeRemove,this),this.app.systems.on("update",this.onUpdate,this);}}px._buildAccessors(p2.prototype,p4);class p6{get parent(){return this._parent}get name(){return this._name}get path(){return this._parent?`${this._parent.path}.${this._name}`:this._name}get point(){return this._point}get pointLength(){return this._pointLength}set weight(e){this._weight=e;}get weight(){return this._parent?this._parent.weight*this._weight:this._weight}get normalizedWeight(){let e=this._state.totalWeight;return 0===e?0:this.weight/e}get speed(){return this._weightedSpeed*this._speed}get absoluteSpeed(){return Math.abs(this._speed)}set weightedSpeed(e){this._weightedSpeed=e;}get weightedSpeed(){return this._weightedSpeed}set animTrack(e){this._animTrack=e;}get animTrack(){return this._animTrack}constructor(e,t,i,s,r=1){this._state=e,this._parent=t,this._name=i,Array.isArray(s)?(this._point=new ef(s[0],s[1]),this._pointLength=this._point.length()):(this._point=s,this._pointLength=s),this._speed=r,this._weightedSpeed=1,this._weight=1,this._animTrack=null;}}class p8 extends p6{get weight(){return this.calculateWeights(),this._parent?this._parent.weight*this._weight:this._weight}get syncAnimations(){return this._syncAnimations}getChild(e){for(let t=0;te.point-t.point),super(e,t,i,s,r,a,n,o,l);}}class p7 extends p8{pointDistanceCache(e,t){let i=`${e}${t}`;return this._pointCache[i]||(this._pointCache[i]=this._children[t].point.clone().sub(this._children[e].point)),this._pointCache[i]}calculateWeights(){let e,t;if(!this.updateParameterValues()){p7._p.set(...this._parameterValues),e=0,t=0;for(let i=0;ie.path===i);if(s>=0)this._animationList[s].animTrack=t;else {let i=this._getNodeFromPath(e);i.animTrack=t,this._animationList.push(i);}this._updateHasAnimations();}_updateHasAnimations(){this._hasAnimations=this._animationList.length>0&&this._animationList.every(e=>e.animTrack&&e.animTrack!==pQ.EMPTY);}get name(){return this._name}set animations(e){this._animationList=e,this._updateHasAnimations();}get animations(){return this._animationList}get hasAnimations(){return this._hasAnimations}set speed(e){this._speed=e;}get speed(){return this._speed}set loop(e){this._loop=e;}get loop(){return this._loop}get nodeCount(){return this._blendTree&&this._blendTree.constructor!==p6?this._blendTree.getNodeCount():1}get playable(){return -1!==pX.indexOf(this.name)||this.animations.length===this.nodeCount}get looping(){if(this.animations.length>0){let e=`${this.name}.${this.animations[0].animTrack.name}`,t=this._controller.animEvaluator.findClip(e);if(t)return t.loop}return false}get totalWeight(){let e=0;for(let t=0;te&&(e=i.animTrack.duration);}return e}constructor(e,t,i=1,s=true,r){this._animations={},this._animationList=[],this._controller=e,this._name=t,this._speed=i,this._loop=s,this._hasAnimations=false,r?this._blendTree=this._createTree(r.type,this,null,t,1,r.parameter?[r.parameter]:r.parameters,r.children,r.syncAnimations,this._createTree,this._controller.findParameter):this._blendTree=new p6(this,null,t,1,i);}}class ms{get from(){return this._from}set to(e){this._to=e;}get to(){return this._to}get time(){return this._time}get priority(){return this._priority}get conditions(){return this._conditions}get exitTime(){return this._exitTime}get transitionOffset(){return this._transitionOffset}get interruptionSource(){return this._interruptionSource}get hasExitTime(){return !!this.exitTime}constructor({from:e,to:t,time:i=0,priority:s=0,conditions:r=[],exitTime:a=null,transitionOffset:n=null,interruptionSource:o=pC}){this._from=e,this._to=t,this._time=i,this._priority=s,this._conditions=r,this._exitTime=a,this._transitionOffset=n,this._interruptionSource=o;}}class mr{get animEvaluator(){return this._animEvaluator}set activeState(e){this._activeStateName=e;}get activeState(){return this._findState(this._activeStateName)}get activeStateName(){return this._activeStateName}get activeStateAnimations(){return this.activeState.animations}set previousState(e){this._previousStateName=e;}get previousState(){return this._findState(this._previousStateName)}get previousStateName(){return this._previousStateName}get playable(){let e=true;for(let t=0;tt.from===e)).sort(hx),this._findTransitionsFromStateCache[e]=t),t}_findTransitionsBetweenStates(e,t){let i=this._findTransitionsBetweenStatesCache[`${e}->${t}`];return i||((i=this._transitions.filter(i=>i.from===e&&i.to===t)).sort(hx),this._findTransitionsBetweenStatesCache[`${e}->${t}`]=i),i}_transitionHasConditionsMet(e){let t=e.conditions;for(let e=0;ei.value))return false;break;case pL:if(!(s.value=i.value))return false;break;case pO:if(!(s.value<=i.value))return false;break;case pF:if(s.value!==i.value)return false;break;case pN:if(s.value===i.value)return false}}return true}_findTransition(e,t){let i=[];if(e&&t)i=i.concat(this._findTransitionsBetweenStates(e,t));else if(this._isTransitioning)switch(this._transitionInterruptionSource){case pA:i=(i=i.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState("ANY"));break;case pP:i=(i=i.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState("ANY"));break;case pI:i=(i=(i=i.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState("ANY"));break;case pD:i=(i=(i=i.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState("ANY"));}else i=(i=i.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState("ANY"));if((i=i.filter(e=>{if(e.to===this.activeStateName)return false;if(e.hasExitTime){let t=this._getActiveStateProgressForTime(this._timeInStateBefore),i=this._getActiveStateProgressForTime(this._timeInState);if(e.exitTime<1&&this.activeState.loop&&(t-=Math.floor(t),i-=Math.floor(i)),i===t){if(i!==e.exitTime)return null}else if(!(e.exitTime>t&&e.exitTime<=i))return null}return this._transitionHasConditionsMet(e)})).length>0){let e=i[0];return "END"===e.to&&(e.to=this._findTransitionsFromState(pW)[0].to),e}return null}updateStateFromTransition(e){let t,i,s;this.previousState=e.from?this.activeStateName:null,this.activeState=e.to,this._activeStateDurationDirty=true;for(let t=0;t0&&e.transitionOffset<1,n=0,o=0;if(a){let t=r.timelineDuration*e.transitionOffset;n=t,o=t;}this._timeInState=n,this._timeInStateBefore=o;for(let t=0;t0?s.blendWeight=0:s.blendWeight=r.animations[t].normalizedWeight,s.play(),a)s.time=r.timelineDuration*e.transitionOffset;else {let e=r.speed>=0?0:this.activeStateDuration;s.time=e;}}}_transitionToState(e){if(!this._findState(e))return;let t=this._findTransition(this._activeStateName,e);t||(this._animEvaluator.removeClips(),t=new ms({from:null,to:e})),this.updateStateFromTransition(t);}assignAnimation(e,t,i,s){let r=e.split("."),a=this._findState(r[0]);a||(a=new mi(this,r[0],i),this._states[r[0]]=a,this._stateNames.push(r[0])),a.addAnimation(r,t),this._animEvaluator.updateClipTrack(a.name,t),void 0!==i&&(a.speed=i),void 0!==s&&(a.loop=s),!this._playing&&this._activate&&this.playable&&this.play(),this._activeStateDurationDirty=true;}removeNodeAnimations(e){if(-1!==pX.indexOf(e))return false;let t=this._findState(e);return !!t&&(t.animations=[],true)}play(e){e&&this._transitionToState(e),this._playing=true;}pause(){this._playing=false;}reset(){this._previousStateName=null,this._activeStateName=pW,this._playing=false,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=false,this._timeInState=0,this._timeInStateBefore=0,this._animEvaluator.removeClips();}rebind(){this._animEvaluator.rebind();}update(e){let t,i,s;if(!this._playing)return;(this.activeState.loop||this._timeInStatethis.activeStateDuration&&(this._timeInState=this.activeStateDuration,e=this.activeStateDuration-this._timeInStateBefore));let r=this._findTransition(this._activeStateName);if(r&&this.updateStateFromTransition(r),this._isTransitioning)if(this._currTransitionTime+=e,this._currTransitionTime<=this._totalTransitionTime){let e=0!==this._totalTransitionTime?this._currTransitionTime/this._totalTransitionTime:1;for(let r=0;rthis._findParameter(e),this._animEvaluator=e,this._eventHandler=r,this._findParameter=a,this._consumeTrigger=n;for(let e=0;enew ms({...e})),this._activate=s;}}let ma=new ef,mn=new ed,mo=new ep,ml=new es,mh=new ex;class mc extends p1{static _packFloat(e){return e[0]}static _packBoolean(e){return !!e[0]}static _packVec2(e){return ma.x=e[0],ma.y=e[1],ma}static _packVec3(e){return mn.x=e[0],mn.y=e[1],mn.z=e[2],mn}static _packVec4(e){return mo.x=e[0],mo.y=e[1],mo.z=e[2],mo.w=e[3],mo}static _packColor(e){return ml.r=e[0],ml.g=e[1],ml.b=e[2],ml.a=e[3],ml}static _packQuat(e){return mh.x=e[0],mh.y=e[1],mh.z=e[2],mh.w=e[3],mh}resolve(e){let t,i,s,r=pJ.encode(e.entityPath,e.component,e.propertyPath),a=this.targetCache[r];if(a)return a;switch(e.component){case "entity":t=this._getEntityFromHierarchy(e.entityPath),s=pJ.encode(t.path,"entity",e.propertyPath),i=t;break;case "graph":if(!(i=this.findNode(e)))return null;s=pJ.encode(i.path,"graph",e.propertyPath);break;default:if(!(i=(t=this._getEntityFromHierarchy(e.entityPath)).findComponent(e.component)))return null;s=pJ.encode(t.path,e.component,e.propertyPath);}return a=this._createAnimTargetForProperty(i,e.propertyPath,s),this.targetCache[r]=a,a}update(e){let t=this.activeNodes;if(t)for(let e=0;e{t(i(e));},get:()=>e}}let n=s[r];if("object"==typeof n&&n.hasOwnProperty("copy"))return function(e){n.copy(i(e));};if(-1!==[ef,ed,ep,es,ex].indexOf(s.constructor)&&t.length>1){let a=t.length>2?this._resolvePath(e,t.slice(0,-1)):e,n=t[t.length-2];return function(e){s[r]=i(e),a[n]=s;}}return function(e){s[r]=i(e);}}_createAnimTargetForProperty(e,t,i){let s,r,a;if(this.handlers&&t[0].startsWith("weight."))return this.handlers.weight(e,t[0].replace("weight.",""));if(this.handlers&&"material"===t[0]&&2===t.length){let i=t[1];if(i.endsWith("Map"))return this.handlers.materialTexture(e,i)}let n=this._resolvePath(e,t,true);if(void 0===n)return null;if("number"==typeof n)s=this._setter(e,t,mc._packFloat),r="vector",a=1;else if("boolean"==typeof n)s=this._setter(e,t,mc._packBoolean),r="vector",a=1;else if("object"==typeof n)switch(n.constructor){case ef:s=this._setter(e,t,mc._packVec2),r="vector",a=2;break;case ed:s=this._setter(e,t,mc._packVec3),r="vector",a=3;break;case ep:s=this._setter(e,t,mc._packVec4),r="vector",a=4;break;case es:s=this._setter(e,t,mc._packColor),r="vector",a=4;break;case ex:s=this._setter(e,t,mc._packQuat),r="quaternion",a=4;break;default:return null}return -1!==t.indexOf("material")?new p0(t=>{s(t),e.material.update();},r,a,i):new p0(s,r,a,i)}rebind(){this.targetCache={},this.animComponent.rootBone?this.graph=this.animComponent.rootBone:this.graph=this.animComponent.entity;let e={},t=function(i){e[i.name]=i;for(let e=0;e{this._stateGraph=e.resource,this.loadStateGraph(this._stateGraph);}),i.on("change",this._onStateGraphAssetChangeEvent,this),this.system.app.assets.load(i)),this._stateGraphAsset=t));}get stateGraphAsset(){return this._stateGraphAsset}set normalizeWeights(e){this._normalizeWeights=e,this.unbind();}get normalizeWeights(){return this._normalizeWeights}set animationAssets(e){this._animationAssets=e,this.loadAnimationAssets();}get animationAssets(){return this._animationAssets}set speed(e){this._speed=e;}get speed(){return this._speed}set activate(e){this._activate=e;}get activate(){return this._activate}set playing(e){this._playing=e;}get playing(){return this._playing}set rootBone(e){if("string"==typeof e){let t=this.entity.root.findByGuid(e);this._rootBone=t;}else e instanceof f9?this._rootBone=e:this._rootBone=null;this.rebind();}get rootBone(){return this._rootBone}set stateGraph(e){this._stateGraph=e;}get stateGraph(){return this._stateGraph}get layers(){return this._layers}set layerIndices(e){this._layerIndices=e;}get layerIndices(){return this._layerIndices}set parameters(e){this._parameters=e;}get parameters(){return this._parameters}set targets(e){this._targets=e;}get targets(){return this._targets}get playable(){for(let e=0;e0?this._layers[0]:null}_onStateGraphAssetChangeEvent(e){let t=this.animationAssets,i=this.layers.map(e=>e.mask);this.removeStateGraph(),this._stateGraph=new mu(e._data),this.loadStateGraph(this._stateGraph),this.animationAssets=t,this.loadAnimationAssets(),this.layers.forEach((e,t)=>{e.mask=i[t];}),this.rebind();}dirtifyTargets(){let e=Object.values(this._targets);for(let t=0;te.blendTree)&&(t=true);}t||this.setupAnimationAssets();}setupAnimationAssets(){for(let e=0;e{this._targets[e].unbind();});}rebind(){this._targets={};for(let e=0;e{this.parameters[e].value=false;}),this._consumedTriggers.clear();}resolveDuplicatedEntityReferenceProperties(e,t){e.rootBone&&t[e.rootBone.getGuid()]?this.rootBone=t[e.rootBone.getGuid()]:this.rebind();}constructor(...e){super(...e),this._stateGraphAsset=null,this._animationAssets={},this._speed=1,this._activate=true,this._playing=false,this._rootBone=null,this._stateGraph=null,this._layers=[],this._layerIndices={},this._parameters={},this._targets={},this._consumedTriggers=new Set,this._normalizeWeights=false,this.findParameter=e=>this._parameters[e],this.consumeTrigger=e=>{this._consumedTriggers.add(e);};}}class mp{constructor(){this.enabled=true;}}let mm=["enabled"];class m_ extends pT{initializeComponentData(e,t,i){super.initializeComponentData(e,t,mm);let s=["animationAssets","stateGraph","layers","masks"];Object.keys(t).forEach(i=>{s.includes(i)||(e[i]=t[i]);}),t.stateGraph&&(e.stateGraph=t.stateGraph,e.loadStateGraph(e.stateGraph)),t.layers&&t.layers.forEach((t,i)=>{t._controller.states.forEach(s=>{t._controller._states[s]._animationList.forEach(s=>{if(s.animTrack&&s.animTrack!==pQ.EMPTY)e.layers[i].assignAnimation(s.name,s.animTrack);else {let r=this.app.assets.get(t._component._animationAssets[`${t.name}:${s.name}`].asset);r&&!r.loaded&&r.once("load",()=>{e.layers[i].assignAnimation(s.name,r.resource);});}});});}),t.animationAssets&&(e.animationAssets=Object.assign(e.animationAssets,t.animationAssets)),t.masks&&Object.keys(t.masks).forEach(i=>{if(e.layers[i]){let s=t.masks[i].mask,r={};Object.keys(s).forEach(e=>{r[decodeURI(e)]=s[e];}),e.layers[i].mask=r;}});}onAnimationUpdate(e){let t=this.store;for(let i in t)if(t.hasOwnProperty(i)){let s=t[i].entity.anim;s.data.enabled&&s.entity.enabled&&s.playing&&s.update(e);}}cloneComponent(e,t){let i;e.anim.rootBone&&e.anim.rootBone!==e||(i={},e.anim.layers.forEach((e,s)=>{if(e.mask){let r={};Object.keys(e.mask).forEach(i=>{let s=i.split("/");s.shift(),r[[t.name,...s].join("/")]=e.mask[i];}),i[s]={mask:r};}}));let s={enabled:e.anim.enabled,stateGraphAsset:e.anim.stateGraphAsset,animationAssets:e.anim.animationAssets,speed:e.anim.speed,activate:e.anim.activate,playing:e.anim.playing,rootBone:e.anim.rootBone,stateGraph:e.anim.stateGraph,layers:e.anim.layers,layerIndices:e.anim.layerIndices,parameters:e.anim.parameters,normalizeWeights:e.anim.normalizeWeights,masks:i};return this.addComponent(t,s)}onBeforeRemove(e,t){t.onBeforeRemove();}destroy(){super.destroy(),this.app.systems.off("animationUpdate",this.onAnimationUpdate,this);}constructor(e){super(e),this.id="anim",this.ComponentType=mf,this.DataType=mp,this.schema=mm,this.on("beforeremove",this.onBeforeRemove,this),this.app.systems.on("animationUpdate",this.onAnimationUpdate,this);}}px._buildAccessors(mf.prototype,mm);class mg extends px{setCurrentListener(){if(this.enabled&&this.entity.audiolistener&&this.entity.enabled){this.system.current=this.entity;let e=this.system.current.getPosition();this.system.manager.listener.setPosition(e);}}onEnable(){this.setCurrentListener();}onDisable(){this.system.current===this.entity&&(this.system.current=null);}}class mv{constructor(){this.enabled=true;}}let mS=["enabled"];class my extends pT{initializeComponentData(e,t,i){i=["enabled"],super.initializeComponentData(e,t,i);}onUpdate(e){if(this.current){let e=this.current.getPosition();this.manager.listener.setPosition(e);let t=this.current.getWorldTransform();this.manager.listener.setOrientation(t);}}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this);}constructor(e){super(e),this.id="audiolistener",this.ComponentType=mg,this.DataType=mv,this.schema=mS,this.manager=e.soundManager,this.current=null,this.app.systems.on("update",this.onUpdate,this);}}px._buildAccessors(mg.prototype,mS);let mx="group",mT="image",mE="text",mw="stretch",mb="contain",mC="cover",mA="DEFAULT",mP="HOVER",mI="PRESSED",mD="INACTIVE",mR={};mR[mA]="_defaultTint",mR[mP]="hoverTint",mR[mI]="pressedTint",mR[mD]="inactiveTint";let mL={};mL[mA]="_defaultSpriteAsset",mL[mP]="hoverSpriteAsset",mL[mI]="pressedSpriteAsset",mL[mD]="inactiveSpriteAsset";let mM={};mM[mA]="_defaultSpriteFrame",mM[mP]="hoverSpriteFrame",mM[mI]="pressedSpriteFrame",mM[mD]="inactiveSpriteFrame";class mO extends px{get data(){let e=this.system.store[this.entity.getGuid()];return e?e.data:null}set enabled(e){this._setValue("enabled",e);}get enabled(){return this.data.enabled}set active(e){this._setValue("active",e);}get active(){return this.data.active}set imageEntity(e){if(this._imageEntity!==e){let t="string"==typeof e;(!this._imageEntity||!t||this._imageEntity.getGuid()!==e)&&(this._imageEntity&&this._imageEntityUnsubscribe(),e instanceof oJ?this._imageEntity=e:t?this._imageEntity=this.system.app.getEntityFromIndex(e)||null:this._imageEntity=null,this._imageEntity&&this._imageEntitySubscribe(),this._imageEntity?this.data.imageEntity=this._imageEntity.getGuid():t&&e&&(this.data.imageEntity=e));}}get imageEntity(){return this._imageEntity}set hitPadding(e){this._setValue("hitPadding",e);}get hitPadding(){return this.data.hitPadding}set transitionMode(e){this._setValue("transitionMode",e);}get transitionMode(){return this.data.transitionMode}set hoverTint(e){this._setValue("hoverTint",e);}get hoverTint(){return this.data.hoverTint}set pressedTint(e){this._setValue("pressedTint",e);}get pressedTint(){return this.data.pressedTint}set inactiveTint(e){this._setValue("inactiveTint",e);}get inactiveTint(){return this.data.inactiveTint}set fadeDuration(e){this._setValue("fadeDuration",e);}get fadeDuration(){return this.data.fadeDuration}set hoverSpriteAsset(e){this._setValue("hoverSpriteAsset",e);}get hoverSpriteAsset(){return this.data.hoverSpriteAsset}set hoverSpriteFrame(e){this._setValue("hoverSpriteFrame",e);}get hoverSpriteFrame(){return this.data.hoverSpriteFrame}set pressedSpriteAsset(e){this._setValue("pressedSpriteAsset",e);}get pressedSpriteAsset(){return this.data.pressedSpriteAsset}set pressedSpriteFrame(e){this._setValue("pressedSpriteFrame",e);}get pressedSpriteFrame(){return this.data.pressedSpriteFrame}set inactiveSpriteAsset(e){this._setValue("inactiveSpriteAsset",e);}get inactiveSpriteAsset(){return this.data.inactiveSpriteAsset}set inactiveSpriteFrame(e){this._setValue("inactiveSpriteFrame",e);}get inactiveSpriteFrame(){return this.data.inactiveSpriteFrame}_setValue(e,t){let i=this.data,s=i[e];i[e]=t,this.fire("set",e,s,t);}_toggleLifecycleListeners(e,t){this[e]("set_active",this._onSetActive,this),this[e]("set_transitionMode",this._onSetTransitionMode,this),this[e]("set_hoverTint",this._onSetTransitionValue,this),this[e]("set_pressedTint",this._onSetTransitionValue,this),this[e]("set_inactiveTint",this._onSetTransitionValue,this),this[e]("set_hoverSpriteAsset",this._onSetTransitionValue,this),this[e]("set_hoverSpriteFrame",this._onSetTransitionValue,this),this[e]("set_pressedSpriteAsset",this._onSetTransitionValue,this),this[e]("set_pressedSpriteFrame",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteAsset",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteFrame",this._onSetTransitionValue,this),"on"===e?this._evtElementAdd=this.entity.on("element:add",this._onElementComponentAdd,this):(this._evtElementAdd?.off(),this._evtElementAdd=null);}_onSetActive(e,t,i){t!==i&&this._updateVisualState();}_onSetTransitionMode(e,t,i){t!==i&&(this._cancelTween(),this._resetToDefaultVisualState(t),this._forceReapplyVisualState());}_onSetTransitionValue(e,t,i){t!==i&&this._forceReapplyVisualState();}_imageEntitySubscribe(){this._evtImageEntityElementAdd=this._imageEntity.on("element:add",this._onImageElementGain,this),this._imageEntity.element&&this._onImageElementGain();}_imageEntityUnsubscribe(){this._evtImageEntityElementAdd?.off(),this._evtImageEntityElementAdd=null,this._imageEntity?.element&&this._onImageElementLose();}_imageEntityElementSubscribe(){let e=this._imageEntity.element;this._evtImageEntityElementRemove=e.once("beforeremove",this._onImageElementLose,this),this._evtImageEntityElementColor=e.on("set:color",this._onSetColor,this),this._evtImageEntityElementOpacity=e.on("set:opacity",this._onSetOpacity,this),this._evtImageEntityElementSpriteAsset=e.on("set:spriteAsset",this._onSetSpriteAsset,this),this._evtImageEntityElementSpriteFrame=e.on("set:spriteFrame",this._onSetSpriteFrame,this);}_imageEntityElementUnsubscribe(){this._evtImageEntityElementRemove?.off(),this._evtImageEntityElementRemove=null,this._evtImageEntityElementColor?.off(),this._evtImageEntityElementColor=null,this._evtImageEntityElementOpacity?.off(),this._evtImageEntityElementOpacity=null,this._evtImageEntityElementSpriteAsset?.off(),this._evtImageEntityElementSpriteAsset=null,this._evtImageEntityElementSpriteFrame?.off(),this._evtImageEntityElementSpriteFrame=null;}_onElementComponentRemove(){this._toggleHitElementListeners("off");}_onElementComponentAdd(){this._toggleHitElementListeners("on");}_onImageElementLose(){this._imageEntityElementUnsubscribe(),this._cancelTween(),this._resetToDefaultVisualState(this.transitionMode);}_onImageElementGain(){this._imageEntityElementSubscribe(),this._storeDefaultVisualState(),this._forceReapplyVisualState();}_toggleHitElementListeners(e){if(this.entity.element){let t="on"===e;t&&this._hasHitElementListeners||(this.entity.element[e]("beforeremove",this._onElementComponentRemove,this),this.entity.element[e]("mouseenter",this._onMouseEnter,this),this.entity.element[e]("mouseleave",this._onMouseLeave,this),this.entity.element[e]("mousedown",this._onMouseDown,this),this.entity.element[e]("mouseup",this._onMouseUp,this),this.entity.element[e]("touchstart",this._onTouchStart,this),this.entity.element[e]("touchend",this._onTouchEnd,this),this.entity.element[e]("touchleave",this._onTouchLeave,this),this.entity.element[e]("touchcancel",this._onTouchCancel,this),this.entity.element[e]("selectstart",this._onSelectStart,this),this.entity.element[e]("selectend",this._onSelectEnd,this),this.entity.element[e]("selectenter",this._onSelectEnter,this),this.entity.element[e]("selectleave",this._onSelectLeave,this),this.entity.element[e]("click",this._onClick,this),this._hasHitElementListeners=t);}}_storeDefaultVisualState(){let e=this._imageEntity?.element;e&&e.type!==mx&&(this._storeDefaultColor(e.color),this._storeDefaultOpacity(e.opacity),this._storeDefaultSpriteAsset(e.spriteAsset),this._storeDefaultSpriteFrame(e.spriteFrame));}_storeDefaultColor(e){this._defaultTint.r=e.r,this._defaultTint.g=e.g,this._defaultTint.b=e.b;}_storeDefaultOpacity(e){this._defaultTint.a=e;}_storeDefaultSpriteAsset(e){this._defaultSpriteAsset=e;}_storeDefaultSpriteFrame(e){this._defaultSpriteFrame=e;}_onSetColor(e){this._isApplyingTint||(this._storeDefaultColor(e),this._forceReapplyVisualState());}_onSetOpacity(e){this._isApplyingTint||(this._storeDefaultOpacity(e),this._forceReapplyVisualState());}_onSetSpriteAsset(e){this._isApplyingSprite||(this._storeDefaultSpriteAsset(e),this._forceReapplyVisualState());}_onSetSpriteFrame(e){this._isApplyingSprite||(this._storeDefaultSpriteFrame(e),this._forceReapplyVisualState());}_onMouseEnter(e){this._isHovering=true,this._updateVisualState(),this._fireIfActive("mouseenter",e);}_onMouseLeave(e){this._isHovering=false,this._isPressed=false,this._updateVisualState(),this._fireIfActive("mouseleave",e);}_onMouseDown(e){this._isPressed=true,this._updateVisualState(),this._fireIfActive("mousedown",e);}_onMouseUp(e){this._isPressed=false,this._updateVisualState(),this._fireIfActive("mouseup",e);}_onTouchStart(e){this._isPressed=true,this._updateVisualState(),this._fireIfActive("touchstart",e);}_onTouchEnd(e){e.event.preventDefault(),this._isPressed=false,this._updateVisualState(),this._fireIfActive("touchend",e);}_onTouchLeave(e){this._isPressed=false,this._updateVisualState(),this._fireIfActive("touchleave",e);}_onTouchCancel(e){this._isPressed=false,this._updateVisualState(),this._fireIfActive("touchcancel",e);}_onSelectStart(e){this._isPressed=true,this._updateVisualState(),this._fireIfActive("selectstart",e);}_onSelectEnd(e){this._isPressed=false,this._updateVisualState(),this._fireIfActive("selectend",e);}_onSelectEnter(e){this._hoveringCounter++,1===this._hoveringCounter&&(this._isHovering=true,this._updateVisualState()),this._fireIfActive("selectenter",e);}_onSelectLeave(e){this._hoveringCounter--,0===this._hoveringCounter&&(this._isHovering=false,this._isPressed=false,this._updateVisualState()),this._fireIfActive("selectleave",e);}_onClick(e){this._fireIfActive("click",e);}_fireIfActive(e,t){this.data.active&&this.fire(e,t);}_updateVisualState(e){let t=this._visualState,i=this._determineVisualState();if((t!==i||e)&&this.enabled)switch(this._visualState=i,t===mP&&this._fireIfActive("hoverend"),t===mI&&this._fireIfActive("pressedend"),i===mP&&this._fireIfActive("hoverstart"),i===mI&&this._fireIfActive("pressedstart"),this.transitionMode){case 0:{let e=this[mR[this._visualState]];this._applyTint(e);break}case 1:{let e=mL[this._visualState],t=mM[this._visualState],i=this[e],s=this[t];this._applySprite(i,s);}}}_forceReapplyVisualState(){this._updateVisualState(true);}_resetToDefaultVisualState(e){if(this._imageEntity?.element)switch(e){case 0:this._cancelTween(),this._applyTintImmediately(this._defaultTint);break;case 1:this._applySprite(this._defaultSpriteAsset,this._defaultSpriteFrame);}}_determineVisualState(){return this.active?this._isPressed?mI:this._isHovering?mP:mA:mD}_applySprite(e,t){let i=this._imageEntity?.element;i&&(t=t||0,this._isApplyingSprite=true,i.spriteAsset!==e&&(i.spriteAsset=e),i.spriteFrame!==t&&(i.spriteFrame=t),this._isApplyingSprite=false);}_applyTint(e){this._cancelTween(),0===this.fadeDuration?this._applyTintImmediately(e):this._applyTintWithTween(e);}_applyTintImmediately(e){let t=this._imageEntity?.element;if(!e||!t||t.type===mx)return;let i=mF(e);this._isApplyingTint=true,i.equals(t.color)||(t.color=i),t.opacity!==e.a&&(t.opacity=e.a),this._isApplyingTint=false;}_applyTintWithTween(e){let t=this._imageEntity?.element;if(!e||!t||t.type===mx)return;let i=mF(e),s=t.color,r=t.opacity;i.equals(s)&&e.a===r||(this._tweenInfo={startTime:Q(),from:new es(s.r,s.g,s.b,r),to:e.clone(),lerpColor:new es});}_updateTintTween(){let e=Q()-this._tweenInfo.startTime,t=0===this.fadeDuration?1:e/this.fadeDuration;if(Math.abs((t=ei.clamp(t,0,1))-1)>1e-5){let e=this._tweenInfo.lerpColor;e.lerp(this._tweenInfo.from,this._tweenInfo.to,t),this._applyTintImmediately(new es(e.r,e.g,e.b,e.a));}else this._applyTintImmediately(this._tweenInfo.to),this._cancelTween();}_cancelTween(){delete this._tweenInfo;}onUpdate(){this._tweenInfo&&this._updateTintTween();}onEnable(){this._isHovering=false,this._hoveringCounter=0,this._isPressed=false,this._toggleHitElementListeners("on"),this._forceReapplyVisualState();}onDisable(){this._toggleHitElementListeners("off"),this._resetToDefaultVisualState(this.transitionMode);}onRemove(){this._imageEntityUnsubscribe(),this._toggleLifecycleListeners("off",this.system),this.onDisable();}resolveDuplicatedEntityReferenceProperties(e,t){e.imageEntity&&(this.imageEntity=t[e.imageEntity.getGuid()]);}constructor(e,t){super(e,t),this._visualState=mA,this._isHovering=false,this._hoveringCounter=0,this._isPressed=false,this._defaultTint=new es(1,1,1,1),this._defaultSpriteAsset=null,this._defaultSpriteFrame=0,this._imageEntity=null,this._evtElementAdd=null,this._evtImageEntityElementAdd=null,this._evtImageEntityElementRemove=null,this._evtImageEntityElementColor=null,this._evtImageEntityElementOpacity=null,this._evtImageEntityElementSpriteAsset=null,this._evtImageEntityElementSpriteFrame=null,this._visualState=mA,this._isHovering=false,this._hoveringCounter=0,this._isPressed=false,this._defaultTint=new es(1,1,1,1),this._defaultSpriteAsset=null,this._defaultSpriteFrame=0,this._toggleLifecycleListeners("on",e);}}function mF(e){return new es(e.r,e.g,e.b)}mO.EVENT_MOUSEDOWN="mousedown",mO.EVENT_MOUSEUP="mouseup",mO.EVENT_MOUSEENTER="mouseenter",mO.EVENT_MOUSELEAVE="mouseleave",mO.EVENT_CLICK="click",mO.EVENT_TOUCHSTART="touchstart",mO.EVENT_TOUCHEND="touchend",mO.EVENT_TOUCHCANCEL="touchcancel",mO.EVENT_TOUCHLEAVE="touchleave",mO.EVENT_SELECTSTART="selectstart",mO.EVENT_SELECTEND="selectend",mO.EVENT_SELECTENTER="selectenter",mO.EVENT_SELECTLEAVE="selectleave",mO.EVENT_HOVERSTART="hoverstart",mO.EVENT_HOVEREND="hoverend",mO.EVENT_PRESSEDSTART="pressedstart",mO.EVENT_PRESSEDEND="pressedend";class mN{constructor(){this.enabled=true,this.active=true,this.imageEntity=null,this.hitPadding=new ep,this.transitionMode=0,this.hoverTint=new es(.75,.75,.75),this.pressedTint=new es(.5,.5,.5),this.inactiveTint=new es(.25,.25,.25),this.fadeDuration=0,this.hoverSpriteAsset=null,this.hoverSpriteFrame=0,this.pressedSpriteAsset=null,this.pressedSpriteFrame=0,this.inactiveSpriteAsset=null,this.inactiveSpriteFrame=0;}}let mB=["enabled","active",{name:"hitPadding",type:"vec4"},"transitionMode",{name:"hoverTint",type:"rgba"},{name:"pressedTint",type:"rgba"},{name:"inactiveTint",type:"rgba"},"fadeDuration","hoverSpriteAsset","hoverSpriteFrame","pressedSpriteAsset","pressedSpriteFrame","inactiveSpriteAsset","inactiveSpriteFrame"];class mk extends pT{initializeComponentData(e,t,i){e.imageEntity=t.imageEntity,super.initializeComponentData(e,t,mB);}onUpdate(e){let t=this.store;for(let e in t){let i=t[e].entity,s=i.button;s.enabled&&i.enabled&&s.onUpdate();}}_onRemoveComponent(e,t){t.onRemove();}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this);}constructor(e){super(e),this.id="button",this.ComponentType=mO,this.DataType=mN,this.schema=mB,this.on("beforeremove",this._onRemoveComponent,this),this.app.systems.on("update",this.onUpdate,this);}}let mU=new ed,mz=new ex;class mV extends px{get data(){let e=this.system.store[this.entity.getGuid()];return e?e.data:null}set enabled(e){this._setValue("enabled",e);}get enabled(){return this.data.enabled}set type(e){this._setValue("type",e);}get type(){return this.data.type}set halfExtents(e){this._setValue("halfExtents",e);}get halfExtents(){return this.data.halfExtents}set linearOffset(e){this._setValue("linearOffset",e);}get linearOffset(){return this.data.linearOffset}set angularOffset(e){this._setValue("angularOffset",e);}get angularOffset(){return this.data.angularOffset}set radius(e){this._setValue("radius",e);}get radius(){return this.data.radius}set axis(e){this._setValue("axis",e);}get axis(){return this.data.axis}set height(e){this._setValue("height",e);}get height(){return this.data.height}set asset(e){this._setValue("asset",e);}get asset(){return this.data.asset}set renderAsset(e){this._setValue("renderAsset",e);}get renderAsset(){return this.data.renderAsset}set convexHull(e){this._setValue("convexHull",e);}get convexHull(){return this.data.convexHull}set shape(e){this._setValue("shape",e);}get shape(){return this.data.shape}set model(e){this._setValue("model",e);}get model(){return this.data.model}set render(e){this._setValue("render",e);}get render(){return this.data.render}set checkVertexDuplicates(e){this._setValue("checkVertexDuplicates",e);}get checkVertexDuplicates(){return this.data.checkVertexDuplicates}_setValue(e,t){let i=this.data,s=i[e];i[e]=t,this.fire("set",e,s,t);}onSetType(e,t,i){t!==i&&this.system.changeType(this,t,i);}onSetHalfExtents(e,t,i){let s=this.data.type;this.data.initialized&&"box"===s&&this.system.recreatePhysicalShapes(this);}onSetOffset(e,t,i){this._hasOffset=!this.data.linearOffset.equals(ed.ZERO)||!this.data.angularOffset.equals(ex.IDENTITY),this.data.initialized&&this.system.recreatePhysicalShapes(this);}onSetRadius(e,t,i){let s=this.data.type;this.data.initialized&&("sphere"===s||"capsule"===s||"cylinder"===s||"cone"===s)&&this.system.recreatePhysicalShapes(this);}onSetHeight(e,t,i){let s=this.data.type;this.data.initialized&&("capsule"===s||"cylinder"===s||"cone"===s)&&this.system.recreatePhysicalShapes(this);}onSetAxis(e,t,i){let s=this.data.type;this.data.initialized&&("capsule"===s||"cylinder"===s||"cone"===s)&&this.system.recreatePhysicalShapes(this);}onSetAsset(e,t,i){let s=this.system.app.assets;if(t){let e=s.get(t);e&&e.off("remove",this.onAssetRemoved,this);}if(i){i instanceof fX&&(this.data.asset=i.id);let e=s.get(this.data.asset);e&&(e.off("remove",this.onAssetRemoved,this),e.on("remove",this.onAssetRemoved,this));}this.data.initialized&&"mesh"===this.data.type&&(i||(this.data.model=null),this.system.recreatePhysicalShapes(this));}onSetRenderAsset(e,t,i){let s=this.system.app.assets;if(t){let e=s.get(t);e&&e.off("remove",this.onRenderAssetRemoved,this);}if(i){i instanceof fX&&(this.data.renderAsset=i.id);let e=s.get(this.data.renderAsset);e&&(e.off("remove",this.onRenderAssetRemoved,this),e.on("remove",this.onRenderAssetRemoved,this));}this.data.initialized&&"mesh"===this.data.type&&(i||(this.data.render=null),this.system.recreatePhysicalShapes(this));}onSetModel(e,t,i){this.data.initialized&&"mesh"===this.data.type&&this.system.implementations.mesh.doRecreatePhysicalShape(this);}onSetRender(e,t,i){this.onSetModel(e,t,i);}onAssetRemoved(e){e.off("remove",this.onAssetRemoved,this),this.data.asset===e.id&&(this.asset=null);}onRenderAssetRemoved(e){e.off("remove",this.onRenderAssetRemoved,this),this.data.renderAsset===e.id&&(this.renderAsset=null);}getCompoundChildShapeIndex(e){let t=this.data.shape,i=t.getNumChildShapes();for(let s=0;stypeof Ammo){if(this._compoundParent)this.system.recreatePhysicalShapes(this);else if(!this.entity.rigidbody){let e=this.entity.parent;for(;e;){if(e.collision&&"compound"===e.collision.type){0===e.collision.shape.getNumChildShapes()?this.system.recreatePhysicalShapes(e.collision):this.system.recreatePhysicalShapes(this);break}e=e.parent;}}}}_updateCompound(){let e=this.entity;if(e._dirtyWorld){let t=e._dirtyLocal,i=e;for(;i&&!t&&(!i.collision||i.collision!==this._compoundParent);)i._dirtyLocal&&(t=true),i=i.parent;if(t){e.forEach(this.system.implementations.compound._updateEachDescendantTransform,e);let t=this._compoundParent.entity.rigidbody;t&&t.activate();}}}getShapePosition(){let e=this.entity.getPosition();if(this._hasOffset){let t=this.entity.getRotation(),i=this.data.linearOffset;return mz.copy(t).transformVector(i,mU),mU.add(e)}return e}getShapeRotation(){let e=this.entity.getRotation();return this._hasOffset?mz.copy(e).mul(this.data.angularOffset):e}onEnable(){if("mesh"===this.data.type&&(this.data.asset||this.data.renderAsset)&&this.data.initialized){let e=this.system.app.assets.get(this.data.asset||this.data.renderAsset);if(e&&(!e.resource||!this.data.shape))return void this.system.recreatePhysicalShapes(this)}if(this.entity.rigidbody)this.entity.rigidbody.enabled&&this.entity.rigidbody.enableSimulation();else if(this._compoundParent&&this!==this._compoundParent)if(0===this._compoundParent.shape.getNumChildShapes())this.system.recreatePhysicalShapes(this._compoundParent);else {let e=this.system._getNodeTransform(this.entity,this._compoundParent.entity);this._compoundParent.shape.addChildShape(e,this.data.shape),Ammo.destroy(e),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate();}else this.entity.trigger&&this.entity.trigger.enable();}onDisable(){this.entity.rigidbody?this.entity.rigidbody.disableSimulation():this._compoundParent&&this!==this._compoundParent?!this._compoundParent.entity._destroying&&(this.system._removeCompoundChild(this._compoundParent,this.data.shape),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()):this.entity.trigger&&this.entity.trigger.disable();}onBeforeRemove(){this.asset&&(this.asset=null),this.renderAsset&&(this.renderAsset=null),this.entity.off("insert",this._onInsert,this),this.off();}constructor(e,t){super(e,t),this._compoundParent=null,this._hasOffset=false,this.entity.on("insert",this._onInsert,this),this.on("set_type",this.onSetType,this),this.on("set_convexHull",this.onSetModel,this),this.on("set_halfExtents",this.onSetHalfExtents,this),this.on("set_linearOffset",this.onSetOffset,this),this.on("set_angularOffset",this.onSetOffset,this),this.on("set_radius",this.onSetRadius,this),this.on("set_height",this.onSetHeight,this),this.on("set_axis",this.onSetAxis,this),this.on("set_asset",this.onSetAsset,this),this.on("set_renderAsset",this.onSetRenderAsset,this),this.on("set_model",this.onSetModel,this),this.on("set_render",this.onSetRender,this);}}mV.EVENT_CONTACT="contact",mV.EVENT_COLLISIONSTART="collisionstart",mV.EVENT_COLLISIONEND="collisionend",mV.EVENT_TRIGGERENTER="triggerenter",mV.EVENT_TRIGGERLEAVE="triggerleave";class mG{constructor(){this.enabled=true,this.type="box",this.halfExtents=new ed(.5,.5,.5),this.linearOffset=new ed,this.angularOffset=new ex,this.radius=.5,this.axis=1,this.height=2,this.convexHull=false,this.asset=null,this.renderAsset=null,this.checkVertexDuplicates=true,this.shape=null,this.model=null,this.render=null,this.initialized=false;}}let mH="static",mW="dynamic",mX="kinematic";class mY{initialize(e){let t=this.entity,i=e.shape;if(i&&"u">typeof Ammo){t.trigger&&t.trigger.destroy();let e=this.component;if(e){let t=e.getShapePosition(),i=e.getShapeRotation();a.setValue(t.x,t.y,t.z),n.setValue(i.x,i.y,i.z,i.w);}else {let e=t.getPosition(),i=t.getRotation();a.setValue(e.x,e.y,e.z),n.setValue(i.x,i.y,i.z,i.w);}o.setOrigin(a),o.setRotation(n);let s=this.app.systems.rigidbody.createBody(1,i,o);s.setRestitution(0),s.setFriction(0),s.setDamping(0,0),a.setValue(0,0,0),s.setLinearFactor(a),s.setAngularFactor(a),s.setCollisionFlags(4|s.getCollisionFlags()),s.entity=t,this.body=s,this.component.enabled&&t.enabled&&this.enable();}}destroy(){this.body&&(this.disable(),this.app.systems.rigidbody.destroyBody(this.body),this.body=null);}_getEntityTransform(e){let t=this.component;if(t){let e=t.getShapePosition(),i=t.getShapeRotation();a.setValue(e.x,e.y,e.z),n.setValue(i.x,i.y,i.z,i.w);}else {let e=this.entity.getPosition(),t=this.entity.getRotation();a.setValue(e.x,e.y,e.z),n.setValue(t.x,t.y,t.z,t.w);}e.setOrigin(a),e.setRotation(n);}updateTransform(){this._getEntityTransform(o);let e=this.body;e.setWorldTransform(o),e.activate();}enable(){let e=this.body;if(!e)return;let t=this.app.systems.rigidbody;0>t._triggers.indexOf(this)&&(t.addBody(e,16,65517),t._triggers.push(this)),e.forceActivationState(1),this.updateTransform();}disable(){let e=this.body;if(!e)return;let t=this.app.systems.rigidbody,i=t._triggers.indexOf(this);i>-1&&(t.removeBody(e),t._triggers.splice(i,1)),e.forceActivationState(5);}constructor(e,t,i){this.entity=t.entity,this.component=t,this.app=e,"u">typeof Ammo&&!a&&(a=new Ammo.btVector3,n=new Ammo.btQuaternion,o=new Ammo.btTransform),this.initialize(i);}}let mq=new ey,mj=new ed,mK=new ed,m$=new ex,mZ=new oJ,mQ=["enabled","type","halfExtents","linearOffset","angularOffset","radius","axis","height","convexHull","asset","renderAsset","shape","model","render","checkVertexDuplicates"];class mJ{beforeInitialize(e,t){t.shape=null,t.model=new hF,t.model.graph=new oJ;}afterInitialize(e,t){this.recreatePhysicalShapes(e),e.data.initialized=true;}reset(e,t){this.beforeInitialize(e,t),this.afterInitialize(e,t);}recreatePhysicalShapes(e){let t=e.entity,i=e.data;if("u">typeof Ammo){t.trigger&&(t.trigger.destroy(),delete t.trigger),i.shape&&(e._compoundParent&&(e!==e._compoundParent&&this.system._removeCompoundChild(e._compoundParent,i.shape),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate()),this.destroyShape(i)),i.shape=this.createPhysicalShape(e.entity,i);let s=!e._compoundParent;if("compound"!==i.type||e._compoundParent&&e!==e._compoundParent){if("compound"!==i.type&&!e.rigidbody){e._compoundParent=null;let i=t.parent;for(;i;){if(i.collision&&"compound"===i.collision.type){e._compoundParent=i.collision;break}i=i.parent;}}}else e._compoundParent=e,t.forEach(this._addEachDescendant,e);e._compoundParent&&e!==e._compoundParent&&(s&&0===e._compoundParent.shape.getNumChildShapes()?this.system.recreatePhysicalShapes(e._compoundParent):(this.system.updateCompoundChildTransform(t,true),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate())),t.rigidbody?(t.rigidbody.disableSimulation(),t.rigidbody.createBody(),t.enabled&&t.rigidbody.enabled&&t.rigidbody.enableSimulation()):e._compoundParent||(t.trigger?t.trigger.initialize(i):t.trigger=new mY(this.system.app,e,i));}}createPhysicalShape(e,t){}updateTransform(e,t,i,s){e.entity.trigger&&e.entity.trigger.updateTransform();}destroyShape(e){e.shape&&(Ammo.destroy(e.shape),e.shape=null);}beforeRemove(e,t){t.data.shape&&(t._compoundParent&&!t._compoundParent.entity._destroying&&(this.system._removeCompoundChild(t._compoundParent,t.data.shape),t._compoundParent.entity.rigidbody&&t._compoundParent.entity.rigidbody.activate()),t._compoundParent=null,this.destroyShape(t.data));}remove(e,t){e.rigidbody&&e.rigidbody.body&&e.rigidbody.disableSimulation(),e.trigger&&(e.trigger.destroy(),delete e.trigger);}clone(e,t){let i=this.system.store[e.getGuid()],s={enabled:i.data.enabled,type:i.data.type,halfExtents:[i.data.halfExtents.x,i.data.halfExtents.y,i.data.halfExtents.z],linearOffset:[i.data.linearOffset.x,i.data.linearOffset.y,i.data.linearOffset.z],angularOffset:[i.data.angularOffset.x,i.data.angularOffset.y,i.data.angularOffset.z,i.data.angularOffset.w],radius:i.data.radius,axis:i.data.axis,height:i.data.height,convexHull:i.data.convexHull,asset:i.data.asset,renderAsset:i.data.renderAsset,model:i.data.model,render:i.data.render,checkVertexDuplicates:i.data.checkVertexDuplicates};return this.system.addComponent(t,s)}constructor(e){this.system=e;}}class m0 extends mJ{createPhysicalShape(e,t){if("u">typeof Ammo){let e=t.halfExtents,i=new Ammo.btVector3(e?e.x:.5,e?e.y:.5,e?e.z:.5),s=new Ammo.btBoxShape(i);return Ammo.destroy(i),s}}}class m1 extends mJ{createPhysicalShape(e,t){if("u">typeof Ammo)return new Ammo.btSphereShape(t.radius)}}class m2 extends mJ{createPhysicalShape(e,t){let i=t.axis??1,s=t.radius??.5,r=Math.max((t.height??2)-2*s,0),a=null;if("u">typeof Ammo)switch(i){case 0:a=new Ammo.btCapsuleShapeX(s,r);break;case 1:a=new Ammo.btCapsuleShape(s,r);break;case 2:a=new Ammo.btCapsuleShapeZ(s,r);}return a}}class m3 extends mJ{createPhysicalShape(e,t){let i=t.axis??1,s=t.radius??.5,r=t.height??1,a=null,n=null;if("u">typeof Ammo)switch(i){case 0:a=new Ammo.btVector3(.5*r,s,s),n=new Ammo.btCylinderShapeX(a);break;case 1:a=new Ammo.btVector3(s,.5*r,s),n=new Ammo.btCylinderShape(a);break;case 2:a=new Ammo.btVector3(s,s,.5*r),n=new Ammo.btCylinderShapeZ(a);}return a&&Ammo.destroy(a),n}}class m4 extends mJ{createPhysicalShape(e,t){let i=t.axis??1,s=t.radius??.5,r=t.height??1,a=null;if("u">typeof Ammo)switch(i){case 0:a=new Ammo.btConeShapeX(s,r);break;case 1:a=new Ammo.btConeShape(s,r);break;case 2:a=new Ammo.btConeShapeZ(s,r);}return a}}class m5 extends mJ{beforeInitialize(e,t){}createAmmoHull(e,t,i,s){let r=new Ammo.btConvexHullShape,a=new Ammo.btVector3,n=[];e.getPositions(n);for(let e=0;e{let s,n=i[e*t]*g,o=i[e*t+1]*v,l=i[e*t+2]*S;if(r){let e=`${n}:${o}:${l}`;if(void 0!==(s=_.get(e)))return s;p.setValue(n,o,l),s=a.findOrAddVertex(p,false),_.set(e,s);}else p.setValue(n,o,l),s=a.findOrAddVertex(p,false);return s};for(let e=0;etypeof Ammo&&(t.model||t.render)){let i=new Ammo.btCompoundShape,s=e.getWorldTransform().getScale();if(t.render){let e=t.render.meshes;for(let r=0;r{s[i]===a&&(s[i]=t.resource,this.doRecreatePhysicalShape(e));},o=e=>{e.ready(e=>{if(e.data.containerAsset){let t=r.get(e.data.containerAsset);t.loaded?n(e):(t.ready(()=>{n(e);}),r.load(t));}else n(e);}),r.load(e);},l=r.get(t);l?o(l):r.once(`add:${t}`,o);}doRecreatePhysicalShape(e){let t=e.entity,i=e.data;i.model||i.render?(this.destroyShape(i),i.shape=this.createPhysicalShape(t,i),t.rigidbody?(t.rigidbody.disableSimulation(),t.rigidbody.createBody(),t.enabled&&t.rigidbody.enabled&&t.rigidbody.enableSimulation()):t.trigger?t.trigger.initialize(i):t.trigger=new mY(this.system.app,e,i)):(this.beforeRemove(t,e),this.remove(t,i));}updateTransform(e,t,i,s){if(e.shape){let t=e.entity.getWorldTransform().getScale(),i=e.shape.getLocalScaling();(t.x!==i.x()||t.y!==i.y()||t.z!==i.z())&&this.doRecreatePhysicalShape(e);}super.updateTransform(e,t,i,s);}destroyShape(e){if(!e.shape)return;let t=e.shape.getNumChildShapes();for(let i=0;itypeof Ammo)return new Ammo.btCompoundShape}_addEachDescendant(e){e.collision&&!e.rigidbody&&(e.collision._compoundParent=this,e!==this.entity&&e.collision.system.recreatePhysicalShapes(e.collision));}_updateEachDescendant(e){!e.collision||e.collision._compoundParent===this&&(e.collision._compoundParent=null,e===this.entity||e.rigidbody||e.collision.system.recreatePhysicalShapes(e.collision));}_updateEachDescendantTransform(e){e.collision&&e.collision._compoundParent===this.collision._compoundParent&&this.collision.system.updateCompoundChildTransform(e,false);}}class m8 extends pT{initializeComponentData(e,t,i){let s;i=["type","halfExtents","radius","axis","height","convexHull","shape","model","asset","render","renderAsset","enabled","linearOffset","angularOffset","checkVertexDuplicates"];let r={};for(let e=0,s=i.length;e=0&&this.model.meshInstances.splice(e,1);}this._entity.enabled&&this._element.enabled&&this._element.addModelToLayers(this.model),e||(this.unmaskMeshInstance?.destroy(),this.unmaskMeshInstance=null);}}setMaterial(e){this.meshInstance&&(this.meshInstance.material=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.material=e));}setParameter(e,t){this.meshInstance&&(this.meshInstance.setParameter(e,t),this.unmaskMeshInstance&&this.unmaskMeshInstance.setParameter(e,t));}deleteParameter(e){this.meshInstance&&(this.meshInstance.deleteParameter(e),this.unmaskMeshInstance&&this.unmaskMeshInstance.deleteParameter(e));}setUnmaskDrawOrder(){if(!this.meshInstance)return;let e=function(t){let i,s=t.children,r=s.length;if(r){for(let e=0;enew iB(r,[{semantic:e8,components:3,type:6},{semantic:e9,components:3,type:6},{semantic:tr,components:2,type:6}])),o=new iR(r,n,4,{data:a.buffer}),l=new on(r);return l.vertexBuffer=o,l.primitive[0].type=5,l.primitive[0].base=0,l.primitive[0].count=4,l.primitive[0].indexed=false,l.aabb.setMinMax(ed.ZERO,new ed(t,i,0)),this._updateMesh(l),l}_updateMesh(e){let t=this._element,i=t.calculatedWidth,s=t.calculatedHeight;if(t.fitMode!==mw&&this._targetAspectRatio>0){let e=t.calculatedWidth/t.calculatedHeight;t.fitMode===mb&&e>this._targetAspectRatio||t.fitMode===mC&&e0&&(this._targetAspectRatio=i.rect.z/i.rect.w);}this.mesh=e?t:this._defaultMesh,this.refreshMesh();}refreshMesh(){this.mesh&&(this._element._beingInitialized?this._meshDirty=true:this._updateMesh(this.mesh));}_updateAabb(e){return e.center.set(0,0,0),e.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001),e.setFromTransformedAabb(e,this._renderable.node.getWorldTransform()),e}_toggleMask(){this._element._dirtifyMask();let e=this._element._isScreenSpace();this._updateMaterial(e),this._renderable.setMask(!!this._mask);}_onMaterialLoad(e){this.material=e.resource;}_onMaterialAdded(e){this._system.app.assets.off(`add:${e.id}`,this._onMaterialAdded,this),this._materialAsset===e.id&&this._bindMaterialAsset(e);}_bindMaterialAsset(e){this._entity.enabled&&(e.on("load",this._onMaterialLoad,this),e.on("change",this._onMaterialChange,this),e.on("remove",this._onMaterialRemove,this),e.resource?this._onMaterialLoad(e):this._system.app.assets.load(e));}_unbindMaterialAsset(e){e.off("load",this._onMaterialLoad,this),e.off("change",this._onMaterialChange,this),e.off("remove",this._onMaterialRemove,this);}_onMaterialChange(){}_onMaterialRemove(){}_onTextureAdded(e){this._system.app.assets.off(`add:${e.id}`,this._onTextureAdded,this),this._textureAsset===e.id&&this._bindTextureAsset(e);}_bindTextureAsset(e){this._entity.enabled&&(e.on("load",this._onTextureLoad,this),e.on("change",this._onTextureChange,this),e.on("remove",this._onTextureRemove,this),e.resource?this._onTextureLoad(e):this._system.app.assets.load(e));}_unbindTextureAsset(e){e.off("load",this._onTextureLoad,this),e.off("change",this._onTextureChange,this),e.off("remove",this._onTextureRemove,this);}_onTextureLoad(e){this.texture=e.resource;}_onTextureChange(e){}_onTextureRemove(e){}_onSpriteAssetAdded(e){this._system.app.assets.off(`add:${e.id}`,this._onSpriteAssetAdded,this),this._spriteAsset===e.id&&this._bindSpriteAsset(e);}_bindSpriteAsset(e){this._entity.enabled&&(e.on("load",this._onSpriteAssetLoad,this),e.on("change",this._onSpriteAssetChange,this),e.on("remove",this._onSpriteAssetRemove,this),e.resource?this._onSpriteAssetLoad(e):this._system.app.assets.load(e));}_unbindSpriteAsset(e){e.off("load",this._onSpriteAssetLoad,this),e.off("change",this._onSpriteAssetChange,this),e.off("remove",this._onSpriteAssetRemove,this),e.data.textureAtlasAsset&&this._system.app.assets.off(`load:${e.data.textureAtlasAsset}`,this._onTextureAtlasLoad,this);}_onSpriteAssetLoad(e){if(e&&e.resource)if(e.resource.atlas)this.sprite=e.resource;else {let t=e.data.textureAtlasAsset;if(t){let e=this._system.app.assets;e.off(`load:${t}`,this._onTextureAtlasLoad,this),e.once(`load:${t}`,this._onTextureAtlasLoad,this);}}else this.sprite=null;}_onSpriteAssetChange(e){this._onSpriteAssetLoad(e);}_onSpriteAssetRemove(e){}_bindSprite(e){this._evtSetMeshes=e.on("set:meshes",this._onSpriteMeshesChange,this),e.on("set:pixelsPerUnit",this._onSpritePpuChange,this),e.on("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.on("set:texture",this._onAtlasTextureChange,this);}_unbindSprite(e){this._evtSetMeshes?.off(),this._evtSetMeshes=null,e.off("set:pixelsPerUnit",this._onSpritePpuChange,this),e.off("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.off("set:texture",this._onAtlasTextureChange,this);}_onSpriteMeshesChange(){this._sprite&&(this._spriteFrame=ei.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite();}_onSpritePpuChange(){0!==this.sprite.renderMode&&null===this._pixelsPerUnit&&this._updateSprite();}_onAtlasTextureChange(){this.sprite&&this.sprite.atlas&&this.sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"));}_onTextureAtlasLoad(e){let t=this._spriteAsset;t instanceof fX?this._onSpriteAssetLoad(t):this._onSpriteAssetLoad(this._system.app.assets.get(t));}onEnable(){if(this._materialAsset){let e=this._system.app.assets.get(this._materialAsset);e&&e.resource!==this._material&&this._bindMaterialAsset(e);}if(this._textureAsset){let e=this._system.app.assets.get(this._textureAsset);e&&e.resource!==this._texture&&this._bindTextureAsset(e);}if(this._spriteAsset){let e=this._system.app.assets.get(this._spriteAsset);e&&e.resource!==this._sprite&&this._bindSpriteAsset(e);}this._element.addModelToLayers(this._renderable.model);}onDisable(){this._element.removeModelFromLayers(this._renderable.model);}_setStencil(e){this._renderable.meshInstance.stencilFront=e,this._renderable.meshInstance.stencilBack=e;let t=0;if(this._element.maskedBy&&(t=this._element.maskedBy.element._image._maskRef),this._renderable.unmaskMeshInstance){let e=new iU({ref:t+1,func:2,zpass:5});this._renderable.unmaskMeshInstance.stencilFront=e,this._renderable.unmaskMeshInstance.stencilBack=e;}}_updateRenderableEmissive(){m9.linear(this._color),this._colorUniform[0]=m9.r,this._colorUniform[1]=m9.g,this._colorUniform[2]=m9.b,this._renderable.setParameter("material_emissive",this._colorUniform);}set color(e){let{r:t,g:i,b:s}=e;(this._color.r!==t||this._color.g!==i||this._color.b!==s)&&(this._color.r=t,this._color.g=i,this._color.b=s,this._updateRenderableEmissive()),this._element&&this._element.fire("set:color",this._color);}get color(){return this._color}set opacity(e){e!==this._color.a&&(this._color.a=e,this._renderable.setParameter("material_opacity",e)),this._element&&this._element.fire("set:opacity",e);}get opacity(){return this._color.a}set rect(e){let t,i,s,r;e instanceof ep?(t=e.x,i=e.y,s=e.z,r=e.w):(t=e[0],i=e[1],s=e[2],r=e[3]),(t!==this._rect.x||i!==this._rect.y||s!==this._rect.z||r!==this._rect.w)&&(this._rect.set(t,i,s,r),this._renderable.mesh&&(this._element._beingInitialized?this._meshDirty=true:this._updateMesh(this._renderable.mesh)));}get rect(){return this._rect}_removeMaterialAssetEvents(){if(this._materialAsset){let e=this._system.app.assets;e.off(`add:${this._materialAsset}`,this._onMaterialAdded,this);let t=e.get(this._materialAsset);t&&(t.off("load",this._onMaterialLoad,this),t.off("change",this._onMaterialChange,this),t.off("remove",this._onMaterialRemove,this));}}set material(e){if(this._material!==e){if(!e){let t=this._element._isScreenSpace();e=this.mask?t?this._system.defaultScreenSpaceImageMaskMaterial:this._system.defaultImageMaskMaterial:t?this._system.defaultScreenSpaceImageMaterial:this._system.defaultImageMaterial;}if(this._material=e,this._materialAsset){let t=this._system.app.assets.get(this._materialAsset);t&&t.resource===e||(this._removeMaterialAssetEvents(),this._materialAsset=null);}e&&(this._renderable.setMaterial(e),this._hasUserMaterial()?(this._renderable.deleteParameter("material_opacity"),this._renderable.deleteParameter("material_emissive")):(this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",this._color.a)));}}get material(){return this._material}set materialAsset(e){let t=this._system.app.assets,i=e;if(e instanceof fX&&(i=e.id),this._materialAsset!==i)if(this._removeMaterialAssetEvents(),this._materialAsset=i,this._materialAsset){let e=t.get(this._materialAsset);e?this._bindMaterialAsset(e):(this._materialAsset=null,this.material=null,this._materialAsset=i,t.on(`add:${this._materialAsset}`,this._onMaterialAdded,this));}else this._materialAsset=null,this.material=null,this._materialAsset=i;}get materialAsset(){return this._materialAsset}set texture(e){if(this._texture!==e){if(this._textureAsset){let t=this._system.app.assets.get(this._textureAsset);t&&t.resource!==e&&(this.textureAsset=null);}if(this._texture=e,e){this._spriteAsset&&(this.spriteAsset=null),this._renderable.setParameter("texture_emissiveMap",this._texture),this._renderable.setParameter("texture_opacityMap",this._texture),this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",this._color.a);let e=this._texture.width/this._texture.height;e!==this._targetAspectRatio&&(this._targetAspectRatio=e,this._element.fitMode!==mw&&this.refreshMesh());}else this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"),this._targetAspectRatio=-1,this._element.fitMode!==mw&&this.refreshMesh();}}get texture(){return this._texture}set textureAsset(e){let t=this._system.app.assets,i=e;if(e instanceof fX&&(i=e.id),this._textureAsset!==i){if(this._textureAsset){t.off(`add:${this._textureAsset}`,this._onTextureAdded,this);let e=t.get(this._textureAsset);e&&(e.off("load",this._onTextureLoad,this),e.off("change",this._onTextureChange,this),e.off("remove",this._onTextureRemove,this));}if(this._textureAsset=i,this._textureAsset){let e=t.get(this._textureAsset);e?this._bindTextureAsset(e):(this.texture=null,t.on(`add:${this._textureAsset}`,this._onTextureAdded,this));}else this.texture=null;}}get textureAsset(){return this._textureAsset}set spriteAsset(e){let t=this._system.app.assets,i=e;if(e instanceof fX&&(i=e.id),this._spriteAsset!==i){if(this._spriteAsset){t.off(`add:${this._spriteAsset}`,this._onSpriteAssetAdded,this);let e=t.get(this._spriteAsset);e&&this._unbindSpriteAsset(e);}if(this._spriteAsset=i,this._spriteAsset){let e=t.get(this._spriteAsset);e?this._bindSpriteAsset(e):(this.sprite=null,t.on(`add:${this._spriteAsset}`,this._onSpriteAssetAdded,this));}else this.sprite=null;}this._element&&this._element.fire("set:spriteAsset",i);}get spriteAsset(){return this._spriteAsset}set sprite(e){if(this._sprite!==e){if(this._sprite&&this._unbindSprite(this._sprite),this._spriteAsset){let t=this._system.app.assets.get(this._spriteAsset);t&&t.resource!==e&&(this.spriteAsset=null);}this._sprite=e,this._sprite&&(this._bindSprite(this._sprite),this._textureAsset&&(this.textureAsset=null)),this._sprite&&this._sprite.atlas&&this._sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap")),this._sprite&&(this._spriteFrame=ei.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite();}}get sprite(){return this._sprite}set spriteFrame(e){let t=this._spriteFrame;this._sprite?this._spriteFrame=ei.clamp(e,0,this._sprite.frameKeys.length-1):this._spriteFrame=e,this._spriteFrame!==t&&this._updateSprite(),this._element&&this._element.fire("set:spriteFrame",e);}get spriteFrame(){return this._spriteFrame}set mesh(e){this._renderable.setMesh(e),this._defaultMesh===e?this._renderable.setAabbFunc(null):this._renderable.setAabbFunc(this._updateAabbFunc);}get mesh(){return this._renderable.mesh}set mask(e){this._mask!==e&&(this._mask=e,this._toggleMask());}get mask(){return this._mask}set pixelsPerUnit(e){this._pixelsPerUnit!==e&&(this._pixelsPerUnit=e,this._sprite&&(1===this._sprite.renderMode||2===this._sprite.renderMode)&&this._updateSprite());}get pixelsPerUnit(){return this._pixelsPerUnit}get aabb(){return this._renderable.meshInstance?this._renderable.meshInstance.aabb:null}constructor(e){this._evtSetMeshes=null,this._element=e,this._entity=e.entity,this._system=e.system,this._textureAsset=null,this._texture=null,this._materialAsset=null,this._material=null,this._spriteAsset=null,this._sprite=null,this._spriteFrame=0,this._pixelsPerUnit=null,this._targetAspectRatio=-1,this._rect=new ep(0,0,1,1),this._mask=false,this._maskRef=0,this._outerScale=new ef,this._outerScaleUniform=new Float32Array(2),this._innerOffset=new ep,this._innerOffsetUniform=new Float32Array(4),this._atlasRect=new ep,this._atlasRectUniform=new Float32Array(4),this._defaultMesh=this._createMesh(),this._renderable=new _e(this._entity,this._defaultMesh,this._material),this._color=new es(1,1,1,1),this._colorUniform=new Float32Array([1,1,1]),this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",1),this._updateAabbFunc=this._updateAabb.bind(this),this._onScreenChange(this._element.screen),this._element.on("resize",this._onParentResizeOrPivotChange,this),this._element.on("set:pivot",this._onParentResizeOrPivotChange,this),this._element.on("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.on("set:screen",this._onScreenChange,this),this._element.on("set:draworder",this._onDrawOrderChange,this),this._element.on("screen:set:resolution",this._onResolutionChange,this),!e._beingInitialized&&e.enabled&&e.entity.enabled&&this.onEnable();}}class _i extends X{set defaultAsset(e){let t=e instanceof fX?e.id:e;this._defaultAsset!==t&&(this._defaultAsset&&this._unbindDefaultAsset(),this._defaultAsset=t,this._defaultAsset&&this._bindDefaultAsset(),this._onSetLocale(this._app.i18n.locale));}get defaultAsset(){return this._defaultAsset}set localizedAsset(e){let t=e instanceof fX?e.id:e;this._localizedAsset!==t&&(this._localizedAsset&&(this._app.assets.off(`add:${this._localizedAsset}`,this._onLocalizedAssetAdd,this),this._unbindLocalizedAsset()),this._localizedAsset=t,this._localizedAsset&&(this._app.assets.get(this._localizedAsset)?this._bindLocalizedAsset():this._app.assets.once(`add:${this._localizedAsset}`,this._onLocalizedAssetAdd,this)));}get localizedAsset(){return this._localizedAsset}set autoLoad(e){this._autoLoad!==e&&(this._autoLoad=e,this._autoLoad&&this._localizedAsset&&(this._unbindLocalizedAsset(),this._bindLocalizedAsset()));}get autoLoad(){return this._autoLoad}set disableLocalization(e){this._disableLocalization!==e&&(this._disableLocalization=e,this._onSetLocale(this._app.i18n.locale));}get disableLocalization(){return this._disableLocalization}_bindDefaultAsset(){let e=this._app.assets.get(this._defaultAsset);e?this._onDefaultAssetAdd(e):this._app.assets.once(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this);}_unbindDefaultAsset(){if(!this._defaultAsset)return;this._app.assets.off(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this);let e=this._app.assets.get(this._defaultAsset);e&&(e.off("add:localized",this._onLocaleAdd,this),e.off("remove:localized",this._onLocaleRemove,this),e.off("remove",this._onDefaultAssetRemove,this));}_onDefaultAssetAdd(e){this._defaultAsset===e.id&&(e.on("add:localized",this._onLocaleAdd,this),e.on("remove:localized",this._onLocaleRemove,this),e.once("remove",this._onDefaultAssetRemove,this));}_onDefaultAssetRemove(e){this._defaultAsset===e.id&&(e.off("add:localized",this._onLocaleAdd,this),e.off("remove:localized",this._onLocaleAdd,this),this._app.assets.once(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this));}_bindLocalizedAsset(){if(!this._autoLoad)return;let e=this._app.assets.get(this._localizedAsset);e&&(e.on("load",this._onLocalizedAssetLoad,this),e.on("change",this._onLocalizedAssetChange,this),e.on("remove",this._onLocalizedAssetRemove,this),e.resource?this._onLocalizedAssetLoad(e):this._app.assets.load(e));}_unbindLocalizedAsset(){let e=this._app.assets.get(this._localizedAsset);e&&(e.off("load",this._onLocalizedAssetLoad,this),e.off("change",this._onLocalizedAssetChange,this),e.off("remove",this._onLocalizedAssetRemove,this));}_onLocalizedAssetAdd(e){this._localizedAsset===e.id&&this._bindLocalizedAsset();}_onLocalizedAssetLoad(e){this.fire("load",e);}_onLocalizedAssetChange(e,t,i,s){this.fire("change",e,t,i,s);}_onLocalizedAssetRemove(e){this._localizedAsset===e.id&&(this.localizedAsset=this._defaultAsset),this.fire("remove",e);}_onLocaleAdd(e,t){this._app.i18n.locale===e&&this._onSetLocale(e);}_onLocaleRemove(e,t){this._app.i18n.locale===e&&this._onSetLocale(e);}_onSetLocale(e){if(!this._defaultAsset){this.localizedAsset=null;return}let t=this._app.assets.get(this._defaultAsset);if(!t||this._disableLocalization){this.localizedAsset=this._defaultAsset;return}let i=t.getLocalizedAssetId(e);if(!i){this.localizedAsset=this._defaultAsset;return}this.localizedAsset=i;}destroy(){this.defaultAsset=null,this._app.i18n.off(f2.EVENT_CHANGE,this._onSetLocale,this),this.off();}constructor(e){super(),this._app=e,e.i18n.on(f2.EVENT_CHANGE,this._onSetLocale,this),this._autoLoad=false,this._disableLocalization=false,this._defaultAsset=null,this._localizedAsset=null;}}let _s="msdf",_r="bitmap",_a=/[\w|/]/;class _n{read(){let e=this._read();for(;8===e;)e=this._read();return 0!==e&&1!==e&&(this._last=this._index),e}buf(){return this._buf}last(){return this._last}error(){return this._error}debugPrint(){let e=["EOF","ERROR","TEXT","OPEN_BRACKET","CLOSE_BRACKET","EQUALS","STRING","IDENTIFIER","WHITESPACE"],t=this.read(),i="";for(;i+=`${(i.length>0?"\n":"")+e[t]} '${this.buf().join("")}'`,0!==t&&1!==t;)t=this.read();return i}_read(){return (this._buf=[],this._eof())?0:"text"===this._mode?this._text():this._tag()}_text(){for(;;)switch(this._cur){case null:return 2*(this._buf.length>0);case "[":return this._mode="tag",this._buf.length>0?2:this._tag();case "\\":this._next(),"["===this._cur?this._store():this._output("\\");break;default:this._store();}}_tag(){switch(this._cur){case null:return this._error="unexpected end of input reading tag",1;case "[":return this._store(),3;case "]":return this._store(),this._mode="text",4;case "=":return this._store(),5;case " ":case " ":case "\n":case "\r":case "\v":case "\f":return this._whitespace();case '"':return this._string();default:if(!this._isIdentifierSymbol(this._cur))return this._error="unrecognized character",1;return this._identifier()}}_whitespace(){for(this._store();-1!==" \n\r\v\f".indexOf(this._cur);)this._store();return 8}_string(){for(this._next();;)switch(this._cur){case null:return this._error="unexpected end of input reading string",1;case '"':return this._next(),6;default:this._store();}}_identifier(){for(this._store();null!==this._cur&&this._isIdentifierSymbol(this._cur);)this._store();return 7}_isIdentifierSymbol(e){return 1===e.length&&null!==e.match(_a)}_eof(){return null===this._cur}_next(){return this._eof()||(this._index++,this._cur=this._index0?this._symbols[0]:null,this._buf=[],this._mode="text",this._error=null;}}class _o{parse(e,t){for(;;)switch(this._scanner.read()){case 0:return true;case 1:default:return false;case 2:Array.prototype.push.apply(e,this._scanner.buf());break;case 3:if(!this._parseTag(e,t))return false}}error(){return `Error evaluating markup at #${this._scanner.last().toString()} (${this._scanner.error()||this._error})`}_parseTag(e,t){let i=this._scanner.read();if(7!==i)return this._error="expected identifier",false;let s=this._scanner.buf().join("");if("/"===s[0]){for(let r=t.length-1;r>=0;--r)if(s===`/${t[r].name}`&&null===t[r].end){if(t[r].end=e.length,4!==(i=this._scanner.read()))return this._error="expected close bracket",false;return true}return this._error="failed to find matching tag",false}let r={name:s,value:null,attributes:{},start:e.length,end:null};if(5===(i=this._scanner.read())){if(6!==(i=this._scanner.read()))return this._error="expected string",false;r.value=this._scanner.buf().join(""),i=this._scanner.read();}for(;;){switch(i){case 4:return t.push(r),true;case 7:{let e=this._scanner.buf().join("");if(5!==(i=this._scanner.read()))return this._error="expected equals",false;if(6!==(i=this._scanner.read()))return this._error="expected string",false;let t=this._scanner.buf().join("");r.attributes[e]=t;break}default:return this._error="expected close bracket or identifier",false}i=this._scanner.read();}}constructor(e){this._scanner=new _n(e),this._error=null;}}class _l{static evaluate(e){var t=e;let i=new _o(t),s=[],r=[];if(!i.parse(s,r)||r.find(e=>null===e.end))return {symbols:t,tags:null};let a=function(e,t){if(0===e.length)return null;let i={};for(let t=0;te-t),a=[];for(let e=0;evoid 0===e.find(e=>e===t));}(t.close),null!==t.open&&function(e){for(let t=0;tt[e]));}}else this._rtl=false;let i=(e,t)=>`${e.toString(true).toLowerCase()}:${t.toFixed(2)}`,s=(e,t)=>`${e.toString(true).toLowerCase()}:${t.x.toFixed(2)}:${t.y.toFixed(2)}`;if(t){let e={},r={},a={};this._colorPalette=[Math.round(255*this._color.r),Math.round(255*this._color.g),Math.round(255*this._color.b)],this._outlinePalette=[Math.round(255*this._outlineColor.r),Math.round(255*this._outlineColor.g),Math.round(255*this._outlineColor.b),Math.round(255*this._outlineColor.a),Math.round(255*this._outlineThickness)],this._shadowPalette=[Math.round(255*this._shadowColor.r),Math.round(255*this._shadowColor.g),Math.round(255*this._shadowColor.b),Math.round(255*this._shadowColor.a),Math.round(127*this._shadowOffset.x),Math.round(127*this._shadowOffset.y)],this._symbolColors=[],this._symbolOutlineParams=[],this._symbolShadowParams=[],e[this._color.toString(false).toLowerCase()]=0,r[i(this._outlineColor,this._outlineThickness)]=0,a[s(this._shadowColor,this._shadowOffset)]=0;for(let n=0,o=this._symbols.length;n=1e-4,T=this._element.calculatedWidth;(!this.autoWidth||x)&&this._wrapLines||(T=1/0);let E=0,w=0;function b(e,t,i){a._lineWidths.push(Math.abs(i));let s=g>t?t+1:g,r=g>t?g+1:t,n=e.slice(s,r);if(y){let e=n.length;for(;e--&&y>0;)_c.test(n[e])&&(n.splice(e,1),y--);}a._lineContents.push(n.join("")),c=0,d-=a._scaledLineHeight,p++,v=0,S=0,y=0,m=0,g=t;}let C=true;for(;C;){C=false,l?this._scaledLineHeight=this._lineHeight*this._fontSize/(this._maxFontSize||1e-4):this._scaledLineHeight=this._lineHeight,this.width=0,this.height=0,this._lineWidths=[],this._lineContents=[],c=0,d=0,u=0,f=0,p=1,m=0,_=0,g=0,v=0,S=0,y=0;let a=this._fontSize/32;E=this._fontMinY*a,w=this._fontMaxY*a;for(let e=0;e=h?null:this._symbols[l+1],_c.test(e)){y++,(!this._wrapLines||this._maxLines<0||p0){let t=this._font.data.kerning;if(t){let i=t[H.getCodePoint(this._symbols[l-1])||0];i&&(e=i[H.getCodePoint(this._symbols[l])||0]||0);}}F=t.scale||1,z=a*((t.width+t.height)/2)/F,U=(t.xadvance+e)*a,B=(t.xoffset-e)*a,k=t.yoffset*a;}let V=_d.test(e),G=t&&t.map||0,W=-this._font.data.info.maps[G].width/this._font.data.info.maps[G].height,X=this._meshInfo[G],Y=c+this._spacing*U;if(Y>T&&S>0&&!V&&(this._maxLines<0||pthis._element.calculatedWidth&&(N=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1e-4)),(N=ei.clamp(N,n,o))!==this._element.fontSize)||(this.height=Math.max(this.height,w-(d+E)),this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&(N=ei.clamp(this._fontSize-1,n,o))!==this._element.fontSize)){this._fontSize=N,C=true;break}c+=this._spacing*U,V||(f=c),(this._isWordBoundary(e)||this._isValidNextChar(s)&&(this._isNextCJKBoundary(e,s)||this._isNextCJKWholeWord(s)))&&(v++,m=f,_=l+1),S++;let Z=this._getUv(e);if(X.uvs[4*i*2+0]=Z[0],X.uvs[4*i*2+1]=1-Z[1],X.uvs[4*i*2+2]=Z[2],X.uvs[4*i*2+3]=1-Z[1],X.uvs[4*i*2+4]=Z[2],X.uvs[4*i*2+5]=1-Z[3],X.uvs[4*i*2+6]=Z[0],X.uvs[4*i*2+7]=1-Z[3],this._symbolColors){let e=3*this._symbolColors[l];x=this._colorPalette[e],A=this._colorPalette[e+1],P=this._colorPalette[e+2];}if(X.colors[4*i*4+0]=x,X.colors[4*i*4+1]=A,X.colors[4*i*4+2]=P,X.colors[4*i*4+3]=255,X.colors[4*i*4+4]=x,X.colors[4*i*4+5]=A,X.colors[4*i*4+6]=P,X.colors[4*i*4+7]=255,X.colors[4*i*4+8]=x,X.colors[4*i*4+9]=A,X.colors[4*i*4+10]=P,X.colors[4*i*4+11]=255,X.colors[4*i*4+12]=x,X.colors[4*i*4+13]=A,X.colors[4*i*4+14]=P,X.colors[4*i*4+15]=255,this._symbolOutlineParams){let e=5*this._symbolOutlineParams[l];I=this._outlinePalette[e]+256*this._outlinePalette[e+1],D=this._outlinePalette[e+2]+256*this._outlinePalette[e+3],R=this._outlinePalette[e+4];}if(X.outlines[4*i*3+0]=I,X.outlines[4*i*3+1]=D,X.outlines[4*i*3+2]=R,X.outlines[4*i*3+3]=I,X.outlines[4*i*3+4]=D,X.outlines[4*i*3+5]=R,X.outlines[4*i*3+6]=I,X.outlines[4*i*3+7]=D,X.outlines[4*i*3+8]=R,X.outlines[4*i*3+9]=I,X.outlines[4*i*3+10]=D,X.outlines[4*i*3+11]=R,this._symbolShadowParams){let e=6*this._symbolShadowParams[l];L=this._shadowPalette[e]+256*this._shadowPalette[e+1],M=this._shadowPalette[e+2]+256*this._shadowPalette[e+3],O=this._shadowPalette[e+4]+127+256*Math.round(W*this._shadowPalette[e+5]+127);}X.shadows[4*i*3+0]=L,X.shadows[4*i*3+1]=M,X.shadows[4*i*3+2]=O,X.shadows[4*i*3+3]=L,X.shadows[4*i*3+4]=M,X.shadows[4*i*3+5]=O,X.shadows[4*i*3+6]=L,X.shadows[4*i*3+7]=M,X.shadows[4*i*3+8]=O,X.shadows[4*i*3+9]=L,X.shadows[4*i*3+10]=M,X.shadows[4*i*3+11]=O,X.quad++;}!C&&g=s?(r.element[e8].set(0,0,0),r.element[tr].set(0,0),r.element[ti].set(0,0,0,0),r.element[ty].set(0,0,0,0),r.element[tx].set(0,0,0,0)):(r.element[e8].set(this._meshInfo[e].positions[3*t+0],this._meshInfo[e].positions[3*t+1],this._meshInfo[e].positions[3*t+2]),r.element[tr].set(this._meshInfo[e].uvs[2*t+0],this._meshInfo[e].uvs[2*t+1]),r.element[ti].set(this._meshInfo[e].colors[4*t+0],this._meshInfo[e].colors[4*t+1],this._meshInfo[e].colors[4*t+2],this._meshInfo[e].colors[4*t+3]),r.element[ty].set(this._meshInfo[e].outlines[3*t+0],this._meshInfo[e].outlines[3*t+1],this._meshInfo[e].outlines[3*t+2]),r.element[tx].set(this._meshInfo[e].shadows[3*t+0],this._meshInfo[e].shadows[3*t+1],this._meshInfo[e].shadows[3*t+2])),r.next();r.end(),this._meshInfo[e].meshInstance.mesh.aabb.compute(this._meshInfo[e].positions),this._meshInfo[e].meshInstance._aabbVer=-1;}this._aabbDirty=true;}_onFontRender(){this.font=this._font;}_onFontLoad(e){this.font!==e.resource&&(this.font=e.resource);}_onFontChange(e,t,i,s){if("data"===t){this._font.data=i;let e=this._font.data.info.maps.length;for(let t=0;tthis._font.textures.length&&(this._meshInfo.length=this._font.textures.length),this._updateText();}get font(){return this._font}set alignment(e){e instanceof ef?this._alignment.set(e.x,e.y):this._alignment.set(e[0],e[1]),this._font&&this._updateText();}get alignment(){return this._alignment}set autoWidth(e){let t=this._autoWidth;if(this._autoWidth=e,e&&1e-4>Math.abs(this._element.anchor.x-this._element.anchor.z)&&(this._element.width=this.width),t!==e){let e=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;e!==this._fontSize&&(this._fontSize=e,this._font&&this._updateText());}}get autoWidth(){return this._autoWidth}set autoHeight(e){let t=this._autoHeight;if(this._autoHeight=e,e&&1e-4>Math.abs(this._element.anchor.y-this._element.anchor.w)&&(this._element.height=this.height),t!==e){let e=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;e!==this._fontSize&&(this._fontSize=e,this._font&&this._updateText());}}get autoHeight(){return this._autoHeight}set rtlReorder(e){this._rtlReorder!==e&&(this._rtlReorder=e,this._font&&this._updateText());}get rtlReorder(){return this._rtlReorder}set unicodeConverter(e){this._unicodeConverter!==e&&(this._unicodeConverter=e,this._setText(this._text));}get unicodeConverter(){return this._unicodeConverter}get aabb(){if(this._aabbDirty){let e=false;for(let t=0;t.001}get _hasSplitAnchorsY(){return Math.abs(this._anchor.y-this._anchor.w)>.001}get aabb(){return this._image?this._image.aabb:this._text?this._text.aabb:null}set anchor(e){e instanceof ep?this._anchor.copy(e):this._anchor.set(...e),this.entity._parent||this.screen?this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY):this._calculateLocalAnchors(),this._anchorDirty=true,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:anchor",this._anchor);}get anchor(){return this._anchor}set batchGroupId(e){this._batchGroupId!==e&&(this.entity.enabled&&this._batchGroupId>=0&&this.system.app.batcher?.remove(n7.ELEMENT,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(n7.ELEMENT,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&(this._image&&this._image._renderable.model?this.addModelToLayers(this._image._renderable.model):this._text&&this._text._model&&this.addModelToLayers(this._text._model)),this._batchGroupId=e);}get batchGroupId(){return this._batchGroupId}set bottom(e){this._margin.y=e;let t=this.entity.getLocalPosition(),i=this._absTop,s=this._localAnchor.y+e;this._setHeight(i-s),t.y=e+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(t);}get bottom(){return this._margin.y}set calculatedWidth(e){this._setCalculatedWidth(e,true);}get calculatedWidth(){return this._calculatedWidth}set calculatedHeight(e){this._setCalculatedHeight(e,true);}get calculatedHeight(){return this._calculatedHeight}get canvasCorners(){if(!this._canvasCornersDirty||!this.screen||!this.screen.screen.screenSpace)return this._canvasCorners;let e=this.system.app.graphicsDevice,t=this.screenCorners,i=e.canvas.clientWidth/e.width,s=e.canvas.clientHeight/e.height;for(let r=0;r<4;r++)this._canvasCorners[r].set(t[r].x*i,(e.height-t[r].y)*s);return this._canvasCornersDirty=false,this._canvasCorners}set drawOrder(e){let t=0;this.screen&&(t=this.screen.screen.priority),e>0xffffff&&(e=0xffffff),this._drawOrder=(t<<24)+e,this.fire("set:draworder",this._drawOrder);}get drawOrder(){return this._drawOrder}set height(e){this._height=e,this._hasSplitAnchorsY||this._setCalculatedHeight(e,true),this.fire("set:height",this._height);}get height(){return this._height}set layers(e){if(this._addedModels.length)for(let e=0;e=0&&this.system._prerender.splice(t,1),0>this.system._prerender.indexOf(e)&&this.system._prerender.push(e);}e=t;}}_onPrerender(){for(let e=0;ethis.layers.indexOf(e.id))&&(this._image?e.addMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.addMeshInstances(this._text._model.meshInstances));}onLayerRemoved(e){!(0>this.layers.indexOf(e.id))&&(this._image?e.removeMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.removeMeshInstances(this._text._model.meshInstances));}onEnable(){let e=this.system.app.scene,t=e.layers;this._image&&this._image.onEnable(),this._text&&this._text.onEnable(),this._group&&this._group.onEnable(),this.useInput&&this.system.app.elementInput&&this.system.app.elementInput.addElement(this),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this._batchGroupId>=0&&this.system.app.batcher?.insert(n7.ELEMENT,this.batchGroupId,this.entity),this.fire("enableelement");}onDisable(){let e=this.system.app.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,e&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._image&&this._image.onDisable(),this._text&&this._text.onDisable(),this._group&&this._group.onDisable(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this._batchGroupId>=0&&this.system.app.batcher?.remove(n7.ELEMENT,this.batchGroupId,this.entity),this.fire("disableelement");}onRemove(){this.entity.off("insert",this._onInsert,this),this._unpatch(),this._image&&this._image.destroy(),this._text&&this._text.destroy(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this.screen&&this.screen.screen&&(this._unbindScreen(this.screen.screen),this.screen.screen.syncDrawOrder()),this.off();}_calculateSize(e,t){if(!this.entity._parent&&!this.screen)return;this._calculateLocalAnchors();let i=this._absRight-this._absLeft,s=this._absTop-this._absBottom;e?this._setWidth(i):this._setCalculatedWidth(i,false),t?this._setHeight(s):this._setCalculatedHeight(s,false);let r=this.entity.getLocalPosition();r.x=this._margin.x+this._calculatedWidth*this._pivot.x,r.y=this._margin.y+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(r),this._sizeDirty=false;}_setWidth(e){this._width=e,this._setCalculatedWidth(e,false),this.fire("set:width",this._width);}_setHeight(e){this._height=e,this._setCalculatedHeight(e,false),this.fire("set:height",this._height);}_setCalculatedWidth(e,t){if(!(1e-4>=Math.abs(e-this._calculatedWidth))){if(this._calculatedWidth=e,this.entity._dirtifyLocal(),t){let e=this.entity.getLocalPosition(),t=this._pivot;this._margin.x=e.x-this._calculatedWidth*t.x,this._margin.z=this._localAnchor.z-this._localAnchor.x-this._calculatedWidth-this._margin.x;}this._flagChildrenAsDirty(),this.fire("set:calculatedWidth",this._calculatedWidth),this.fire("resize",this._calculatedWidth,this._calculatedHeight);}}_setCalculatedHeight(e,t){if(!(1e-4>=Math.abs(e-this._calculatedHeight))){if(this._calculatedHeight=e,this.entity._dirtifyLocal(),t){let e=this.entity.getLocalPosition(),t=this._pivot;this._margin.y=e.y-this._calculatedHeight*t.y,this._margin.w=this._localAnchor.w-this._localAnchor.y-this._calculatedHeight-this._margin.y;}this._flagChildrenAsDirty(),this.fire("set:calculatedHeight",this._calculatedHeight),this.fire("resize",this._calculatedWidth,this._calculatedHeight);}}_flagChildrenAsDirty(){let e=this.entity._children;for(let t=0,i=e.length;t=0&&this._addedModels.splice(t,1);for(let t=0;ti)&&!(l>s)&&!(h.001,a=Math.abs(e.anchor.y-e.anchor.w)>.001,n=false;void 0!==t.margin&&(t.margin instanceof ep?e.margin.copy(t.margin):e._margin.set(t.margin[0],t.margin[1],t.margin[2],t.margin[3]),n=true),void 0!==t.left&&(e._margin.x=t.left,n=true),void 0!==t.bottom&&(e._margin.y=t.bottom,n=true),void 0!==t.right&&(e._margin.z=t.right,n=true),void 0!==t.top&&(e._margin.w=t.top,n=true),n&&(e.margin=e._margin);let o=false;void 0===t.width||r?r&&(o=true):e.width=t.width,void 0===t.height||a?a&&(o=true):e.height=t.height,o&&(e.anchor=e.anchor),void 0!==t.enabled&&(e.enabled=t.enabled),void 0!==t.useInput&&(e.useInput=t.useInput),void 0!==t.fitMode&&(e.fitMode=t.fitMode),e.batchGroupId=void 0===t.batchGroupId||null===t.batchGroupId?-1:t.batchGroupId,t.layers&&Array.isArray(t.layers)&&(e.layers=t.layers.slice(0)),void 0!==t.type&&(e.type=t.type),e.type===mT?(void 0!==t.rect&&(e.rect=t.rect),void 0!==t.color&&((s=t.color)instanceof es||(s=new es(t.color[0],t.color[1],t.color[2])),e.color=s),void 0!==t.opacity&&(e.opacity=t.opacity),void 0!==t.textureAsset&&(e.textureAsset=t.textureAsset),t.texture&&(e.texture=t.texture),void 0!==t.spriteAsset&&(e.spriteAsset=t.spriteAsset),t.sprite&&(e.sprite=t.sprite),void 0!==t.spriteFrame&&(e.spriteFrame=t.spriteFrame),void 0!==t.pixelsPerUnit&&null!==t.pixelsPerUnit&&(e.pixelsPerUnit=t.pixelsPerUnit),void 0!==t.materialAsset&&(e.materialAsset=t.materialAsset),t.material&&(e.material=t.material),void 0!==t.mask&&(e.mask=t.mask)):e.type===mE&&(void 0!==t.autoWidth&&(e.autoWidth=t.autoWidth),void 0!==t.autoHeight&&(e.autoHeight=t.autoHeight),void 0!==t.rtlReorder&&(e.rtlReorder=t.rtlReorder),void 0!==t.unicodeConverter&&(e.unicodeConverter=t.unicodeConverter),null!==t.text&&void 0!==t.text?e.text=t.text:null!==t.key&&void 0!==t.key&&(e.key=t.key),void 0!==t.color&&((s=t.color)instanceof es||(s=new es(s[0],s[1],s[2])),e.color=s),void 0!==t.opacity&&(e.opacity=t.opacity),void 0!==t.spacing&&(e.spacing=t.spacing),void 0!==t.fontSize&&(e.fontSize=t.fontSize,t.lineHeight||(e.lineHeight=t.fontSize)),void 0!==t.lineHeight&&(e.lineHeight=t.lineHeight),void 0!==t.maxLines&&(e.maxLines=t.maxLines),void 0!==t.wrapLines&&(e.wrapLines=t.wrapLines),void 0!==t.minFontSize&&(e.minFontSize=t.minFontSize),void 0!==t.maxFontSize&&(e.maxFontSize=t.maxFontSize),t.autoFitWidth&&(e.autoFitWidth=t.autoFitWidth),t.autoFitHeight&&(e.autoFitHeight=t.autoFitHeight),void 0!==t.fontAsset&&(e.fontAsset=t.fontAsset),void 0!==t.font&&(e.font=t.font),void 0!==t.alignment&&(e.alignment=t.alignment),void 0!==t.outlineColor&&(e.outlineColor=t.outlineColor),void 0!==t.outlineThickness&&(e.outlineThickness=t.outlineThickness),void 0!==t.shadowColor&&(e.shadowColor=t.shadowColor),void 0!==t.shadowOffset&&(e.shadowOffset=t.shadowOffset),void 0!==t.enableMarkup&&(e.enableMarkup=t.enableMarkup));let l=e._parseUpToScreen();l.screen&&e._updateScreen(l.screen),super.initializeComponentData(e,t,i),e._beingInitialized=false,e.type===mT&&e._image._meshDirty&&e._image._updateMesh(e._image.mesh);}onAddComponent(e,t){e.fire("element:add");}onRemoveComponent(e,t){t.onRemove();}cloneComponent(e,t){let i=e.element,s={enabled:i.enabled,width:i.width,height:i.height,anchor:i.anchor.clone(),pivot:i.pivot.clone(),margin:i.margin.clone(),alignment:i.alignment&&i.alignment.clone()||i.alignment,autoWidth:i.autoWidth,autoHeight:i.autoHeight,type:i.type,rect:i.rect&&i.rect.clone()||i.rect,rtlReorder:i.rtlReorder,unicodeConverter:i.unicodeConverter,materialAsset:i.materialAsset,material:i.material,color:i.color&&i.color.clone()||i.color,opacity:i.opacity,textureAsset:i.textureAsset,texture:i.texture,spriteAsset:i.spriteAsset,sprite:i.sprite,spriteFrame:i.spriteFrame,pixelsPerUnit:i.pixelsPerUnit,spacing:i.spacing,lineHeight:i.lineHeight,wrapLines:i.wrapLines,layers:i.layers,fontSize:i.fontSize,minFontSize:i.minFontSize,maxFontSize:i.maxFontSize,autoFitWidth:i.autoFitWidth,autoFitHeight:i.autoFitHeight,maxLines:i.maxLines,fontAsset:i.fontAsset,font:i.font,useInput:i.useInput,fitMode:i.fitMode,batchGroupId:i.batchGroupId,mask:i.mask,outlineColor:i.outlineColor&&i.outlineColor.clone()||i.outlineColor,outlineThickness:i.outlineThickness,shadowColor:i.shadowColor&&i.shadowColor.clone()||i.shadowColor,shadowOffset:i.shadowOffset&&i.shadowOffset.clone()||i.shadowOffset,enableMarkup:i.enableMarkup};return void 0!==i.key&&null!==i.key?s.key=i.key:s.text=i.text,this.addComponent(t,s)}getTextElementMaterial(e,t,i){let s=(e&&1)|(t&&2)|(i&&4),r=this._defaultTextMaterials[s];if(r)return r;let a="TextMaterial";return r=new ud,t?(r.msdfMap=this._defaultTexture,r.msdfTextAttribute=i,r.emissive.set(1,1,1)):(a=`Bitmap${a}`,r.emissive.set(1,1,1),r.emissiveMap=this._defaultTexture,r.opacityMap=this._defaultTexture,r.opacityMapChannel="a"),e&&(a=`ScreenSpace${a}`,r.depthTest=false),r.name=`default${a}`,r.useLighting=false,r.useTonemap=false,r.useFog=false,r.useSkybox=false,r.diffuse.set(0,0,0),r.opacity=.5,r.blendType=4,r.depthWrite=false,r.emissiveVertexColor=true,r.update(),this._defaultTextMaterials[s]=r,r}_createBaseImageMaterial(){let e=new ud;return e.diffuse.set(0,0,0),e.emissive.set(1,1,1),e.emissiveMap=this._defaultTexture,e.opacityMap=this._defaultTexture,e.opacityMapChannel="a",e.useLighting=false,e.useTonemap=false,e.useFog=false,e.useSkybox=false,e.blendType=4,e.depthWrite=false,e}getImageElementMaterial(e,t,i,s){if(e)if(t)if(i)return this.defaultScreenSpaceImageMask9SlicedMaterial||(this.defaultScreenSpaceImageMask9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMask9SlicedMaterial.name="defaultScreenSpaceImageMask9SlicedMaterial",this.defaultScreenSpaceImageMask9SlicedMaterial.nineSlicedMode=1,this.defaultScreenSpaceImageMask9SlicedMaterial.depthTest=false,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9SlicedMaterial.redWrite=false,this.defaultScreenSpaceImageMask9SlicedMaterial.greenWrite=false,this.defaultScreenSpaceImageMask9SlicedMaterial.blueWrite=false,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaWrite=false,this.defaultScreenSpaceImageMask9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9SlicedMaterial)),this.defaultScreenSpaceImageMask9SlicedMaterial;else if(s)return this.defaultScreenSpaceImageMask9TiledMaterial||(this.defaultScreenSpaceImageMask9TiledMaterial=this.defaultScreenSpaceImage9TiledMaterial.clone(),this.defaultScreenSpaceImageMask9TiledMaterial.name="defaultScreenSpaceImageMask9TiledMaterial",this.defaultScreenSpaceImageMask9TiledMaterial.nineSlicedMode=2,this.defaultScreenSpaceImageMask9TiledMaterial.depthTest=false,this.defaultScreenSpaceImageMask9TiledMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9TiledMaterial.redWrite=false,this.defaultScreenSpaceImageMask9TiledMaterial.greenWrite=false,this.defaultScreenSpaceImageMask9TiledMaterial.blueWrite=false,this.defaultScreenSpaceImageMask9TiledMaterial.alphaWrite=false,this.defaultScreenSpaceImageMask9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9TiledMaterial)),this.defaultScreenSpaceImageMask9TiledMaterial;else return this.defaultScreenSpaceImageMaskMaterial||(this.defaultScreenSpaceImageMaskMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaskMaterial.name="defaultScreenSpaceImageMaskMaterial",this.defaultScreenSpaceImageMaskMaterial.depthTest=false,this.defaultScreenSpaceImageMaskMaterial.alphaTest=1,this.defaultScreenSpaceImageMaskMaterial.redWrite=false,this.defaultScreenSpaceImageMaskMaterial.greenWrite=false,this.defaultScreenSpaceImageMaskMaterial.blueWrite=false,this.defaultScreenSpaceImageMaskMaterial.alphaWrite=false,this.defaultScreenSpaceImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaskMaterial)),this.defaultScreenSpaceImageMaskMaterial;else if(i)return this.defaultScreenSpaceImage9SlicedMaterial||(this.defaultScreenSpaceImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9SlicedMaterial.name="defaultScreenSpaceImage9SlicedMaterial",this.defaultScreenSpaceImage9SlicedMaterial.nineSlicedMode=1,this.defaultScreenSpaceImage9SlicedMaterial.depthTest=false,this.defaultScreenSpaceImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9SlicedMaterial)),this.defaultScreenSpaceImage9SlicedMaterial;else if(s)return this.defaultScreenSpaceImage9TiledMaterial||(this.defaultScreenSpaceImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9TiledMaterial.name="defaultScreenSpaceImage9TiledMaterial",this.defaultScreenSpaceImage9TiledMaterial.nineSlicedMode=2,this.defaultScreenSpaceImage9TiledMaterial.depthTest=false,this.defaultScreenSpaceImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9TiledMaterial)),this.defaultScreenSpaceImage9TiledMaterial;else return this.defaultScreenSpaceImageMaterial||(this.defaultScreenSpaceImageMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaterial.name="defaultScreenSpaceImageMaterial",this.defaultScreenSpaceImageMaterial.depthTest=false,this.defaultScreenSpaceImageMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaterial)),this.defaultScreenSpaceImageMaterial;if(t)if(i)return this.defaultImage9SlicedMaskMaterial||(this.defaultImage9SlicedMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaskMaterial.name="defaultImage9SlicedMaskMaterial",this.defaultImage9SlicedMaskMaterial.nineSlicedMode=1,this.defaultImage9SlicedMaskMaterial.alphaTest=1,this.defaultImage9SlicedMaskMaterial.redWrite=false,this.defaultImage9SlicedMaskMaterial.greenWrite=false,this.defaultImage9SlicedMaskMaterial.blueWrite=false,this.defaultImage9SlicedMaskMaterial.alphaWrite=false,this.defaultImage9SlicedMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaskMaterial)),this.defaultImage9SlicedMaskMaterial;else if(s)return this.defaultImage9TiledMaskMaterial||(this.defaultImage9TiledMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaskMaterial.name="defaultImage9TiledMaskMaterial",this.defaultImage9TiledMaskMaterial.nineSlicedMode=2,this.defaultImage9TiledMaskMaterial.alphaTest=1,this.defaultImage9TiledMaskMaterial.redWrite=false,this.defaultImage9TiledMaskMaterial.greenWrite=false,this.defaultImage9TiledMaskMaterial.blueWrite=false,this.defaultImage9TiledMaskMaterial.alphaWrite=false,this.defaultImage9TiledMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaskMaterial)),this.defaultImage9TiledMaskMaterial;else return this.defaultImageMaskMaterial||(this.defaultImageMaskMaterial=this._createBaseImageMaterial(),this.defaultImageMaskMaterial.name="defaultImageMaskMaterial",this.defaultImageMaskMaterial.alphaTest=1,this.defaultImageMaskMaterial.redWrite=false,this.defaultImageMaskMaterial.greenWrite=false,this.defaultImageMaskMaterial.blueWrite=false,this.defaultImageMaskMaterial.alphaWrite=false,this.defaultImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaskMaterial)),this.defaultImageMaskMaterial;return i?(this.defaultImage9SlicedMaterial||(this.defaultImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaterial.name="defaultImage9SlicedMaterial",this.defaultImage9SlicedMaterial.nineSlicedMode=1,this.defaultImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaterial)),this.defaultImage9SlicedMaterial):s?(this.defaultImage9TiledMaterial||(this.defaultImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaterial.name="defaultImage9TiledMaterial",this.defaultImage9TiledMaterial.nineSlicedMode=2,this.defaultImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaterial)),this.defaultImage9TiledMaterial):(this.defaultImageMaterial||(this.defaultImageMaterial=this._createBaseImageMaterial(),this.defaultImageMaterial.name="defaultImageMaterial",this.defaultImageMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaterial)),this.defaultImageMaterial)}registerUnicodeConverter(e){this._unicodeConverter=e;}registerRtlReorder(e){this._rtlReorder=e;}getUnicodeConverter(){return this._unicodeConverter}getRtlReorder(){return this._rtlReorder}constructor(e){super(e),this.id="element",this.ComponentType=_D,this.DataType=_R,this.schema=_L,this._unicodeConverter=null,this._rtlReorder=null,this._defaultTexture=new ic(e.graphicsDevice,{width:1,height:1,format:20,name:"element-system"});let t=this._defaultTexture.lock(),i=new Uint8Array(4);i[0]=255,i[1]=255,i[2]=255,i[3]=255,t.set(i),this._defaultTexture.unlock(),this.defaultImageMaterial=null,this.defaultImage9SlicedMaterial=null,this.defaultImage9TiledMaterial=null,this.defaultImageMaskMaterial=null,this.defaultImage9SlicedMaskMaterial=null,this.defaultImage9TiledMaskMaterial=null,this.defaultScreenSpaceImageMaterial=null,this.defaultScreenSpaceImage9SlicedMaterial=null,this.defaultScreenSpaceImage9TiledMaterial=null,this.defaultScreenSpaceImageMask9SlicedMaterial=null,this.defaultScreenSpaceImageMask9TiledMaterial=null,this.defaultScreenSpaceImageMaskMaterial=null,this._defaultTextMaterials={},this.defaultImageMaterials=[],this.on("add",this.onAddComponent,this),this.on("beforeremove",this.onRemoveComponent,this);}}let _O="free",_F="limited",_N="locked",_B=["angularDampingX","angularDampingY","angularDampingZ","angularEquilibriumX","angularEquilibriumY","angularEquilibriumZ","angularLimitsX","angularLimitsY","angularLimitsZ","angularMotionX","angularMotionY","angularMotionZ","angularSpringX","angularSpringY","angularSpringZ","angularStiffnessX","angularStiffnessY","angularStiffnessZ","breakForce","enableCollision","enabled","entityA","entityB","linearDampingX","linearDampingY","linearDampingZ","linearEquilibriumX","linearEquilibriumY","linearEquilibriumZ","linearLimitsX","linearLimitsY","linearLimitsZ","linearMotionX","linearMotionY","linearMotionZ","linearSpringX","linearSpringY","linearSpringZ","linearStiffnessX","linearStiffnessY","linearStiffnessZ"];class _k extends px{set entityA(e){this._destroyConstraint(),this._entityA=e,this._createConstraint();}get entityA(){return this._entityA}set entityB(e){this._destroyConstraint(),this._entityB=e,this._createConstraint();}get entityB(){return this._entityB}set breakForce(e){this._constraint&&this._breakForce!==e&&(this._constraint.setBreakingImpulseThreshold(e),this._breakForce=e);}get breakForce(){return this._breakForce}set enableCollision(e){this._destroyConstraint(),this._enableCollision=e,this._createConstraint();}get enableCollision(){return this._enableCollision}set angularLimitsX(e){this._angularLimitsX.equals(e)||(this._angularLimitsX.copy(e),this._updateAngularLimits());}get angularLimitsX(){return this._angularLimitsX}set angularMotionX(e){this._angularMotionX!==e&&(this._angularMotionX=e,this._updateAngularLimits());}get angularMotionX(){return this._angularMotionX}set angularLimitsY(e){this._angularLimitsY.equals(e)||(this._angularLimitsY.copy(e),this._updateAngularLimits());}get angularLimitsY(){return this._angularLimitsY}set angularMotionY(e){this._angularMotionY!==e&&(this._angularMotionY=e,this._updateAngularLimits());}get angularMotionY(){return this._angularMotionY}set angularLimitsZ(e){this._angularLimitsZ.equals(e)||(this._angularLimitsZ.copy(e),this._updateAngularLimits());}get angularLimitsZ(){return this._angularLimitsZ}set angularMotionZ(e){this._angularMotionZ!==e&&(this._angularMotionZ=e,this._updateAngularLimits());}get angularMotionZ(){return this._angularMotionZ}set linearLimitsX(e){this._linearLimitsX.equals(e)||(this._linearLimitsX.copy(e),this._updateLinearLimits());}get linearLimitsX(){return this._linearLimitsX}set linearMotionX(e){this._linearMotionX!==e&&(this._linearMotionX=e,this._updateLinearLimits());}get linearMotionX(){return this._linearMotionX}set linearLimitsY(e){this._linearLimitsY.equals(e)||(this._linearLimitsY.copy(e),this._updateLinearLimits());}get linearLimitsY(){return this._linearLimitsY}set linearMotionY(e){this._linearMotionY!==e&&(this._linearMotionY=e,this._updateLinearLimits());}get linearMotionY(){return this._linearMotionY}set linearLimitsZ(e){this._linearLimitsZ.equals(e)||(this._linearLimitsZ.copy(e),this._updateLinearLimits());}get linearLimitsZ(){return this._linearLimitsZ}set linearMotionZ(e){this._linearMotionZ!==e&&(this._linearMotionZ=e,this._updateLinearLimits());}get linearMotionZ(){return this._linearMotionZ}_convertTransform(e,t){let i=e.getTranslation(),s=new ex;s.setFromMat4(e);let r=new Ammo.btVector3(i.x,i.y,i.z),a=new Ammo.btQuaternion(s.x,s.y,s.z,s.w);t.setOrigin(r),t.setRotation(a),Ammo.destroy(r),Ammo.destroy(a);}_updateAngularLimits(){let e=this._constraint;if(e){let t,i,s,r,a,n;this._angularMotionX===_F?(t=this._angularLimitsX.x*ei.DEG_TO_RAD,r=this._angularLimitsX.y*ei.DEG_TO_RAD):this._angularMotionX===_O?(t=1,r=0):t=r=0,this._angularMotionY===_F?(i=this._angularLimitsY.x*ei.DEG_TO_RAD,a=this._angularLimitsY.y*ei.DEG_TO_RAD):this._angularMotionY===_O?(i=1,a=0):i=a=0,this._angularMotionZ===_F?(s=this._angularLimitsZ.x*ei.DEG_TO_RAD,n=this._angularLimitsZ.y*ei.DEG_TO_RAD):this._angularMotionZ===_O?(s=1,n=0):s=n=0;let o=new Ammo.btVector3(t,i,s);e.setAngularLowerLimit(o),o.setValue(r,a,n),e.setAngularUpperLimit(o),Ammo.destroy(o);}}_updateLinearLimits(){let e=this._constraint;if(e){let t,i,s,r,a,n;this._linearMotionX===_F?(t=this._linearLimitsX.x,r=this._linearLimitsX.y):this._linearMotionX===_O?(t=1,r=0):t=r=0,this._linearMotionY===_F?(i=this._linearLimitsY.x,a=this._linearLimitsY.y):this._linearMotionY===_O?(i=1,a=0):i=a=0,this._linearMotionZ===_F?(s=this._linearLimitsZ.x,n=this._linearLimitsZ.y):this._linearMotionZ===_O?(s=1,n=0):s=n=0;let o=new Ammo.btVector3(t,i,s);e.setLinearLowerLimit(o),o.setValue(r,a,n),e.setLinearUpperLimit(o),Ammo.destroy(o);}}_createConstraint(){if(this._entityA&&this._entityA.rigidbody){this._destroyConstraint();let e=new ey,t=this._entityA.rigidbody.body;t.activate();let i=this.entity.getWorldTransform(),s=this._entityA.getWorldTransform().clone().invert();e.mul2(s,i);let r=new Ammo.btTransform;if(this._convertTransform(e,r),this._entityB&&this._entityB.rigidbody){let s=this._entityB.rigidbody.body;s.activate();let a=this._entityB.getWorldTransform().clone().invert();e.mul2(a,i);let n=new Ammo.btTransform;this._convertTransform(e,n),this._constraint=new Ammo.btGeneric6DofSpringConstraint(t,s,r,n,!this._enableCollision),Ammo.destroy(n);}else this._constraint=new Ammo.btGeneric6DofSpringConstraint(t,r,!this._enableCollision);Ammo.destroy(r);let a=["X","Y","Z","X","Y","Z"];for(let e=0;e<6;e++){let t=e<3?"_linear":"_angular";this._constraint.enableSpring(e,this[`${t}Spring${a[e]}`]),this._constraint.setDamping(e,this[`${t}Damping${a[e]}`]),this._constraint.setEquilibriumPoint(e,this[`${t}Equilibrium${a[e]}`]),this._constraint.setStiffness(e,this[`${t}Stiffness${a[e]}`]);}this._constraint.setBreakingImpulseThreshold(this._breakForce),this._updateLinearLimits(),this._updateAngularLimits(),this.system.app.systems.rigidbody.dynamicsWorld.addConstraint(this._constraint,!this._enableCollision);}}_destroyConstraint(){this._constraint&&(this.system.app.systems.rigidbody.dynamicsWorld.removeConstraint(this._constraint),Ammo.destroy(this._constraint),this._constraint=null);}initFromData(e){for(let t of _B)e.hasOwnProperty(t)&&(e[t]instanceof ef?this[`_${t}`].copy(e[t]):this[`_${t}`]=e[t]);this._createConstraint();}onEnable(){this._createConstraint();}onDisable(){this._destroyConstraint();}_onSetEnabled(e,t,i){}_onBeforeRemove(){this.fire("remove");}constructor(e,t){super(e,t),this._constraint=null,this._entityA=null,this._entityB=null,this._breakForce=34e37,this._enableCollision=true,this._linearMotionX=_N,this._linearLimitsX=new ef(0,0),this._linearSpringX=false,this._linearStiffnessX=0,this._linearDampingX=1,this._linearEquilibriumX=0,this._linearMotionY=_N,this._linearLimitsY=new ef(0,0),this._linearSpringY=false,this._linearStiffnessY=0,this._linearDampingY=1,this._linearEquilibriumY=0,this._linearMotionZ=_N,this._linearLimitsZ=new ef(0,0),this._linearSpringZ=false,this._linearStiffnessZ=0,this._linearDampingZ=1,this._linearEquilibriumZ=0,this._angularMotionX=_N,this._angularLimitsX=new ef(0,0),this._angularSpringX=false,this._angularStiffnessX=0,this._angularDampingX=1,this._angularEquilibriumX=0,this._angularMotionY=_N,this._angularLimitsY=new ef(0,0),this._angularSpringY=false,this._angularStiffnessY=0,this._angularDampingY=1,this._angularEquilibriumY=0,this._angularMotionZ=_N,this._angularLimitsZ=new ef(0,0),this._angularSpringZ=false,this._angularEquilibriumZ=0,this._angularDampingZ=1,this._angularStiffnessZ=0,this.on("set_enabled",this._onSetEnabled,this);}}let _U={Damping:"setDamping",Equilibrium:"setEquilibriumPoint",Spring:"enableSpring",Stiffness:"setStiffness"};["linear","angular"].forEach(e=>{["Damping","Equilibrium","Spring","Stiffness"].forEach(t=>{["X","Y","Z"].forEach(i=>{let s=e+t+i,r=`_${s}`,a=3*("linear"!==e);"Y"===i&&(a+=1),"Z"===i&&(a+=2),Object.defineProperty(_k.prototype,s,{get:function(){return this[r]},set:function(e){this[r]!==e&&(this[r]=e,this._constraint[_U[t]](a,e));}});});});});class _z{constructor(){this.enabled=true;}}let _V=["enabled"];class _G extends pT{initializeComponentData(e,t,i){e.initFromData(t),super.initializeComponentData(e,t,_V);}constructor(e){super(e),this.id="joint",this.app=e,this.ComponentType=_k,this.DataType=_z,this.schema=_V;}}px._buildAccessors(_k.prototype,_V);class _H extends px{set minWidth(e){e!==this._minWidth&&(this._minWidth=e,this.fire("resize"));}get minWidth(){return this._minWidth}set minHeight(e){e!==this._minHeight&&(this._minHeight=e,this.fire("resize"));}get minHeight(){return this._minHeight}set maxWidth(e){e!==this._maxWidth&&(this._maxWidth=e,this.fire("resize"));}get maxWidth(){return this._maxWidth}set maxHeight(e){e!==this._maxHeight&&(this._maxHeight=e,this.fire("resize"));}get maxHeight(){return this._maxHeight}set fitWidthProportion(e){e!==this._fitWidthProportion&&(this._fitWidthProportion=e,this.fire("resize"));}get fitWidthProportion(){return this._fitWidthProportion}set fitHeightProportion(e){e!==this._fitHeightProportion&&(this._fitHeightProportion=e,this.fire("resize"));}get fitHeightProportion(){return this._fitHeightProportion}set excludeFromLayout(e){e!==this._excludeFromLayout&&(this._excludeFromLayout=e,this.fire("resize"));}get excludeFromLayout(){return this._excludeFromLayout}constructor(...e){super(...e),this._minWidth=0,this._minHeight=0,this._maxWidth=null,this._maxHeight=null,this._fitWidthProportion=0,this._fitHeightProportion=0,this._excludeFromLayout=false;}}class _W{constructor(){this.enabled=true;}}let _X=["enabled"];class _Y extends pT{initializeComponentData(e,t,i){ void 0!==t.enabled&&(e.enabled=t.enabled),void 0!==t.minWidth&&(e.minWidth=t.minWidth),void 0!==t.minHeight&&(e.minHeight=t.minHeight),void 0!==t.maxWidth&&(e.maxWidth=t.maxWidth),void 0!==t.maxHeight&&(e.maxHeight=t.maxHeight),void 0!==t.fitWidthProportion&&(e.fitWidthProportion=t.fitWidthProportion),void 0!==t.fitHeightProportion&&(e.fitHeightProportion=t.fitHeightProportion),void 0!==t.excludeFromLayout&&(e.excludeFromLayout=t.excludeFromLayout),super.initializeComponentData(e,t,i);}cloneComponent(e,t){let i=e.layoutchild;return this.addComponent(t,{enabled:i.enabled,minWidth:i.minWidth,minHeight:i.minHeight,maxWidth:i.maxWidth,maxHeight:i.maxHeight,fitWidthProportion:i.fitWidthProportion,fitHeightProportion:i.fitHeightProportion,excludeFromLayout:i.excludeFromLayout})}constructor(e){super(e),this.id="layoutchild",this.ComponentType=_H,this.DataType=_W,this.schema=_X;}}px._buildAccessors(_H.prototype,_X);let _q={};_q[0]={axis:"x",size:"width",calculatedSize:"calculatedWidth",minSize:"minWidth",maxSize:"maxWidth",fitting:"widthFitting",fittingProportion:"fitWidthProportion"},_q[1]={axis:"y",size:"height",calculatedSize:"calculatedHeight",minSize:"minHeight",maxSize:"maxHeight",fitting:"heightFitting",fittingProportion:"fitHeightProportion"};let _j={};_j[0]=1,_j[1]=0;let _K={minWidth:0,minHeight:0,maxWidth:1/0,maxHeight:1/0,width:null,height:null,fitWidthProportion:0,fitHeightProportion:0},_$="NONE",_Z="APPLY_STRETCHING",_Q="APPLY_SHRINKING",_J=new ef;function _0(e){let t,i=_q[e],s=_q[_j[e]];function r(e,t){return -t[s.size]*e.pivot[s.axis]}function a(e){let t=e.entity.layoutchild;return !t||!t.enabled||!t.excludeFromLayout}function n(e,t,i){switch(e){case 0:return _$;case 1:if(t=i)return _Q;return _$;case 3:if(tMath.abs(r)&&1e-5>Math.abs(a)?t:t*r/a}function d(e){let t=[];for(let i=0;ie+i[t],0)}function m(e,t){let i=p(e,t),s=[],r=e.length;if(0===i)for(let e=0;ei?s[t]-e[t]:e[t]-s[t]).map(v)}function g(e,t){e.index=t;}function v(e){return e.index}function S(e,t){let i=[];i[t[e.length-1]]=e[t[e.length-1]];for(let s=e.length-2;s>=0;--s)i[t[s]]=i[t[s+1]]+e[t[s]];return i}return function(e,c){var u;let f,p;e=e.filter(a),_J.x=(t=c).containerSize.x-t.padding.x-t.padding.z,_J.y=t.containerSize.y-t.padding.y-t.padding.w,function(e){for(let t=0;t0&&(a+=t.spacing[i.axis]);let l=r[o][i.size];a+=l,!n&&a>_J[i.axis]&&0!==s[s.length-1].length&&(a=l,s.push([])),s[s.length-1].push(e[o]),n&&a>_J[i.axis]&&o!==e.length-1&&(a=0,s.push([]));}return s}(e)),_=function(e,i){let r=[],a=[];for(let t=0;tn.largestSize[s.size]&&(n.largestElement=n[e],n.largestSize=r);}r.push(n.largestElement),a.push(n.largestSize);}let c=o(a,s),d=n(t[s.fitting],c,_J[s.axis]);d===_Z?l(a,c,s):d===_Q&&h(a,c,s);for(let r=0;r{this._listenForReflowEvents(e,"off");}),this.system.app.systems.element.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.element.off("beforeremove",this._onElementOrLayoutComponentRemove,this),this.system.app.systems.layoutchild.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.layoutchild.off("beforeremove",this._onElementOrLayoutComponentRemove,this);}constructor(e,t){super(e,t),this._orientation=0,this._reverseX=false,this._reverseY=true,this._alignment=new ef(0,1),this._padding=new ep,this._spacing=new ef,this._widthFitting=0,this._heightFitting=0,this._wrap=false,this._layoutCalculator=new _2,this._listenForReflowEvents(this.entity,"on"),this.entity.children.forEach(e=>{this._listenForReflowEvents(e,"on");}),this.entity.on("childinsert",this._onChildInsert,this),this.entity.on("childremove",this._onChildRemove,this),e.app.systems.element.on("add",this._onElementOrLayoutComponentAdd,this),e.app.systems.element.on("beforeremove",this._onElementOrLayoutComponentRemove,this),e.app.systems.layoutchild.on("add",this._onElementOrLayoutComponentAdd,this),e.app.systems.layoutchild.on("beforeremove",this._onElementOrLayoutComponentRemove,this);}}class _6{constructor(){this.enabled=true;}}let _8=["enabled"];class _9 extends pT{initializeComponentData(e,t,i){ void 0!==t.enabled&&(e.enabled=t.enabled),void 0!==t.orientation&&(e.orientation=t.orientation),void 0!==t.reverseX&&(e.reverseX=t.reverseX),void 0!==t.reverseY&&(e.reverseY=t.reverseY),void 0!==t.alignment&&(e.alignment=Array.isArray(t.alignment)?new ef(t.alignment):t.alignment),void 0!==t.padding&&(e.padding=Array.isArray(t.padding)?new ep(t.padding):t.padding),void 0!==t.spacing&&(e.spacing=Array.isArray(t.spacing)?new ef(t.spacing):t.spacing),void 0!==t.widthFitting&&(e.widthFitting=t.widthFitting),void 0!==t.heightFitting&&(e.heightFitting=t.heightFitting),void 0!==t.wrap&&(e.wrap=t.wrap),super.initializeComponentData(e,t,i);}cloneComponent(e,t){let i=e.layoutgroup;return this.addComponent(t,{enabled:i.enabled,orientation:i.orientation,reverseX:i.reverseX,reverseY:i.reverseY,alignment:i.alignment,padding:i.padding,spacing:i.spacing,widthFitting:i.widthFitting,heightFitting:i.heightFitting,wrap:i.wrap})}scheduleReflow(e){ -1===this._reflowQueue.indexOf(e)&&this._reflowQueue.push(e);}_onPostUpdate(){this._processReflowQueue();}_processReflowQueue(){if(0===this._reflowQueue.length)return;let e=0;for(;this._reflowQueue.length>0;){let t=this._reflowQueue.slice();this._reflowQueue.length=0,t.sort((e,t)=>e.entity.graphDepth-t.entity.graphDepth);for(let e=0;e=100)break}}_onRemoveComponent(e,t){t.onRemove();}destroy(){super.destroy(),this.app.systems.off("postUpdate",this._onPostUpdate,this);}constructor(e){super(e),this.id="layoutgroup",this.ComponentType=_5,this.DataType=_6,this.schema=_8,this._reflowQueue=[],this.on("beforeremove",this._onRemoveComponent,this),this.app.systems.on("postUpdate",this._onPostUpdate,this);}}px._buildAccessors(_5.prototype,_8);class _7{destroy(e){this.map.forEach(e=>e.mesh.destroy());}constructor(){this.map=new Map;}}let ge=new is,gt=(e,t)=>{let i=ge.get(e,()=>new _7),s=i.map.get(t);if(!s){let r,a;switch(t){case "box":r=on.fromGeometry(e,new c5),a={x:2,y:2,z:2,uv:2/3};break;case "capsule":r=on.fromGeometry(e,new ux({radius:.5,height:2})),a={x:2*Math.PI,y:Math.PI,z:2*Math.PI,uv:1/3+1/3/3*2};break;case "cone":r=on.fromGeometry(e,new uT({baseRadius:.5,peakRadius:0,height:1})),a={x:2.54,y:2.54,z:2.54,uv:1/3+1/3/3};break;case "cylinder":r=on.fromGeometry(e,new uE({radius:.5,height:1})),a={x:Math.PI,y:1.58,z:Math.PI,uv:1/3+1/3/3*2};break;case "plane":r=on.fromGeometry(e,new uw({halfExtents:new ef(.5,.5),widthSegments:1,lengthSegments:1})),a={x:0,y:1,z:0,uv:1};break;case "sphere":r=on.fromGeometry(e,new c6({radius:.5})),a={x:Math.PI,y:Math.PI,z:Math.PI,uv:1};break;case "torus":r=on.fromGeometry(e,new ub({tubeRadius:.2,ringRadius:.3})),a={x:.5*Math.PI*.5-.1*Math.PI*.1,y:.4,z:.4,uv:1};break;default:throw Error(`Invalid primitive type: ${t}`)}r.incRefCount(),s={mesh:r,area:a},i.map.set(t,s);}return s};class gi extends px{set meshInstances(e){this._model&&(this._model.meshInstances=e);}get meshInstances(){return this._model?this._model.meshInstances:null}set customAabb(e){if(this._customAabb=e,this._model){let e=this._model.meshInstances;if(e)for(let t=0;t=0&&this.system.app.batcher?.remove(n7.MODEL,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(n7.MODEL,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._batchGroupId=e);}get batchGroupId(){return this._batchGroupId}set materialAsset(e){let t=e;e instanceof fX&&(t=e.id);let i=this.system.app.assets;if(t!==this._materialAsset){if(this._materialAsset){i.off(`add:${this._materialAsset}`,this._onMaterialAssetAdd,this);let e=i.get(this._materialAsset);e&&this._unbindMaterialAsset(e);}if(this._materialAsset=t,this._materialAsset){let e=i.get(this._materialAsset);e?this._bindMaterialAsset(e):(this._setMaterial(this.system.defaultMaterial),i.on(`add:${this._materialAsset}`,this._onMaterialAssetAdd,this));}else this._setMaterial(this.system.defaultMaterial);}}get materialAsset(){return this._materialAsset}set material(e){this._material!==e&&(this.materialAsset=null,this._setMaterial(e));}get material(){return this._material}set mapping(e){if("asset"!==this._type||(this._unsetMaterialEvents(),e||(e={}),this._mapping=e,!this._model))return;let t=this._model.meshInstances,i=this.asset?this.system.app.assets.get(this.asset):null,s=i?i.data.mapping:null,r=null;for(let i=0,a=t.length;ithis.layers.indexOf(e.id)||e.addMeshInstances(this.meshInstances);}onLayerRemoved(e){0>this.layers.indexOf(e.id)||e.removeMeshInstances(this.meshInstances);}_setMaterialEvent(e,t,i,s){let r=`${t}:${i}`;this.system.app.assets.on(r,s,this),this._materialEvents||(this._materialEvents=[]),this._materialEvents[e]||(this._materialEvents[e]={}),this._materialEvents[e][r]={id:i,handler:s};}_unsetMaterialEvents(){let e=this.system.app.assets,t=this._materialEvents;if(t){for(let i=0,s=t.length;i=0&&t.batcher?.insert(n7.MODEL,this.batchGroupId,this.entity);}onDisable(){let e=this.system.app,t=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._batchGroupId>=0&&e.batcher?.remove(n7.MODEL,this.batchGroupId,this.entity),this._model&&this.removeModelFromLayers();}hide(){if(this._model){let e=this._model.meshInstances;for(let t=0,i=e.length;tthis.layers.indexOf(e.id)||e.addMeshInstances([this.emitter.meshInstance]);}onLayerRemoved(e){!this.emitter||0>this.layers.indexOf(e.id)||e.removeMeshInstances([this.emitter.meshInstance]);}_bindColorMapAsset(e){if(e.on("load",this._onColorMapAssetLoad,this),e.on("unload",this._onColorMapAssetUnload,this),e.on("remove",this._onColorMapAssetRemove,this),e.on("change",this._onColorMapAssetChange,this),e.resource)this._onColorMapAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}}_unbindColorMapAsset(e){e.off("load",this._onColorMapAssetLoad,this),e.off("unload",this._onColorMapAssetUnload,this),e.off("remove",this._onColorMapAssetRemove,this),e.off("change",this._onColorMapAssetChange,this);}_onColorMapAssetLoad(e){this.colorMap=e.resource;}_onColorMapAssetUnload(e){this.colorMap=null;}_onColorMapAssetRemove(e){this._onColorMapAssetUnload(e);}_onColorMapAssetChange(e){}onSetColorMapAsset(e,t,i){let s=this.system.app.assets;if(t){let e=s.get(t);e&&this._unbindColorMapAsset(e);}if(i){i instanceof fX&&(this.data.colorMapAsset=i.id,i=i.id);let e=s.get(i);e?this._bindColorMapAsset(e):s.once(`add:${i}`,e=>{this._bindColorMapAsset(e);});}else this.colorMap=null;}_bindNormalMapAsset(e){if(e.on("load",this._onNormalMapAssetLoad,this),e.on("unload",this._onNormalMapAssetUnload,this),e.on("remove",this._onNormalMapAssetRemove,this),e.on("change",this._onNormalMapAssetChange,this),e.resource)this._onNormalMapAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}}_unbindNormalMapAsset(e){e.off("load",this._onNormalMapAssetLoad,this),e.off("unload",this._onNormalMapAssetUnload,this),e.off("remove",this._onNormalMapAssetRemove,this),e.off("change",this._onNormalMapAssetChange,this);}_onNormalMapAssetLoad(e){this.normalMap=e.resource;}_onNormalMapAssetUnload(e){this.normalMap=null;}_onNormalMapAssetRemove(e){this._onNormalMapAssetUnload(e);}_onNormalMapAssetChange(e){}onSetNormalMapAsset(e,t,i){let s=this.system.app.assets;if(t){let e=s.get(t);e&&this._unbindNormalMapAsset(e);}if(i){i instanceof fX&&(this.data.normalMapAsset=i.id,i=i.id);let e=s.get(i);e?this._bindNormalMapAsset(e):s.once(`add:${i}`,e=>{this._bindNormalMapAsset(e);});}else this.normalMap=null;}_bindMeshAsset(e){if(e.on("load",this._onMeshAssetLoad,this),e.on("unload",this._onMeshAssetUnload,this),e.on("remove",this._onMeshAssetRemove,this),e.on("change",this._onMeshAssetChange,this),e.resource)this._onMeshAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}}_unbindMeshAsset(e){e.off("load",this._onMeshAssetLoad,this),e.off("unload",this._onMeshAssetUnload,this),e.off("remove",this._onMeshAssetRemove,this),e.off("change",this._onMeshAssetChange,this);}_onMeshAssetLoad(e){this._onMeshChanged(e.resource);}_onMeshAssetUnload(e){this.mesh=null;}_onMeshAssetRemove(e){this._onMeshAssetUnload(e);}_onMeshAssetChange(e){}onSetMeshAsset(e,t,i){let s=this.system.app.assets;if(t){let e=s.get(t);e&&this._unbindMeshAsset(e);}if(i){i instanceof fX&&(this.data.meshAsset=i.id,i=i.id);let e=s.get(i);e&&this._bindMeshAsset(e);}else this._onMeshChanged(null);}onSetMesh(e,t,i){!i||i instanceof fX||"number"==typeof i?this.meshAsset=i:this._onMeshChanged(i);}_onMeshChanged(e){!e||e instanceof on||(e=e.meshInstances[0]?e.meshInstances[0].mesh:null),this.data.mesh=e,this.emitter&&(this.emitter.mesh=e,this.emitter.resetMaterial(),this.rebuild());}onSetRenderAsset(e,t,i){let s=this.system.app.assets;if(t){let e=s.get(t);e&&this._unbindRenderAsset(e);}if(i){i instanceof fX&&(this.data.renderAsset=i.id,i=i.id);let e=s.get(i);e&&this._bindRenderAsset(e);}else this._onRenderChanged(null);}_bindRenderAsset(e){if(e.on("load",this._onRenderAssetLoad,this),e.on("unload",this._onRenderAssetUnload,this),e.on("remove",this._onRenderAssetRemove,this),e.resource)this._onRenderAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}}_unbindRenderAsset(e){e.off("load",this._onRenderAssetLoad,this),e.off("unload",this._onRenderAssetUnload,this),e.off("remove",this._onRenderAssetRemove,this),this._evtSetMeshes?.off(),this._evtSetMeshes=null;}_onRenderAssetLoad(e){this._onRenderChanged(e.resource);}_onRenderAssetUnload(e){this._onRenderChanged(null);}_onRenderAssetRemove(e){this._onRenderAssetUnload(e);}_onRenderChanged(e){e?(this._evtSetMeshes?.off(),this._evtSetMeshes=e.on("set:meshes",this._onRenderSetMeshes,this),e.meshes&&this._onRenderSetMeshes(e.meshes)):this._onMeshChanged(null);}_onRenderSetMeshes(e){this._onMeshChanged(e&&e[0]);}onSetLoop(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetTime());}onSetBlendType(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.material.blendType=i,this.emitter.resetMaterial(),this.rebuild());}_requestDepth(){!this._requestedDepth&&(l||(l=this.system.app.scene.layers.getLayerById(1)),l&&(l.incrementCounter(),this._requestedDepth=true));}_releaseDepth(){this._requestedDepth&&l&&(l.decrementCounter(),this._requestedDepth=false);}onSetDepthSoftening(e,t,i){t!==i&&(i?this.enabled&&this.entity.enabled&&this._requestDepth():this.enabled&&this.entity.enabled&&this._releaseDepth(),this.emitter&&(this.emitter[e]=i),this.emitter&&(this.reset(),this.emitter.resetMaterial(),this.rebuild()));}onSetSimpleProperty(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetMaterial());}onSetComplexProperty(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetMaterial(),this.rebuild(),this.reset());}onSetGraphProperty(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.rebuildGraphs(),this.emitter.resetMaterial());}onEnable(){let e=this.system.app.scene,t=e.layers,i=this.data;for(let e=0,t=gh.length;e=0))continue;t=this.system.app.assets.get(t);}t&&!t.resource&&this.system.app.assets.load(t);}}if(!this.system.app.graphicsDevice.disableParticleSystem){if(!this.emitter){let e=i.mesh;e instanceof on||(e=null),this.emitter=new cy(this.system.app.graphicsDevice,{numParticles:i.numParticles,emitterExtents:i.emitterExtents,emitterExtentsInner:i.emitterExtentsInner,emitterRadius:i.emitterRadius,emitterRadiusInner:i.emitterRadiusInner,emitterShape:i.emitterShape,initialVelocity:i.initialVelocity,wrap:i.wrap,localSpace:i.localSpace,screenSpace:i.screenSpace,wrapBounds:i.wrapBounds,lifetime:i.lifetime,rate:i.rate,rate2:i.rate2,orientation:i.orientation,particleNormal:i.particleNormal,animTilesX:i.animTilesX,animTilesY:i.animTilesY,animStartFrame:i.animStartFrame,animNumFrames:i.animNumFrames,animNumAnimations:i.animNumAnimations,animIndex:i.animIndex,randomizeAnimIndex:i.randomizeAnimIndex,animSpeed:i.animSpeed,animLoop:i.animLoop,startAngle:i.startAngle,startAngle2:i.startAngle2,scaleGraph:i.scaleGraph,scaleGraph2:i.scaleGraph2,colorGraph:i.colorGraph,colorGraph2:i.colorGraph2,alphaGraph:i.alphaGraph,alphaGraph2:i.alphaGraph2,localVelocityGraph:i.localVelocityGraph,localVelocityGraph2:i.localVelocityGraph2,velocityGraph:i.velocityGraph,velocityGraph2:i.velocityGraph2,rotationSpeedGraph:i.rotationSpeedGraph,rotationSpeedGraph2:i.rotationSpeedGraph2,radialSpeedGraph:i.radialSpeedGraph,radialSpeedGraph2:i.radialSpeedGraph2,colorMap:i.colorMap,normalMap:i.normalMap,loop:i.loop,preWarm:i.preWarm,sort:i.sort,stretch:i.stretch,alignToMotion:i.alignToMotion,lighting:i.lighting,halfLambert:i.halfLambert,intensity:i.intensity,depthSoftening:i.depthSoftening,scene:this.system.app.scene,mesh:e,depthWrite:i.depthWrite,noFog:i.noFog,node:this.entity,blendType:i.blendType}),this.emitter.meshInstance.node=this.entity,this.emitter.drawOrder=this.drawOrder,i.autoPlay||(this.pause(),this.emitter.meshInstance.visible=false);}this.emitter.colorMap&&this.addMeshInstanceToLayers(),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&i.depthSoftening&&this._requestDepth();}}onDisable(){let e=this.system.app.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,e&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.emitter&&(this.removeMeshInstanceFromLayers(),this.data.depthSoftening&&this._releaseDepth(),this.emitter.camera=null);}onBeforeRemove(){this.enabled&&(this.enabled=false),this.emitter&&(this.emitter.destroy(),this.emitter=null);for(let e=0;e{this.on(`set_${e}`,this.onSetSimpleProperty,this);}),go.forEach(e=>{this.on(`set_${e}`,this.onSetComplexProperty,this);}),gl.forEach(e=>{this.on(`set_${e}`,this.onSetGraphProperty,this);});}}class gd{constructor(){this.numParticles=1,this.rate=1,this.rate2=null,this.startAngle=0,this.startAngle2=null,this.lifetime=50,this.emitterExtents=new ed,this.emitterExtentsInner=new ed,this.emitterRadius=0,this.emitterRadiusInner=0,this.emitterShape=0,this.initialVelocity=0,this.wrap=false,this.wrapBounds=new ed,this.localSpace=false,this.screenSpace=false,this.colorMap=null,this.colorMapAsset=null,this.normalMap=null,this.normalMapAsset=null,this.loop=true,this.preWarm=false,this.sort=0,this.mode=0,this.scene=null,this.lighting=false,this.halfLambert=false,this.intensity=1,this.stretch=0,this.alignToMotion=false,this.depthSoftening=0,this.renderAsset=null,this.meshAsset=null,this.mesh=null,this.depthWrite=false,this.noFog=false,this.orientation=0,this.particleNormal=new ed(0,1,0),this.animTilesX=1,this.animTilesY=1,this.animStartFrame=0,this.animNumFrames=1,this.animNumAnimations=1,this.animIndex=0,this.randomizeAnimIndex=false,this.animSpeed=1,this.animLoop=true,this.scaleGraph=null,this.scaleGraph2=null,this.colorGraph=null,this.colorGraph2=null,this.alphaGraph=null,this.alphaGraph2=null,this.localVelocityGraph=null,this.localVelocityGraph2=null,this.velocityGraph=null,this.velocityGraph2=null,this.rotationSpeedGraph=null,this.rotationSpeedGraph2=null,this.radialSpeedGraph=null,this.radialSpeedGraph2=null,this.blendType=2,this.enabled=true,this.paused=false,this.autoPlay=true,this.layers=[0];}}let gu={particlePS:` +`;var lB=15,P8={glslBilateralDeNoisePS:rB,glslDilatePS:aB},w8={wgslBilateralDeNoisePS:oB,wgslDilatePS:nB},h0=class{constructor(t){n(this,"shaderDilate",[]);n(this,"shaderDenoise",[]);this.device=t,ne.get(this.device,fe).add(P8),ne.get(this.device,se).add(w8),this.constantTexSource=t.scope.resolve("source"),this.constantPixelOffset=t.scope.resolve("pixelOffset"),this.pixelOffset=new Float32Array(2),this.sigmas=null,this.constantSigmas=null,this.kernel=null}setSourceTexture(t){this.constantTexSource.setValue(t)}prepare(t,e){this.pixelOffset[0]=1/t,this.pixelOffset[1]=1/e,this.constantPixelOffset.setValue(this.pixelOffset)}prepareDenoise(t,e,s){let i=s?0:1;if(!this.shaderDenoise[i]){let r=new Map;r.set("{MSIZE}",15),s&&r.set("HDR",""),this.shaderDenoise[i]=Se.createShader(this.device,{uniqueName:`lmBilateralDeNoise-${s?"hdr":"rgbm"}`,attributes:{vertex_position:ee},vertexGLSL:ne.get(this.device,fe).get("fullscreenQuadVS"),vertexWGSL:ne.get(this.device,se).get("fullscreenQuadVS"),fragmentGLSL:ne.get(this.device,fe).get("glslBilateralDeNoisePS"),fragmentWGSL:ne.get(this.device,se).get("wgslBilateralDeNoisePS"),fragmentDefines:r}),this.sigmas=new Float32Array(2),this.constantSigmas=this.device.scope.resolve("sigmas"),this.constantKernel=this.device.scope.resolve("kernel[0]"),this.bZnorm=this.device.scope.resolve("bZnorm")}this.sigmas[0]=t,this.sigmas[1]=e,this.constantSigmas.setValue(this.sigmas),this.evaluateDenoiseUniforms(t,e)}getDenoise(t){let e=t?0:1;return this.shaderDenoise[e]}getDilate(t,e){let s=e?0:1;if(!this.shaderDilate[s]){let i=e?`#define HDR +`:"";this.shaderDilate[s]=Se.createShader(t,{uniqueName:`lmDilate-${e?"hdr":"rgbm"}`,attributes:{vertex_position:ee},vertexGLSL:ne.get(this.device,fe).get("fullscreenQuadVS"),vertexWGSL:ne.get(this.device,se).get("fullscreenQuadVS"),fragmentGLSL:i+ne.get(this.device,fe).get("glslDilatePS"),fragmentWGSL:i+ne.get(this.device,se).get("wgslDilatePS")})}return this.shaderDilate[s]}evaluateDenoiseUniforms(t,e){function s(o,l){return .39894*Math.exp(-.5*o*o/(l*l))/l}this.kernel=this.kernel||new Float32Array(lB);let i=this.kernel,r=Math.floor((lB-1)/2);for(let o=0;o<=r;++o){let l=s(o,t);i[r+o]=l,i[r-o]=l}this.constantKernel.setValue(this.kernel);let a=1/s(0,e);this.bZnorm.setValue(a)}};var f0=class extends yt{constructor(e,s,i,r,a,o){super(e);n(this,"viewBindGroups",[]);this.renderer=s,this.camera=i,this.worldClusters=r,this.receivers=a,this.lightArray=o}destroy(){this.viewBindGroups.forEach(e=>{e.defaultUniformBuffer.destroy(),e.destroy()}),this.viewBindGroups.length=0}execute(){let e=this.device,{renderer:s,camera:i,receivers:r,renderTarget:a,worldClusters:o,lightArray:l}=this;e.supportsUniformBuffers&&!s.viewUniformFormat&&s.initViewBindGroupFormat(s.scene.clusteredLightingEnabled),s.renderForwardLayer(i,a,null,void 0,Sr,this.viewBindGroups,{meshInstances:r,splitLights:l,lightClusters:o})}};var I8=2048,R8=0,b8=1,u0=new x,Em=class{constructor(t,e,s,i,r){this.device=t,this.root=e,this.scene=s,this.renderer=i,this.assets=r,this.shadowMapCache=i.shadowMapCache,this._tempSet=new Set,this._initCalled=!1,this.passMaterials=[],this.ambientAOMaterial=null,this.fog="",this.ambientLight=new F,this.renderTargets=new Map,this.stats={renderPasses:0,lightmapCount:0,totalRenderTime:0,forwardTime:0,fboTime:0,shadowMapTime:0,compileTime:0,shadersLinked:0}}destroy(){yr.decRef(this.blackTex),this.blackTex=null,yr.destroy(),this.device=null,this.root=null,this.scene=null,this.renderer=null,this.assets=null,this.camera?.destroy(),this.camera=null}initBake(t){if(this.bakeHDR=this.scene.lightmapPixelFormat!==ce,!this._initCalled){this._initCalled=!0,this.lightmapFilters=new h0(t),this.constantBakeDir=t.scope.resolve("bakeDir"),this.materials=[],this.blackTex=new Z(this.device,{width:4,height:4,format:ce,type:_i,name:"lightmapBlack"}),yr.incRef(this.blackTex);let e=new Bs(this.device);e.clearColor.set(0,0,0,0),e.clearColorBuffer=!0,e.clearDepthBuffer=!1,e.clearStencilBuffer=!1,e.frustumCulling=!1,e.projection=ni,e.aspectRatio=1,e.node=new Pe,this.camera=e,this.camera.shaderParams.gammaCorrection=Zi,this.camera.shaderParams.toneMapping=Qn}if(this.scene.clusteredLightingEnabled){let e=new zc(t.supportsAreaLights,t.maxTextureSize,()=>{});this.lightingParams=e;let s=this.scene.lighting;e.shadowsEnabled=s.shadowsEnabled,e.shadowAtlasResolution=s.shadowAtlasResolution,e.cookiesEnabled=s.cookiesEnabled,e.cookieAtlasResolution=s.cookieAtlasResolution,e.areaLightsEnabled=s.areaLightsEnabled,e.cells=new x(3,3,3),e.maxLightsPerCell=4,this.worldClusters=new sl(t),this.worldClusters.name="ClusterLightmapper",this.shadowLocalClusteredPass=new Bp(t,this.renderer.shadowRenderer,this.renderer._shadowRendererLocal)}}finishBake(t){this.materials=[];function e(s){yr.decRef(s.colorBuffer),s.destroy()}this.renderTargets.forEach(s=>{e(s)}),this.renderTargets.clear(),t.forEach(s=>{s.renderTargets.forEach(i=>{e(i)}),s.renderTargets.length=0}),this.ambientAOMaterial=null,this.worldClusters&&(this.worldClusters.destroy(),this.worldClusters=null)}createMaterialForPass(t,e,s){let i=new it;return i.name=`lmMaterial-pass:${e}-ambient:${s}`,i.setDefine("UV1LAYOUT",""),i.setDefine("LIT_LIGHTMAP_BAKING",""),e===R8?(i.setDefine("LIT_LIGHTMAP_BAKING_COLOR",""),s?i.setDefine("LIT_LIGHTMAP_BAKING_ADD_AMBIENT",""):i.ambient=new F(0,0,0),this.bakeHDR||i.setDefine("LIGHTMAP_RGBM",""),i.lightMap=this.blackTex):(i.setDefine("LIT_LIGHTMAP_BAKING_DIR",""),i.setDefine("STD_LIGHTMAP_DIR","")),i.cull=0,i.forceUv1=!0,i.update(),i}createMaterials(t,e,s){for(let i=0;i0&&e.push(new nu(t,a))}}for(let r=0;r0){this.renderer.shadowRenderer.frameUpdate();let u=e===zf?2:1;this.setLightmapping(l,!1,u),this.initBake(s),this.bakeInternal(u,l,h);let d=yc;e===zf&&(d|=Ff),this.scene.ambientBake&&(d|=Bf),this.setLightmapping(l,!0,u,d),this.finishBake(l)}let f=Tt();this.stats.totalRenderTime=f-i,this.stats.shadersLinked=s._shaderStats.linked-r,this.stats.compileTime=s._shaderStats.compileTime-o,this.stats.fboTime=s._renderTargetCreationTime-a,this.stats.lightmapCount=l.length}allocateTextures(t,e){for(let s=0;s0){e.copy(t[0].aabb);for(let s=1;s1&&P>1&&v.light.bakeDir&&(P=1);for(let A=0;A1&&v.prepareVirtualLight(A,P),v.startBake();let w=!1,I=this.lightCameraPrepare(a,v);for(T=0;T0&&A>0||E&&g>0);g++){let M=D.renderTargets[g],H=D.renderTargets[g].colorBuffer.width,U=this.renderTargets.get(H),L=U.colorBuffer;g===0?C=i.updateShaders:C&&(i.updateShaders=!0);let b=this.passMaterials[g];for(E&&A+1===P&&g===0&&(b=this.ambientAOMaterial),p=0;p{let r=typeof i=="object"?i.name:i;Object.defineProperty(e,r,{get:function(){return this.data[r]},set:function(a){let o=this.data,l=o[r];o[r]=a,this.fire("set",r,l,a)},configurable:!0})}),e._accessorsBuilt=!0}buildAccessors(e){d0._buildAccessors(this,e)}onSetEnabled(e,s,i){s!==i&&this.entity.enabled&&(i?this.onEnable():this.onDisable())}onEnable(){}onDisable(){}onPostStateChange(){}get data(){let e=this.system.store[this.entity.guid];return e?e.data:null}set enabled(e){}get enabled(){return!0}};n(d0,"order",0);var le=d0;var Fe=class extends J{constructor(e){super();n(this,"id");this.app=e,this.store={},this.schema=[]}addComponent(e,s={}){let i=new this.ComponentType(this,e),r=new this.DataType;return this.store[e.guid]={entity:e,data:r},e[this.id]=i,e.c[this.id]=i,this.initializeComponentData(i,s,[]),this.fire("add",e,i),i}removeComponent(e){let s=this.id,i=this.store[e.guid],r=e.c[s];r.fire("beforeremove"),this.fire("beforeremove",e,r),delete this.store[e.guid],e[s]=void 0,delete e.c[s],this.fire("remove",e,i.data)}cloneComponent(e,s){let i=this.store[e.guid];return this.addComponent(s,i.data)}initializeComponentData(e,s={},i){for(let r=0,a=i.length;r{r&&typeof r=="object"&&r.type===e&&s.push(r)}),s}destroy(){this.off()}};function D8(c,t){if(!c)return c;switch(t){case"rgb":return c instanceof F?c.clone():new F(c[0],c[1],c[2]);case"rgba":return c instanceof F?c.clone():new F(c[0],c[1],c[2],c[3]);case"vec2":return c instanceof B?c.clone():new B(c[0],c[1]);case"vec3":return c instanceof x?c.clone():new x(c[0],c[1],c[2]);case"vec4":return c instanceof Q?c.clone():new Q(c[0],c[1],c[2],c[3]);case"boolean":case"number":case"string":return c;case"entity":return c;default:throw new Error(`Could not convert unhandled type: ${t}`)}}var cB=0,OI=1,FI=2;var p0=class{constructor(){this._left=1/0,this._right=-1/0,this._len=0,this._recip=0,this._p0=0,this._p1=0,this._t=0,this._hermite={valid:!1,p0:0,m0:0,p1:0,m1:0}}update(t,e){if(t=this._right){let s=e.length;if(!s)this._left=-1/0,this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=0;else if(t=e[s-1])this._left=e[s-1],this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=s-1;else{let i=this._findKey(t,e);this._left=e[i],this._right=e[i+1],this._len=this._right-this._left;let r=1/this._len;this._recip=isFinite(r)?r:0,this._p0=i,this._p1=i+1}}this._t=this._recip===0?0:(t-this._left)*this._recip,this._hermite.valid=!1}_findKey(t,e){let s=0;for(;t>=e[s+1];)s++;return s}eval(t,e,s){let i=s._data,r=s._components,a=this._p0*r;if(e===0)for(let o=0;o=t:!1}nextEventBehindTime(t){return this.nextEvent?t===this.track.duration?this.isReverse?this.nextEvent.time>=t:this.nextEvent.time<=t:this.isReverse?this.nextEvent.time>t:this.nextEvent.time=this.track.events.length?this._eventCursor=0:this._eventCursor<0&&(this._eventCursor=this.track.events.length-1)}clipFrameTime(t){let e=MS.eventFrame;e.start=0,e.end=t,e.residual=0,this.isReverse?t<0&&(e.start=this.track.duration,e.end=0,e.residual=t+this.track.duration):t>this.track.duration&&(e.start=0,e.end=this.track.duration,e.residual=t-this.track.duration)}alignCursorToCurrentTime(){for(this.resetEventCursor();this.nextEventBehindTime(this._time)&&this._eventCursor!==this.eventCursorEnd;)this.moveEventCursor()}fireNextEvent(){this._eventHandler.fire(this.nextEvent.name,{track:this.track,...this.nextEvent}),this.moveEventCursor()}fireNextEventInFrame(t,e){return this.nextEventAheadOfTime(t)&&this.nextEventBehindTime(e)?(this.fireNextEvent(),!0):!1}activeEventsForFrame(t,e){let s=MS.eventFrame;this.clipFrameTime(e);let i=this.eventCursor;for(;this.fireNextEventInFrame(t,s.end)&&i!==this.eventCursor;);this.loop&&Math.abs(s.residual)>0&&this.activeEventsForFrame(s.start,s.residual)}progressForTime(t){return t*this._speed/this._track.duration}_update(t){if(this._playing){let e=this._time,s=this._track.duration,i=this._speed,r=this._loop;this._track.events.length>0&&s>0&&this.activeEventsForFrame(e,e+i*t),e+=i*t,i>=0?e>s&&(r?e=e%s||0:(e=this._track.duration,this.pause())):e<0&&(r?e=s+(e%s||0):(e=0,this.pause())),this._time=e}this._time!==this._snapshot._time&&this._track.eval(this._time,this._snapshot)}play(){this._playing=!0,this._time=0}stop(){this._playing=!1,this._time=0}pause(){this._playing=!1}resume(){this._playing=!0}reset(){this._time=0}};n(MS,"eventFrame",{start:0,end:0,residual:0});var th=MS;var Am="NONE",NI="PREV_STATE",BI="NEXT_STATE",UI="PREV_STATE_NEXT_STATE",kI="NEXT_STATE_PREV_STATE",zI="GREATER_THAN",GI="LESS_THAN",VI="GREATER_THAN_EQUAL_TO",HI="LESS_THAN_EQUAL_TO",WI="EQUAL_TO",XI="NOT_EQUAL_TO",m0="INTEGER",_0="FLOAT",g0="BOOLEAN",cu="TRIGGER",hB="1D",YI="2D_DIRECTIONAL",KI="2D_CARTESIAN",jI="DIRECT",hu="START",qI="END",fu="ANY",sh=[hu,"END","ANY"],OS="OVERWRITE",$I="ADDITIVE";var Ir=class c{static dot(t,e){let s=t.length,i=0;for(let r=0;r0){e=1/Math.sqrt(e);let s=t.length;for(let i=0;i0&&(r=1/Math.sqrt(r));for(let a=0;a0;)this.removeClip(0)}updateClipTrack(t,e){this._clips.forEach(s=>{s.name.includes(t)&&(s.track=e)}),this.rebind()}findClip(t){let e=this._clips;for(let s=0;s{this.addClip(e)})}assignMask(t){return this._binder.assignMask(t)}update(t,e=!0){let s=this._clips,i=s.map((o,l)=>l);Ir.stableSort(i,(o,l)=>s[o].blendOrder0&&h._update(t),!e)break;let p,m,_;if(d>=1)for(let S=0;S0)for(let S=0;Se.time-s.time)}get events(){return this._events}};var S0=class S0{constructor(t,e,s,i,r,a=new rh([])){this._name=t,this._duration=e,this._inputs=s,this._outputs=i,this._curves=r,this._animEvents=a}get name(){return this._name}get duration(){return this._duration}get inputs(){return this._inputs}get outputs(){return this._outputs}get curves(){return this._curves}set events(t){this._animEvents=t}get events(){return this._animEvents.events}eval(t,e){e._time=t;let s=this._inputs,i=this._outputs,r=this._curves,a=e._cache,o=e._results;for(let l=0;l0&&s.push(i),s}static encode(t,e,s){return`${Array.isArray(t)?t.join("/"):t}/${e}/${Array.isArray(s)?s.join("/"):s}`}resolve(t){return null}unresolve(t){}update(t){}};var ml=class{constructor(t,e,s,i){t.set?(this._set=t.set,this._get=t.get):this._set=t,this._type=e,this._components=s,this._targetPath=i,this._isTransform=this._targetPath.substring(this._targetPath.length-13)==="localRotation"||this._targetPath.substring(this._targetPath.length-13)==="localPosition"||this._targetPath.substring(this._targetPath.length-10)==="localScale",this._isWeight=this._targetPath.indexOf("weight.")!==-1}get set(){return this._set}get get(){return this._get}get type(){return this._type}get components(){return this._components}get targetPath(){return this._targetPath}get isTransform(){return this._isTransform}get isWeight(){return this._isWeight}get usesLayerBlending(){return this._isTransform||this._isWeight}};var ah=class c{constructor(t){n(this,"_isPathInMask",(t,e)=>{let s=this._mask[t];if(s){if(s.children||e&&s.value!==!1)return!0}else return!1;return!1});if(this.graph=t,!t)return;this._mask=null;let e={},s=function(r){e[r.name]=r;for(let a=0;a0){let h={set:f=>{for(let u=0;u[l[0].getWeight(a)]};return c.createAnimTarget(h,"number",1,r,`weight.${a}`)}return null},materialTexture:(r,a)=>{let o=i(r);if(o){let l;for(let h=0;h{let u=this.animComponent.system.app.assets.get(f[0]);u&&u.resource&&u.type==="texture"&&(l.material[a]=u.resource,l.material.update())};return c.createAnimTarget(h,"vector",1,r,"materialTexture","material")}}return null}}}_isPathActive(t){if(!this._mask)return!0;let e=[t.entityPath[0],this.graph.name];for(let s=0;sr instanceof ae?r.id:r);this.loadAnimationAssets(i)}get assets(){return this._assets}set currentTime(e){if(this.skeleton&&(this.skeleton.currentTime=e,this.skeleton.addTime(0),this.skeleton.updateGraph()),this.animEvaluator){let s=this.animEvaluator.clips;for(let i=0;i0)return e[e.length-1].time}return 0}get duration(){return this.currAnim?this.animations[this.currAnim].duration:0}set loop(e){if(this._loop=e,this.skeleton&&(this.skeleton.looping=e),this.animEvaluator)for(let s=0;s0&&!!this.prevAnim,this.blending&&(this.blend=0,this.blendSpeed=1/s),this.skeleton&&(this.blending?(this.fromSkel.animation=i,this.fromSkel.addTime(this.skeleton._time),this.toSkel.animation=r):this.skeleton.animation=r),this.animEvaluator){let a=this.animEvaluator;if(this.blending)for(;a.clips.length>1;)a.removeClip(0);else this.animEvaluator.removeClips();let o=new th(this.animations[this.currAnim],0,1,!0,this.loop);o.name=this.currAnim,o.blendWeight=this.blending?0:1,o.reset(),this.animEvaluator.addClip(o)}}this.playing=!0}}getAnimation(e){return this.animations[e]}setModel(e){e!==this.model&&(this._resetAnimationController(),this.model=e,this.animations&&this.currAnim&&this.animations[this.currAnim]&&this.play(this.currAnim))}onSetAnimations(){let e=this.entity.model;if(e){let s=e.model;s&&s!==this.model&&this.setModel(s)}if(!this.currAnim&&this.activate&&this.enabled&&this.entity.enabled){let s=Object.keys(this._animations);s.length>0&&this.play(s[0])}}_resetAnimationController(){this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null}_createAnimationController(){let e=this.model,s=this.animations,i=!1,r=!1;for(let o in s)s.hasOwnProperty(o)&&(s[o].constructor===Qs?r=!0:i=!0);let a=e.getGraph();i?(this.fromSkel=new Hc(a),this.toSkel=new Hc(a),this.skeleton=new Hc(a),this.skeleton.looping=this.loop,this.skeleton.setGraph(a)):r&&(this.animEvaluator=new ih(new ah(this.entity)))}loadAnimationAssets(e){if(!e||!e.length)return;let s=this.system.app.assets,i=a=>{if(a.resources.length>1)for(let o=0;o{a.off("change",this.onAssetChanged,this),a.on("change",this.onAssetChanged,this),a.off("remove",this.onAssetRemoved,this),a.on("remove",this.onAssetRemoved,this),a.resource?i(a):(a.once("load",i,this),this.enabled&&this.entity.enabled&&s.load(a))};for(let a=0,o=e.length;a1){if(r&&r.length>1)for(let o=0;o1)for(let o=0;o1)for(let a=0;a1)for(let s=0;s0&&this.play(i[0])}}onBeforeRemove(){for(let e=0;e=1&&(this.blend=1)),this.playing){let i=this.skeleton;if(i!==null&&this.model!==null){if(this.blending)i.blend(this.fromSkel,this.toSkel,this.blend);else{let r=e*this.speed;i.addTime(r),this.speed>0&&i._time===i.animation.duration&&!this.loop?this.playing=!1:this.speed<0&&i._time===0&&!this.loop&&(this.playing=!1)}this.blending&&this.blend===1&&(i.animation=this.toSkel.animation),i.updateGraph()}}let s=this.animEvaluator;if(s){for(let i=0;i1&&(s.clips[1].blendWeight=this.blend),s.update(e)}this.blending&&this.blend===1&&(this.blending=!1)}};var x0=class{constructor(){n(this,"enabled",!0)}};var ZI=["enabled"],Pm=class extends Fe{constructor(t){super(t),this.id="animation",this.ComponentType=uu,this.DataType=x0,this.schema=ZI,this.on("beforeremove",this.onBeforeRemove,this),this.app.systems.on("update",this.onUpdate,this)}initializeComponentData(t,e,s){s=["activate","enabled","loop","speed","assets"];for(let i of s)e.hasOwnProperty(i)&&(t[i]=e[i]);super.initializeComponentData(t,e,ZI)}cloneComponent(t,e){this.addComponent(e,{}),e.animation.assets=t.animation.assets.slice(),e.animation.speed=t.animation.speed,e.animation.loop=t.animation.loop,e.animation.activate=t.animation.activate,e.animation.enabled=t.animation.enabled;let s={},i=t.animation.animations;for(let o in i)i.hasOwnProperty(o)&&(s[o]=i[o]);e.animation.animations=s;let r={},a=t.animation.animationsIndex;for(let o in a)a.hasOwnProperty(o)&&(r[o]=a[o]);return e.animation.animationsIndex=r,e.animation}onBeforeRemove(t,e){e.onBeforeRemove()}onUpdate(t){let e=this.store;for(let s in e)if(e.hasOwnProperty(s)){let i=e[s];i.data.enabled&&i.entity.enabled&&i.entity.animation.update(t)}}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}};le._buildAccessors(uu.prototype,ZI);var Qo=class{constructor(t,e,s,i,r=1){this._state=t,this._parent=e,this._name=s,Array.isArray(i)?(this._point=new B(i[0],i[1]),this._pointLength=this._point.length()):(this._point=i,this._pointLength=i),this._speed=r,this._weightedSpeed=1,this._weight=1,this._animTrack=null}get parent(){return this._parent}get name(){return this._name}get path(){return this._parent?`${this._parent.path}.${this._name}`:this._name}get point(){return this._point}get pointLength(){return this._pointLength}set weight(t){this._weight=t}get weight(){return this._parent?this._parent.weight*this._weight:this._weight}get normalizedWeight(){let t=this._state.totalWeight;return t===0?0:this.weight/t}get speed(){return this._weightedSpeed*this._speed}get absoluteSpeed(){return Math.abs(this._speed)}set weightedSpeed(t){this._weightedSpeed=t}get weightedSpeed(){return this._weightedSpeed}set animTrack(t){this._animTrack=t}get animTrack(){return this._animTrack}};var Jo=class c extends Qo{constructor(t,e,s,i,r,a,o,l,h){super(t,e,s,i),this._parameters=r,this._parameterValues=new Array(r.length),this._children=[],this._findParameter=h,this._syncAnimations=o!==!1,this._pointCache={};for(let f=0;ff.point-u.point),super(t,e,s,i,r,a,o,l,h)}calculateWeights(){if(this.updateParameterValues())return;let t=0;this._children[0].weight=0;for(let e=0;er.path===s);if(i>=0)this._animationList[i].animTrack=e;else{let r=this._getNodeFromPath(t);r.animTrack=e,this._animationList.push(r)}this._updateHasAnimations()}_updateHasAnimations(){this._hasAnimations=this._animationList.length>0&&this._animationList.every(t=>t.animTrack&&t.animTrack!==Qs.EMPTY)}get name(){return this._name}set animations(t){this._animationList=t,this._updateHasAnimations()}get animations(){return this._animationList}get hasAnimations(){return this._hasAnimations}set speed(t){this._speed=t}get speed(){return this._speed}set loop(t){this._loop=t}get loop(){return this._loop}get nodeCount(){return!this._blendTree||this._blendTree.constructor===Qo?1:this._blendTree.getNodeCount()}get playable(){return sh.indexOf(this.name)!==-1||this.animations.length===this.nodeCount}get looping(){if(this.animations.length>0){let t=`${this.name}.${this.animations[0].animTrack.name}`,e=this._controller.animEvaluator.findClip(t);if(e)return e.loop}return!1}get totalWeight(){let t=0;for(let e=0;et&&(t=s.animTrack.duration)}return t}};var oh=class{constructor({from:t,to:e,time:s=0,priority:i=0,conditions:r=[],exitTime:a=null,transitionOffset:o=null,interruptionSource:l=Am}){this._from=t,this._to=e,this._time=s,this._priority=i,this._conditions=r,this._exitTime=a,this._transitionOffset=o,this._interruptionSource=l}get from(){return this._from}set to(t){this._to=t}get to(){return this._to}get time(){return this._time}get priority(){return this._priority}get conditions(){return this._conditions}get exitTime(){return this._exitTime}get transitionOffset(){return this._transitionOffset}get interruptionSource(){return this._interruptionSource}get hasExitTime(){return!!this.exitTime}};var wm=class{constructor(t,e,s,i,r,a,o){n(this,"_states",{});n(this,"_stateNames",[]);n(this,"_findTransitionsFromStateCache",{});n(this,"_findTransitionsBetweenStatesCache",{});n(this,"_previousStateName",null);n(this,"_activeStateName",hu);n(this,"_activeStateDuration",0);n(this,"_activeStateDurationDirty",!0);n(this,"_playing",!1);n(this,"_activate");n(this,"_transitions");n(this,"_currTransitionTime",1);n(this,"_totalTransitionTime",1);n(this,"_isTransitioning",!1);n(this,"_transitionInterruptionSource",Am);n(this,"_transitionPreviousStates",[]);n(this,"_timeInState",0);n(this,"_timeInStateBefore",0);n(this,"findParameter",t=>this._findParameter(t));this._animEvaluator=t,this._eventHandler=r,this._findParameter=a,this._consumeTrigger=o;for(let l=0;lnew oh({...l})),this._activate=i}get animEvaluator(){return this._animEvaluator}set activeState(t){this._activeStateName=t}get activeState(){return this._findState(this._activeStateName)}get activeStateName(){return this._activeStateName}get activeStateAnimations(){return this.activeState.animations}set previousState(t){this._previousStateName=t}get previousState(){return this._findState(this._previousStateName)}get previousStateName(){return this._previousStateName}get playable(){let t=!0;for(let e=0;es.from===t),Uc(e),this._findTransitionsFromStateCache[t]=e),e}_findTransitionsBetweenStates(t,e){let s=this._findTransitionsBetweenStatesCache[`${t}->${e}`];return s||(s=this._transitions.filter(i=>i.from===t&&i.to===e),Uc(s),this._findTransitionsBetweenStatesCache[`${t}->${e}`]=s),s}_transitionHasConditionsMet(t){let e=t.conditions;for(let s=0;si.value))return!1;break;case GI:if(!(r.value=i.value))return!1;break;case HI:if(!(r.value<=i.value))return!1;break;case WI:if(r.value!==i.value)return!1;break;case XI:if(r.value===i.value)return!1;break}}return!0}_findTransition(t,e){let s=[];if(t&&e)s=s.concat(this._findTransitionsBetweenStates(t,e));else if(!this._isTransitioning)s=s.concat(this._findTransitionsFromState(this._activeStateName)),s=s.concat(this._findTransitionsFromState("ANY"));else switch(this._transitionInterruptionSource){case NI:s=s.concat(this._findTransitionsFromState(this._previousStateName)),s=s.concat(this._findTransitionsFromState("ANY"));break;case BI:s=s.concat(this._findTransitionsFromState(this._activeStateName)),s=s.concat(this._findTransitionsFromState("ANY"));break;case UI:s=s.concat(this._findTransitionsFromState(this._previousStateName)),s=s.concat(this._findTransitionsFromState(this._activeStateName)),s=s.concat(this._findTransitionsFromState("ANY"));break;case kI:s=s.concat(this._findTransitionsFromState(this._activeStateName)),s=s.concat(this._findTransitionsFromState(this._previousStateName)),s=s.concat(this._findTransitionsFromState("ANY"));break;case Am:default:}if(s=s.filter(i=>{if(i.to===this.activeStateName)return!1;if(i.hasExitTime){let r=this._getActiveStateProgressForTime(this._timeInStateBefore),a=this._getActiveStateProgressForTime(this._timeInState);if(i.exitTime<1&&this.activeState.loop&&(r-=Math.floor(r),a-=Math.floor(a)),a===r){if(a!==i.exitTime)return null}else if(!(i.exitTime>r&&i.exitTime<=a))return null}return this._transitionHasConditionsMet(i)}),s.length>0){let i=s[0];if(i.to==="END"){let r=this._findTransitionsFromState(hu)[0];i.to=r.to}return i}return null}updateStateFromTransition(t){let e,s,i;this.previousState=t.from?this.activeStateName:null,this.activeState=t.to,this._activeStateDurationDirty=!0;for(let h=0;h0&&t.transitionOffset<1,o=0,l=0;if(a){let h=r.timelineDuration*t.transitionOffset;o=h,l=h}this._timeInState=o,this._timeInStateBefore=l;for(let h=0;h0?i.blendWeight=0:i.blendWeight=r.animations[h].normalizedWeight,i.play(),a)i.time=r.timelineDuration*t.transitionOffset;else{let f=r.speed>=0?0:this.activeStateDuration;i.time=f}}}_transitionToState(t){if(!this._findState(t))return;let e=this._findTransition(this._activeStateName,t);e||(this._animEvaluator.removeClips(),e=new oh({from:null,to:t})),this.updateStateFromTransition(e)}assignAnimation(t,e,s,i){let r=t.split("."),a=this._findState(r[0]);a||(a=new FS(this,r[0],s),this._states[r[0]]=a,this._stateNames.push(r[0])),a.addAnimation(r,e),this._animEvaluator.updateClipTrack(a.name,e),s!==void 0&&(a.speed=s),i!==void 0&&(a.loop=i),!this._playing&&this._activate&&this.playable&&this.play(),this._activeStateDurationDirty=!0}removeNodeAnimations(t){if(sh.indexOf(t)!==-1)return!1;let e=this._findState(t);return e?(e.animations=[],!0):!1}play(t){t&&this._transitionToState(t),this._playing=!0}pause(){this._playing=!1}reset(){this._previousStateName=null,this._activeStateName=hu,this._playing=!1,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=!1,this._timeInState=0,this._timeInStateBefore=0,this._animEvaluator.removeClips()}rebind(){this._animEvaluator.rebind()}update(t){if(!this._playing)return;let e,s,i;(this.activeState.loop||this._timeInStatethis.activeStateDuration&&(this._timeInState=this.activeStateDuration,t=this.activeStateDuration-this._timeInStateBefore));let r=this._findTransition(this._activeStateName);if(r&&this.updateStateFromTransition(r),this._isTransitioning)if(this._currTransitionTime+=t,this._currTransitionTime<=this._totalTransitionTime){let a=this._totalTransitionTime!==0?this._currTransitionTime/this._totalTransitionTime:1;for(let o=0;o{f(s(u))},get:()=>h}}let o=i[r];if(typeof o=="object"&&o.hasOwnProperty("copy"))return function(l){o.copy(s(l))};if([B,x,Q,F,$].indexOf(i.constructor)!==-1&&e.length>1){let l=e.length>2?this._resolvePath(t,e.slice(0,-1)):t,h=e[e.length-2];return function(f){i[r]=s(f),l[h]=i}}return function(l){i[r]=s(l)}}_createAnimTargetForProperty(t,e,s){if(this.handlers&&e[0].startsWith("weight."))return this.handlers.weight(t,e[0].replace("weight.",""));if(this.handlers&&e[0]==="material"&&e.length===2){let l=e[1];if(l.endsWith("Map"))return this.handlers.materialTexture(t,l)}let i=this._resolvePath(t,e,!0);if(typeof i>"u")return null;let r,a,o;if(typeof i=="number")r=this._setter(t,e,c._packFloat),a="vector",o=1;else if(typeof i=="boolean")r=this._setter(t,e,c._packBoolean),a="vector",o=1;else if(typeof i=="object")switch(i.constructor){case B:r=this._setter(t,e,c._packVec2),a="vector",o=2;break;case x:r=this._setter(t,e,c._packVec3),a="vector",o=3;break;case Q:r=this._setter(t,e,c._packVec4),a="vector",o=4;break;case F:r=this._setter(t,e,c._packColor),a="vector",o=4;break;case $:r=this._setter(t,e,c._packQuat),a="quaternion",o=4;break;default:return null}return e.indexOf("material")!==-1?new ml(l=>{r(l),t.material.update()},a,o,s):new ml(r,a,o,s)}rebind(){this.targetCache={},this.animComponent.rootBone?this.graph=this.animComponent.rootBone:this.graph=this.animComponent.entity;let t={},e=function(s){t[s.name]=s;for(let i=0;ithis._parameters[e]);n(this,"consumeTrigger",e=>{this._consumedTriggers.add(e)})}set stateGraphAsset(e){if(e===null){this.removeStateGraph();return}this._stateGraphAsset&&this.system.app.assets.get(this._stateGraphAsset).off("change",this._onStateGraphAssetChangeEvent,this);let s,i;e instanceof ae?(s=e.id,i=this.system.app.assets.get(s),i||(this.system.app.assets.add(e),i=this.system.app.assets.get(s))):(s=e,i=this.system.app.assets.get(s)),!(!i||this._stateGraphAsset===s)&&(i.resource?(this._stateGraph=i.resource,this.loadStateGraph(this._stateGraph),i.on("change",this._onStateGraphAssetChangeEvent,this)):(i.once("load",r=>{this._stateGraph=r.resource,this.loadStateGraph(this._stateGraph)}),i.on("change",this._onStateGraphAssetChangeEvent,this),this.system.app.assets.load(i)),this._stateGraphAsset=s)}get stateGraphAsset(){return this._stateGraphAsset}set normalizeWeights(e){this._normalizeWeights=e,this.unbind()}get normalizeWeights(){return this._normalizeWeights}set animationAssets(e){this._animationAssets=e,this.loadAnimationAssets()}get animationAssets(){return this._animationAssets}set speed(e){this._speed=e}get speed(){return this._speed}set activate(e){this._activate=e}get activate(){return this._activate}set playing(e){this._playing=e}get playing(){return this._playing}set rootBone(e){if(typeof e=="string"){let s=this.entity.root.findByGuid(e);this._rootBone=s}else e instanceof Ne?this._rootBone=e:this._rootBone=null;this.rebind()}get rootBone(){return this._rootBone}set stateGraph(e){this._stateGraph=e}get stateGraph(){return this._stateGraph}get layers(){return this._layers}set layerIndices(e){this._layerIndices=e}get layerIndices(){return this._layerIndices}set parameters(e){this._parameters=e}get parameters(){return this._parameters}set targets(e){this._targets=e}get targets(){return this._targets}get playable(){for(let e=0;e0?this._layers[0]:null}_onStateGraphAssetChangeEvent(e){let s=this.animationAssets,i=this.layers.map(r=>r.mask);this.removeStateGraph(),this._stateGraph=new en(e._data),this.loadStateGraph(this._stateGraph),this.animationAssets=s,this.loadAnimationAssets(),this.layers.forEach((r,a)=>{r.mask=i[a]}),this.rebind()}dirtifyTargets(){let e=Object.values(this._targets);for(let s=0;sa.blendTree)&&(s=!0)}s||this.setupAnimationAssets()}setupAnimationAssets(){for(let e=0;e{this._targets[e].unbind()})}rebind(){this._targets={};for(let e=0;e{this.parameters[s].value=!1}),this._consumedTriggers.clear()}resolveDuplicatedEntityReferenceProperties(e,s){e.rootBone&&s[e.rootBone.guid]?this.rootBone=s[e.rootBone.guid]:this.rebind()}};var P0=class{constructor(){n(this,"enabled",!0)}};var JI=["enabled"],Rm=class extends Fe{constructor(t){super(t),this.id="anim",this.ComponentType=du,this.DataType=P0,this.schema=JI,this.on("beforeremove",this.onBeforeRemove,this),this.app.systems.on("animationUpdate",this.onAnimationUpdate,this)}initializeComponentData(t,e,s){super.initializeComponentData(t,e,JI);let i=["animationAssets","stateGraph","layers","masks"];Object.keys(e).forEach(r=>{i.includes(r)||(t[r]=e[r])}),e.stateGraph&&(t.stateGraph=e.stateGraph,t.loadStateGraph(t.stateGraph)),e.layers&&e.layers.forEach((r,a)=>{r._controller.states.forEach(o=>{r._controller._states[o]._animationList.forEach(l=>{if(!l.animTrack||l.animTrack===Qs.EMPTY){let h=this.app.assets.get(r._component._animationAssets[`${r.name}:${l.name}`].asset);h&&!h.loaded&&h.once("load",()=>{t.layers[a].assignAnimation(l.name,h.resource)})}else t.layers[a].assignAnimation(l.name,l.animTrack)})})}),e.animationAssets&&(t.animationAssets=Object.assign(t.animationAssets,e.animationAssets)),e.masks&&Object.keys(e.masks).forEach(r=>{if(t.layers[r]){let a=e.masks[r].mask,o={};Object.keys(a).forEach(l=>{o[decodeURI(l)]=a[l]}),t.layers[r].mask=o}})}onAnimationUpdate(t){let e=this.store;for(let s in e)if(e.hasOwnProperty(s)){let i=e[s].entity.anim;i.data.enabled&&i.entity.enabled&&i.playing&&i.update(t)}}cloneComponent(t,e){let s;(!t.anim.rootBone||t.anim.rootBone===t)&&(s={},t.anim.layers.forEach((r,a)=>{if(r.mask){let o={};Object.keys(r.mask).forEach(l=>{let h=l.split("/");h.shift();let f=[e.name,...h].join("/");o[f]=r.mask[l]}),s[a]={mask:o}}}));let i={enabled:t.anim.enabled,stateGraphAsset:t.anim.stateGraphAsset,animationAssets:t.anim.animationAssets,speed:t.anim.speed,activate:t.anim.activate,playing:t.anim.playing,rootBone:t.anim.rootBone,stateGraph:t.anim.stateGraph,layers:t.anim.layers,layerIndices:t.anim.layerIndices,parameters:t.anim.parameters,normalizeWeights:t.anim.normalizeWeights,masks:s};return this.addComponent(e,i)}onBeforeRemove(t,e){e.onBeforeRemove()}destroy(){super.destroy(),this.app.systems.off("animationUpdate",this.onAnimationUpdate,this)}};le._buildAccessors(du.prototype,JI);var pu=class extends le{setCurrentListener(){if(this.enabled&&this.entity.audiolistener&&this.entity.enabled){this.system.current=this.entity;let t=this.system.current.getPosition();this.system.manager.listener.setPosition(t)}}onEnable(){this.setCurrentListener()}onDisable(){this.system.current===this.entity&&(this.system.current=null)}};var w0=class{constructor(){n(this,"enabled",!0)}};var fB=["enabled"],bm=class extends Fe{constructor(t){super(t),this.id="audiolistener",this.ComponentType=pu,this.DataType=w0,this.schema=fB,this.manager=t.soundManager,this.current=null,this.app.systems.on("update",this.onUpdate,this)}initializeComponentData(t,e,s){s=["enabled"],super.initializeComponentData(t,e,s)}onUpdate(t){if(this.current){let e=this.current.getPosition();this.manager.listener.setPosition(e);let s=this.current.getWorldTransform();this.manager.listener.setOrientation(s)}}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}};le._buildAccessors(pu.prototype,fB);var eR=0,uB=1;var mu="group",Dm="image",kS="text",_u="stretch",tR="contain",sR="cover";var us={DEFAULT:"DEFAULT",HOVER:"HOVER",PRESSED:"PRESSED",INACTIVE:"INACTIVE"},zS={};zS[us.DEFAULT]="_defaultTint";zS[us.HOVER]="hoverTint";zS[us.PRESSED]="pressedTint";zS[us.INACTIVE]="inactiveTint";var GS={};GS[us.DEFAULT]="_defaultSpriteAsset";GS[us.HOVER]="hoverSpriteAsset";GS[us.PRESSED]="pressedSpriteAsset";GS[us.INACTIVE]="inactiveSpriteAsset";var VS={};VS[us.DEFAULT]="_defaultSpriteFrame";VS[us.HOVER]="hoverSpriteFrame";VS[us.PRESSED]="pressedSpriteFrame";VS[us.INACTIVE]="inactiveSpriteFrame";var es=class extends le{constructor(e,s){super(e,s);n(this,"_visualState",us.DEFAULT);n(this,"_isHovering",!1);n(this,"_hoveringCounter",0);n(this,"_isPressed",!1);n(this,"_defaultTint",new F(1,1,1,1));n(this,"_defaultSpriteAsset",null);n(this,"_defaultSpriteFrame",0);n(this,"_imageEntity",null);n(this,"_evtElementAdd",null);n(this,"_evtImageEntityElementAdd",null);n(this,"_evtImageEntityElementRemove",null);n(this,"_evtImageEntityElementColor",null);n(this,"_evtImageEntityElementOpacity",null);n(this,"_evtImageEntityElementSpriteAsset",null);n(this,"_evtImageEntityElementSpriteFrame",null);this._toggleLifecycleListeners("on",e)}set enabled(e){this._setValue("enabled",e)}get enabled(){return this.data.enabled}set active(e){this._setValue("active",e)}get active(){return this.data.active}set imageEntity(e){if(this._imageEntity!==e){let s=typeof e=="string";if(this._imageEntity&&s&&this._imageEntity.guid===e)return;this._imageEntity&&this._imageEntityUnsubscribe(),e instanceof Pe?this._imageEntity=e:s?this._imageEntity=this.system.app.getEntityFromIndex(e)||null:this._imageEntity=null,this._imageEntity&&this._imageEntitySubscribe(),this._imageEntity?this.data.imageEntity=this._imageEntity.guid:s&&e&&(this.data.imageEntity=e)}}get imageEntity(){return this._imageEntity}set hitPadding(e){this._setValue("hitPadding",e)}get hitPadding(){return this.data.hitPadding}set transitionMode(e){this._setValue("transitionMode",e)}get transitionMode(){return this.data.transitionMode}set hoverTint(e){this._setValue("hoverTint",e)}get hoverTint(){return this.data.hoverTint}set pressedTint(e){this._setValue("pressedTint",e)}get pressedTint(){return this.data.pressedTint}set inactiveTint(e){this._setValue("inactiveTint",e)}get inactiveTint(){return this.data.inactiveTint}set fadeDuration(e){this._setValue("fadeDuration",e)}get fadeDuration(){return this.data.fadeDuration}set hoverSpriteAsset(e){this._setValue("hoverSpriteAsset",e)}get hoverSpriteAsset(){return this.data.hoverSpriteAsset}set hoverSpriteFrame(e){this._setValue("hoverSpriteFrame",e)}get hoverSpriteFrame(){return this.data.hoverSpriteFrame}set pressedSpriteAsset(e){this._setValue("pressedSpriteAsset",e)}get pressedSpriteAsset(){return this.data.pressedSpriteAsset}set pressedSpriteFrame(e){this._setValue("pressedSpriteFrame",e)}get pressedSpriteFrame(){return this.data.pressedSpriteFrame}set inactiveSpriteAsset(e){this._setValue("inactiveSpriteAsset",e)}get inactiveSpriteAsset(){return this.data.inactiveSpriteAsset}set inactiveSpriteFrame(e){this._setValue("inactiveSpriteFrame",e)}get inactiveSpriteFrame(){return this.data.inactiveSpriteFrame}_setValue(e,s){let i=this.data,r=i[e];i[e]=s,this.fire("set",e,r,s)}_toggleLifecycleListeners(e,s){this[e]("set_active",this._onSetActive,this),this[e]("set_transitionMode",this._onSetTransitionMode,this),this[e]("set_hoverTint",this._onSetTransitionValue,this),this[e]("set_pressedTint",this._onSetTransitionValue,this),this[e]("set_inactiveTint",this._onSetTransitionValue,this),this[e]("set_hoverSpriteAsset",this._onSetTransitionValue,this),this[e]("set_hoverSpriteFrame",this._onSetTransitionValue,this),this[e]("set_pressedSpriteAsset",this._onSetTransitionValue,this),this[e]("set_pressedSpriteFrame",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteAsset",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteFrame",this._onSetTransitionValue,this),e==="on"?this._evtElementAdd=this.entity.on("element:add",this._onElementComponentAdd,this):(this._evtElementAdd?.off(),this._evtElementAdd=null)}_onSetActive(e,s,i){s!==i&&this._updateVisualState()}_onSetTransitionMode(e,s,i){s!==i&&(this._cancelTween(),this._resetToDefaultVisualState(s),this._forceReapplyVisualState())}_onSetTransitionValue(e,s,i){s!==i&&this._forceReapplyVisualState()}_imageEntitySubscribe(){this._evtImageEntityElementAdd=this._imageEntity.on("element:add",this._onImageElementGain,this),this._imageEntity.element&&this._onImageElementGain()}_imageEntityUnsubscribe(){this._evtImageEntityElementAdd?.off(),this._evtImageEntityElementAdd=null,this._imageEntity?.element&&this._onImageElementLose()}_imageEntityElementSubscribe(){let e=this._imageEntity.element;this._evtImageEntityElementRemove=e.once("beforeremove",this._onImageElementLose,this),this._evtImageEntityElementColor=e.on("set:color",this._onSetColor,this),this._evtImageEntityElementOpacity=e.on("set:opacity",this._onSetOpacity,this),this._evtImageEntityElementSpriteAsset=e.on("set:spriteAsset",this._onSetSpriteAsset,this),this._evtImageEntityElementSpriteFrame=e.on("set:spriteFrame",this._onSetSpriteFrame,this)}_imageEntityElementUnsubscribe(){this._evtImageEntityElementRemove?.off(),this._evtImageEntityElementRemove=null,this._evtImageEntityElementColor?.off(),this._evtImageEntityElementColor=null,this._evtImageEntityElementOpacity?.off(),this._evtImageEntityElementOpacity=null,this._evtImageEntityElementSpriteAsset?.off(),this._evtImageEntityElementSpriteAsset=null,this._evtImageEntityElementSpriteFrame?.off(),this._evtImageEntityElementSpriteFrame=null}_onElementComponentRemove(){this._toggleHitElementListeners("off")}_onElementComponentAdd(){this._toggleHitElementListeners("on")}_onImageElementLose(){this._imageEntityElementUnsubscribe(),this._cancelTween(),this._resetToDefaultVisualState(this.transitionMode)}_onImageElementGain(){this._imageEntityElementSubscribe(),this._storeDefaultVisualState(),this._forceReapplyVisualState()}_toggleHitElementListeners(e){if(this.entity.element){let s=e==="on";if(s&&this._hasHitElementListeners)return;this.entity.element[e]("beforeremove",this._onElementComponentRemove,this),this.entity.element[e]("mouseenter",this._onMouseEnter,this),this.entity.element[e]("mouseleave",this._onMouseLeave,this),this.entity.element[e]("mousedown",this._onMouseDown,this),this.entity.element[e]("mouseup",this._onMouseUp,this),this.entity.element[e]("touchstart",this._onTouchStart,this),this.entity.element[e]("touchend",this._onTouchEnd,this),this.entity.element[e]("touchleave",this._onTouchLeave,this),this.entity.element[e]("touchcancel",this._onTouchCancel,this),this.entity.element[e]("selectstart",this._onSelectStart,this),this.entity.element[e]("selectend",this._onSelectEnd,this),this.entity.element[e]("selectenter",this._onSelectEnter,this),this.entity.element[e]("selectleave",this._onSelectLeave,this),this.entity.element[e]("click",this._onClick,this),this._hasHitElementListeners=s}}_storeDefaultVisualState(){let e=this._imageEntity?.element;!e||e.type===mu||(this._storeDefaultColor(e.color),this._storeDefaultOpacity(e.opacity),this._storeDefaultSpriteAsset(e.spriteAsset),this._storeDefaultSpriteFrame(e.spriteFrame))}_storeDefaultColor(e){this._defaultTint.r=e.r,this._defaultTint.g=e.g,this._defaultTint.b=e.b}_storeDefaultOpacity(e){this._defaultTint.a=e}_storeDefaultSpriteAsset(e){this._defaultSpriteAsset=e}_storeDefaultSpriteFrame(e){this._defaultSpriteFrame=e}_onSetColor(e){this._isApplyingTint||(this._storeDefaultColor(e),this._forceReapplyVisualState())}_onSetOpacity(e){this._isApplyingTint||(this._storeDefaultOpacity(e),this._forceReapplyVisualState())}_onSetSpriteAsset(e){this._isApplyingSprite||(this._storeDefaultSpriteAsset(e),this._forceReapplyVisualState())}_onSetSpriteFrame(e){this._isApplyingSprite||(this._storeDefaultSpriteFrame(e),this._forceReapplyVisualState())}_onMouseEnter(e){this._isHovering=!0,this._updateVisualState(),this._fireIfActive("mouseenter",e)}_onMouseLeave(e){this._isHovering=!1,this._isPressed=!1,this._updateVisualState(),this._fireIfActive("mouseleave",e)}_onMouseDown(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("mousedown",e)}_onMouseUp(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("mouseup",e)}_onTouchStart(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("touchstart",e)}_onTouchEnd(e){e.event.preventDefault(),this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchend",e)}_onTouchLeave(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchleave",e)}_onTouchCancel(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchcancel",e)}_onSelectStart(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("selectstart",e)}_onSelectEnd(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("selectend",e)}_onSelectEnter(e){this._hoveringCounter++,this._hoveringCounter===1&&(this._isHovering=!0,this._updateVisualState()),this._fireIfActive("selectenter",e)}_onSelectLeave(e){this._hoveringCounter--,this._hoveringCounter===0&&(this._isHovering=!1,this._isPressed=!1,this._updateVisualState()),this._fireIfActive("selectleave",e)}_onClick(e){this._fireIfActive("click",e)}_fireIfActive(e,s){this.data.active&&this.fire(e,s)}_updateVisualState(e){let s=this._visualState,i=this._determineVisualState();if((s!==i||e)&&this.enabled)switch(this._visualState=i,s===us.HOVER&&this._fireIfActive("hoverend"),s===us.PRESSED&&this._fireIfActive("pressedend"),i===us.HOVER&&this._fireIfActive("hoverstart"),i===us.PRESSED&&this._fireIfActive("pressedstart"),this.transitionMode){case 0:{let r=zS[this._visualState],a=this[r];this._applyTint(a);break}case 1:{let r=GS[this._visualState],a=VS[this._visualState],o=this[r],l=this[a];this._applySprite(o,l);break}}}_forceReapplyVisualState(){this._updateVisualState(!0)}_resetToDefaultVisualState(e){if(this._imageEntity?.element)switch(e){case 0:this._cancelTween(),this._applyTintImmediately(this._defaultTint);break;case 1:this._applySprite(this._defaultSpriteAsset,this._defaultSpriteFrame);break}}_determineVisualState(){if(this.active){if(this._isPressed)return us.PRESSED;if(this._isHovering)return us.HOVER}else return us.INACTIVE;return us.DEFAULT}_applySprite(e,s){let i=this._imageEntity?.element;i&&(s=s||0,this._isApplyingSprite=!0,i.spriteAsset!==e&&(i.spriteAsset=e),i.spriteFrame!==s&&(i.spriteFrame=s),this._isApplyingSprite=!1)}_applyTint(e){this._cancelTween(),this.fadeDuration===0?this._applyTintImmediately(e):this._applyTintWithTween(e)}_applyTintImmediately(e){let s=this._imageEntity?.element;if(!e||!s||s.type===mu)return;let i=dB(e);this._isApplyingTint=!0,i.equals(s.color)||(s.color=i),s.opacity!==e.a&&(s.opacity=e.a),this._isApplyingTint=!1}_applyTintWithTween(e){let s=this._imageEntity?.element;if(!e||!s||s.type===mu)return;let i=dB(e),r=s.color,a=s.opacity;i.equals(r)&&e.a===a||(this._tweenInfo={startTime:Tt(),from:new F(r.r,r.g,r.b,a),to:e.clone(),lerpColor:new F})}_updateTintTween(){let e=Tt()-this._tweenInfo.startTime,s=this.fadeDuration===0?1:e/this.fadeDuration;if(s=R.clamp(s,0,1),Math.abs(s-1)>1e-5){let i=this._tweenInfo.lerpColor;i.lerp(this._tweenInfo.from,this._tweenInfo.to,s),this._applyTintImmediately(new F(i.r,i.g,i.b,i.a))}else this._applyTintImmediately(this._tweenInfo.to),this._cancelTween()}_cancelTween(){delete this._tweenInfo}onUpdate(){this._tweenInfo&&this._updateTintTween()}onEnable(){this._isHovering=!1,this._hoveringCounter=0,this._isPressed=!1,this._toggleHitElementListeners("on"),this._forceReapplyVisualState()}onDisable(){this._toggleHitElementListeners("off"),this._resetToDefaultVisualState(this.transitionMode)}onRemove(){this._imageEntityUnsubscribe(),this._toggleLifecycleListeners("off",this.system),this.onDisable()}resolveDuplicatedEntityReferenceProperties(e,s){e.imageEntity&&(this.imageEntity=s[e.imageEntity.guid])}};n(es,"EVENT_MOUSEDOWN","mousedown"),n(es,"EVENT_MOUSEUP","mouseup"),n(es,"EVENT_MOUSEENTER","mouseenter"),n(es,"EVENT_MOUSELEAVE","mouseleave"),n(es,"EVENT_CLICK","click"),n(es,"EVENT_TOUCHSTART","touchstart"),n(es,"EVENT_TOUCHEND","touchend"),n(es,"EVENT_TOUCHCANCEL","touchcancel"),n(es,"EVENT_TOUCHLEAVE","touchleave"),n(es,"EVENT_SELECTSTART","selectstart"),n(es,"EVENT_SELECTEND","selectend"),n(es,"EVENT_SELECTENTER","selectenter"),n(es,"EVENT_SELECTLEAVE","selectleave"),n(es,"EVENT_HOVERSTART","hoverstart"),n(es,"EVENT_HOVEREND","hoverend"),n(es,"EVENT_PRESSEDSTART","pressedstart"),n(es,"EVENT_PRESSEDEND","pressedend");function dB(c){return new F(c.r,c.g,c.b)}var I0=class{constructor(){n(this,"enabled",!0);n(this,"active",!0);n(this,"imageEntity",null);n(this,"hitPadding",new Q);n(this,"transitionMode",0);n(this,"hoverTint",new F(.75,.75,.75));n(this,"pressedTint",new F(.5,.5,.5));n(this,"inactiveTint",new F(.25,.25,.25));n(this,"fadeDuration",0);n(this,"hoverSpriteAsset",null);n(this,"hoverSpriteFrame",0);n(this,"pressedSpriteAsset",null);n(this,"pressedSpriteFrame",0);n(this,"inactiveSpriteAsset",null);n(this,"inactiveSpriteFrame",0)}};var pB=["enabled","active",{name:"hitPadding",type:"vec4"},"transitionMode",{name:"hoverTint",type:"rgba"},{name:"pressedTint",type:"rgba"},{name:"inactiveTint",type:"rgba"},"fadeDuration","hoverSpriteAsset","hoverSpriteFrame","pressedSpriteAsset","pressedSpriteFrame","inactiveSpriteAsset","inactiveSpriteFrame"],Lm=class extends Fe{constructor(t){super(t),this.id="button",this.ComponentType=es,this.DataType=I0,this.schema=pB,this.on("beforeremove",this._onRemoveComponent,this),this.app.systems.on("update",this.onUpdate,this)}initializeComponentData(t,e,s){t.imageEntity=e.imageEntity,super.initializeComponentData(t,e,pB)}onUpdate(t){let e=this.store;for(let s in e){let i=e[s].entity,r=i.button;r.enabled&&i.enabled&&r.onUpdate()}}_onRemoveComponent(t,e){e.onRemove()}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}};var mB=new x,_B=new $,eo=class extends le{constructor(e,s){super(e,s);n(this,"_compoundParent",null);n(this,"_hasOffset",!1);this.entity.on("insert",this._onInsert,this),this.on("set_type",this.onSetType,this),this.on("set_convexHull",this.onSetModel,this),this.on("set_halfExtents",this.onSetHalfExtents,this),this.on("set_linearOffset",this.onSetOffset,this),this.on("set_angularOffset",this.onSetOffset,this),this.on("set_radius",this.onSetRadius,this),this.on("set_height",this.onSetHeight,this),this.on("set_axis",this.onSetAxis,this),this.on("set_asset",this.onSetAsset,this),this.on("set_renderAsset",this.onSetRenderAsset,this),this.on("set_model",this.onSetModel,this),this.on("set_render",this.onSetRender,this)}set enabled(e){this._setValue("enabled",e)}get enabled(){return this.data.enabled}set type(e){this._setValue("type",e)}get type(){return this.data.type}set halfExtents(e){this._setValue("halfExtents",e)}get halfExtents(){return this.data.halfExtents}set linearOffset(e){this._setValue("linearOffset",e)}get linearOffset(){return this.data.linearOffset}set angularOffset(e){this._setValue("angularOffset",e)}get angularOffset(){return this.data.angularOffset}set radius(e){this._setValue("radius",e)}get radius(){return this.data.radius}set axis(e){this._setValue("axis",e)}get axis(){return this.data.axis}set height(e){this._setValue("height",e)}get height(){return this.data.height}set asset(e){this._setValue("asset",e)}get asset(){return this.data.asset}set renderAsset(e){this._setValue("renderAsset",e)}get renderAsset(){return this.data.renderAsset}set convexHull(e){this._setValue("convexHull",e)}get convexHull(){return this.data.convexHull}set shape(e){this._setValue("shape",e)}get shape(){return this.data.shape}set model(e){this._setValue("model",e)}get model(){return this.data.model}set render(e){this._setValue("render",e)}get render(){return this.data.render}set checkVertexDuplicates(e){this._setValue("checkVertexDuplicates",e)}get checkVertexDuplicates(){return this.data.checkVertexDuplicates}_setValue(e,s){let i=this.data,r=i[e];i[e]=s,this.fire("set",e,r,s)}onSetType(e,s,i){s!==i&&this.system.changeType(this,s,i)}onSetHalfExtents(e,s,i){let r=this.data.type;this.data.initialized&&r==="box"&&this.system.recreatePhysicalShapes(this)}onSetOffset(e,s,i){this._hasOffset=!this.data.linearOffset.equals(x.ZERO)||!this.data.angularOffset.equals($.IDENTITY),this.data.initialized&&this.system.recreatePhysicalShapes(this)}onSetRadius(e,s,i){let r=this.data.type;this.data.initialized&&(r==="sphere"||r==="capsule"||r==="cylinder"||r==="cone")&&this.system.recreatePhysicalShapes(this)}onSetHeight(e,s,i){let r=this.data.type;this.data.initialized&&(r==="capsule"||r==="cylinder"||r==="cone")&&this.system.recreatePhysicalShapes(this)}onSetAxis(e,s,i){let r=this.data.type;this.data.initialized&&(r==="capsule"||r==="cylinder"||r==="cone")&&this.system.recreatePhysicalShapes(this)}onSetAsset(e,s,i){let r=this.system.app.assets;if(s){let a=r.get(s);a&&a.off("remove",this.onAssetRemoved,this)}if(i){i instanceof ae&&(this.data.asset=i.id);let a=r.get(this.data.asset);a&&(a.off("remove",this.onAssetRemoved,this),a.on("remove",this.onAssetRemoved,this))}this.data.initialized&&this.data.type==="mesh"&&(i||(this.data.model=null),this.system.recreatePhysicalShapes(this))}onSetRenderAsset(e,s,i){let r=this.system.app.assets;if(s){let a=r.get(s);a&&a.off("remove",this.onRenderAssetRemoved,this)}if(i){i instanceof ae&&(this.data.renderAsset=i.id);let a=r.get(this.data.renderAsset);a&&(a.off("remove",this.onRenderAssetRemoved,this),a.on("remove",this.onRenderAssetRemoved,this))}this.data.initialized&&this.data.type==="mesh"&&(i||(this.data.render=null),this.system.recreatePhysicalShapes(this))}onSetModel(e,s,i){this.data.initialized&&this.data.type==="mesh"&&this.system.implementations.mesh.doRecreatePhysicalShape(this)}onSetRender(e,s,i){this.onSetModel(e,s,i)}onAssetRemoved(e){e.off("remove",this.onAssetRemoved,this),this.data.asset===e.id&&(this.asset=null)}onRenderAssetRemoved(e){e.off("remove",this.onRenderAssetRemoved,this),this.data.renderAsset===e.id&&(this.renderAsset=null)}getCompoundChildShapeIndex(e){let s=this.data.shape,i=s.getNumChildShapes();for(let r=0;r"u")){if(this._compoundParent)this.system.recreatePhysicalShapes(this);else if(!this.entity.rigidbody){let s=this.entity.parent;for(;s;){if(s.collision&&s.collision.type==="compound"){s.collision.shape.getNumChildShapes()===0?this.system.recreatePhysicalShapes(s.collision):this.system.recreatePhysicalShapes(this);break}s=s.parent}}}}_updateCompound(){let e=this.entity;if(e._dirtyWorld){let s=e._dirtyLocal,i=e;for(;i&&!s&&!(i.collision&&i.collision===this._compoundParent);)i._dirtyLocal&&(s=!0),i=i.parent;if(s){e.forEach(this.system.implementations.compound._updateEachDescendantTransform,e);let r=this._compoundParent.entity.rigidbody;r&&r.activate()}}}getShapePosition(){let e=this.entity.getPosition();if(this._hasOffset){let s=this.entity.getRotation(),i=this.data.linearOffset;return _B.copy(s).transformVector(i,mB),mB.add(e)}return e}getShapeRotation(){let e=this.entity.getRotation();return this._hasOffset?_B.copy(e).mul(this.data.angularOffset):e}onEnable(){if(this.data.type==="mesh"&&(this.data.asset||this.data.renderAsset)&&this.data.initialized){let e=this.system.app.assets.get(this.data.asset||this.data.renderAsset);if(e&&(!e.resource||!this.data.shape)){this.system.recreatePhysicalShapes(this);return}}if(this.entity.rigidbody)this.entity.rigidbody.enabled&&this.entity.rigidbody.enableSimulation();else if(this._compoundParent&&this!==this._compoundParent)if(this._compoundParent.shape.getNumChildShapes()===0)this.system.recreatePhysicalShapes(this._compoundParent);else{let e=this.system._getNodeTransform(this.entity,this._compoundParent.entity);this._compoundParent.shape.addChildShape(e,this.data.shape),Ammo.destroy(e),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()}else this.entity.trigger&&this.entity.trigger.enable()}onDisable(){this.entity.rigidbody?this.entity.rigidbody.disableSimulation():this._compoundParent&&this!==this._compoundParent?this._compoundParent.entity._destroying||(this.system._removeCompoundChild(this._compoundParent,this.data.shape),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()):this.entity.trigger&&this.entity.trigger.disable()}onBeforeRemove(){this.asset&&(this.asset=null),this.renderAsset&&(this.renderAsset=null),this.entity.off("insert",this._onInsert,this),this.off()}};n(eo,"EVENT_CONTACT","contact"),n(eo,"EVENT_COLLISIONSTART","collisionstart"),n(eo,"EVENT_COLLISIONEND","collisionend"),n(eo,"EVENT_TRIGGERENTER","triggerenter"),n(eo,"EVENT_TRIGGERLEAVE","triggerleave");var R0=class{constructor(){n(this,"enabled",!0);n(this,"type","box");n(this,"halfExtents",new x(.5,.5,.5));n(this,"linearOffset",new x);n(this,"angularOffset",new $);n(this,"radius",.5);n(this,"axis",1);n(this,"height",2);n(this,"convexHull",!1);n(this,"asset",null);n(this,"renderAsset",null);n(this,"checkVertexDuplicates",!0);n(this,"shape",null);n(this,"model",null);n(this,"render",null);n(this,"initialized",!1)}};var Sl="static",Ui="dynamic",tn="kinematic",gB=1,b0=2,gu=4,Mm=1,SB=2,xB=3,HS=4,WS=5,fke=0,uke=1,vB=1,iR=2,TB=4,dke=8,yB=16,pke=32,mke=64,_ke=128,gke=256,Ske=512,xke=1024,vke=2048,Tke=4096,yke=8192,Eke=16384,Ake=0,rR=65535,Cke=2,D0=65533,Pke=65529;var to,Su,Om,XS=class{constructor(t,e,s){this.entity=e.entity,this.component=e,this.app=t,typeof Ammo<"u"&&!to&&(to=new Ammo.btVector3,Su=new Ammo.btQuaternion,Om=new Ammo.btTransform),this.initialize(s)}initialize(t){let e=this.entity,s=t.shape;if(s&&typeof Ammo<"u"){e.trigger&&e.trigger.destroy();let i=1,r=this.component;if(r){let o=r.getShapePosition(),l=r.getShapeRotation();to.setValue(o.x,o.y,o.z),Su.setValue(l.x,l.y,l.z,l.w)}else{let o=e.getPosition(),l=e.getRotation();to.setValue(o.x,o.y,o.z),Su.setValue(l.x,l.y,l.z,l.w)}Om.setOrigin(to),Om.setRotation(Su);let a=this.app.systems.rigidbody.createBody(i,s,Om);a.setRestitution(0),a.setFriction(0),a.setDamping(0,0),to.setValue(0,0,0),a.setLinearFactor(to),a.setAngularFactor(to),a.setCollisionFlags(a.getCollisionFlags()|4),a.entity=e,this.body=a,this.component.enabled&&e.enabled&&this.enable()}}destroy(){this.body&&(this.disable(),this.app.systems.rigidbody.destroyBody(this.body),this.body=null)}_getEntityTransform(t){let e=this.component;if(e){let s=e.getShapePosition(),i=e.getShapeRotation();to.setValue(s.x,s.y,s.z),Su.setValue(i.x,i.y,i.z,i.w)}else{let s=this.entity.getPosition(),i=this.entity.getRotation();to.setValue(s.x,s.y,s.z),Su.setValue(i.x,i.y,i.z,i.w)}t.setOrigin(to),t.setRotation(Su)}updateTransform(){this._getEntityTransform(Om);let t=this.body;t.setWorldTransform(Om),t.activate()}enable(){let t=this.body;if(!t)return;let e=this.app.systems.rigidbody;e._triggers.indexOf(this)<0&&(e.addBody(t,16,65517),e._triggers.push(this)),t.forceActivationState(1),this.updateTransform()}disable(){let t=this.body;if(!t)return;let e=this.app.systems.rigidbody,s=e._triggers.indexOf(this);s>-1&&(e.removeBody(t),e._triggers.splice(s,1)),t.forceActivationState(5)}};var L0=new W,L8=new x,M8=new x,xu=new $,EB=new Pe,O8=["enabled","type","halfExtents","linearOffset","angularOffset","radius","axis","height","convexHull","asset","renderAsset","shape","model","render","checkVertexDuplicates"],xl=class{constructor(t){this.system=t}beforeInitialize(t,e){e.shape=null,e.model=new Ei,e.model.graph=new Pe}afterInitialize(t,e){this.recreatePhysicalShapes(t),t.data.initialized=!0}reset(t,e){this.beforeInitialize(t,e),this.afterInitialize(t,e)}recreatePhysicalShapes(t){let e=t.entity,s=t.data;if(typeof Ammo<"u"){e.trigger&&(e.trigger.destroy(),delete e.trigger),s.shape&&(t._compoundParent&&(t!==t._compoundParent&&this.system._removeCompoundChild(t._compoundParent,s.shape),t._compoundParent.entity.rigidbody&&t._compoundParent.entity.rigidbody.activate()),this.destroyShape(s)),s.shape=this.createPhysicalShape(t.entity,s);let i=!t._compoundParent;if(s.type==="compound"&&(!t._compoundParent||t===t._compoundParent))t._compoundParent=t,e.forEach(this._addEachDescendant,t);else if(s.type!=="compound"&&!t.rigidbody){t._compoundParent=null;let r=e.parent;for(;r;){if(r.collision&&r.collision.type==="compound"){t._compoundParent=r.collision;break}r=r.parent}}t._compoundParent&&t!==t._compoundParent&&(i&&t._compoundParent.shape.getNumChildShapes()===0?this.system.recreatePhysicalShapes(t._compoundParent):(this.system.updateCompoundChildTransform(e,!0),t._compoundParent.entity.rigidbody&&t._compoundParent.entity.rigidbody.activate())),e.rigidbody?(e.rigidbody.disableSimulation(),e.rigidbody.createBody(),e.enabled&&e.rigidbody.enabled&&e.rigidbody.enableSimulation()):t._compoundParent||(e.trigger?e.trigger.initialize(s):e.trigger=new XS(this.system.app,t,s))}}createPhysicalShape(t,e){}updateTransform(t,e,s,i){t.entity.trigger&&t.entity.trigger.updateTransform()}destroyShape(t){t.shape&&(Ammo.destroy(t.shape),t.shape=null)}beforeRemove(t,e){e.data.shape&&(e._compoundParent&&!e._compoundParent.entity._destroying&&(this.system._removeCompoundChild(e._compoundParent,e.data.shape),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate()),e._compoundParent=null,this.destroyShape(e.data))}remove(t,e){t.rigidbody&&t.rigidbody.body&&t.rigidbody.disableSimulation(),t.trigger&&(t.trigger.destroy(),delete t.trigger)}clone(t,e){let s=this.system.store[t.guid],i={enabled:s.data.enabled,type:s.data.type,halfExtents:[s.data.halfExtents.x,s.data.halfExtents.y,s.data.halfExtents.z],linearOffset:[s.data.linearOffset.x,s.data.linearOffset.y,s.data.linearOffset.z],angularOffset:[s.data.angularOffset.x,s.data.angularOffset.y,s.data.angularOffset.z,s.data.angularOffset.w],radius:s.data.radius,axis:s.data.axis,height:s.data.height,convexHull:s.data.convexHull,asset:s.data.asset,renderAsset:s.data.renderAsset,model:s.data.model,render:s.data.render,checkVertexDuplicates:s.data.checkVertexDuplicates};return this.system.addComponent(e,i)}},aR=class extends xl{createPhysicalShape(t,e){if(typeof Ammo<"u"){let s=e.halfExtents,i=new Ammo.btVector3(s?s.x:.5,s?s.y:.5,s?s.z:.5),r=new Ammo.btBoxShape(i);return Ammo.destroy(i),r}}},oR=class extends xl{createPhysicalShape(t,e){if(typeof Ammo<"u")return new Ammo.btSphereShape(e.radius)}},nR=class extends xl{createPhysicalShape(t,e){let s=e.axis??1,i=e.radius??.5,r=Math.max((e.height??2)-2*i,0),a=null;if(typeof Ammo<"u")switch(s){case 0:a=new Ammo.btCapsuleShapeX(i,r);break;case 1:a=new Ammo.btCapsuleShape(i,r);break;case 2:a=new Ammo.btCapsuleShapeZ(i,r);break}return a}},lR=class extends xl{createPhysicalShape(t,e){let s=e.axis??1,i=e.radius??.5,r=e.height??1,a=null,o=null;if(typeof Ammo<"u")switch(s){case 0:a=new Ammo.btVector3(r*.5,i,i),o=new Ammo.btCylinderShapeX(a);break;case 1:a=new Ammo.btVector3(i,r*.5,i),o=new Ammo.btCylinderShape(a);break;case 2:a=new Ammo.btVector3(i,i,r*.5),o=new Ammo.btCylinderShapeZ(a);break}return a&&Ammo.destroy(a),o}},cR=class extends xl{createPhysicalShape(t,e){let s=e.axis??1,i=e.radius??.5,r=e.height??1,a=null;if(typeof Ammo<"u")switch(s){case 0:a=new Ammo.btConeShapeX(i,r);break;case 1:a=new Ammo.btConeShape(i,r);break;case 2:a=new Ammo.btConeShapeZ(i,r);break}return a}},hR=class extends xl{beforeInitialize(t,e){}createAmmoHull(t,e,s,i){let r=new Ammo.btConvexHullShape,a=new Ammo.btVector3,o=[];t.getPositions(o);for(let h=0;h{let O=p[D*d]*P,G=p[D*d+1]*A,M=p[D*d+2]*w,H;if(r){let U=`${O}:${G}:${M}`;if(H=E.get(U),H!==void 0)return H;S.setValue(O,G,M),H=o.findOrAddVertex(S,!1),E.set(U,H)}else S.setValue(O,G,M),H=o.findOrAddVertex(S,!1);return H};for(let D=0;D<_;D++)g=I(m[v+D*3]),T=I(m[v+D*3+1]),C=I(m[v+D*3+2]),o.addIndex(g),o.addIndex(T),o.addIndex(C);Ammo.destroy(S)}let l=new Ammo.btBvhTriangleMeshShape(o,!0);if(!i){let f=a._getNodeScaling(e);l.setLocalScaling(f),Ammo.destroy(f)}let h=a._getNodeTransform(e);s.addChildShape(h,l),Ammo.destroy(h)}createPhysicalShape(t,e){if(!(typeof Ammo>"u")&&(e.model||e.render)){let s=new Ammo.btCompoundShape,r=t.getWorldTransform().getScale();if(e.render){let a=e.render.meshes;for(let o=0;o{i[s]===a&&(i[s]=f.resource,this.doRecreatePhysicalShape(t))},l=f=>{f.ready(u=>{if(u.data.containerAsset){let d=r.get(u.data.containerAsset);d.loaded?o(u):(d.ready(()=>{o(u)}),r.load(d))}else o(u)}),r.load(f)},h=r.get(e);h?l(h):r.once(`add:${e}`,l)}doRecreatePhysicalShape(t){let e=t.entity,s=t.data;s.model||s.render?(this.destroyShape(s),s.shape=this.createPhysicalShape(e,s),e.rigidbody?(e.rigidbody.disableSimulation(),e.rigidbody.createBody(),e.enabled&&e.rigidbody.enabled&&e.rigidbody.enableSimulation()):e.trigger?e.trigger.initialize(s):e.trigger=new XS(this.system.app,t,s)):(this.beforeRemove(e,t),this.remove(e,s))}updateTransform(t,e,s,i){if(t.shape){let a=t.entity.getWorldTransform().getScale(),o=t.shape.getLocalScaling();(a.x!==o.x()||a.y!==o.y()||a.z!==o.z())&&this.doRecreatePhysicalShape(t)}super.updateTransform(t,e,s,i)}destroyShape(t){if(!t.shape)return;let e=t.shape.getNumChildShapes();for(let s=0;s=0&&this.model.meshInstances.splice(e,1)}this._entity.enabled&&this._element.enabled&&this._element.addModelToLayers(this.model),t||(this.unmaskMeshInstance?.destroy(),this.unmaskMeshInstance=null)}}setMaterial(t){this.meshInstance&&(this.meshInstance.material=t,this.unmaskMeshInstance&&(this.unmaskMeshInstance.material=t))}setParameter(t,e){this.meshInstance&&(this.meshInstance.setParameter(t,e),this.unmaskMeshInstance&&this.unmaskMeshInstance.setParameter(t,e))}deleteParameter(t){this.meshInstance&&(this.meshInstance.deleteParameter(t),this.unmaskMeshInstance&&this.unmaskMeshInstance.deleteParameter(t))}setUnmaskDrawOrder(){if(!this.meshInstance)return;let t=function(e){let s,i=e.children,r=i.length;if(r){for(let o=0;onew Ft(r,[{semantic:ee,components:3,type:ye},{semantic:Ot,components:3,type:ye},{semantic:_t,components:2,type:ye}])),l=new ft(r,o,4,{data:a.buffer}),h=new _e(r);return h.vertexBuffer=l,h.primitive[0].type=Ks,h.primitive[0].base=0,h.primitive[0].count=4,h.primitive[0].indexed=!1,h.aabb.setMinMax(x.ZERO,new x(e,s,0)),this._updateMesh(h),h}_updateMesh(t){let e=this._element,s=e.calculatedWidth,i=e.calculatedHeight;if(e.fitMode!==_u&&this._targetAspectRatio>0){let a=e.calculatedWidth/e.calculatedHeight;e.fitMode===tR&&a>this._targetAspectRatio||e.fitMode===sR&&a0&&(this._targetAspectRatio=s.rect.z/s.rect.w)}this.mesh=t?e:this._defaultMesh,this.refreshMesh()}refreshMesh(){this.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this.mesh))}_updateAabb(t){return t.center.set(0,0,0),t.halfExtents.set(this._outerScale.x*.5,this._outerScale.y*.5,.001),t.setFromTransformedAabb(t,this._renderable.node.getWorldTransform()),t}_toggleMask(){this._element._dirtifyMask();let t=this._element._isScreenSpace();this._updateMaterial(t),this._renderable.setMask(!!this._mask)}_onMaterialLoad(t){this.material=t.resource}_onMaterialAdded(t){this._system.app.assets.off(`add:${t.id}`,this._onMaterialAdded,this),this._materialAsset===t.id&&this._bindMaterialAsset(t)}_bindMaterialAsset(t){this._entity.enabled&&(t.on("load",this._onMaterialLoad,this),t.on("change",this._onMaterialChange,this),t.on("remove",this._onMaterialRemove,this),t.resource?this._onMaterialLoad(t):this._system.app.assets.load(t))}_unbindMaterialAsset(t){t.off("load",this._onMaterialLoad,this),t.off("change",this._onMaterialChange,this),t.off("remove",this._onMaterialRemove,this)}_onMaterialChange(){}_onMaterialRemove(){}_onTextureAdded(t){this._system.app.assets.off(`add:${t.id}`,this._onTextureAdded,this),this._textureAsset===t.id&&this._bindTextureAsset(t)}_bindTextureAsset(t){this._entity.enabled&&(t.on("load",this._onTextureLoad,this),t.on("change",this._onTextureChange,this),t.on("remove",this._onTextureRemove,this),t.resource?this._onTextureLoad(t):this._system.app.assets.load(t))}_unbindTextureAsset(t){t.off("load",this._onTextureLoad,this),t.off("change",this._onTextureChange,this),t.off("remove",this._onTextureRemove,this)}_onTextureLoad(t){this.texture=t.resource}_onTextureChange(t){}_onTextureRemove(t){}_onSpriteAssetAdded(t){this._system.app.assets.off(`add:${t.id}`,this._onSpriteAssetAdded,this),this._spriteAsset===t.id&&this._bindSpriteAsset(t)}_bindSpriteAsset(t){this._entity.enabled&&(t.on("load",this._onSpriteAssetLoad,this),t.on("change",this._onSpriteAssetChange,this),t.on("remove",this._onSpriteAssetRemove,this),t.resource?this._onSpriteAssetLoad(t):this._system.app.assets.load(t))}_unbindSpriteAsset(t){t.off("load",this._onSpriteAssetLoad,this),t.off("change",this._onSpriteAssetChange,this),t.off("remove",this._onSpriteAssetRemove,this),t.data.textureAtlasAsset&&this._system.app.assets.off(`load:${t.data.textureAtlasAsset}`,this._onTextureAtlasLoad,this)}_onSpriteAssetLoad(t){if(!t||!t.resource)this.sprite=null;else if(t.resource.atlas)this.sprite=t.resource;else{let e=t.data.textureAtlasAsset;if(e){let s=this._system.app.assets;s.off(`load:${e}`,this._onTextureAtlasLoad,this),s.once(`load:${e}`,this._onTextureAtlasLoad,this)}}}_onSpriteAssetChange(t){this._onSpriteAssetLoad(t)}_onSpriteAssetRemove(t){}_bindSprite(t){this._evtSetMeshes=t.on("set:meshes",this._onSpriteMeshesChange,this),t.on("set:pixelsPerUnit",this._onSpritePpuChange,this),t.on("set:atlas",this._onAtlasTextureChange,this),t.atlas&&t.atlas.on("set:texture",this._onAtlasTextureChange,this)}_unbindSprite(t){this._evtSetMeshes?.off(),this._evtSetMeshes=null,t.off("set:pixelsPerUnit",this._onSpritePpuChange,this),t.off("set:atlas",this._onAtlasTextureChange,this),t.atlas&&t.atlas.off("set:texture",this._onAtlasTextureChange,this)}_onSpriteMeshesChange(){this._sprite&&(this._spriteFrame=R.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()}_onSpritePpuChange(){this.sprite.renderMode!==Ti&&this._pixelsPerUnit===null&&this._updateSprite()}_onAtlasTextureChange(){this.sprite&&this.sprite.atlas&&this.sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"))}_onTextureAtlasLoad(t){let e=this._spriteAsset;e instanceof ae?this._onSpriteAssetLoad(e):this._onSpriteAssetLoad(this._system.app.assets.get(e))}onEnable(){if(this._materialAsset){let t=this._system.app.assets.get(this._materialAsset);t&&t.resource!==this._material&&this._bindMaterialAsset(t)}if(this._textureAsset){let t=this._system.app.assets.get(this._textureAsset);t&&t.resource!==this._texture&&this._bindTextureAsset(t)}if(this._spriteAsset){let t=this._system.app.assets.get(this._spriteAsset);t&&t.resource!==this._sprite&&this._bindSpriteAsset(t)}this._element.addModelToLayers(this._renderable.model)}onDisable(){this._element.removeModelFromLayers(this._renderable.model)}_setStencil(t){this._renderable.meshInstance.stencilFront=t,this._renderable.meshInstance.stencilBack=t;let e=0;if(this._element.maskedBy&&(e=this._element.maskedBy.element._image._maskRef),this._renderable.unmaskMeshInstance){let s=new Ls({ref:e+1,func:2,zpass:$C});this._renderable.unmaskMeshInstance.stencilFront=s,this._renderable.unmaskMeshInstance.stencilBack=s}}_updateRenderableEmissive(){M0.linear(this._color),this._colorUniform[0]=M0.r,this._colorUniform[1]=M0.g,this._colorUniform[2]=M0.b,this._renderable.setParameter("material_emissive",this._colorUniform)}set color(t){let{r:e,g:s,b:i}=t;(this._color.r!==e||this._color.g!==s||this._color.b!==i)&&(this._color.r=e,this._color.g=s,this._color.b=i,this._updateRenderableEmissive()),this._element&&this._element.fire("set:color",this._color)}get color(){return this._color}set opacity(t){t!==this._color.a&&(this._color.a=t,this._renderable.setParameter("material_opacity",t)),this._element&&this._element.fire("set:opacity",t)}get opacity(){return this._color.a}set rect(t){let e,s,i,r;t instanceof Q?(e=t.x,s=t.y,i=t.z,r=t.w):(e=t[0],s=t[1],i=t[2],r=t[3]),!(e===this._rect.x&&s===this._rect.y&&i===this._rect.z&&r===this._rect.w)&&(this._rect.set(e,s,i,r),this._renderable.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this._renderable.mesh)))}get rect(){return this._rect}_removeMaterialAssetEvents(){if(this._materialAsset){let t=this._system.app.assets;t.off(`add:${this._materialAsset}`,this._onMaterialAdded,this);let e=t.get(this._materialAsset);e&&(e.off("load",this._onMaterialLoad,this),e.off("change",this._onMaterialChange,this),e.off("remove",this._onMaterialRemove,this))}}set material(t){if(this._material!==t){if(!t){let e=this._element._isScreenSpace();this.mask?t=e?this._system.defaultScreenSpaceImageMaskMaterial:this._system.defaultImageMaskMaterial:t=e?this._system.defaultScreenSpaceImageMaterial:this._system.defaultImageMaterial}if(this._material=t,this._materialAsset){let e=this._system.app.assets.get(this._materialAsset);(!e||e.resource!==t)&&(this._removeMaterialAssetEvents(),this._materialAsset=null)}t&&(this._renderable.setMaterial(t),this._hasUserMaterial()?(this._renderable.deleteParameter("material_opacity"),this._renderable.deleteParameter("material_emissive")):(this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",this._color.a)))}}get material(){return this._material}set materialAsset(t){let e=this._system.app.assets,s=t;if(t instanceof ae&&(s=t.id),this._materialAsset!==s)if(this._removeMaterialAssetEvents(),this._materialAsset=s,this._materialAsset){let i=e.get(this._materialAsset);i?this._bindMaterialAsset(i):(this._materialAsset=null,this.material=null,this._materialAsset=s,e.on(`add:${this._materialAsset}`,this._onMaterialAdded,this))}else this._materialAsset=null,this.material=null,this._materialAsset=s}get materialAsset(){return this._materialAsset}set texture(t){if(this._texture!==t){if(this._textureAsset){let e=this._system.app.assets.get(this._textureAsset);e&&e.resource!==t&&(this.textureAsset=null)}if(this._texture=t,t){this._spriteAsset&&(this.spriteAsset=null),this._renderable.setParameter("texture_emissiveMap",this._texture),this._renderable.setParameter("texture_opacityMap",this._texture),this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",this._color.a);let e=this._texture.width/this._texture.height;e!==this._targetAspectRatio&&(this._targetAspectRatio=e,this._element.fitMode!==_u&&this.refreshMesh())}else this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"),this._targetAspectRatio=-1,this._element.fitMode!==_u&&this.refreshMesh()}}get texture(){return this._texture}set textureAsset(t){let e=this._system.app.assets,s=t;if(t instanceof ae&&(s=t.id),this._textureAsset!==s){if(this._textureAsset){e.off(`add:${this._textureAsset}`,this._onTextureAdded,this);let i=e.get(this._textureAsset);i&&(i.off("load",this._onTextureLoad,this),i.off("change",this._onTextureChange,this),i.off("remove",this._onTextureRemove,this))}if(this._textureAsset=s,this._textureAsset){let i=e.get(this._textureAsset);i?this._bindTextureAsset(i):(this.texture=null,e.on(`add:${this._textureAsset}`,this._onTextureAdded,this))}else this.texture=null}}get textureAsset(){return this._textureAsset}set spriteAsset(t){let e=this._system.app.assets,s=t;if(t instanceof ae&&(s=t.id),this._spriteAsset!==s){if(this._spriteAsset){e.off(`add:${this._spriteAsset}`,this._onSpriteAssetAdded,this);let i=e.get(this._spriteAsset);i&&this._unbindSpriteAsset(i)}if(this._spriteAsset=s,this._spriteAsset){let i=e.get(this._spriteAsset);i?this._bindSpriteAsset(i):(this.sprite=null,e.on(`add:${this._spriteAsset}`,this._onSpriteAssetAdded,this))}else this.sprite=null}this._element&&this._element.fire("set:spriteAsset",s)}get spriteAsset(){return this._spriteAsset}set sprite(t){if(this._sprite!==t){if(this._sprite&&this._unbindSprite(this._sprite),this._spriteAsset){let e=this._system.app.assets.get(this._spriteAsset);e&&e.resource!==t&&(this.spriteAsset=null)}this._sprite=t,this._sprite&&(this._bindSprite(this._sprite),this._textureAsset&&(this.textureAsset=null)),this._sprite&&this._sprite.atlas&&this._sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap")),this._sprite&&(this._spriteFrame=R.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()}}get sprite(){return this._sprite}set spriteFrame(t){let e=this._spriteFrame;this._sprite?this._spriteFrame=R.clamp(t,0,this._sprite.frameKeys.length-1):this._spriteFrame=t,this._spriteFrame!==e&&this._updateSprite(),this._element&&this._element.fire("set:spriteFrame",t)}get spriteFrame(){return this._spriteFrame}set mesh(t){this._renderable.setMesh(t),this._defaultMesh===t?this._renderable.setAabbFunc(null):this._renderable.setAabbFunc(this._updateAabbFunc)}get mesh(){return this._renderable.mesh}set mask(t){this._mask!==t&&(this._mask=t,this._toggleMask())}get mask(){return this._mask}set pixelsPerUnit(t){this._pixelsPerUnit!==t&&(this._pixelsPerUnit=t,this._sprite&&(this._sprite.renderMode===It||this._sprite.renderMode===Rt)&&this._updateSprite())}get pixelsPerUnit(){return this._pixelsPerUnit}get aabb(){return this._renderable.meshInstance?this._renderable.meshInstance.aabb:null}};var Bm=class extends J{constructor(t){super(),this._app=t,t.i18n.on(fa.EVENT_CHANGE,this._onSetLocale,this),this._autoLoad=!1,this._disableLocalization=!1,this._defaultAsset=null,this._localizedAsset=null}set defaultAsset(t){let e=t instanceof ae?t.id:t;this._defaultAsset!==e&&(this._defaultAsset&&this._unbindDefaultAsset(),this._defaultAsset=e,this._defaultAsset&&this._bindDefaultAsset(),this._onSetLocale(this._app.i18n.locale))}get defaultAsset(){return this._defaultAsset}set localizedAsset(t){let e=t instanceof ae?t.id:t;this._localizedAsset!==e&&(this._localizedAsset&&(this._app.assets.off(`add:${this._localizedAsset}`,this._onLocalizedAssetAdd,this),this._unbindLocalizedAsset()),this._localizedAsset=e,this._localizedAsset&&(this._app.assets.get(this._localizedAsset)?this._bindLocalizedAsset():this._app.assets.once(`add:${this._localizedAsset}`,this._onLocalizedAssetAdd,this)))}get localizedAsset(){return this._localizedAsset}set autoLoad(t){this._autoLoad!==t&&(this._autoLoad=t,this._autoLoad&&this._localizedAsset&&(this._unbindLocalizedAsset(),this._bindLocalizedAsset()))}get autoLoad(){return this._autoLoad}set disableLocalization(t){this._disableLocalization!==t&&(this._disableLocalization=t,this._onSetLocale(this._app.i18n.locale))}get disableLocalization(){return this._disableLocalization}_bindDefaultAsset(){let t=this._app.assets.get(this._defaultAsset);t?this._onDefaultAssetAdd(t):this._app.assets.once(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this)}_unbindDefaultAsset(){if(!this._defaultAsset)return;this._app.assets.off(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this);let t=this._app.assets.get(this._defaultAsset);t&&(t.off("add:localized",this._onLocaleAdd,this),t.off("remove:localized",this._onLocaleRemove,this),t.off("remove",this._onDefaultAssetRemove,this))}_onDefaultAssetAdd(t){this._defaultAsset===t.id&&(t.on("add:localized",this._onLocaleAdd,this),t.on("remove:localized",this._onLocaleRemove,this),t.once("remove",this._onDefaultAssetRemove,this))}_onDefaultAssetRemove(t){this._defaultAsset===t.id&&(t.off("add:localized",this._onLocaleAdd,this),t.off("remove:localized",this._onLocaleAdd,this),this._app.assets.once(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this))}_bindLocalizedAsset(){if(!this._autoLoad)return;let t=this._app.assets.get(this._localizedAsset);t&&(t.on("load",this._onLocalizedAssetLoad,this),t.on("change",this._onLocalizedAssetChange,this),t.on("remove",this._onLocalizedAssetRemove,this),t.resource?this._onLocalizedAssetLoad(t):this._app.assets.load(t))}_unbindLocalizedAsset(){let t=this._app.assets.get(this._localizedAsset);t&&(t.off("load",this._onLocalizedAssetLoad,this),t.off("change",this._onLocalizedAssetChange,this),t.off("remove",this._onLocalizedAssetRemove,this))}_onLocalizedAssetAdd(t){this._localizedAsset===t.id&&this._bindLocalizedAsset()}_onLocalizedAssetLoad(t){this.fire("load",t)}_onLocalizedAssetChange(t,e,s,i){this.fire("change",t,e,s,i)}_onLocalizedAssetRemove(t){this._localizedAsset===t.id&&(this.localizedAsset=this._defaultAsset),this.fire("remove",t)}_onLocaleAdd(t,e){this._app.i18n.locale===t&&this._onSetLocale(t)}_onLocaleRemove(t,e){this._app.i18n.locale===t&&this._onSetLocale(t)}_onSetLocale(t){if(!this._defaultAsset){this.localizedAsset=null;return}let e=this._app.assets.get(this._defaultAsset);if(!e||this._disableLocalization){this.localizedAsset=this._defaultAsset;return}let s=e.getLocalizedAssetId(t);if(!s){this.localizedAsset=this._defaultAsset;return}this.localizedAsset=s}destroy(){this.defaultAsset=null,this._app.i18n.off(fa.EVENT_CHANGE,this._onSetLocale,this),this.off()}};var vu="msdf",dR="bitmap";var N8=` +\r\v\f`,B8=/[\w|/]/,pR=class{constructor(t){this._symbols=t,this._index=0,this._last=0,this._cur=this._symbols.length>0?this._symbols[0]:null,this._buf=[],this._mode="text",this._error=null}read(){let t=this._read();for(;t===8;)t=this._read();return t!==0&&t!==1&&(this._last=this._index),t}buf(){return this._buf}last(){return this._last}error(){return this._error}debugPrint(){let t=["EOF","ERROR","TEXT","OPEN_BRACKET","CLOSE_BRACKET","EQUALS","STRING","IDENTIFIER","WHITESPACE"],e=this.read(),s="";for(;s+=`${(s.length>0?` +`:"")+t[e]} '${this.buf().join("")}'`,!(e===0||e===1);)e=this.read();return s}_read(){return this._buf=[],this._eof()?0:this._mode==="text"?this._text():this._tag()}_text(){for(;;)switch(this._cur){case null:return this._buf.length>0?2:0;case"[":return this._mode="tag",this._buf.length>0?2:this._tag();case"\\":this._next(),this._cur==="["?this._store():this._output("\\");break;default:this._store();break}}_tag(){switch(this._cur){case null:return this._error="unexpected end of input reading tag",1;case"[":return this._store(),3;case"]":return this._store(),this._mode="text",4;case"=":return this._store(),5;case" ":case" ":case` +`:case"\r":case"\v":case"\f":return this._whitespace();case'"':return this._string();default:return this._isIdentifierSymbol(this._cur)?this._identifier():(this._error="unrecognized character",1)}}_whitespace(){for(this._store();N8.indexOf(this._cur)!==-1;)this._store();return 8}_string(){for(this._next();;)switch(this._cur){case null:return this._error="unexpected end of input reading string",1;case'"':return this._next(),6;default:this._store();break}}_identifier(){for(this._store();this._cur!==null&&this._isIdentifierSymbol(this._cur);)this._store();return 7}_isIdentifierSymbol(t){return t.length===1&&t.match(B8)!==null}_eof(){return this._cur===null}_next(){return this._eof()||(this._index++,this._cur=this._index=0;--a)if(i===`/${e[a].name}`&&e[a].end===null)return e[a].end=t.length,s=this._scanner.read(),s!==4?(this._error="expected close bracket",!1):!0;return this._error="failed to find matching tag",!1}let r={name:i,value:null,attributes:{},start:t.length,end:null};if(s=this._scanner.read(),s===5){if(s=this._scanner.read(),s!==6)return this._error="expected string",!1;r.value=this._scanner.buf().join(""),s=this._scanner.read()}for(;;){switch(s){case 4:return e.push(r),!0;case 7:{let a=this._scanner.buf().join("");if(s=this._scanner.read(),s!==5)return this._error="expected equals",!1;if(s=this._scanner.read(),s!==6)return this._error="expected string",!1;let o=this._scanner.buf().join("");r.attributes[a]=o;break}default:return this._error="expected close bracket or identifier",!1}s=this._scanner.read()}}};function AB(c,t){for(let e in t){if(!t.hasOwnProperty(e))continue;let s=t[e];s instanceof Object?(c.hasOwnProperty(e)||(c[e]={}),AB(c[e],t[e])):c[e]=s}}function U8(c){if(c.length===0)return null;let t={};for(let e=0;ef.find(d=>d===u)===void 0)}function r(f){for(let u=0;uf-u),o=[];for(let f=0;fa.end===null))return{symbols:c,tags:null};let r=k8(s,e.length);return{symbols:e,tags:r}}var O0=class{static evaluate(t){return z8(t)}};var _R=class{constructor(){this.count=0,this.quad=0,this.lines={},this.positions=[],this.normals=[],this.uvs=[],this.colors=[],this.indices=[],this.outlines=[],this.shadows=[],this.meshInstance=null}};function G8(c,t){let e=new _e(c);return e.setPositions(t.positions),e.setNormals(t.normals),e.setColors32(t.colors),e.setUvs(0,t.uvs),e.setIndices(t.indices),e.setVertexStream(rc,t.outlines,3,void 0,ye,!1),e.setVertexStream(ac,t.shadows,3,void 0,ye,!1),e.update(),e}var CB=/^[\r\n]$/,V8=/^[ \t]$/,PB=/^[ \t\-]|\u200b$/,H8=/^[a-z0-9]$/i,wB=/^[\u1100-\u11ff]|[\u3000-\u9fff\ua960-\ua97f]|[\uac00-\ud7ff]$/,W8=/^[〕〉》」』】〙〗〟ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻]$/,X8=["\u200B","\u061C","\u200E","\u200F","\u202A","\u202B","\u202C","\u202D","\u202E","\u2066","\u2067","\u2068","\u2069"],Y8={width:0,height:0,xadvance:0,xoffset:0,yoffset:0},IB=new F,K8=new B,Et=new F,Um=class{constructor(t){this._element=t,this._system=t.system,this._entity=t.entity,this._text="",this._symbols=[],this._colorPalette=[],this._outlinePalette=[],this._shadowPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null,this._i18nKey=null,this._fontAsset=new Bm(this._system.app),this._fontAsset.disableLocalization=!0,this._fontAsset.on("load",this._onFontLoad,this),this._fontAsset.on("change",this._onFontChange,this),this._fontAsset.on("remove",this._onFontRemove,this),this._font=null,this._color=new F(1,1,1,1),this._colorUniform=new Float32Array(3),this._spacing=1,this._fontSize=32,this._fontMinY=0,this._fontMaxY=0,this._originalFontSize=32,this._maxFontSize=32,this._minFontSize=8,this._autoFitWidth=!1,this._autoFitHeight=!1,this._maxLines=-1,this._lineHeight=32,this._scaledLineHeight=32,this._wrapLines=!1,this._drawOrder=0,this._alignment=new B(.5,.5),this._autoWidth=!0,this._autoHeight=!0,this.width=0,this.height=0,this._node=new Pe,this._model=new Ei,this._model.graph=this._node,this._entity.addChild(this._node),this._meshInfo=[],this._material=null,this._aabbDirty=!0,this._aabb=new ge,this._noResize=!1,this._currentMaterialType=null,this._maskedMaterialSrc=null,this._rtlReorder=!1,this._unicodeConverter=!1,this._rtl=!1,this._outlineColor=new F(0,0,0,1),this._outlineColorUniform=new Float32Array(4),this._outlineThicknessScale=.2,this._outlineThickness=0,this._shadowColor=new F(0,0,0,1),this._shadowColorUniform=new Float32Array(4),this._shadowOffsetScale=.005,this._shadowOffset=new B(0,0),this._shadowOffsetUniform=new Float32Array(2),this._enableMarkup=!1,this._onScreenChange(this._element.screen),t.on("resize",this._onParentResize,this),t.on("set:screen",this._onScreenChange,this),t.on("screen:set:screenspace",this._onScreenSpaceChange,this),t.on("set:draworder",this._onDrawOrderChange,this),t.on("set:pivot",this._onPivotChange,this),this._system.app.i18n.on(fa.EVENT_CHANGE,this._onLocaleSet,this),this._system.app.i18n.on("data:add",this._onLocalizationData,this),this._system.app.i18n.on("data:remove",this._onLocalizationData,this),this._rangeStart=0,this._rangeEnd=0,!t._beingInitialized&&t.enabled&&t.entity.enabled&&this.onEnable()}destroy(){this._setMaterial(null),this._model&&(this._element.removeModelFromLayers(this._model),this._model.destroy(),this._model=null),this._fontAsset.destroy(),this.font=null,this._element.off("resize",this._onParentResize,this),this._element.off("set:screen",this._onScreenChange,this),this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.off("set:draworder",this._onDrawOrderChange,this),this._element.off("set:pivot",this._onPivotChange,this),this._system.app.i18n.off(fa.EVENT_CHANGE,this._onLocaleSet,this),this._system.app.i18n.off("data:add",this._onLocalizationData,this),this._system.app.i18n.off("data:remove",this._onLocalizationData,this)}_onParentResize(t,e){this._noResize||this._font&&this._updateText()}_onScreenChange(t){t?this._updateMaterial(t.screen.screenSpace):this._updateMaterial(!1)}_onScreenSpaceChange(t){this._updateMaterial(t)}_onDrawOrderChange(t){if(this._drawOrder=t,this._model)for(let e=0,s=this._model.meshInstances.length;ee[p]))}}else this._rtl=!1;let s=(u,d)=>`${u.toString(!0).toLowerCase()}:${d.toFixed(2)}`,i=(u,d)=>`${u.toString(!0).toLowerCase()}:${d.x.toFixed(2)}:${d.y.toFixed(2)}`;if(e){let u={},d={},p={};this._colorPalette=[Math.round(this._color.r*255),Math.round(this._color.g*255),Math.round(this._color.b*255)],this._outlinePalette=[Math.round(this._outlineColor.r*255),Math.round(this._outlineColor.g*255),Math.round(this._outlineColor.b*255),Math.round(this._outlineColor.a*255),Math.round(this._outlineThickness*255)],this._shadowPalette=[Math.round(this._shadowColor.r*255),Math.round(this._shadowColor.g*255),Math.round(this._shadowColor.b*255),Math.round(this._shadowColor.a*255),Math.round(this._shadowOffset.x*127),Math.round(this._shadowOffset.y*127)],this._symbolColors=[],this._symbolOutlineParams=[],this._symbolShadowParams=[],u[this._color.toString(!1).toLowerCase()]=0,d[s(this._outlineColor,this._outlineThickness)]=0,p[i(this._shadowColor,this._shadowOffset)]=0;for(let m=0,_=this._symbols.length;m<_;++m){let S=e[m],g=0;if(S&&S.color&&S.color.value){let v=S.color.value;if(v.length===7&&v[0]==="#"){let E=v.substring(1).toLowerCase();u.hasOwnProperty(E)?g=u[E]:/^[0-9a-f]{6}$/.test(E)&&(g=this._colorPalette.length/3,u[E]=g,this._colorPalette.push(parseInt(E.substring(0,2),16)),this._colorPalette.push(parseInt(E.substring(2,4),16)),this._colorPalette.push(parseInt(E.substring(4,6),16)))}}this._symbolColors.push(g);let T=0;if(S&&S.outline&&(S.outline.attributes.color||S.outline.attributes.thickness)){let v=S.outline.attributes.color?IB.fromString(S.outline.attributes.color):this._outlineColor,E=Number(S.outline.attributes.thickness);(Number.isNaN(v.r)||Number.isNaN(v.g)||Number.isNaN(v.b)||Number.isNaN(v.a))&&(v=this._outlineColor),Number.isNaN(E)&&(E=this._outlineThickness);let y=s(v,E);d.hasOwnProperty(y)?T=d[y]:(T=this._outlinePalette.length/5,d[y]=T,this._outlinePalette.push(Math.round(v.r*255),Math.round(v.g*255),Math.round(v.b*255),Math.round(v.a*255),Math.round(E*255)))}this._symbolOutlineParams.push(T);let C=0;if(S&&S.shadow&&(S.shadow.attributes.color||S.shadow.attributes.offset||S.shadow.attributes.offsetX||S.shadow.attributes.offsetY)){let v=S.shadow.attributes.color?IB.fromString(S.shadow.attributes.color):this._shadowColor,E=Number(S.shadow.attributes.offset),y=Number(S.shadow.attributes.offsetX),P=Number(S.shadow.attributes.offsetY);(Number.isNaN(v.r)||Number.isNaN(v.g)||Number.isNaN(v.b)||Number.isNaN(v.a))&&(v=this._shadowColor);let A=K8.set(Number.isNaN(y)?Number.isNaN(E)?this._shadowOffset.x:E:y,Number.isNaN(P)?Number.isNaN(E)?this._shadowOffset.y:E:P),w=i(v,A);p.hasOwnProperty(w)?C=p[w]:(C=this._shadowPalette.length/6,p[w]=C,this._shadowPalette.push(Math.round(v.r*255),Math.round(v.g*255),Math.round(v.b*255),Math.round(v.a*255),Math.round(A.x*127),Math.round(A.y*127)))}this._symbolShadowParams.push(C)}}else this._colorPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null;this._updateMaterialEmissive(),this._updateMaterialOutline(),this._updateMaterialShadow();let r=this._calculateCharsPerTexture(),a=!1,o=this._element,l=o._isScreenSpace(),h=o._isScreenCulled(),f=function(u){return o.isVisibleForCamera(u)};for(let u=0,d=this._meshInfo.length;u=1e-4,v=this._element.calculatedWidth;(this.autoWidth&&!C||!this._wrapLines)&&(v=Number.POSITIVE_INFINITY);let E=0,y=0,P,A,w,I;function D(L,b,N){e._lineWidths.push(Math.abs(N));let k=_>b?b+1:_,z=_>b?_+1:b,V=L.slice(k,z);if(T){let q=V.length;for(;q--&&T>0;)CB.test(V[q])&&(V.splice(q,1),T--)}e._lineContents.push(V.join("")),l=0,h-=e._scaledLineHeight,d++,S=0,g=0,T=0,p=0,_=b}let O=!0;for(;O;){O=!1,r?this._scaledLineHeight=this._lineHeight*this._fontSize/(this._maxFontSize||1e-4):this._scaledLineHeight=this._lineHeight,this.width=0,this.height=0,this._lineWidths=[],this._lineContents=[],l=0,h=0,f=0,u=0,d=1,p=0,m=0,_=0,S=0,g=0,T=0;let L=this._fontSize/a;E=this._fontMinY*L,y=this._fontMaxY*L;for(let oe=0;oe=o?null:this._symbols[oe+1],CB.test(P)){T++,(!this._wrapLines||this._maxLines<0||d0){let Px=this._font.data.kerning;if(Px){let wx=Px[Nr.getCodePoint(this._symbols[oe-1])||0];wx&&(mt=wx[Nr.getCodePoint(this._symbols[oe])||0]||0)}}Vs=A.scale||1,ds=(A.width+A.height)/2,Lt=L*ds/Vs,Ve=(A.xadvance+mt)*L,qe=(A.xoffset-mt)*L,ot=A.yoffset*L}let Cs=V8.test(P),di=A&&A.map||0,Qu=-this._font.data.info.maps[di].width/this._font.data.info.maps[di].height,de=this._meshInfo[di],Qb=l+this._spacing*Ve;if(Qb>v&&g>0&&!Cs&&(this._maxLines<0||dthis._element.calculatedWidth&&(Vl=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1e-4)),Vl=R.clamp(Vl,s,i),Vl!==this._element.fontSize)){this._fontSize=Vl,O=!0;break}if(this.height=Math.max(this.height,y-(h+E)),this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&(Vl=R.clamp(this._fontSize-1,s,i),Vl!==this._element.fontSize)){this._fontSize=Vl,O=!0;break}l+=this._spacing*Ve,Cs||(u=l),(this._isWordBoundary(P)||this._isValidNextChar(I)&&(this._isNextCJKBoundary(P,I)||this._isNextCJKWholeWord(I)))&&(S++,p=u,m=oe+1),g++;let Hl=this._getUv(P);if(de.uvs[w*4*2+0]=Hl[0],de.uvs[w*4*2+1]=1-Hl[1],de.uvs[w*4*2+2]=Hl[2],de.uvs[w*4*2+3]=1-Hl[1],de.uvs[w*4*2+4]=Hl[2],de.uvs[w*4*2+5]=1-Hl[3],de.uvs[w*4*2+6]=Hl[0],de.uvs[w*4*2+7]=1-Hl[3],this._symbolColors){let mt=this._symbolColors[oe]*3;b=this._colorPalette[mt],N=this._colorPalette[mt+1],k=this._colorPalette[mt+2]}if(de.colors[w*4*4+0]=b,de.colors[w*4*4+1]=N,de.colors[w*4*4+2]=k,de.colors[w*4*4+3]=255,de.colors[w*4*4+4]=b,de.colors[w*4*4+5]=N,de.colors[w*4*4+6]=k,de.colors[w*4*4+7]=255,de.colors[w*4*4+8]=b,de.colors[w*4*4+9]=N,de.colors[w*4*4+10]=k,de.colors[w*4*4+11]=255,de.colors[w*4*4+12]=b,de.colors[w*4*4+13]=N,de.colors[w*4*4+14]=k,de.colors[w*4*4+15]=255,this._symbolOutlineParams){let mt=this._symbolOutlineParams[oe]*5;z=this._outlinePalette[mt]+this._outlinePalette[mt+1]*256,V=this._outlinePalette[mt+2]+this._outlinePalette[mt+3]*256,q=this._outlinePalette[mt+4]}if(de.outlines[w*4*3+0]=z,de.outlines[w*4*3+1]=V,de.outlines[w*4*3+2]=q,de.outlines[w*4*3+3]=z,de.outlines[w*4*3+4]=V,de.outlines[w*4*3+5]=q,de.outlines[w*4*3+6]=z,de.outlines[w*4*3+7]=V,de.outlines[w*4*3+8]=q,de.outlines[w*4*3+9]=z,de.outlines[w*4*3+10]=V,de.outlines[w*4*3+11]=q,this._symbolShadowParams){let mt=this._symbolShadowParams[oe]*6;re=this._shadowPalette[mt]+this._shadowPalette[mt+1]*256,te=this._shadowPalette[mt+2]+this._shadowPalette[mt+3]*256,j=this._shadowPalette[mt+4]+127+Math.round(Qu*this._shadowPalette[mt+5]+127)*256}de.shadows[w*4*3+0]=re,de.shadows[w*4*3+1]=te,de.shadows[w*4*3+2]=j,de.shadows[w*4*3+3]=re,de.shadows[w*4*3+4]=te,de.shadows[w*4*3+5]=j,de.shadows[w*4*3+6]=re,de.shadows[w*4*3+7]=te,de.shadows[w*4*3+8]=j,de.shadows[w*4*3+9]=re,de.shadows[w*4*3+10]=te,de.shadows[w*4*3+11]=j,de.quad++}O||_=k?(z.element[ee].set(0,0,0),z.element[_t].set(0,0),z.element[Ct].set(0,0,0,0),z.element[rc].set(0,0,0,0),z.element[ac].set(0,0,0,0)):(z.element[ee].set(this._meshInfo[L].positions[V*3+0],this._meshInfo[L].positions[V*3+1],this._meshInfo[L].positions[V*3+2]),z.element[_t].set(this._meshInfo[L].uvs[V*2+0],this._meshInfo[L].uvs[V*2+1]),z.element[Ct].set(this._meshInfo[L].colors[V*4+0],this._meshInfo[L].colors[V*4+1],this._meshInfo[L].colors[V*4+2],this._meshInfo[L].colors[V*4+3]),z.element[rc].set(this._meshInfo[L].outlines[V*3+0],this._meshInfo[L].outlines[V*3+1],this._meshInfo[L].outlines[V*3+2]),z.element[ac].set(this._meshInfo[L].shadows[V*3+0],this._meshInfo[L].shadows[V*3+1],this._meshInfo[L].shadows[V*3+2])),z.next();z.end(),this._meshInfo[L].meshInstance.mesh.aabb.compute(this._meshInfo[L].positions),this._meshInfo[L].meshInstance._aabbVer=-1}this._aabbDirty=!0}_onFontRender(){this.font=this._font}_onFontLoad(t){this.font!==t.resource&&(this.font=t.resource)}_onFontChange(t,e,s,i){if(e==="data"){this._font.data=s;let r=this._font.data.info.maps.length;for(let a=0;athis._font.textures.length&&(this._meshInfo.length=this._font.textures.length),this._updateText()}get font(){return this._font}set alignment(t){t instanceof B?this._alignment.set(t.x,t.y):this._alignment.set(t[0],t[1]),this._font&&this._updateText()}get alignment(){return this._alignment}set autoWidth(t){let e=this._autoWidth;if(this._autoWidth=t,t&&Math.abs(this._element.anchor.x-this._element.anchor.z)<1e-4&&(this._element.width=this.width),e!==t){let s=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;s!==this._fontSize&&(this._fontSize=s,this._font&&this._updateText())}}get autoWidth(){return this._autoWidth}set autoHeight(t){let e=this._autoHeight;if(this._autoHeight=t,t&&Math.abs(this._element.anchor.y-this._element.anchor.w)<1e-4&&(this._element.height=this.height),e!==t){let s=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;s!==this._fontSize&&(this._fontSize=s,this._font&&this._updateText())}}get autoHeight(){return this._autoHeight}set rtlReorder(t){this._rtlReorder!==t&&(this._rtlReorder=t,this._font&&this._updateText())}get rtlReorder(){return this._rtlReorder}set unicodeConverter(t){this._unicodeConverter!==t&&(this._unicodeConverter=t,this._setText(this._text))}get unicodeConverter(){return this._unicodeConverter}get aabb(){if(this._aabbDirty){let t=!1;for(let e=0;e.001}get _hasSplitAnchorsY(){return Math.abs(this._anchor.y-this._anchor.w)>.001}get aabb(){return this._image?this._image.aabb:this._text?this._text.aabb:null}set anchor(e){e instanceof Q?this._anchor.copy(e):this._anchor.set(...e),!this.entity._parent&&!this.screen?this._calculateLocalAnchors():this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this._anchorDirty=!0,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:anchor",this._anchor)}get anchor(){return this._anchor}set batchGroupId(e){this._batchGroupId!==e&&(this.entity.enabled&&this._batchGroupId>=0&&this.system.app.batcher?.remove(pt.ELEMENT,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(pt.ELEMENT,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&(this._image&&this._image._renderable.model?this.addModelToLayers(this._image._renderable.model):this._text&&this._text._model&&this.addModelToLayers(this._text._model)),this._batchGroupId=e)}get batchGroupId(){return this._batchGroupId}set bottom(e){this._margin.y=e;let s=this.entity.getLocalPosition(),i=this._absTop,r=this._localAnchor.y+e;this._setHeight(i-r),s.y=e+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(s)}get bottom(){return this._margin.y}set calculatedWidth(e){this._setCalculatedWidth(e,!0)}get calculatedWidth(){return this._calculatedWidth}set calculatedHeight(e){this._setCalculatedHeight(e,!0)}get calculatedHeight(){return this._calculatedHeight}get canvasCorners(){if(!this._canvasCornersDirty||!this.screen||!this.screen.screen.screenSpace)return this._canvasCorners;let e=this.system.app.graphicsDevice,s=this.screenCorners,i=e.canvas.clientWidth/e.width,r=e.canvas.clientHeight/e.height;for(let a=0;a<4;a++)this._canvasCorners[a].set(s[a].x*i,(e.height-s[a].y)*r);return this._canvasCornersDirty=!1,this._canvasCorners}set drawOrder(e){let s=0;this.screen&&(s=this.screen.screen.priority),e>16777215&&(e=16777215),this._drawOrder=(s<<24)+e,this.fire("set:draworder",this._drawOrder)}get drawOrder(){return this._drawOrder}set height(e){this._height=e,this._hasSplitAnchorsY||this._setCalculatedHeight(e,!0),this.fire("set:height",this._height)}get height(){return this._height}set layers(e){if(this._addedModels.length)for(let s=0;s=0&&this.system._prerender.splice(i,1),this.system._prerender.indexOf(e)<0&&this.system._prerender.push(e)}e=s}}_onPrerender(){for(let e=0;e=0&&this.system.app.batcher?.insert(pt.ELEMENT,this.batchGroupId,this.entity),this.fire("enableelement")}onDisable(){let s=this.system.app.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,s&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._image&&this._image.onDisable(),this._text&&this._text.onDisable(),this._group&&this._group.onDisable(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this._batchGroupId>=0&&this.system.app.batcher?.remove(pt.ELEMENT,this.batchGroupId,this.entity),this.fire("disableelement")}onRemove(){this.entity.off("insert",this._onInsert,this),this._unpatch(),this._image&&this._image.destroy(),this._text&&this._text.destroy(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this.screen&&this.screen.screen&&(this._unbindScreen(this.screen.screen),this.screen.screen.syncDrawOrder()),this.off()}_calculateSize(e,s){if(!this.entity._parent&&!this.screen)return;this._calculateLocalAnchors();let i=this._absRight-this._absLeft,r=this._absTop-this._absBottom;e?this._setWidth(i):this._setCalculatedWidth(i,!1),s?this._setHeight(r):this._setCalculatedHeight(r,!1);let a=this.entity.getLocalPosition();a.x=this._margin.x+this._calculatedWidth*this._pivot.x,a.y=this._margin.y+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(a),this._sizeDirty=!1}_setWidth(e){this._width=e,this._setCalculatedWidth(e,!1),this.fire("set:width",this._width)}_setHeight(e){this._height=e,this._setCalculatedHeight(e,!1),this.fire("set:height",this._height)}_setCalculatedWidth(e,s){if(!(Math.abs(e-this._calculatedWidth)<=1e-4)){if(this._calculatedWidth=e,this.entity._dirtifyLocal(),s){let i=this.entity.getLocalPosition(),r=this._pivot;this._margin.x=i.x-this._calculatedWidth*r.x,this._margin.z=this._localAnchor.z-this._localAnchor.x-this._calculatedWidth-this._margin.x}this._flagChildrenAsDirty(),this.fire("set:calculatedWidth",this._calculatedWidth),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}}_setCalculatedHeight(e,s){if(!(Math.abs(e-this._calculatedHeight)<=1e-4)){if(this._calculatedHeight=e,this.entity._dirtifyLocal(),s){let i=this.entity.getLocalPosition(),r=this._pivot;this._margin.y=i.y-this._calculatedHeight*r.y,this._margin.w=this._localAnchor.w-this._localAnchor.y-this._calculatedHeight-this._margin.y}this._flagChildrenAsDirty(),this.fire("set:calculatedHeight",this._calculatedHeight),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}}_flagChildrenAsDirty(){let e=this.entity._children;for(let s=0,i=e.length;s=0&&this._addedModels.splice(s,1);for(let i=0;ii||f>r||u.001,r=Math.abs(t.anchor.y-t.anchor.w)>.001,a=!1,o;e.margin!==void 0&&(e.margin instanceof Q?t.margin.copy(e.margin):t._margin.set(e.margin[0],e.margin[1],e.margin[2],e.margin[3]),a=!0),e.left!==void 0&&(t._margin.x=e.left,a=!0),e.bottom!==void 0&&(t._margin.y=e.bottom,a=!0),e.right!==void 0&&(t._margin.z=e.right,a=!0),e.top!==void 0&&(t._margin.w=e.top,a=!0),a&&(t.margin=t._margin);let l=!1;e.width!==void 0&&!i?t.width=e.width:i&&(l=!0),e.height!==void 0&&!r?t.height=e.height:r&&(l=!0),l&&(t.anchor=t.anchor),e.enabled!==void 0&&(t.enabled=e.enabled),e.useInput!==void 0&&(t.useInput=e.useInput),e.fitMode!==void 0&&(t.fitMode=e.fitMode),t.batchGroupId=e.batchGroupId===void 0||e.batchGroupId===null?-1:e.batchGroupId,e.layers&&Array.isArray(e.layers)&&(t.layers=e.layers.slice(0)),e.type!==void 0&&(t.type=e.type),t.type===Dm?(e.rect!==void 0&&(t.rect=e.rect),e.color!==void 0&&(o=e.color,o instanceof F||(o=new F(e.color[0],e.color[1],e.color[2])),t.color=o),e.opacity!==void 0&&(t.opacity=e.opacity),e.textureAsset!==void 0&&(t.textureAsset=e.textureAsset),e.texture&&(t.texture=e.texture),e.spriteAsset!==void 0&&(t.spriteAsset=e.spriteAsset),e.sprite&&(t.sprite=e.sprite),e.spriteFrame!==void 0&&(t.spriteFrame=e.spriteFrame),e.pixelsPerUnit!==void 0&&e.pixelsPerUnit!==null&&(t.pixelsPerUnit=e.pixelsPerUnit),e.materialAsset!==void 0&&(t.materialAsset=e.materialAsset),e.material&&(t.material=e.material),e.mask!==void 0&&(t.mask=e.mask)):t.type===kS&&(e.autoWidth!==void 0&&(t.autoWidth=e.autoWidth),e.autoHeight!==void 0&&(t.autoHeight=e.autoHeight),e.rtlReorder!==void 0&&(t.rtlReorder=e.rtlReorder),e.unicodeConverter!==void 0&&(t.unicodeConverter=e.unicodeConverter),e.text!==null&&e.text!==void 0?t.text=e.text:e.key!==null&&e.key!==void 0&&(t.key=e.key),e.color!==void 0&&(o=e.color,o instanceof F||(o=new F(o[0],o[1],o[2])),t.color=o),e.opacity!==void 0&&(t.opacity=e.opacity),e.spacing!==void 0&&(t.spacing=e.spacing),e.fontSize!==void 0&&(t.fontSize=e.fontSize,e.lineHeight||(t.lineHeight=e.fontSize)),e.lineHeight!==void 0&&(t.lineHeight=e.lineHeight),e.maxLines!==void 0&&(t.maxLines=e.maxLines),e.wrapLines!==void 0&&(t.wrapLines=e.wrapLines),e.minFontSize!==void 0&&(t.minFontSize=e.minFontSize),e.maxFontSize!==void 0&&(t.maxFontSize=e.maxFontSize),e.autoFitWidth&&(t.autoFitWidth=e.autoFitWidth),e.autoFitHeight&&(t.autoFitHeight=e.autoFitHeight),e.fontAsset!==void 0&&(t.fontAsset=e.fontAsset),e.font!==void 0&&(t.font=e.font),e.alignment!==void 0&&(t.alignment=e.alignment),e.outlineColor!==void 0&&(t.outlineColor=e.outlineColor),e.outlineThickness!==void 0&&(t.outlineThickness=e.outlineThickness),e.shadowColor!==void 0&&(t.shadowColor=e.shadowColor),e.shadowOffset!==void 0&&(t.shadowOffset=e.shadowOffset),e.enableMarkup!==void 0&&(t.enableMarkup=e.enableMarkup));let h=t._parseUpToScreen();h.screen&&t._updateScreen(h.screen),super.initializeComponentData(t,e,s),t._beingInitialized=!1,t.type===Dm&&t._image._meshDirty&&t._image._updateMesh(t._image.mesh)}onAddComponent(t,e){t.fire("element:add")}onRemoveComponent(t,e){e.onRemove()}cloneComponent(t,e){let s=t.element,i={enabled:s.enabled,width:s.width,height:s.height,anchor:s.anchor.clone(),pivot:s.pivot.clone(),margin:s.margin.clone(),alignment:s.alignment&&s.alignment.clone()||s.alignment,autoWidth:s.autoWidth,autoHeight:s.autoHeight,type:s.type,rect:s.rect&&s.rect.clone()||s.rect,rtlReorder:s.rtlReorder,unicodeConverter:s.unicodeConverter,materialAsset:s.materialAsset,material:s.material,color:s.color&&s.color.clone()||s.color,opacity:s.opacity,textureAsset:s.textureAsset,texture:s.texture,spriteAsset:s.spriteAsset,sprite:s.sprite,spriteFrame:s.spriteFrame,pixelsPerUnit:s.pixelsPerUnit,spacing:s.spacing,lineHeight:s.lineHeight,wrapLines:s.wrapLines,layers:s.layers,fontSize:s.fontSize,minFontSize:s.minFontSize,maxFontSize:s.maxFontSize,autoFitWidth:s.autoFitWidth,autoFitHeight:s.autoFitHeight,maxLines:s.maxLines,fontAsset:s.fontAsset,font:s.font,useInput:s.useInput,fitMode:s.fitMode,batchGroupId:s.batchGroupId,mask:s.mask,outlineColor:s.outlineColor&&s.outlineColor.clone()||s.outlineColor,outlineThickness:s.outlineThickness,shadowColor:s.shadowColor&&s.shadowColor.clone()||s.shadowColor,shadowOffset:s.shadowOffset&&s.shadowOffset.clone()||s.shadowOffset,enableMarkup:s.enableMarkup};return s.key!==void 0&&s.key!==null?i.key=s.key:i.text=s.text,this.addComponent(e,i)}getTextElementMaterial(t,e,s){let i=(t&&1)|(e&&2)|(s&&4),r=this._defaultTextMaterials[i];if(r)return r;let a="TextMaterial";return r=new it,e?(r.msdfMap=this._defaultTexture,r.msdfTextAttribute=s,r.emissive.set(1,1,1)):(a=`Bitmap${a}`,r.emissive.set(1,1,1),r.emissiveMap=this._defaultTexture,r.opacityMap=this._defaultTexture,r.opacityMapChannel="a"),t&&(a=`ScreenSpace${a}`,r.depthTest=!1),r.name=`default${a}`,r.useLighting=!1,r.useTonemap=!1,r.useFog=!1,r.useSkybox=!1,r.diffuse.set(0,0,0),r.opacity=.5,r.blendType=Ms,r.depthWrite=!1,r.emissiveVertexColor=!0,r.update(),this._defaultTextMaterials[i]=r,r}_createBaseImageMaterial(){let t=new it;return t.diffuse.set(0,0,0),t.emissive.set(1,1,1),t.emissiveMap=this._defaultTexture,t.opacityMap=this._defaultTexture,t.opacityMapChannel="a",t.useLighting=!1,t.useTonemap=!1,t.useFog=!1,t.useSkybox=!1,t.blendType=Ms,t.depthWrite=!1,t}getImageElementMaterial(t,e,s,i){return t?e?s?(this.defaultScreenSpaceImageMask9SlicedMaterial||(this.defaultScreenSpaceImageMask9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMask9SlicedMaterial.name="defaultScreenSpaceImageMask9SlicedMaterial",this.defaultScreenSpaceImageMask9SlicedMaterial.nineSlicedMode=It,this.defaultScreenSpaceImageMask9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9SlicedMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9SlicedMaterial)),this.defaultScreenSpaceImageMask9SlicedMaterial):i?(this.defaultScreenSpaceImageMask9TiledMaterial||(this.defaultScreenSpaceImageMask9TiledMaterial=this.defaultScreenSpaceImage9TiledMaterial.clone(),this.defaultScreenSpaceImageMask9TiledMaterial.name="defaultScreenSpaceImageMask9TiledMaterial",this.defaultScreenSpaceImageMask9TiledMaterial.nineSlicedMode=Rt,this.defaultScreenSpaceImageMask9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9TiledMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9TiledMaterial)),this.defaultScreenSpaceImageMask9TiledMaterial):(this.defaultScreenSpaceImageMaskMaterial||(this.defaultScreenSpaceImageMaskMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaskMaterial.name="defaultScreenSpaceImageMaskMaterial",this.defaultScreenSpaceImageMaskMaterial.depthTest=!1,this.defaultScreenSpaceImageMaskMaterial.alphaTest=1,this.defaultScreenSpaceImageMaskMaterial.redWrite=!1,this.defaultScreenSpaceImageMaskMaterial.greenWrite=!1,this.defaultScreenSpaceImageMaskMaterial.blueWrite=!1,this.defaultScreenSpaceImageMaskMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaskMaterial)),this.defaultScreenSpaceImageMaskMaterial):s?(this.defaultScreenSpaceImage9SlicedMaterial||(this.defaultScreenSpaceImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9SlicedMaterial.name="defaultScreenSpaceImage9SlicedMaterial",this.defaultScreenSpaceImage9SlicedMaterial.nineSlicedMode=It,this.defaultScreenSpaceImage9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9SlicedMaterial)),this.defaultScreenSpaceImage9SlicedMaterial):i?(this.defaultScreenSpaceImage9TiledMaterial||(this.defaultScreenSpaceImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9TiledMaterial.name="defaultScreenSpaceImage9TiledMaterial",this.defaultScreenSpaceImage9TiledMaterial.nineSlicedMode=Rt,this.defaultScreenSpaceImage9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9TiledMaterial)),this.defaultScreenSpaceImage9TiledMaterial):(this.defaultScreenSpaceImageMaterial||(this.defaultScreenSpaceImageMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaterial.name="defaultScreenSpaceImageMaterial",this.defaultScreenSpaceImageMaterial.depthTest=!1,this.defaultScreenSpaceImageMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaterial)),this.defaultScreenSpaceImageMaterial):e?s?(this.defaultImage9SlicedMaskMaterial||(this.defaultImage9SlicedMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaskMaterial.name="defaultImage9SlicedMaskMaterial",this.defaultImage9SlicedMaskMaterial.nineSlicedMode=It,this.defaultImage9SlicedMaskMaterial.alphaTest=1,this.defaultImage9SlicedMaskMaterial.redWrite=!1,this.defaultImage9SlicedMaskMaterial.greenWrite=!1,this.defaultImage9SlicedMaskMaterial.blueWrite=!1,this.defaultImage9SlicedMaskMaterial.alphaWrite=!1,this.defaultImage9SlicedMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaskMaterial)),this.defaultImage9SlicedMaskMaterial):i?(this.defaultImage9TiledMaskMaterial||(this.defaultImage9TiledMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaskMaterial.name="defaultImage9TiledMaskMaterial",this.defaultImage9TiledMaskMaterial.nineSlicedMode=Rt,this.defaultImage9TiledMaskMaterial.alphaTest=1,this.defaultImage9TiledMaskMaterial.redWrite=!1,this.defaultImage9TiledMaskMaterial.greenWrite=!1,this.defaultImage9TiledMaskMaterial.blueWrite=!1,this.defaultImage9TiledMaskMaterial.alphaWrite=!1,this.defaultImage9TiledMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaskMaterial)),this.defaultImage9TiledMaskMaterial):(this.defaultImageMaskMaterial||(this.defaultImageMaskMaterial=this._createBaseImageMaterial(),this.defaultImageMaskMaterial.name="defaultImageMaskMaterial",this.defaultImageMaskMaterial.alphaTest=1,this.defaultImageMaskMaterial.redWrite=!1,this.defaultImageMaskMaterial.greenWrite=!1,this.defaultImageMaskMaterial.blueWrite=!1,this.defaultImageMaskMaterial.alphaWrite=!1,this.defaultImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaskMaterial)),this.defaultImageMaskMaterial):s?(this.defaultImage9SlicedMaterial||(this.defaultImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaterial.name="defaultImage9SlicedMaterial",this.defaultImage9SlicedMaterial.nineSlicedMode=It,this.defaultImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaterial)),this.defaultImage9SlicedMaterial):i?(this.defaultImage9TiledMaterial||(this.defaultImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaterial.name="defaultImage9TiledMaterial",this.defaultImage9TiledMaterial.nineSlicedMode=Rt,this.defaultImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaterial)),this.defaultImage9TiledMaterial):(this.defaultImageMaterial||(this.defaultImageMaterial=this._createBaseImageMaterial(),this.defaultImageMaterial.name="defaultImageMaterial",this.defaultImageMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaterial)),this.defaultImageMaterial)}registerUnicodeConverter(t){this._unicodeConverter=t}registerRtlReorder(t){this._rtlReorder=t}getUnicodeConverter(){return this._unicodeConverter}getRtlReorder(){return this._rtlReorder}};var nh="free",lh="limited",ch="locked";var $8=["angularDampingX","angularDampingY","angularDampingZ","angularEquilibriumX","angularEquilibriumY","angularEquilibriumZ","angularLimitsX","angularLimitsY","angularLimitsZ","angularMotionX","angularMotionY","angularMotionZ","angularSpringX","angularSpringY","angularSpringZ","angularStiffnessX","angularStiffnessY","angularStiffnessZ","breakForce","enableCollision","enabled","entityA","entityB","linearDampingX","linearDampingY","linearDampingZ","linearEquilibriumX","linearEquilibriumY","linearEquilibriumZ","linearLimitsX","linearLimitsY","linearLimitsZ","linearMotionX","linearMotionY","linearMotionZ","linearSpringX","linearSpringY","linearSpringZ","linearStiffnessX","linearStiffnessY","linearStiffnessZ"],hh=class extends le{constructor(t,e){super(t,e),this._constraint=null,this._entityA=null,this._entityB=null,this._breakForce=34e37,this._enableCollision=!0,this._linearMotionX=ch,this._linearLimitsX=new B(0,0),this._linearSpringX=!1,this._linearStiffnessX=0,this._linearDampingX=1,this._linearEquilibriumX=0,this._linearMotionY=ch,this._linearLimitsY=new B(0,0),this._linearSpringY=!1,this._linearStiffnessY=0,this._linearDampingY=1,this._linearEquilibriumY=0,this._linearMotionZ=ch,this._linearLimitsZ=new B(0,0),this._linearSpringZ=!1,this._linearStiffnessZ=0,this._linearDampingZ=1,this._linearEquilibriumZ=0,this._angularMotionX=ch,this._angularLimitsX=new B(0,0),this._angularSpringX=!1,this._angularStiffnessX=0,this._angularDampingX=1,this._angularEquilibriumX=0,this._angularMotionY=ch,this._angularLimitsY=new B(0,0),this._angularSpringY=!1,this._angularStiffnessY=0,this._angularDampingY=1,this._angularEquilibriumY=0,this._angularMotionZ=ch,this._angularLimitsZ=new B(0,0),this._angularSpringZ=!1,this._angularEquilibriumZ=0,this._angularDampingZ=1,this._angularStiffnessZ=0,this.on("set_enabled",this._onSetEnabled,this)}set entityA(t){this._destroyConstraint(),this._entityA=t,this._createConstraint()}get entityA(){return this._entityA}set entityB(t){this._destroyConstraint(),this._entityB=t,this._createConstraint()}get entityB(){return this._entityB}set breakForce(t){this._constraint&&this._breakForce!==t&&(this._constraint.setBreakingImpulseThreshold(t),this._breakForce=t)}get breakForce(){return this._breakForce}set enableCollision(t){this._destroyConstraint(),this._enableCollision=t,this._createConstraint()}get enableCollision(){return this._enableCollision}set angularLimitsX(t){this._angularLimitsX.equals(t)||(this._angularLimitsX.copy(t),this._updateAngularLimits())}get angularLimitsX(){return this._angularLimitsX}set angularMotionX(t){this._angularMotionX!==t&&(this._angularMotionX=t,this._updateAngularLimits())}get angularMotionX(){return this._angularMotionX}set angularLimitsY(t){this._angularLimitsY.equals(t)||(this._angularLimitsY.copy(t),this._updateAngularLimits())}get angularLimitsY(){return this._angularLimitsY}set angularMotionY(t){this._angularMotionY!==t&&(this._angularMotionY=t,this._updateAngularLimits())}get angularMotionY(){return this._angularMotionY}set angularLimitsZ(t){this._angularLimitsZ.equals(t)||(this._angularLimitsZ.copy(t),this._updateAngularLimits())}get angularLimitsZ(){return this._angularLimitsZ}set angularMotionZ(t){this._angularMotionZ!==t&&(this._angularMotionZ=t,this._updateAngularLimits())}get angularMotionZ(){return this._angularMotionZ}set linearLimitsX(t){this._linearLimitsX.equals(t)||(this._linearLimitsX.copy(t),this._updateLinearLimits())}get linearLimitsX(){return this._linearLimitsX}set linearMotionX(t){this._linearMotionX!==t&&(this._linearMotionX=t,this._updateLinearLimits())}get linearMotionX(){return this._linearMotionX}set linearLimitsY(t){this._linearLimitsY.equals(t)||(this._linearLimitsY.copy(t),this._updateLinearLimits())}get linearLimitsY(){return this._linearLimitsY}set linearMotionY(t){this._linearMotionY!==t&&(this._linearMotionY=t,this._updateLinearLimits())}get linearMotionY(){return this._linearMotionY}set linearLimitsZ(t){this._linearLimitsZ.equals(t)||(this._linearLimitsZ.copy(t),this._updateLinearLimits())}get linearLimitsZ(){return this._linearLimitsZ}set linearMotionZ(t){this._linearMotionZ!==t&&(this._linearMotionZ=t,this._updateLinearLimits())}get linearMotionZ(){return this._linearMotionZ}_convertTransform(t,e){let s=t.getTranslation(),i=new $;i.setFromMat4(t);let r=new Ammo.btVector3(s.x,s.y,s.z),a=new Ammo.btQuaternion(i.x,i.y,i.z,i.w);e.setOrigin(r),e.setRotation(a),Ammo.destroy(r),Ammo.destroy(a)}_updateAngularLimits(){let t=this._constraint;if(t){let e,s,i,r,a,o;this._angularMotionX===lh?(e=this._angularLimitsX.x*R.DEG_TO_RAD,r=this._angularLimitsX.y*R.DEG_TO_RAD):this._angularMotionX===nh?(e=1,r=0):e=r=0,this._angularMotionY===lh?(s=this._angularLimitsY.x*R.DEG_TO_RAD,a=this._angularLimitsY.y*R.DEG_TO_RAD):this._angularMotionY===nh?(s=1,a=0):s=a=0,this._angularMotionZ===lh?(i=this._angularLimitsZ.x*R.DEG_TO_RAD,o=this._angularLimitsZ.y*R.DEG_TO_RAD):this._angularMotionZ===nh?(i=1,o=0):i=o=0;let l=new Ammo.btVector3(e,s,i);t.setAngularLowerLimit(l),l.setValue(r,a,o),t.setAngularUpperLimit(l),Ammo.destroy(l)}}_updateLinearLimits(){let t=this._constraint;if(t){let e,s,i,r,a,o;this._linearMotionX===lh?(e=this._linearLimitsX.x,r=this._linearLimitsX.y):this._linearMotionX===nh?(e=1,r=0):e=r=0,this._linearMotionY===lh?(s=this._linearLimitsY.x,a=this._linearLimitsY.y):this._linearMotionY===nh?(s=1,a=0):s=a=0,this._linearMotionZ===lh?(i=this._linearLimitsZ.x,o=this._linearLimitsZ.y):this._linearMotionZ===nh?(i=1,o=0):i=o=0;let l=new Ammo.btVector3(e,s,i);t.setLinearLowerLimit(l),l.setValue(r,a,o),t.setLinearUpperLimit(l),Ammo.destroy(l)}}_createConstraint(){if(this._entityA&&this._entityA.rigidbody){this._destroyConstraint();let t=new W,e=this._entityA.rigidbody.body;e.activate();let s=this.entity.getWorldTransform(),r=this._entityA.getWorldTransform().clone().invert();t.mul2(r,s);let a=new Ammo.btTransform;if(this._convertTransform(t,a),this._entityB&&this._entityB.rigidbody){let f=this._entityB.rigidbody.body;f.activate();let d=this._entityB.getWorldTransform().clone().invert();t.mul2(d,s);let p=new Ammo.btTransform;this._convertTransform(t,p),this._constraint=new Ammo.btGeneric6DofSpringConstraint(e,f,a,p,!this._enableCollision),Ammo.destroy(p)}else this._constraint=new Ammo.btGeneric6DofSpringConstraint(e,a,!this._enableCollision);Ammo.destroy(a);let o=["X","Y","Z","X","Y","Z"];for(let f=0;f<6;f++){let u=f<3?"_linear":"_angular";this._constraint.enableSpring(f,this[`${u}Spring${o[f]}`]),this._constraint.setDamping(f,this[`${u}Damping${o[f]}`]),this._constraint.setEquilibriumPoint(f,this[`${u}Equilibrium${o[f]}`]),this._constraint.setStiffness(f,this[`${u}Stiffness${o[f]}`])}this._constraint.setBreakingImpulseThreshold(this._breakForce),this._updateLinearLimits(),this._updateAngularLimits(),this.system.app.systems.rigidbody.dynamicsWorld.addConstraint(this._constraint,!this._enableCollision)}}_destroyConstraint(){this._constraint&&(this.system.app.systems.rigidbody.dynamicsWorld.removeConstraint(this._constraint),Ammo.destroy(this._constraint),this._constraint=null)}initFromData(t){for(let e of $8)t.hasOwnProperty(e)&&(t[e]instanceof B?this[`_${e}`].copy(t[e]):this[`_${e}`]=t[e]);this._createConstraint()}onEnable(){this._createConstraint()}onDisable(){this._destroyConstraint()}_onSetEnabled(t,e,s){}_onBeforeRemove(){this.fire("remove")}},Z8={Damping:"setDamping",Equilibrium:"setEquilibriumPoint",Spring:"enableSpring",Stiffness:"setStiffness"};["linear","angular"].forEach(c=>{["Damping","Equilibrium","Spring","Stiffness"].forEach(t=>{["X","Y","Z"].forEach(e=>{let s=c+t+e,i=`_${s}`,r=c==="linear"?0:3;e==="Y"&&(r+=1),e==="Z"&&(r+=2),Object.defineProperty(hh.prototype,s,{get:function(){return this[i]},set:function(a){this[i]!==a&&(this[i]=a,this._constraint[Z8[t]](r,a))}})})})});var U0=class{constructor(){n(this,"enabled",!0)}};var SR=["enabled"],Gm=class extends Fe{constructor(t){super(t),this.id="joint",this.app=t,this.ComponentType=hh,this.DataType=U0,this.schema=SR}initializeComponentData(t,e,s){t.initFromData(e),super.initializeComponentData(t,e,SR)}};le._buildAccessors(hh.prototype,SR);var Tu=class extends le{constructor(){super(...arguments);n(this,"_minWidth",0);n(this,"_minHeight",0);n(this,"_maxWidth",null);n(this,"_maxHeight",null);n(this,"_fitWidthProportion",0);n(this,"_fitHeightProportion",0);n(this,"_excludeFromLayout",!1)}set minWidth(e){e!==this._minWidth&&(this._minWidth=e,this.fire("resize"))}get minWidth(){return this._minWidth}set minHeight(e){e!==this._minHeight&&(this._minHeight=e,this.fire("resize"))}get minHeight(){return this._minHeight}set maxWidth(e){e!==this._maxWidth&&(this._maxWidth=e,this.fire("resize"))}get maxWidth(){return this._maxWidth}set maxHeight(e){e!==this._maxHeight&&(this._maxHeight=e,this.fire("resize"))}get maxHeight(){return this._maxHeight}set fitWidthProportion(e){e!==this._fitWidthProportion&&(this._fitWidthProportion=e,this.fire("resize"))}get fitWidthProportion(){return this._fitWidthProportion}set fitHeightProportion(e){e!==this._fitHeightProportion&&(this._fitHeightProportion=e,this.fire("resize"))}get fitHeightProportion(){return this._fitHeightProportion}set excludeFromLayout(e){e!==this._excludeFromLayout&&(this._excludeFromLayout=e,this.fire("resize"))}get excludeFromLayout(){return this._excludeFromLayout}};var k0=class{constructor(){n(this,"enabled",!0)}};var bB=["enabled"],Vm=class extends Fe{constructor(t){super(t),this.id="layoutchild",this.ComponentType=Tu,this.DataType=k0,this.schema=bB}initializeComponentData(t,e,s){e.enabled!==void 0&&(t.enabled=e.enabled),e.minWidth!==void 0&&(t.minWidth=e.minWidth),e.minHeight!==void 0&&(t.minHeight=e.minHeight),e.maxWidth!==void 0&&(t.maxWidth=e.maxWidth),e.maxHeight!==void 0&&(t.maxHeight=e.maxHeight),e.fitWidthProportion!==void 0&&(t.fitWidthProportion=e.fitWidthProportion),e.fitHeightProportion!==void 0&&(t.fitHeightProportion=e.fitHeightProportion),e.excludeFromLayout!==void 0&&(t.excludeFromLayout=e.excludeFromLayout),super.initializeComponentData(t,e,s)}cloneComponent(t,e){let s=t.layoutchild;return this.addComponent(e,{enabled:s.enabled,minWidth:s.minWidth,minHeight:s.minHeight,maxWidth:s.maxWidth,maxHeight:s.maxHeight,fitWidthProportion:s.fitWidthProportion,fitHeightProportion:s.fitHeightProportion,excludeFromLayout:s.excludeFromLayout})}};le._buildAccessors(Tu.prototype,bB);var xR=0,Q8=1,DB=2,J8=3;var z0={};z0[Ge]={axis:"x",size:"width",calculatedSize:"calculatedWidth",minSize:"minWidth",maxSize:"maxWidth",fitting:"widthFitting",fittingProportion:"fitWidthProportion"};z0[dt]={axis:"y",size:"height",calculatedSize:"calculatedHeight",minSize:"minHeight",maxSize:"maxHeight",fitting:"heightFitting",fittingProportion:"fitHeightProportion"};var vR={};vR[Ge]=dt;vR[dt]=Ge;var eK={minWidth:0,minHeight:0,maxWidth:Number.POSITIVE_INFINITY,maxHeight:Number.POSITIVE_INFINITY,width:null,height:null,fitWidthProportion:0,fitHeightProportion:0},Rr={NONE:"NONE",APPLY_STRETCHING:"APPLY_STRETCHING",APPLY_SHRINKING:"APPLY_SHRINKING"},br=new B;function LB(c){let t,e=z0[c],s=z0[vR[c]];function i(b,N){return-N[e.size]*b.pivot[e.axis]}function r(b,N){return-N[s.size]*b.pivot[s.axis]}function a(b,N){return N[e.size]*(1-b.pivot[e.axis])}function o(b,N){return N[s.size]*(1-b.pivot[s.axis])}function l(b,N){b=b.filter(h),t=N,br.x=t.containerSize.x-t.padding.x-t.padding.z,br.y=t.containerSize.y-t.padding.y-t.padding.w,f(b);let k=d(u(b)),z=m(k,p(k)),V=v(k,z);return E(k,z,V),y(k,z,V),P(k)}function h(b){let N=b.entity.layoutchild;return!N||!N.enabled||!N.excludeFromLayout}function f(b){for(let N=0;N0&&(z+=t.spacing[e.axis]);let re=k[q][e.size];z+=re,!V&&z>br[e.axis]&&N[N.length-1].length!==0&&(z=re,N.push([])),N[N.length-1].push(b[q]),V&&z>br[e.axis]&&q!==b.length-1&&(z=0,N.push([]))}return N}function d(b){let N=t.orientation===Ge&&t.reverseX||t.orientation===dt&&t.reverseY,k=t.orientation===Ge&&t.reverseY||t.orientation===dt&&t.reverseX;if(N)for(let z=0;zte.largestSize[s.size]&&(te.largestElement=te[j],te.largestSize=oe)}k.push(te.largestElement),z.push(te.largestSize)}let V=S(z,s),q=_(t[s.fitting],V,br[s.axis]);q===Rr.APPLY_STRETCHING?g(z,V,s):q===Rr.APPLY_SHRINKING&&T(z,V,s);for(let re=0;re=k?Rr.APPLY_SHRINKING:Rr.NONE;case 3:return Nk+z[N],0)}function O(b,N){let k=D(b,N),z=[],V=b.length;if(k===0)for(let q=0;qk?V[N]-z[N]:z[N]-V[N]).map(U)}function H(b,N){b.index=N}function U(b){return b.index}function L(b,N){let k=[];k[N[b.length-1]]=b[N[b.length-1]];for(let z=b.length-2;z>=0;--z)k[N[z]]=k[N[z+1]]+b[N[z]];return k}return l}var TR={};TR[Ge]=LB(Ge);TR[dt]=LB(dt);var Hm=class{calculateLayout(t,e){let s=TR[e.orientation];if(s)return s(t,e);throw new Error(`Unrecognized orientation value: ${e.orientation}`)}};function MB(c){return c.element}function tK(c){return c.enabled&&c.element&&c.element.enabled}var yu=class extends le{constructor(e,s){super(e,s);n(this,"_orientation",Ge);n(this,"_reverseX",!1);n(this,"_reverseY",!0);n(this,"_alignment",new B(0,1));n(this,"_padding",new Q);n(this,"_spacing",new B);n(this,"_widthFitting",0);n(this,"_heightFitting",0);n(this,"_wrap",!1);n(this,"_layoutCalculator",new Hm);this._listenForReflowEvents(this.entity,"on"),this.entity.children.forEach(i=>{this._listenForReflowEvents(i,"on")}),this.entity.on("childinsert",this._onChildInsert,this),this.entity.on("childremove",this._onChildRemove,this),e.app.systems.element.on("add",this._onElementOrLayoutComponentAdd,this),e.app.systems.element.on("beforeremove",this._onElementOrLayoutComponentRemove,this),e.app.systems.layoutchild.on("add",this._onElementOrLayoutComponentAdd,this),e.app.systems.layoutchild.on("beforeremove",this._onElementOrLayoutComponentRemove,this)}set orientation(e){e!==this._orientation&&(this._orientation=e,this._scheduleReflow())}get orientation(){return this._orientation}set reverseX(e){e!==this._reverseX&&(this._reverseX=e,this._scheduleReflow())}get reverseX(){return this._reverseX}set reverseY(e){e!==this._reverseY&&(this._reverseY=e,this._scheduleReflow())}get reverseY(){return this._reverseY}set alignment(e){e.equals(this._alignment)||(this._alignment.copy(e),this._scheduleReflow())}get alignment(){return this._alignment}set padding(e){e.equals(this._padding)||(this._padding.copy(e),this._scheduleReflow())}get padding(){return this._padding}set spacing(e){e.equals(this._spacing)||(this._spacing.copy(e),this._scheduleReflow())}get spacing(){return this._spacing}set widthFitting(e){e!==this._widthFitting&&(this._widthFitting=e,this._scheduleReflow())}get widthFitting(){return this._widthFitting}set heightFitting(e){e!==this._heightFitting&&(this._heightFitting=e,this._scheduleReflow())}get heightFitting(){return this._heightFitting}set wrap(e){e!==this._wrap&&(this._wrap=e,this._scheduleReflow())}get wrap(){return this._wrap}_isSelfOrChild(e){return e===this.entity||this.entity.children.indexOf(e)!==-1}_listenForReflowEvents(e,s){e.element&&(e.element[s]("enableelement",this._scheduleReflow,this),e.element[s]("disableelement",this._scheduleReflow,this),e.element[s]("resize",this._scheduleReflow,this),e.element[s]("set:pivot",this._scheduleReflow,this)),e.layoutchild&&(e.layoutchild[s]("set_enabled",this._scheduleReflow,this),e.layoutchild[s]("resize",this._scheduleReflow,this))}_onElementOrLayoutComponentAdd(e){this._isSelfOrChild(e)&&(this._listenForReflowEvents(e,"on"),this._scheduleReflow())}_onElementOrLayoutComponentRemove(e){this._isSelfOrChild(e)&&(this._listenForReflowEvents(e,"off"),this._scheduleReflow())}_onChildInsert(e){this._listenForReflowEvents(e,"on"),this._scheduleReflow()}_onChildRemove(e){this._listenForReflowEvents(e,"off"),this._scheduleReflow()}_scheduleReflow(){this.enabled&&this.entity&&this.entity.enabled&&!this._isPerformingReflow&&this.system.scheduleReflow(this)}reflow(){let e=MB(this.entity),s=this.entity.children.filter(tK).map(MB);if(!e||s.length===0)return;let i=Math.max(e.calculatedWidth,0),r=Math.max(e.calculatedHeight,0),a={orientation:this._orientation,reverseX:this._reverseX,reverseY:this._reverseY,alignment:this._alignment,padding:this._padding,spacing:this._spacing,widthFitting:this._widthFitting,heightFitting:this._heightFitting,wrap:this._wrap,containerSize:new B(i,r)};this._isPerformingReflow=!0;let o=this._layoutCalculator.calculateLayout(s,a);this._isPerformingReflow=!1,this.fire("reflow",o)}onEnable(){this._scheduleReflow()}onRemove(){this.entity.off("childinsert",this._onChildInsert,this),this.entity.off("childremove",this._onChildRemove,this),this._listenForReflowEvents(this.entity,"off"),this.entity.children.forEach(e=>{this._listenForReflowEvents(e,"off")}),this.system.app.systems.element.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.element.off("beforeremove",this._onElementOrLayoutComponentRemove,this),this.system.app.systems.layoutchild.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.layoutchild.off("beforeremove",this._onElementOrLayoutComponentRemove,this)}};var G0=class{constructor(){n(this,"enabled",!0)}};var OB=["enabled"],sK=100,Wm=class extends Fe{constructor(t){super(t),this.id="layoutgroup",this.ComponentType=yu,this.DataType=G0,this.schema=OB,this._reflowQueue=[],this.on("beforeremove",this._onRemoveComponent,this),this.app.systems.on("postUpdate",this._onPostUpdate,this)}initializeComponentData(t,e,s){e.enabled!==void 0&&(t.enabled=e.enabled),e.orientation!==void 0&&(t.orientation=e.orientation),e.reverseX!==void 0&&(t.reverseX=e.reverseX),e.reverseY!==void 0&&(t.reverseY=e.reverseY),e.alignment!==void 0&&(t.alignment=Array.isArray(e.alignment)?new B(e.alignment):e.alignment),e.padding!==void 0&&(t.padding=Array.isArray(e.padding)?new Q(e.padding):e.padding),e.spacing!==void 0&&(t.spacing=Array.isArray(e.spacing)?new B(e.spacing):e.spacing),e.widthFitting!==void 0&&(t.widthFitting=e.widthFitting),e.heightFitting!==void 0&&(t.heightFitting=e.heightFitting),e.wrap!==void 0&&(t.wrap=e.wrap),super.initializeComponentData(t,e,s)}cloneComponent(t,e){let s=t.layoutgroup;return this.addComponent(e,{enabled:s.enabled,orientation:s.orientation,reverseX:s.reverseX,reverseY:s.reverseY,alignment:s.alignment,padding:s.padding,spacing:s.spacing,widthFitting:s.widthFitting,heightFitting:s.heightFitting,wrap:s.wrap})}scheduleReflow(t){this._reflowQueue.indexOf(t)===-1&&this._reflowQueue.push(t)}_onPostUpdate(){this._processReflowQueue()}_processReflowQueue(){if(this._reflowQueue.length===0)return;let t=0;for(;this._reflowQueue.length>0;){let e=this._reflowQueue.slice();this._reflowQueue.length=0,e.sort((s,i)=>s.entity.graphDepth-i.entity.graphDepth);for(let s=0;s=sK)break}}_onRemoveComponent(t,e){e.onRemove()}destroy(){super.destroy(),this.app.systems.off("postUpdate",this._onPostUpdate,this)}};le._buildAccessors(yu.prototype,OB);var yR=class{constructor(){n(this,"map",new Map)}destroy(t){this.map.forEach(e=>e.mesh.destroy())}},iK=new et,V0=(c,t)=>{let e=iK.get(c,()=>new yR),s=e.map.get(t);if(!s){let i,r;switch(t){case"box":i=_e.fromGeometry(c,new ci),r={x:2,y:2,z:2,uv:2/3};break;case"capsule":i=_e.fromGeometry(c,new Yc({radius:.5,height:2})),r={x:Math.PI*2,y:Math.PI,z:Math.PI*2,uv:1/3+1/3/3*2};break;case"cone":i=_e.fromGeometry(c,new qa({baseRadius:.5,peakRadius:0,height:1})),r={x:2.54,y:2.54,z:2.54,uv:1/3+1/3/3};break;case"cylinder":i=_e.fromGeometry(c,new Ci({radius:.5,height:1})),r={x:Math.PI,y:.79*2,z:Math.PI,uv:1/3+1/3/3*2};break;case"plane":i=_e.fromGeometry(c,new $a({halfExtents:new B(.5,.5),widthSegments:1,lengthSegments:1})),r={x:0,y:1,z:0,uv:1};break;case"sphere":i=_e.fromGeometry(c,new wr({radius:.5})),r={x:Math.PI,y:Math.PI,z:Math.PI,uv:1};break;case"torus":i=_e.fromGeometry(c,new Za({tubeRadius:.2,ringRadius:.3})),r={x:Math.PI*.5*.5-Math.PI*.1*.1,y:.4,z:.4,uv:1};break;default:throw new Error(`Invalid primitive type: ${t}`)}i.incRefCount(),s={mesh:i,area:r},e.map.set(t,s)}return s};var Tl=class extends le{constructor(e,s){super(e,s);n(this,"_type","asset");n(this,"_asset",null);n(this,"_model",null);n(this,"_mapping",{});n(this,"_castShadows",!0);n(this,"_receiveShadows",!0);n(this,"_materialAsset",null);n(this,"_material");n(this,"_castShadowsLightmap",!0);n(this,"_lightmapped",!1);n(this,"_lightmapSizeMultiplier",1);n(this,"isStatic",!1);n(this,"_layers",[Os]);n(this,"_batchGroupId",-1);n(this,"_customAabb",null);n(this,"_area",null);n(this,"_materialEvents",null);n(this,"_clonedModel",!1);n(this,"_evtLayersChanged",null);n(this,"_evtLayerAdded",null);n(this,"_evtLayerRemoved",null);this._material=e.defaultMaterial,s.on("remove",this.onRemoveChild,this),s.on("removehierarchy",this.onRemoveChild,this),s.on("insert",this.onInsertChild,this),s.on("inserthierarchy",this.onInsertChild,this)}set meshInstances(e){this._model&&(this._model.meshInstances=e)}get meshInstances(){return this._model?this._model.meshInstances:null}set customAabb(e){if(this._customAabb=e,this._model){let s=this._model.meshInstances;if(s)for(let i=0;i=0&&this.system.app.batcher?.remove(pt.MODEL,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(pt.MODEL,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._batchGroupId=e)}get batchGroupId(){return this._batchGroupId}set materialAsset(e){let s=e;e instanceof ae&&(s=e.id);let i=this.system.app.assets;if(s!==this._materialAsset){if(this._materialAsset){i.off(`add:${this._materialAsset}`,this._onMaterialAssetAdd,this);let r=i.get(this._materialAsset);r&&this._unbindMaterialAsset(r)}if(this._materialAsset=s,this._materialAsset){let r=i.get(this._materialAsset);r?this._bindMaterialAsset(r):(this._setMaterial(this.system.defaultMaterial),i.on(`add:${this._materialAsset}`,this._onMaterialAssetAdd,this))}else this._setMaterial(this.system.defaultMaterial)}}get materialAsset(){return this._materialAsset}set material(e){this._material!==e&&(this.materialAsset=null,this._setMaterial(e))}get material(){return this._material}set mapping(e){if(this._type!=="asset"||(this._unsetMaterialEvents(),e||(e={}),this._mapping=e,!this._model))return;let s=this._model.meshInstances,i=this.asset?this.system.app.assets.get(this.asset):null,r=i?i.data.mapping:null,a=null;for(let o=0,l=s.length;o=0&&e.batcher?.insert(pt.MODEL,this.batchGroupId,this.entity)}onDisable(){let e=this.system.app,i=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,i&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._batchGroupId>=0&&e.batcher?.remove(pt.MODEL,this.batchGroupId,this.entity),this._model&&this.removeModelFromLayers()}hide(){if(this._model){let e=this._model.meshInstances;for(let s=0,i=e.length;s{this.on(`set_${i}`,this.onSetSimpleProperty,this)}),aK.forEach(i=>{this.on(`set_${i}`,this.onSetComplexProperty,this)}),oK.forEach(i=>{this.on(`set_${i}`,this.onSetGraphProperty,this)})}set enabled(e){this._setValue("enabled",e)}get enabled(){return this.data.enabled}set autoPlay(e){this._setValue("autoPlay",e)}get autoPlay(){return this.data.autoPlay}set numParticles(e){this._setValue("numParticles",e)}get numParticles(){return this.data.numParticles}set lifetime(e){this._setValue("lifetime",e)}get lifetime(){return this.data.lifetime}set rate(e){this._setValue("rate",e)}get rate(){return this.data.rate}set rate2(e){this._setValue("rate2",e)}get rate2(){return this.data.rate2}set startAngle(e){this._setValue("startAngle",e)}get startAngle(){return this.data.startAngle}set startAngle2(e){this._setValue("startAngle2",e)}get startAngle2(){return this.data.startAngle2}set loop(e){this._setValue("loop",e)}get loop(){return this.data.loop}set preWarm(e){this._setValue("preWarm",e)}get preWarm(){return this.data.preWarm}set lighting(e){this._setValue("lighting",e)}get lighting(){return this.data.lighting}set halfLambert(e){this._setValue("halfLambert",e)}get halfLambert(){return this.data.halfLambert}set intensity(e){this._setValue("intensity",e)}get intensity(){return this.data.intensity}set depthWrite(e){this._setValue("depthWrite",e)}get depthWrite(){return this.data.depthWrite}set noFog(e){this._setValue("noFog",e)}get noFog(){return this.data.noFog}set depthSoftening(e){this._setValue("depthSoftening",e)}get depthSoftening(){return this.data.depthSoftening}set sort(e){this._setValue("sort",e)}get sort(){return this.data.sort}set blendType(e){this._setValue("blendType",e)}get blendType(){return this.data.blendType}set stretch(e){this._setValue("stretch",e)}get stretch(){return this.data.stretch}set alignToMotion(e){this._setValue("alignToMotion",e)}get alignToMotion(){return this.data.alignToMotion}set emitterShape(e){this._setValue("emitterShape",e)}get emitterShape(){return this.data.emitterShape}set emitterExtents(e){this._setValue("emitterExtents",e)}get emitterExtents(){return this.data.emitterExtents}set emitterExtentsInner(e){this._setValue("emitterExtentsInner",e)}get emitterExtentsInner(){return this.data.emitterExtentsInner}set emitterRadius(e){this._setValue("emitterRadius",e)}get emitterRadius(){return this.data.emitterRadius}set emitterRadiusInner(e){this._setValue("emitterRadiusInner",e)}get emitterRadiusInner(){return this.data.emitterRadiusInner}set initialVelocity(e){this._setValue("initialVelocity",e)}get initialVelocity(){return this.data.initialVelocity}set wrap(e){this._setValue("wrap",e)}get wrap(){return this.data.wrap}set wrapBounds(e){this._setValue("wrapBounds",e)}get wrapBounds(){return this.data.wrapBounds}set localSpace(e){this._setValue("localSpace",e)}get localSpace(){return this.data.localSpace}set screenSpace(e){this._setValue("screenSpace",e)}get screenSpace(){return this.data.screenSpace}set colorMapAsset(e){this._setValue("colorMapAsset",e)}get colorMapAsset(){return this.data.colorMapAsset}set normalMapAsset(e){this._setValue("normalMapAsset",e)}get normalMapAsset(){return this.data.normalMapAsset}set mesh(e){this._setValue("mesh",e)}get mesh(){return this.data.mesh}set meshAsset(e){this._setValue("meshAsset",e)}get meshAsset(){return this.data.meshAsset}set renderAsset(e){this._setValue("renderAsset",e)}get renderAsset(){return this.data.renderAsset}set orientation(e){this._setValue("orientation",e)}get orientation(){return this.data.orientation}set particleNormal(e){this._setValue("particleNormal",e)}get particleNormal(){return this.data.particleNormal}set localVelocityGraph(e){this._setValue("localVelocityGraph",e)}get localVelocityGraph(){return this.data.localVelocityGraph}set localVelocityGraph2(e){this._setValue("localVelocityGraph2",e)}get localVelocityGraph2(){return this.data.localVelocityGraph2}set velocityGraph(e){this._setValue("velocityGraph",e)}get velocityGraph(){return this.data.velocityGraph}set velocityGraph2(e){this._setValue("velocityGraph2",e)}get velocityGraph2(){return this.data.velocityGraph2}set rotationSpeedGraph(e){this._setValue("rotationSpeedGraph",e)}get rotationSpeedGraph(){return this.data.rotationSpeedGraph}set rotationSpeedGraph2(e){this._setValue("rotationSpeedGraph2",e)}get rotationSpeedGraph2(){return this.data.rotationSpeedGraph2}set radialSpeedGraph(e){this._setValue("radialSpeedGraph",e)}get radialSpeedGraph(){return this.data.radialSpeedGraph}set radialSpeedGraph2(e){this._setValue("radialSpeedGraph2",e)}get radialSpeedGraph2(){return this.data.radialSpeedGraph2}set scaleGraph(e){this._setValue("scaleGraph",e)}get scaleGraph(){return this.data.scaleGraph}set scaleGraph2(e){this._setValue("scaleGraph2",e)}get scaleGraph2(){return this.data.scaleGraph2}set colorGraph(e){this._setValue("colorGraph",e)}get colorGraph(){return this.data.colorGraph}set colorGraph2(e){this._setValue("colorGraph2",e)}get colorGraph2(){return this.data.colorGraph2}set alphaGraph(e){this._setValue("alphaGraph",e)}get alphaGraph(){return this.data.alphaGraph}set alphaGraph2(e){this._setValue("alphaGraph2",e)}get alphaGraph2(){return this.data.alphaGraph2}set colorMap(e){this._setValue("colorMap",e)}get colorMap(){return this.data.colorMap}set normalMap(e){this._setValue("normalMap",e)}get normalMap(){return this.data.normalMap}set animTilesX(e){this._setValue("animTilesX",e)}get animTilesX(){return this.data.animTilesX}set animTilesY(e){this._setValue("animTilesY",e)}get animTilesY(){return this.data.animTilesY}set animStartFrame(e){this._setValue("animStartFrame",e)}get animStartFrame(){return this.data.animStartFrame}set animNumFrames(e){this._setValue("animNumFrames",e)}get animNumFrames(){return this.data.animNumFrames}set animNumAnimations(e){this._setValue("animNumAnimations",e)}get animNumAnimations(){return this.data.animNumAnimations}set animIndex(e){this._setValue("animIndex",e)}get animIndex(){return this.data.animIndex}set randomizeAnimIndex(e){this._setValue("randomizeAnimIndex",e)}get randomizeAnimIndex(){return this.data.randomizeAnimIndex}set animSpeed(e){this._setValue("animSpeed",e)}get animSpeed(){return this.data.animSpeed}set animLoop(e){this._setValue("animLoop",e)}get animLoop(){return this.data.animLoop}set layers(e){this._setValue("layers",e)}get layers(){return this.data.layers}set drawOrder(e){this._drawOrder=e,this.emitter&&(this.emitter.drawOrder=e)}get drawOrder(){return this._drawOrder}_setValue(e,s){let i=this.data,r=i[e];i[e]=s,this.fire("set",e,r,s)}addMeshInstanceToLayers(){if(this.emitter)for(let e=0;e{this._bindColorMapAsset(o)})}else this.colorMap=null}_bindNormalMapAsset(e){if(e.on("load",this._onNormalMapAssetLoad,this),e.on("unload",this._onNormalMapAssetUnload,this),e.on("remove",this._onNormalMapAssetRemove,this),e.on("change",this._onNormalMapAssetChange,this),e.resource)this._onNormalMapAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}}_unbindNormalMapAsset(e){e.off("load",this._onNormalMapAssetLoad,this),e.off("unload",this._onNormalMapAssetUnload,this),e.off("remove",this._onNormalMapAssetRemove,this),e.off("change",this._onNormalMapAssetChange,this)}_onNormalMapAssetLoad(e){this.normalMap=e.resource}_onNormalMapAssetUnload(e){this.normalMap=null}_onNormalMapAssetRemove(e){this._onNormalMapAssetUnload(e)}_onNormalMapAssetChange(e){}onSetNormalMapAsset(e,s,i){let r=this.system.app.assets;if(s){let a=r.get(s);a&&this._unbindNormalMapAsset(a)}if(i){i instanceof ae&&(this.data.normalMapAsset=i.id,i=i.id);let a=r.get(i);a?this._bindNormalMapAsset(a):r.once(`add:${i}`,o=>{this._bindNormalMapAsset(o)})}else this.normalMap=null}_bindMeshAsset(e){if(e.on("load",this._onMeshAssetLoad,this),e.on("unload",this._onMeshAssetUnload,this),e.on("remove",this._onMeshAssetRemove,this),e.on("change",this._onMeshAssetChange,this),e.resource)this._onMeshAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}}_unbindMeshAsset(e){e.off("load",this._onMeshAssetLoad,this),e.off("unload",this._onMeshAssetUnload,this),e.off("remove",this._onMeshAssetRemove,this),e.off("change",this._onMeshAssetChange,this)}_onMeshAssetLoad(e){this._onMeshChanged(e.resource)}_onMeshAssetUnload(e){this.mesh=null}_onMeshAssetRemove(e){this._onMeshAssetUnload(e)}_onMeshAssetChange(e){}onSetMeshAsset(e,s,i){let r=this.system.app.assets;if(s){let a=r.get(s);a&&this._unbindMeshAsset(a)}if(i){i instanceof ae&&(this.data.meshAsset=i.id,i=i.id);let a=r.get(i);a&&this._bindMeshAsset(a)}else this._onMeshChanged(null)}onSetMesh(e,s,i){!i||i instanceof ae||typeof i=="number"?this.meshAsset=i:this._onMeshChanged(i)}_onMeshChanged(e){e&&!(e instanceof _e)&&(e.meshInstances[0]?e=e.meshInstances[0].mesh:e=null),this.data.mesh=e,this.emitter&&(this.emitter.mesh=e,this.emitter.resetMaterial(),this.rebuild())}onSetRenderAsset(e,s,i){let r=this.system.app.assets;if(s){let a=r.get(s);a&&this._unbindRenderAsset(a)}if(i){i instanceof ae&&(this.data.renderAsset=i.id,i=i.id);let a=r.get(i);a&&this._bindRenderAsset(a)}else this._onRenderChanged(null)}_bindRenderAsset(e){if(e.on("load",this._onRenderAssetLoad,this),e.on("unload",this._onRenderAssetUnload,this),e.on("remove",this._onRenderAssetRemove,this),e.resource)this._onRenderAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}}_unbindRenderAsset(e){e.off("load",this._onRenderAssetLoad,this),e.off("unload",this._onRenderAssetUnload,this),e.off("remove",this._onRenderAssetRemove,this),this._evtSetMeshes?.off(),this._evtSetMeshes=null}_onRenderAssetLoad(e){this._onRenderChanged(e.resource)}_onRenderAssetUnload(e){this._onRenderChanged(null)}_onRenderAssetRemove(e){this._onRenderAssetUnload(e)}_onRenderChanged(e){if(!e){this._onMeshChanged(null);return}this._evtSetMeshes?.off(),this._evtSetMeshes=e.on("set:meshes",this._onRenderSetMeshes,this),e.meshes&&this._onRenderSetMeshes(e.meshes)}_onRenderSetMeshes(e){this._onMeshChanged(e&&e[0])}onSetLoop(e,s,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetTime())}onSetBlendType(e,s,i){this.emitter&&(this.emitter[e]=i,this.emitter.material.blendType=i,this.emitter.resetMaterial(),this.rebuild())}_requestDepth(){this._requestedDepth||(Ym||(Ym=this.system.app.scene.layers.getLayerById(Zt)),Ym&&(Ym.incrementCounter(),this._requestedDepth=!0))}_releaseDepth(){this._requestedDepth&&Ym&&(Ym.decrementCounter(),this._requestedDepth=!1)}onSetDepthSoftening(e,s,i){s!==i&&(i?(this.enabled&&this.entity.enabled&&this._requestDepth(),this.emitter&&(this.emitter[e]=i)):(this.enabled&&this.entity.enabled&&this._releaseDepth(),this.emitter&&(this.emitter[e]=i)),this.emitter&&(this.reset(),this.emitter.resetMaterial(),this.rebuild()))}onSetSimpleProperty(e,s,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetMaterial())}onSetComplexProperty(e,s,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetMaterial(),this.rebuild(),this.reset())}onSetGraphProperty(e,s,i){this.emitter&&(this.emitter[e]=i,this.emitter.rebuildGraphs(),this.emitter.resetMaterial())}onEnable(){let e=this.system.app.scene,s=e.layers,i=this.data;for(let r=0,a=W0.length;r=0)o=this.system.app.assets.get(o);else continue;o&&!o.resource&&this.system.app.assets.load(o)}}if(!this.system.app.graphicsDevice.disableParticleSystem){if(!this.emitter){let r=i.mesh;r instanceof _e||(r=null),this.emitter=new Xp(this.system.app.graphicsDevice,{numParticles:i.numParticles,emitterExtents:i.emitterExtents,emitterExtentsInner:i.emitterExtentsInner,emitterRadius:i.emitterRadius,emitterRadiusInner:i.emitterRadiusInner,emitterShape:i.emitterShape,initialVelocity:i.initialVelocity,wrap:i.wrap,localSpace:i.localSpace,screenSpace:i.screenSpace,wrapBounds:i.wrapBounds,lifetime:i.lifetime,rate:i.rate,rate2:i.rate2,orientation:i.orientation,particleNormal:i.particleNormal,animTilesX:i.animTilesX,animTilesY:i.animTilesY,animStartFrame:i.animStartFrame,animNumFrames:i.animNumFrames,animNumAnimations:i.animNumAnimations,animIndex:i.animIndex,randomizeAnimIndex:i.randomizeAnimIndex,animSpeed:i.animSpeed,animLoop:i.animLoop,startAngle:i.startAngle,startAngle2:i.startAngle2,scaleGraph:i.scaleGraph,scaleGraph2:i.scaleGraph2,colorGraph:i.colorGraph,colorGraph2:i.colorGraph2,alphaGraph:i.alphaGraph,alphaGraph2:i.alphaGraph2,localVelocityGraph:i.localVelocityGraph,localVelocityGraph2:i.localVelocityGraph2,velocityGraph:i.velocityGraph,velocityGraph2:i.velocityGraph2,rotationSpeedGraph:i.rotationSpeedGraph,rotationSpeedGraph2:i.rotationSpeedGraph2,radialSpeedGraph:i.radialSpeedGraph,radialSpeedGraph2:i.radialSpeedGraph2,colorMap:i.colorMap,normalMap:i.normalMap,loop:i.loop,preWarm:i.preWarm,sort:i.sort,stretch:i.stretch,alignToMotion:i.alignToMotion,lighting:i.lighting,halfLambert:i.halfLambert,intensity:i.intensity,depthSoftening:i.depthSoftening,scene:this.system.app.scene,mesh:r,depthWrite:i.depthWrite,noFog:i.noFog,node:this.entity,blendType:i.blendType}),this.emitter.meshInstance.node=this.entity,this.emitter.drawOrder=this.drawOrder,i.autoPlay||(this.pause(),this.emitter.meshInstance.visible=!1)}this.emitter.colorMap&&this.addMeshInstanceToLayers(),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),s&&(this._evtLayerAdded=s.on("add",this.onLayerAdded,this),this._evtLayerRemoved=s.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&i.depthSoftening&&this._requestDepth()}}onDisable(){let s=this.system.app.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,s&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.emitter&&(this.removeMeshInstanceFromLayers(),this.data.depthSoftening&&this._releaseDepth(),this.emitter.camera=null)}onBeforeRemove(){this.enabled&&(this.enabled=!1),this.emitter&&(this.emitter.destroy(),this.emitter=null);for(let e=0;e= 0.0; inLife = tex2.w; } -`,particleInputRgba8PS:` +`;var VB=` #define PI2 6.283185307179586 uniform vec3 inBoundsSize; uniform vec3 inBoundsCenter; @@ -12315,7 +12659,7 @@ void readInput(float uv) { float maxPosLife = lifetime+1.0; inLife = inLife * (maxNegLife + maxPosLife) - maxNegLife; } -`,particleOutputFloatPS:` +`;var HB=` void writeOutput() { if (gl_FragCoord.y<1.0) { gl_FragColor = vec4(outPos, (outAngle + 1000.0) * visMode); @@ -12323,7 +12667,7 @@ void writeOutput() { gl_FragColor = vec4(outVel, outLife); } } -`,particleOutputRgba8PS:` +`;var WB=` uniform vec3 outBoundsMul; uniform vec3 outBoundsAdd; vec2 encodeFloatRG( float v ) { @@ -12355,7 +12699,7 @@ void writeOutput() { gl_FragColor = encodeFloatRGBA(outLife); } } -`,particleUpdaterAABBPS:` +`;var XB=` uniform mat3 spawnBounds; uniform vec3 spawnPosInnerRatio; vec3 calcSpawnPosition(vec3 inBounds, float rndFactor) { @@ -12375,10 +12719,10 @@ vec3 calcSpawnPosition(vec3 inBounds, float rndFactor) { void addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) { localVelocity -= vec3(0, 0, initialVelocity); } -`,particleUpdaterEndPS:` +`;var YB=` writeOutput(); } -`,particleUpdaterInitPS:` +`;var KB=` varying vec2 vUv0; uniform highp sampler2D particleTexIN; uniform highp sampler2D internalTex0; @@ -12416,20 +12760,20 @@ vec3 outVel; float outAngle; bool outShow; float outLife; -`,particleUpdaterNoRespawnPS:` +`;var jB=` if (outLife >= lifetime) { outLife -= max(lifetime, numParticles * particleRate); visMode = -1.0; } -`,particleUpdaterOnStopPS:` +`;var qB=` visMode = outLife < 0.0? -1.0: visMode; -`,particleUpdaterRespawnPS:` +`;var $B=` if (outLife >= lifetime) { outLife -= max(lifetime, numParticles * particleRate); visMode = 1.0; } visMode = outLife < 0.0? 1.0: visMode; -`,particleUpdaterSpherePS:` +`;var ZB=` uniform float spawnBoundsSphere; uniform float spawnBoundsSphereInnerRatio; vec3 calcSpawnPosition(vec3 inBounds, float rndFactor) { @@ -12445,7 +12789,7 @@ vec3 calcSpawnPosition(vec3 inBounds, float rndFactor) { void addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) { localVelocity += normalize(inBounds - vec3(0.5)) * initialVelocity; } -`,particleUpdaterStartPS:` +`;var QB=` float saturate(float x) { return clamp(x, 0.0, 1.0); } @@ -12510,19 +12854,19 @@ void main(void) { #endif outPos = inPos + outVel * delta; outAngle = inAngle + rotSpeed * delta; -`,particle_billboardVS:` +`;var JB=` quadXY = rotate(quadXY, inAngle, rotMatrix); vec3 localPos = billboard(particlePos, quadXY); -`,particle_blendAddPS:` +`;var eU=` dBlendModeFogFactor = 0.0; rgb *= saturate(gammaCorrectInput(max(a, 0.0))); if ((rgb.r + rgb.g + rgb.b) < 0.000001) discard; -`,particle_blendMultiplyPS:` +`;var tU=` rgb = mix(vec3(1.0), rgb, vec3(a)); if (rgb.r + rgb.g + rgb.b > 2.99) discard; -`,particle_blendNormalPS:` +`;var sU=` if (a < 0.01) discard; -`,particle_cpuVS:` +`;var iU=` attribute vec4 particle_vertexData; attribute vec4 particle_vertexData2; attribute vec4 particle_vertexData3; @@ -12604,7 +12948,7 @@ void main(void) float inAngle = particle_vertexData2.x; vec3 particlePosMoved = vec3(0.0); vec3 meshLocalPos = particle_vertexData3.xyz; -`,particle_cpu_endVS:` +`;var rU=` localPos *= particle_vertexData2.y * emitterScale; localPos += particlePos; #ifdef SCREEN_SPACE @@ -12612,16 +12956,16 @@ void main(void) #else gl_Position = matrix_viewProjection * vec4(localPos, 1.0); #endif -`,particle_customFaceVS:` +`;var aU=` quadXY = rotate(quadXY, inAngle, rotMatrix); vec3 localPos = customFace(particlePos, quadXY); -`,particle_endPS:` +`;var oU=` rgb = addFog(rgb); rgb = toneMap(rgb); rgb = gammaCorrectOutput(rgb); gl_FragColor = vec4(rgb, a); } -`,particle_endVS:` +`;var nU=` localPos *= scale * emitterScale; localPos += particlePos; #ifdef SCREEN_SPACE @@ -12629,12 +12973,12 @@ void main(void) #else gl_Position = matrix_viewProjection * vec4(localPos.xyz, 1.0); #endif -`,particle_halflambertPS:` +`;var lU=` vec3 negNormal = normal * 0.5 + 0.5; vec3 posNormal = -normal * 0.5 + 0.5; negNormal *= negNormal; posNormal *= posNormal; -`,particle_initVS:` +`;var cU=` attribute vec4 particle_vertexData; #if defined(USE_MESH) #if defined(USE_MESH_UV) @@ -12689,29 +13033,29 @@ vec3 inVel; float inAngle; bool inShow; float inLife; -`,particle_lambertPS:` +`;var hU=` vec3 negNormal = max(normal, vec3(0.0)); vec3 posNormal = max(-normal, vec3(0.0)); -`,particle_lightingPS:` +`;var fU=` vec3 light = negNormal.x*lightCube[0] + posNormal.x*lightCube[1] + negNormal.y*lightCube[2] + posNormal.y*lightCube[3] + negNormal.z*lightCube[4] + posNormal.z*lightCube[5]; rgb *= light; -`,particle_localShiftVS:` +`;var uU=` particlePos = (matrix_model * vec4(particlePos, 1.0)).xyz; -`,particle_meshVS:` +`;var dU=` vec3 localPos = meshLocalPos; localPos.xy = rotate(localPos.xy, inAngle, rotMatrix); localPos.yz = rotate(localPos.yz, inAngle, rotMatrix); billboard(particlePos, quadXY); -`,particle_normalVS:` +`;var pU=` Normal = normalize(localPos + matrix_viewInverse[2].xyz); -`,particle_normalMapPS:` +`;var mU=` vec3 normalMap = normalize(texture2D(normalMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)).xyz * 2.0 - 1.0); vec3 normal = ParticleMat * normalMap; -`,particle_pointAlongVS:` +`;var _U=` inAngle = atan(velocityV.x, velocityV.y); -`,particle_simulationPS:` +`;var gU=` #include "particleUpdaterInitPS" #ifdef PACK8 #include "particleInputRgba8PS" @@ -12736,7 +13080,7 @@ float inLife; #include "particleUpdaterOnStopPS" #endif #include "particleUpdaterEndPS" -`,particle_shaderPS:` +`;var SU=` #if NORMAL != NONE #if NORMAL == VERTEX varying vec3 Normal; @@ -12782,7 +13126,7 @@ float inLife; #include "particle_blendMultiplyPS" #endif #include "particle_endPS" -`,particle_shaderVS:` +`;var xU=` #ifdef ANIMTEX uniform vec2 animTexTilesParams; uniform vec4 animTexParams; @@ -12860,30 +13204,30 @@ float inLife; #include "particle_softVS" #endif } -`,particle_softPS:` +`;var vU=` float depth = getLinearScreenDepth(); float particleDepth = vDepth; float depthDiff = saturate(abs(particleDepth - depth) * softening); a *= depthDiff; -`,particle_softVS:` +`;var TU=` vDepth = getLinearDepth(localPos); -`,particle_stretchVS:` +`;var yU=` vec3 moveDir = inVel * stretch; vec3 posPrev = particlePos - moveDir; posPrev += particlePosMoved; vec2 centerToVertexV = normalize((mat3(matrix_view) * localPos).xy); float interpolation = dot(-velocityV, centerToVertexV) * 0.5 + 0.5; particlePos = mix(particlePos, posPrev, interpolation); -`,particle_TBNVS:` +`;var EU=` mat3 rot3 = mat3(rotMatrix[0][0], rotMatrix[0][1], 0.0, rotMatrix[1][0], rotMatrix[1][1], 0.0, 0.0, 0.0, 1.0); ParticleMat = mat3(-matrix_viewInverse[0].xyz, -matrix_viewInverse[1].xyz, matrix_viewInverse[2].xyz) * rot3; -`,particle_wrapVS:` +`;var AU=` vec3 origParticlePos = particlePos; particlePos -= matrix_model[3].xyz; particlePos = mod(particlePos, wrapBounds) - wrapBounds * 0.5; particlePos += matrix_model[3].xyz; particlePosMoved = particlePos - origParticlePos; -`},gf={particlePS:` +`;var CU={particlePS:NB,particleVS:BB,particleAnimFrameClampVS:UB,particleAnimFrameLoopVS:kB,particleAnimTexVS:zB,particleInputFloatPS:GB,particleInputRgba8PS:VB,particleOutputFloatPS:HB,particleOutputRgba8PS:WB,particleUpdaterAABBPS:XB,particleUpdaterEndPS:YB,particleUpdaterInitPS:KB,particleUpdaterNoRespawnPS:jB,particleUpdaterOnStopPS:qB,particleUpdaterRespawnPS:$B,particleUpdaterSpherePS:ZB,particleUpdaterStartPS:QB,particle_billboardVS:JB,particle_blendAddPS:eU,particle_blendMultiplyPS:tU,particle_blendNormalPS:sU,particle_cpuVS:iU,particle_cpu_endVS:rU,particle_customFaceVS:aU,particle_endPS:oU,particle_endVS:nU,particle_halflambertPS:lU,particle_initVS:cU,particle_lambertPS:hU,particle_lightingPS:fU,particle_localShiftVS:uU,particle_meshVS:dU,particle_normalVS:pU,particle_normalMapPS:mU,particle_pointAlongVS:_U,particle_simulationPS:gU,particle_shaderPS:SU,particle_shaderVS:xU,particle_softPS:vU,particle_softVS:TU,particle_stretchVS:yU,particle_TBNVS:EU,particle_wrapVS:AU};var PU=` varying texCoordsAlphaLife: vec4f; var colorMap: texture_2d; var colorMapSampler: sampler; @@ -12911,7 +13255,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { ramp.a = ramp.a + input.texCoordsAlphaLife.z; var rgb: vec3f = tex.rgb * ramp.rgb; var a: f32 = tex.a * ramp.a; -`,particleVS:` +`;var wU=` fn unpack3NFloats(src: f32) -> vec3f { let r = fract(src); let g = fract(src * 256.0); @@ -13008,11 +13352,11 @@ fn vertexMain(input: VertexInput) -> VertexOutput { var particlePos = inPos; var particlePosMoved = vec3f(0.0); var rotMatrix: mat2x2f; -`,particleAnimFrameClampVS:` +`;var IU=` let animFrame: f32 = min(floor(input.texCoordsAlphaLife.w * uniform.animTexParams.y) + uniform.animTexParams.x, uniform.animTexParams.z); -`,particleAnimFrameLoopVS:` +`;var RU=` let animFrame: f32 = floor((output.texCoordsAlphaLife.w * uniform.animTexParams.y + uniform.animTexParams.x) % (uniform.animTexParams.z + 1.0)); -`,particleAnimTexVS:` +`;var bU=` var animationIndex: f32; if (uniform.animTexIndexParams.y == 1.0) { animationIndex = floor((uniform.animTexParams.w + 1.0) * rndFactor3.z) * (uniform.animTexParams.z + 1.0); @@ -13026,7 +13370,7 @@ fn vertexMain(input: VertexInput) -> VertexOutput { let scaled_tcal_xy = current_tcal_xy * uniform.animTexTilesParams.xy; let final_tcal_xy = scaled_tcal_xy + vec2f(atlasX, atlasY); output.texCoordsAlphaLife = vec4f(final_tcal_xy, output.texCoordsAlphaLife.z, output.texCoordsAlphaLife.w); -`,particleInputFloatPS:` +`;var DU=` fn readInput(uv: f32) { let textureSize = textureDimensions(particleTexIN, 0); let texel0: vec2i = vec2i(vec2f(uv, 0.25) * vec2f(textureSize)); @@ -13039,7 +13383,7 @@ fn readInput(uv: f32) { inShow = tex.w >= 0.0; inLife = tex2.w; } -`,particleInputRgba8PS:` +`;var LU=` const PI2: f32 = 6.283185307179586; uniform inBoundsSize: vec3f; uniform inBoundsCenter: vec3f; @@ -13070,7 +13414,7 @@ fn readInput(uv: f32) { let maxNegLife = max(uniform.lifetime, uniform.numParticles * (uniform.rate + uniform.rateDiv)); let maxPosLife = uniform.lifetime + 1.0; inLife = life_decoded * (maxNegLife + maxPosLife) - maxNegLife; -}`,particleOutputFloatPS:` +}`;var MU=` fn getOutput() -> vec4f { if (pcPosition.y < 1.0) { return vec4f(outPos, (outAngle + 1000.0) * visMode); @@ -13078,7 +13422,7 @@ fn getOutput() -> vec4f { return vec4f(outVel, outLife); } } -`,particleOutputRgba8PS:` +`;var OU=` uniform outBoundsMul: vec3f; uniform outBoundsAdd: vec3f; fn encodeFloatRG( v: f32 ) -> vec2f { @@ -13111,7 +13455,7 @@ fn getOutput() -> vec4f { return encodeFloatRGBA(outLife); } } -`,particleUpdaterAABBPS:` +`;var FU=` uniform spawnBounds: mat3x3f; uniform spawnPosInnerRatio: vec3f; fn calcSpawnPosition(inBounds: vec3f, rndFactor: f32) -> vec3f { @@ -13132,11 +13476,11 @@ fn calcSpawnPosition(inBounds: vec3f, rndFactor: f32) -> vec3f { fn addInitialVelocity(localVelocity: ptr, inBounds: vec3f) { *localVelocity = *localVelocity - vec3f(0.0, 0.0, uniform.initialVelocity); } -`,particleUpdaterEndPS:` +`;var NU=` output.color = getOutput(); return output; } -`,particleUpdaterInitPS:` +`;var BU=` varying vUv0: vec2f; var particleTexIN: texture_2d; var internalTex0: texture_2d; @@ -13174,21 +13518,21 @@ var outVel: vec3f; var outAngle: f32; var outShow: bool; var outLife: f32; -`,particleUpdaterNoRespawnPS:` +`;var UU=` if (outLife >= uniform.lifetime) { outLife = outLife - max(uniform.lifetime, uniform.numParticles * particleRate); visMode = -1.0; } -`,particleUpdaterOnStopPS:` +`;var kU=` visMode = select(visMode, -1.0, outLife < 0.0); -`,particleUpdaterRespawnPS:` +`;var zU=` if (outLife >= uniform.lifetime) { let subtractAmount = max(uniform.lifetime, uniform.numParticles * particleRate); outLife = outLife - subtractAmount; visMode = 1.0; } visMode = select(visMode, 1.0, outLife < 0.0); -`,particleUpdaterSpherePS:` +`;var GU=` uniform spawnBoundsSphere: f32; uniform spawnBoundsSphereInnerRatio: f32; fn calcSpawnPosition(inBounds: vec3f, rndFactor: f32) -> vec3f { @@ -13205,7 +13549,7 @@ fn addInitialVelocity(localVelocity: ptr, inBounds: vec3f) { let initialVelOffset: vec3f = normalize(inBounds - vec3f(0.5)) * uniform.initialVelocity; *localVelocity = *localVelocity + initialVelOffset; } -`,particleUpdaterStartPS:` +`;var VU=` fn saturate(x: f32) -> f32 { return clamp(x, 0.0, 1.0); } @@ -13288,27 +13632,27 @@ fn fragmentMain(input : FragmentInput) -> FragmentOutput { #endif outPos = inPos + outVel * uniform.delta; outAngle = inAngle + rotSpeed * uniform.delta; -`,particle_billboardVS:` +`;var HU=` let rotationResult = rotateWithMatrix(quadXY, inAngle); let rotatedQuadXY = rotationResult.rotatedVec; rotMatrix = rotationResult.matrix; var localPos = billboard(particlePos, rotatedQuadXY); -`,particle_blendAddPS:` +`;var WU=` dBlendModeFogFactor = 0.0; rgb = rgb * saturate(gammaCorrectInput(max(a, 0.0))); if ((rgb.r + rgb.g + rgb.b) < 0.000001) { discard; } -`,particle_blendMultiplyPS:` +`;var XU=` rgb = mix(vec3f(1.0), rgb, a); if ((rgb.r + rgb.g + rgb.b) > 2.99) { discard; } -`,particle_blendNormalPS:` +`;var YU=` if (a < 0.01) { discard; } -`,particle_cpuVS:` +`;var KU=` attribute particle_vertexData: vec4f; attribute particle_vertexData2: vec4f; attribute particle_vertexData3: vec4f; @@ -13397,7 +13741,7 @@ fn vertexMain(input: VertexInput) -> VertexOutput { var inAngle = input.particle_vertexData2.x; var particlePosMoved = vec3f(0.0); let meshLocalPos = input.particle_vertexData3.xyz; -`,particle_cpu_endVS:` +`;var jU=` localPos = localPos * input.particle_vertexData2.y * uniform.emitterScale; localPos = localPos + particlePos; #ifdef SCREEN_SPACE @@ -13405,19 +13749,19 @@ fn vertexMain(input: VertexInput) -> VertexOutput { #else output.position = uniform.matrix_viewProjection * vec4f(localPos, 1.0); #endif -`,particle_customFaceVS:` +`;var qU=` let rotationResult = rotateWithMatrix(quadXY, inAngle); let rotatedQuadXY = rotationResult.rotatedVec; rotMatrix = rotationResult.matrix; var localPos = customFace(particlePos, rotatedQuadXY); -`,particle_endPS:` +`;var $U=` rgb = addFog(rgb); rgb = toneMap(rgb); rgb = gammaCorrectOutput(rgb); output.color = vec4f(rgb, a); return output; } -`,particle_endVS:` +`;var ZU=` localPos = localPos * scale * uniform.emitterScale; localPos = localPos + particlePos; #ifdef SCREEN_SPACE @@ -13425,12 +13769,12 @@ fn vertexMain(input: VertexInput) -> VertexOutput { #else output.position = uniform.matrix_viewProjection * vec4f(localPos.xyz, 1.0); #endif -`,particle_halflambertPS:` +`;var QU=` var negNormal: vec3f = normal * 0.5 + 0.5; var posNormal: vec3f = -normal * 0.5 + 0.5; negNormal = negNormal * negNormal; posNormal = posNormal * posNormal; -`,particle_initVS:` +`;var JU=` attribute particle_vertexData: vec4f; #if defined(USE_MESH) #if defined(USE_MESH_UV) @@ -13485,17 +13829,17 @@ var inVel: vec3f; var inAngle: f32; var inShow: bool; var inLife: f32; -`,particle_lambertPS:` +`;var ek=` var negNormal: vec3f = max(normal, vec3(0.0)); var posNormal: vec3f = max(-normal, vec3(0.0)); -`,particle_lightingPS:` +`;var tk=` let light: vec3f = negNormal.x * uniform.lightCube[0] + posNormal.x * uniform.lightCube[1] + negNormal.y * uniform.lightCube[2] + posNormal.y * uniform.lightCube[3] + negNormal.z * uniform.lightCube[4] + posNormal.z * uniform.lightCube[5]; rgb = rgb * light; -`,particle_localShiftVS:` +`;var sk=` particlePos = (uniform.matrix_model * vec4f(particlePos, 1.0)).xyz; -`,particle_meshVS:` +`;var ik=` var localPos = meshLocalPos; let rotResultXY = rotateWithMatrix(localPos.xy, inAngle); localPos = vec3f(rotResultXY.rotatedVec, localPos.z); @@ -13504,16 +13848,16 @@ let rotResultYZ = rotateWithMatrix(localPos.yz, inAngle); localPos = vec3f(localPos.x, rotResultYZ.rotatedVec); rotMatrix = rotResultYZ.matrix; billboard(particlePos, quadXY); -`,particle_normalVS:` +`;var rk=` output.Normal = normalize(localPos + uniform.matrix_viewInverse[2].xyz); -`,particle_normalMapPS:` +`;var ak=` let sampledNormal: vec4f = textureSample(normalMap, normalMapSampler, vec2f(input.texCoordsAlphaLife.x, 1.0 - input.texCoordsAlphaLife.y)); let normalMap: vec3f = normalize(sampledNormal.xyz * 2.0 - 1.0); let ParticleMat = mat3x3(ParticleMat0, ParticleMat1, ParticleMat2); let normal: vec3f = ParticleMat * normalMap; -`,particle_pointAlongVS:` +`;var ok=` inAngle = atan2(velocityV.x, velocityV.y); -`,particle_simulationPS:` +`;var nk=` #include "particleUpdaterInitPS" #ifdef PACK8 #include "particleInputRgba8PS" @@ -13538,7 +13882,7 @@ output.Normal = normalize(localPos + uniform.matrix_viewInverse[2].xyz); #include "particleUpdaterOnStopPS" #endif #include "particleUpdaterEndPS" -`,particle_shaderPS:` +`;var lk=` #if NORMAL != NONE #if NORMAL == VERTEX varying Normal: vec3f; @@ -13587,7 +13931,7 @@ output.Normal = normalize(localPos + uniform.matrix_viewInverse[2].xyz); #include "particle_blendMultiplyPS" #endif #include "particle_endPS" -`,particle_shaderVS:` +`;var ck=` #ifdef ANIMTEX uniform animTexTilesParams: vec2f; uniform animTexParams: vec4f; @@ -13668,14 +14012,14 @@ output.Normal = normalize(localPos + uniform.matrix_viewInverse[2].xyz); #endif return output; } -`,particle_softPS:` +`;var hk=` var depth: f32 = getLinearScreenDepthFrag(); var particleDepth: f32 = vDepth; var depthDiff: f32 = saturate(abs(particleDepth - depth) * uniform.softening); a = a * depthDiff; -`,particle_softVS:` +`;var fk=` output.vDepth = getLinearDepth(localPos); -`,particle_stretchVS:` +`;var uk=` let moveDir: vec3f = inVel * uniform.stretch; var posPrev: vec3f = particlePos - moveDir; posPrev = posPrev + particlePosMoved; @@ -13683,7 +14027,7 @@ output.Normal = normalize(localPos + uniform.matrix_viewInverse[2].xyz); let centerToVertexV: vec2f = normalize((viewRotationTemp * localPos).xy); let interpolation: f32 = dot(-velocityV, centerToVertexV) * 0.5 + 0.5; particlePos = mix(particlePos, posPrev, interpolation); -`,particle_TBNVS:` +`;var dk=` let rot3 = mat3x3f( vec3f(rotMatrix[0][0], rotMatrix[1][0], 0.0), vec3f(rotMatrix[0][1], rotMatrix[1][1], 0.0), @@ -13698,16 +14042,16 @@ output.Normal = normalize(localPos + uniform.matrix_viewInverse[2].xyz); output.ParticleMat0 = tempMat[0]; output.ParticleMat1 = tempMat[1]; output.ParticleMat2 = tempMat[2]; -`,particle_wrapVS:` +`;var pk=` let origParticlePos: vec3f = particlePos; particlePos = particlePos - uniform.matrix_model[3].xyz; particlePos = (particlePos % uniform.wrapBounds) - uniform.wrapBounds * 0.5; particlePos = particlePos + uniform.matrix_model[3].xyz; particlePosMoved = particlePos - origParticlePos; -`},gp=["enabled","autoPlay","numParticles","lifetime","rate","rate2","startAngle","startAngle2","loop","preWarm","lighting","halfLambert","intensity","depthWrite","noFog","depthSoftening","sort","blendType","stretch","alignToMotion","emitterShape","emitterExtents","emitterExtentsInner","emitterRadius","emitterRadiusInner","initialVelocity","wrap","wrapBounds","localSpace","screenSpace","colorMapAsset","normalMapAsset","mesh","meshAsset","renderAsset","orientation","particleNormal","localVelocityGraph","localVelocityGraph2","velocityGraph","velocityGraph2","rotationSpeedGraph","rotationSpeedGraph2","radialSpeedGraph","radialSpeedGraph2","scaleGraph","scaleGraph2","colorGraph","colorGraph2","alphaGraph","alphaGraph2","colorMap","normalMap","animTilesX","animTilesY","animStartFrame","animNumFrames","animNumAnimations","animIndex","randomizeAnimIndex","animSpeed","animLoop","layers"];class gm extends pT{initializeComponentData(e,t,i){let s={};i=[];let r=this.propertyTypes;for(let e in (t.mesh instanceof fX||"number"==typeof t.mesh)&&(t.meshAsset=t.mesh,delete t.mesh),t){if(t.hasOwnProperty(e)&&(i.push(e),s[e]=t[e]),"vec3"===r[e])Array.isArray(s[e])&&(s[e]=new ed(s[e][0],s[e][1],s[e][2]));else if("curve"===r[e]){if(!(s[e]instanceof ea)){let t=s[e].type;s[e]=new ea(s[e].keys),s[e].type=t;}}else if("curveset"===r[e]&&!(s[e]instanceof en)){let t=s[e].type;s[e]=new en(s[e].keys),s[e].type=t;}s.layers&&Array.isArray(s.layers)&&(s.layers=s.layers.slice(0));}super.initializeComponentData(e,s,i);}cloneComponent(e,t){let i=e.particlesystem.data,s=this.schema,r={};for(let e=0,t=s.length;e=t.fixedTimeStep&&(s=Math.floor(t.simTime/t.fixedTimeStep),t.simTime-=s*t.fixedTimeStep),s){s=Math.min(s,t.maxSubSteps);for(let e=0;et.skin===e);t&&(t.incRefCount(),i=t.skinInstance);}return i}static addCachedSkinInstance(e,t,i){let s=gg._skinInstanceCache.get(t);s||(s=[],gg._skinInstanceCache.set(t,s));let r=s.find(t=>t.skin===e);r||(r=new g_(e,i),s.push(r)),r.incRefCount();}static removeCachedSkinInstance(e){if(e){let t=e.rootBone;if(t){let i=gg._skinInstanceCache.get(t);if(i){let s=i.findIndex(t=>t.skinInstance===e);if(s>=0){let r=i[s];r.decRefCount(),0===r.refCount&&(i.splice(s,1),i.length||gg._skinInstanceCache.delete(t),e&&(e.destroy(),r.skinInstance=null));}}}}}}gg._skinInstanceCache=new Map;class gv{set id(e){if(this.url)throw Error("Can't set id and url");this._unbind(),this._id=e,this.asset=this._registry.get(this._id),this._bind();}get id(){return this._id}set url(e){if(this.id)throw Error("Can't set id and url");this._unbind(),this._url=e,this.asset=this._registry.getByUrl(this._url),this._bind();}get url(){return this._url}_bind(){this.id&&(this._onAssetLoad&&(this._evtLoadById=this._registry.on(`load:${this.id}`,this._onLoad,this)),this._onAssetAdd&&(this._evtAddById=this._registry.once(`add:${this.id}`,this._onAdd,this)),this._onAssetRemove&&(this._evtRemoveById=this._registry.on(`remove:${this.id}`,this._onRemove,this)),this._onAssetUnload&&(this._evtUnloadById=this._registry.on(`unload:${this.id}`,this._onUnload,this))),this.url&&(this._onAssetLoad&&(this._evtLoadByUrl=this._registry.on(`load:url:${this.url}`,this._onLoad,this)),this._onAssetAdd&&(this._evtAddByUrl=this._registry.once(`add:url:${this.url}`,this._onAdd,this)),this._onAssetRemove&&(this._evtRemoveByUrl=this._registry.on(`remove:url:${this.url}`,this._onRemove,this)));}_unbind(){this.id&&(this._evtLoadById?.off(),this._evtLoadById=null,this._evtAddById?.off(),this._evtAddById=null,this._evtRemoveById?.off(),this._evtRemoveById=null,this._evtUnloadById?.off(),this._evtUnloadById=null),this.url&&(this._evtLoadByUrl?.off(),this._evtLoadByUrl=null,this._evtAddByUrl?.off(),this._evtAddByUrl=null,this._evtRemoveByUrl?.off(),this._evtRemoveByUrl=null);}_onLoad(e){this._onAssetLoad.call(this._scope,this.propertyName,this.parent,e);}_onAdd(e){this.asset=e,this._onAssetAdd.call(this._scope,this.propertyName,this.parent,e);}_onRemove(e){this._onAssetRemove.call(this._scope,this.propertyName,this.parent,e),this.asset=null;}_onUnload(e){this._onAssetUnload.call(this._scope,this.propertyName,this.parent,e);}constructor(e,t,i,s,r){this._evtLoadById=null,this._evtUnloadById=null,this._evtAddById=null,this._evtRemoveById=null,this._evtLoadByUrl=null,this._evtAddByUrl=null,this._evtRemoveByUrl=null,this.propertyName=e,this.parent=t,this._scope=r,this._registry=i,this.id=null,this.url=null,this.asset=null,this._onAssetLoad=s.load,this._onAssetAdd=s.add,this._onAssetRemove=s.remove,this._onAssetUnload=s.unload;}}class gS extends px{set renderStyle(e){this._renderStyle!==e&&(this._renderStyle=e,oS._prepareRenderStyleForArray(this._meshInstances,e));}get renderStyle(){return this._renderStyle}set customAabb(e){this._customAabb=e;let t=this._meshInstances;if(t)for(let e=0;e=0&&this.system.app.batcher?.remove(n7.RENDER,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(n7.RENDER,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addToLayers(),this._batchGroupId=e);}get batchGroupId(){return this._batchGroupId}set material(e){if(this._material!==e&&(this._material=e,this._meshInstances&&"asset"!==this._type))for(let t=0;te.length){for(let t=e.length;te.id)}set asset(e){let t=e instanceof fX?e.id:e;this._assetReference.id!==t&&(this._assetReference.asset&&this._assetReference.asset.resource&&this._onRenderAssetRemove(),this._assetReference.id=t,this._assetReference.asset&&this._onRenderAssetAdded());}get asset(){return this._assetReference.id}assignAsset(e){let t=e instanceof fX?e.id:e;this._assetReference.id=t;}set rootBone(e){if(this._rootBone!==e){let t="string"==typeof e;this._rootBone&&t&&this._rootBone.getGuid()===e||(this._rootBone&&this._clearSkinInstances(),e instanceof oJ?this._rootBone=e:t?(this._rootBone=this.system.app.getEntityFromIndex(e)||null,this._rootBone):this._rootBone=null,this._rootBone&&this._cloneSkinInstances());}}get rootBone(){return this._rootBone}destroyMeshInstances(){let e=this._meshInstances;if(e){this.removeFromLayers(),this._clearSkinInstances();for(let t=0;tthis.layers.indexOf(e.id)||e.addMeshInstances(this._meshInstances);}onLayerRemoved(e){0>this.layers.indexOf(e.id)||e.removeMeshInstances(this._meshInstances);}onEnable(){let e=this.system.app,t=e.scene,i=t.layers;this._rootBone&&this._cloneSkinInstances(),this._evtLayersChanged=t.on("set:layers",this.onLayersChanged,this),i&&(this._evtLayerAdded=i.on("add",this.onLayerAdded,this),this._evtLayerRemoved=i.on("remove",this.onLayerRemoved,this));let s="asset"===this._type;this._meshInstances&&this._meshInstances.length?this.addToLayers():s&&this.asset&&this._onRenderAssetAdded();for(let e=0;e=0&&e.batcher?.insert(n7.RENDER,this.batchGroupId,this.entity);}onDisable(){let e=this.system.app,t=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,this._rootBone&&this._clearSkinInstances(),t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._batchGroupId>=0&&e.batcher?.remove(n7.RENDER,this.batchGroupId,this.entity),this.removeFromLayers();}hide(){if(this._meshInstances)for(let e=0;ee.mesh);s._onSetMeshes(a);for(let e=0;ethis._pool.length)for(let t=this._pool.length;t=this._pool.length&&this._resize(2*this._pool.length),this._pool[this._count++]}freeAll(){this._count=0;}constructor(e,t){this._pool=[],this._count=0,this._constructor=e,this._resize(t);}}let gb=new ex,gC=new ex,gA=new ed;class gP extends px{static onLibraryLoaded(){"u">typeof Ammo&&(h=new Ammo.btTransform,c=new Ammo.btVector3,d=new Ammo.btVector3,u=new Ammo.btQuaternion);}static onAppDestroy(){Ammo.destroy(h),Ammo.destroy(c),Ammo.destroy(d),Ammo.destroy(u),h=null,c=null,d=null,u=null;}set angularDamping(e){this._angularDamping!==e&&(this._angularDamping=e,this._body&&this._body.setDamping(this._linearDamping,e));}get angularDamping(){return this._angularDamping}set angularFactor(e){!this._angularFactor.equals(e)&&(this._angularFactor.copy(e),this._body&&this._type===mW&&(c.setValue(e.x,e.y,e.z),this._body.setAngularFactor(c)));}get angularFactor(){return this._angularFactor}set angularVelocity(e){this._body&&this._type===mW&&(this._body.activate(),c.setValue(e.x,e.y,e.z),this._body.setAngularVelocity(c),this._angularVelocity.copy(e));}get angularVelocity(){if(this._body&&this._type===mW){let e=this._body.getAngularVelocity();this._angularVelocity.set(e.x(),e.y(),e.z());}return this._angularVelocity}set body(e){this._body!==e&&(this._body=e,e&&this._simulationEnabled&&e.activate());}get body(){return this._body}set friction(e){this._friction!==e&&(this._friction=e,this._body&&this._body.setFriction(e));}get friction(){return this._friction}set group(e){this._group!==e&&(this._group=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()));}get group(){return this._group}set linearDamping(e){this._linearDamping!==e&&(this._linearDamping=e,this._body&&this._body.setDamping(e,this._angularDamping));}get linearDamping(){return this._linearDamping}set linearFactor(e){!this._linearFactor.equals(e)&&(this._linearFactor.copy(e),this._body&&this._type===mW&&(c.setValue(e.x,e.y,e.z),this._body.setLinearFactor(c)));}get linearFactor(){return this._linearFactor}set linearVelocity(e){this._body&&this._type===mW&&(this._body.activate(),c.setValue(e.x,e.y,e.z),this._body.setLinearVelocity(c),this._linearVelocity.copy(e));}get linearVelocity(){if(this._body&&this._type===mW){let e=this._body.getLinearVelocity();this._linearVelocity.set(e.x(),e.y(),e.z());}return this._linearVelocity}set mask(e){this._mask!==e&&(this._mask=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()));}get mask(){return this._mask}set mass(e){if(this._mass!==e&&(this._mass=e,this._body&&this._type===mW)){let t=this.enabled&&this.entity.enabled;t&&this.disableSimulation(),this._body.getCollisionShape().calculateLocalInertia(e,c),this._body.setMassProps(e,c),this._body.updateInertiaTensor(),t&&this.enableSimulation();}}get mass(){return this._mass}set restitution(e){this._restitution!==e&&(this._restitution=e,this._body&&this._body.setRestitution(e));}get restitution(){return this._restitution}set rollingFriction(e){this._rollingFriction!==e&&(this._rollingFriction=e,this._body&&this._body.setRollingFriction(e));}get rollingFriction(){return this._rollingFriction}set type(e){if(this._type!==e){switch(this._type=e,this.disableSimulation(),e){case mW:this._group=1,this._mask=65535;break;case mX:this._group=4,this._mask=65535;break;default:this._group=2,this._mask=65533;}this.createBody();}}get type(){return this._type}createBody(){let e,t=this.entity;if(t.collision&&(e=t.collision.shape,t.trigger&&(t.trigger.destroy(),delete t.trigger)),e){this._body&&(this.system.removeBody(this._body),this.system.destroyBody(this._body),this._body=null);let i=this._type===mW?this._mass:0;this._getEntityTransform(h);let s=this.system.createBody(i,e,h);if(s.setRestitution(this._restitution),s.setFriction(this._friction),s.setRollingFriction(this._rollingFriction),s.setDamping(this._linearDamping,this._angularDamping),this._type===mW){let e=this._linearFactor;c.setValue(e.x,e.y,e.z),s.setLinearFactor(c);let t=this._angularFactor;c.setValue(t.x,t.y,t.z),s.setAngularFactor(c);}else this._type===mX&&(s.setCollisionFlags(2|s.getCollisionFlags()),s.setActivationState(4));s.entity=t,this.body=s,this.enabled&&t.enabled&&this.enableSimulation();}}isActive(){return !!this._body&&this._body.isActive()}activate(){this._body&&this._body.activate();}enableSimulation(){let e=this.entity;if(e.collision&&e.collision.enabled&&!this._simulationEnabled){let t=this._body;if(t){switch(this.system.addBody(t,this._group,this._mask),this._type){case mW:this.system._dynamic.push(this),t.forceActivationState(1),this.syncEntityToBody();break;case mX:this.system._kinematic.push(this),t.forceActivationState(4);break;case mH:t.forceActivationState(1),this.syncEntityToBody();}"compound"===e.collision.type&&this.system._compounds.push(e.collision),t.activate(),this._simulationEnabled=true;}}}disableSimulation(){let e=this._body;if(e&&this._simulationEnabled){let t=this.system,i=t._compounds.indexOf(this.entity.collision);i>-1&&t._compounds.splice(i,1),(i=t._dynamic.indexOf(this))>-1&&t._dynamic.splice(i,1),(i=t._kinematic.indexOf(this))>-1&&t._kinematic.splice(i,1),t.removeBody(e),e.forceActivationState(5),this._simulationEnabled=false;}}applyForce(e,t,i,s,r,a){let n=this._body;n&&(n.activate(),e instanceof ed?c.setValue(e.x,e.y,e.z):c.setValue(e,t,i),t instanceof ed?d.setValue(t.x,t.y,t.z):void 0!==s?d.setValue(s,r,a):d.setValue(0,0,0),n.applyForce(c,d));}applyTorque(e,t,i){let s=this._body;s&&(s.activate(),e instanceof ed?c.setValue(e.x,e.y,e.z):c.setValue(e,t,i),s.applyTorque(c));}applyImpulse(e,t,i,s,r,a){let n=this._body;n&&(n.activate(),e instanceof ed?c.setValue(e.x,e.y,e.z):c.setValue(e,t,i),t instanceof ed?d.setValue(t.x,t.y,t.z):void 0!==s?d.setValue(s,r,a):d.setValue(0,0,0),n.applyImpulse(c,d));}applyTorqueImpulse(e,t,i){let s=this._body;s&&(s.activate(),e instanceof ed?c.setValue(e.x,e.y,e.z):c.setValue(e,t,i),s.applyTorqueImpulse(c));}isStatic(){return this._type===mH}isStaticOrKinematic(){return this._type===mH||this._type===mX}isKinematic(){return this._type===mX}_getEntityTransform(e){let t=this.entity,i=t.collision;if(i){let e=i.getShapePosition(),t=i.getShapeRotation();c.setValue(e.x,e.y,e.z),u.setValue(t.x,t.y,t.z,t.w);}else {let e=t.getPosition(),i=t.getRotation();c.setValue(e.x,e.y,e.z),u.setValue(i.x,i.y,i.z,i.w);}e.setOrigin(c),e.setRotation(u);}syncEntityToBody(){let e=this._body;if(e){if(this._getEntityTransform(h),e.setWorldTransform(h),this._type===mX){let t=e.getMotionState();t&&t.setWorldTransform(h);}e.activate();}}_updateDynamic(){let e=this._body;if(e.isActive()){let t=e.getMotionState();if(t){let e=this.entity;t.getWorldTransform(h);let i=h.getOrigin(),s=h.getRotation(),r=e.collision;if(r&&r._hasOffset){let t=r.data.linearOffset,a=r.data.angularOffset,n=gC.copy(a).invert(),o=gb.set(s.x(),s.y(),s.z(),s.w()).mul(n);o.transformVector(t,gA),e.setPosition(i.x()-gA.x,i.y()-gA.y,i.z()-gA.z),e.setRotation(o);}else e.setPosition(i.x(),i.y(),i.z()),e.setRotation(s.x(),s.y(),s.z(),s.w());}}}_updateKinematic(){let e=this._body.getMotionState();e&&(this._getEntityTransform(h),e.setWorldTransform(h));}teleport(e,t,i,s,r,a){e instanceof ed?this.entity.setPosition(e):this.entity.setPosition(e,t,i),t instanceof ex?this.entity.setRotation(t):t instanceof ed?this.entity.setEulerAngles(t):void 0!==s&&this.entity.setEulerAngles(s,r,a),this.syncEntityToBody();}onEnable(){this._body||this.createBody(),this.enableSimulation();}onDisable(){this.disableSimulation();}constructor(...e){super(...e),this._angularDamping=0,this._angularFactor=new ed(1,1,1),this._angularVelocity=new ed,this._body=null,this._friction=.5,this._group=2,this._linearDamping=0,this._linearFactor=new ed(1,1,1),this._linearVelocity=new ed,this._mask=65533,this._mass=1,this._restitution=0,this._rollingFriction=0,this._simulationEnabled=false,this._type=mH;}}gP.EVENT_CONTACT="contact",gP.EVENT_COLLISIONSTART="collisionstart",gP.EVENT_COLLISIONEND="collisionend",gP.EVENT_TRIGGERENTER="triggerenter",gP.EVENT_TRIGGERLEAVE="triggerleave",gP.order=-1;class gI{constructor(){this.enabled=true;}}class gD{constructor(e,t,i,s){this.entity=e,this.point=t,this.normal=i,this.hitFraction=s;}}class gR{constructor(e,t,i){0!=arguments.length?(this.a=e,this.b=t,this.impulse=i.impulse,this.localPointA=i.localPoint,this.localPointB=i.localPointOther,this.pointA=i.point,this.pointB=i.pointOther,this.normal=i.normal):(this.a=null,this.b=null,this.impulse=0,this.localPointA=new ed,this.localPointB=new ed,this.pointA=new ed,this.pointB=new ed,this.normal=new ed);}}class gL{constructor(e=new ed,t=new ed,i=new ed,s=new ed,r=new ed,a=0){this.localPoint=e,this.localPointOther=t,this.point=i,this.pointOther=s,this.normal=r,this.impulse=a;}}class gM{constructor(e,t){this.other=e,this.contacts=t;}}let gO=["enabled"];class gF extends pT{onLibraryLoaded(){if("u">typeof Ammo){if(this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.overlappingPairCache=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.dynamicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.overlappingPairCache,this.solver,this.collisionConfiguration),this.dynamicsWorld.setInternalTickCallback){let e=Ammo.addFunction(this._checkForCollisions.bind(this),"vif");this.dynamicsWorld.setInternalTickCallback(e);}f=new Ammo.btVector3,p=new Ammo.btVector3,gP.onLibraryLoaded(),this.contactPointPool=new gw(gL,1),this.contactResultPool=new gw(gM,1),this.singleContactResultPool=new gw(gR,1),this.app.systems.on("update",this.onUpdate,this);}else this.app.systems.off("update",this.onUpdate,this);}initializeComponentData(e,t,i){for(let i of ["mass","linearDamping","angularDamping","linearFactor","angularFactor","friction","rollingFriction","restitution","type","group","mask"])if(t.hasOwnProperty(i)){let s=t[i];Array.isArray(s)?e[i]=new ed(s[0],s[1],s[2]):e[i]=s;}super.initializeComponentData(e,t,["enabled"]);}cloneComponent(e,t){let i=e.rigidbody,s={enabled:i.enabled,mass:i.mass,linearDamping:i.linearDamping,angularDamping:i.angularDamping,linearFactor:[i.linearFactor.x,i.linearFactor.y,i.linearFactor.z],angularFactor:[i.angularFactor.x,i.angularFactor.y,i.angularFactor.z],friction:i.friction,rollingFriction:i.rollingFriction,restitution:i.restitution,type:i.type,group:i.group,mask:i.mask};return this.addComponent(t,s)}onBeforeRemove(e,t){t.enabled&&(t.enabled=false),t.body&&(this.destroyBody(t.body),t.body=null);}addBody(e,t,i){ void 0!==t&&void 0!==i?this.dynamicsWorld.addRigidBody(e,t,i):this.dynamicsWorld.addRigidBody(e);}removeBody(e){this.dynamicsWorld.removeRigidBody(e);}createBody(e,t,i){let s=new Ammo.btVector3(0,0,0);0!==e&&t.calculateLocalInertia(e,s);let r=new Ammo.btDefaultMotionState(i),a=new Ammo.btRigidBodyConstructionInfo(e,r,t,s),n=new Ammo.btRigidBody(a);return Ammo.destroy(a),Ammo.destroy(s),n}destroyBody(e){let t=e.getMotionState();t&&Ammo.destroy(t),Ammo.destroy(e);}raycastFirst(e,t,i={}){if(i.filterTags||i.filterCallback)return i.sort=true,this.raycastAll(e,t,i)[0]||null;let s=null;f.setValue(e.x,e.y,e.z),p.setValue(t.x,t.y,t.z);let r=new Ammo.ClosestRayResultCallback(f,p);if("number"==typeof i.filterCollisionGroup&&r.set_m_collisionFilterGroup(i.filterCollisionGroup),"number"==typeof i.filterCollisionMask&&r.set_m_collisionFilterMask(i.filterCollisionMask),this.dynamicsWorld.rayTest(f,p,r),r.hasHit()){let e=r.get_m_collisionObject(),t=Ammo.castObject(e,Ammo.btRigidBody);if(t){let e=r.get_m_hitPointWorld(),i=r.get_m_hitNormalWorld();s=new gD(t.entity,new ed(e.x(),e.y(),e.z()),new ed(i.x(),i.y(),i.z()),r.get_m_closestHitFraction());}}return Ammo.destroy(r),s}raycastAll(e,t,i={}){let s=[];f.setValue(e.x,e.y,e.z),p.setValue(t.x,t.y,t.z);let r=new Ammo.AllHitsRayResultCallback(f,p);if("number"==typeof i.filterCollisionGroup&&r.set_m_collisionFilterGroup(i.filterCollisionGroup),"number"==typeof i.filterCollisionMask&&r.set_m_collisionFilterMask(i.filterCollisionMask),this.dynamicsWorld.rayTest(f,p,r),r.hasHit()){let e=r.get_m_collisionObjects(),t=r.get_m_hitPointWorld(),a=r.get_m_hitNormalWorld(),n=r.get_m_hitFractions(),o=e.size();for(let r=0;re.hitFraction-t.hitFraction);}return Ammo.destroy(r),s}_storeCollision(e,t){let i=false,s=e.getGuid();return this.collisions[s]=this.collisions[s]||{others:[],entity:e},0>this.collisions[s].others.indexOf(t)&&(this.collisions[s].others.push(t),i=true),this.frameCollisions[s]=this.frameCollisions[s]||{others:[],entity:e},this.frameCollisions[s].others.push(t),i}_createContactPointFromAmmo(e){let t=e.get_m_localPointA(),i=e.get_m_localPointB(),s=e.getPositionWorldOnA(),r=e.getPositionWorldOnB(),a=e.get_m_normalWorldOnB(),n=this.contactPointPool.allocate();return n.localPoint.set(t.x(),t.y(),t.z()),n.localPointOther.set(i.x(),i.y(),i.z()),n.point.set(s.x(),s.y(),s.z()),n.pointOther.set(r.x(),r.y(),r.z()),n.normal.set(a.x(),a.y(),a.z()),n.impulse=e.getAppliedImpulse(),n}_createReverseContactPointFromAmmo(e){let t=e.get_m_localPointA(),i=e.get_m_localPointB(),s=e.getPositionWorldOnA(),r=e.getPositionWorldOnB(),a=e.get_m_normalWorldOnB(),n=this.contactPointPool.allocate();return n.localPointOther.set(t.x(),t.y(),t.z()),n.localPoint.set(i.x(),i.y(),i.z()),n.pointOther.set(s.x(),s.y(),s.z()),n.point.set(r.x(),r.y(),r.z()),n.normal.set(a.x(),a.y(),a.z()),n.impulse=e.getAppliedImpulse(),n}_createSingleContactResult(e,t,i){let s=this.singleContactResultPool.allocate();return s.a=e,s.b=t,s.localPointA=i.localPoint,s.localPointB=i.localPointOther,s.pointA=i.point,s.pointB=i.pointOther,s.normal=i.normal,s.impulse=i.impulse,s}_createContactResult(e,t){let i=this.contactResultPool.allocate();return i.other=e,i.contacts=t,i}_cleanOldCollisions(){for(let e in this.collisions)if(this.collisions.hasOwnProperty(e)){let t=this.frameCollisions[e],i=this.collisions[e],s=i.entity,r=s.collision,a=s.rigidbody,n=i.others,o=n.length;for(;o--;){let e=n[o];(!t||0>t.others.indexOf(e))&&(n.splice(o,1),s.trigger?(r&&r.fire("triggerleave",e),e.rigidbody&&e.rigidbody.fire("triggerleave",s)):!e.trigger&&(a&&a.fire("collisionend",e),r&&r.fire("collisionend",e)));}0===n.length&&delete this.collisions[e];}}_hasContactEvent(e){let t=e.collision;if(t&&(t.hasEvent("collisionstart")||t.hasEvent("collisionend")||t.hasEvent("contact")))return true;let i=e.rigidbody;return i&&(i.hasEvent("collisionstart")||i.hasEvent("collisionend")||i.hasEvent("contact"))}_checkForCollisions(e,t){let i=Ammo.wrapPointer(e,Ammo.btDynamicsWorld).getDispatcher(),s=i.getNumManifolds();this.frameCollisions={};for(let e=0;e0)if(4&c||4&d){let e=l.collision&&(l.collision.hasEvent("triggerenter")||l.collision.hasEvent("triggerleave")),i=h.collision&&(h.collision.hasEvent("triggerenter")||h.collision.hasEvent("triggerleave")),s=l.rigidbody&&(l.rigidbody.hasEvent("triggerenter")||l.rigidbody.hasEvent("triggerleave")),r=h.rigidbody&&(h.rigidbody.hasEvent("triggerenter")||h.rigidbody.hasEvent("triggerleave"));e&&(t=this._storeCollision(l,h))&&!(4&d)&&l.collision.fire("triggerenter",h),i&&(t=this._storeCollision(h,l))&&!(4&c)&&h.collision.fire("triggerenter",l),s&&(t||(t=this._storeCollision(h,l)),t&&l.rigidbody.fire("triggerenter",h)),r&&(t||(t=this._storeCollision(l,h)),t&&h.rigidbody.fire("triggerenter",l));}else {let e=this._hasContactEvent(l),i=this._hasContactEvent(h),r=this.hasEvent("contact");if(r||e||i){for(let t=0;ttypeof Ammo&&(Ammo.destroy(this.dynamicsWorld),Ammo.destroy(this.solver),Ammo.destroy(this.overlappingPairCache),Ammo.destroy(this.dispatcher),Ammo.destroy(this.collisionConfiguration),Ammo.destroy(f),Ammo.destroy(p),this.dynamicsWorld=null,this.solver=null,this.overlappingPairCache=null,this.dispatcher=null,this.collisionConfiguration=null,f=null,p=null,gP.onAppDestroy());}constructor(e){super(e),this.maxSubSteps=10,this.fixedTimeStep=1/60,this.gravity=new ed(0,-9.81,0),this._gravityFloat32=new Float32Array(3),this._dynamic=[],this._kinematic=[],this._triggers=[],this._compounds=[],this.id="rigidbody",this._stats=e.stats.frame,this.ComponentType=gP,this.DataType=gI,this.contactPointPool=null,this.contactResultPool=null,this.singleContactResultPool=null,this.schema=gO,this.collisions={},this.frameCollisions={},this.on("beforeremove",this.onBeforeRemove,this);}}gF.EVENT_CONTACT="contact",px._buildAccessors(gP.prototype,gO);let gN="none",gB="blend",gk=new ey;class gU extends px{syncDrawOrder(){this.system.queueDrawOrderSync(this.entity.getGuid(),this._processDrawOrderSync,this);}_recurseDrawOrderSync(e,t){if(!(e instanceof f9))return t;if(e.element){let i=e.element.drawOrder;e.element.drawOrder=t++,e.element._batchGroupId>=0&&i!==e.element.drawOrder&&this.system.app.batcher?.markGroupDirty(e.element._batchGroupId);}e.particlesystem&&(e.particlesystem.drawOrder=t++);let i=e.children;for(let e=0;ee._onScreenRemove()),this._elements.clear(),this.off();}set resolution(e){this._screenSpace?this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height):this._resolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:resolution",this._resolution),this._elements.forEach(e=>e._onScreenResize(this._resolution));}get resolution(){return this._resolution}set referenceResolution(e){this._referenceResolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:referenceresolution",this._resolution),this._elements.forEach(e=>e._onScreenResize(this._resolution));}get referenceResolution(){return this._scaleMode===gN?this._resolution:this._referenceResolution}set screenSpace(e){this._screenSpace=e,this._screenSpace&&this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height),this.resolution=this._resolution,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:screenspace",this._screenSpace),this._elements.forEach(e=>e._onScreenSpaceChange());}get screenSpace(){return this._screenSpace}set scaleMode(e){e!==gN&&e!==gB&&(e=gN),this._screenSpace||e===gN||(e=gN),this._scaleMode=e,this.resolution=this._resolution,this.fire("set:scalemode",this._scaleMode);}get scaleMode(){return this._scaleMode}set scaleBlend(e){this._scaleBlend=e,this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:scaleblend",this._scaleBlend),this._elements.forEach(e=>e._onScreenResize(this._resolution));}get scaleBlend(){return this._scaleBlend}set priority(e){e=ei.clamp(e,0,127),this._priority!==e&&(this._priority=e,this.syncDrawOrder());}get priority(){return this._priority}constructor(e,t){super(e,t),this._resolution=new ef(640,320),this._referenceResolution=new ef(640,320),this._scaleMode=gN,this.scale=1,this._scaleBlend=.5,this._priority=0,this._screenSpace=false,this.cull=this._screenSpace,this._screenMatrix=new ey,this._elements=new Set,e.app.graphicsDevice.on("resizecanvas",this._onResize,this);}}class gz{constructor(){this.enabled=true;}}let gV=["enabled"];class gG extends pT{initializeComponentData(e,t,i){ void 0!==t.priority&&(e.priority=t.priority),void 0!==t.screenSpace&&(e.screenSpace=t.screenSpace),e.cull=e.screenSpace,void 0!==t.scaleMode&&(e.scaleMode=t.scaleMode),void 0!==t.scaleBlend&&(e.scaleBlend=t.scaleBlend),void 0!==t.resolution&&(t.resolution instanceof ef?e._resolution.copy(t.resolution):e._resolution.set(t.resolution[0],t.resolution[1]),e.resolution=e._resolution),void 0!==t.referenceResolution&&(t.referenceResolution instanceof ef?e._referenceResolution.copy(t.referenceResolution):e._referenceResolution.set(t.referenceResolution[0],t.referenceResolution[1]),e.referenceResolution=e._referenceResolution),this._updateDescendantElements(e.entity,e.entity),e.syncDrawOrder(),super.initializeComponentData(e,t,gV);}_updateDescendantElements(e,t){let i=e.children;for(let e=0;ethis.dragThreshold||Math.abs(i)>this.dragThreshold)&&this._disableContentInput();}}_horizontalScrollbarEntitySubscribe(){this._evtHorizontalScrollbarAdd=this._horizontalScrollbarEntity.on("scrollbar:add",this._onHorizontalScrollbarGain,this),this._horizontalScrollbarEntity.scrollbar&&this._onHorizontalScrollbarGain();}_verticalScrollbarEntitySubscribe(){this._evtVerticalScrollbarAdd=this._verticalScrollbarEntity.on("scrollbar:add",this._onVerticalScrollbarGain,this),this._verticalScrollbarEntity.scrollbar&&this._onVerticalScrollbarGain();}_horizontalScrollbarEntityUnsubscribe(){this._evtHorizontalScrollbarAdd?.off(),this._evtHorizontalScrollbarAdd=null,this._horizontalScrollbarEntity.scrollbar&&this._onHorizontalScrollbarLose();}_verticalScrollbarEntityUnsubscribe(){this._evtVerticalScrollbarAdd?.off(),this._evtVerticalScrollbarAdd=null,this._verticalScrollbarEntity.scrollbar&&this._onVerticalScrollbarLose();}_onSetHorizontalScrollbarValue(e){!this._scrollbarUpdateFlags[0]&&this.enabled&&this.entity.enabled&&this._onSetScroll(e,null);}_onSetVerticalScrollbarValue(e){!this._scrollbarUpdateFlags[1]&&this.enabled&&this.entity.enabled&&this._onSetScroll(null,e);}_onHorizontalScrollbarGain(){let e=this._horizontalScrollbarEntity?.scrollbar;this._evtHorizontalScrollbarRemove=e.on("beforeremove",this._onHorizontalScrollbarLose,this),this._evtHorizontalScrollbarValue=e.on("set:value",this._onSetHorizontalScrollbarValue,this),this._syncScrollbarEnabledState(0),this._syncScrollbarPosition(0);}_onVerticalScrollbarGain(){let e=this._verticalScrollbarEntity?.scrollbar;this._evtVerticalScrollbarRemove=e.on("beforeremove",this._onVerticalScrollbarLose,this),this._evtVerticalScrollbarValue=e.on("set:value",this._onSetVerticalScrollbarValue,this),this._syncScrollbarEnabledState(1),this._syncScrollbarPosition(1);}_onHorizontalScrollbarLose(){this._evtHorizontalScrollbarRemove?.off(),this._evtHorizontalScrollbarRemove=null,this._evtHorizontalScrollbarValue?.off(),this._evtHorizontalScrollbarValue=null;}_onVerticalScrollbarLose(){this._evtVerticalScrollbarRemove?.off(),this._evtVerticalScrollbarRemove=null,this._evtVerticalScrollbarValue?.off(),this._evtVerticalScrollbarValue=null;}_onSetHorizontalScrollingEnabled(){this._syncScrollbarEnabledState(0);}_onSetVerticalScrollingEnabled(){this._syncScrollbarEnabledState(1);}_onSetScroll(e,t,i){ false!==i&&this._velocity.set(0,0,0);let s=this._updateAxis(e,"x",0),r=this._updateAxis(t,"y",1);(s||r)&&this.fire("set:scroll",this._scroll);}_updateAxis(e,t,i){let s=null!==e&&Math.abs(e-this._scroll[t])>1e-5;return (s||this._isDragging()||0===e)&&(this._scroll[t]=this._determineNewScrollValue(e,t,i),this._syncContentPosition(i),this._syncScrollbarPosition(i)),s}_determineNewScrollValue(e,t,i){if(!this._getScrollingEnabled(i))return this._scroll[t];switch(this.scrollMode){case 0:return ei.clamp(e,0,this._getMaxScrollValue(i));case 1:return this._setVelocityFromOvershoot(e,t,i),e;default:return e}}_syncAll(){this._syncContentPosition(0),this._syncContentPosition(1),this._syncScrollbarPosition(0),this._syncScrollbarPosition(1),this._syncScrollbarEnabledState(0),this._syncScrollbarEnabledState(1);}_syncContentPosition(e){if(!this._contentEntity)return;let t=this._getAxis(e),i=this._getSign(e),s=this._prevContentSizes[e],r=this._getContentSize(e);if(null!==s&&Math.abs(s-r)>1e-4){let i=this._getMaxOffset(e,s),a=this._getMaxOffset(e,r);0===a?this._scroll[t]=1:this._scroll[t]=ei.clamp(this._scroll[t]*i/a,0,1);}let a=this._scroll[t]*this._getMaxOffset(e),n=this._contentEntity.getLocalPosition();n[t]=a*i,this._contentEntity.setLocalPosition(n),this._prevContentSizes[e]=r;}_syncScrollbarPosition(e){let t=this._scrollbarEntities[e];if(!t?.scrollbar)return;let i=this._getAxis(e);this._scrollbarUpdateFlags[e]=true,t.scrollbar.value=this._scroll[i],t.scrollbar.handleSize=this._getScrollbarHandleSize(i,e),this._scrollbarUpdateFlags[e]=false;}_syncScrollbarEnabledState(e){let t=this._scrollbarEntities[e];if(!t)return;let i=this._getScrollingEnabled(e);switch(this._getScrollbarVisibility(e)){case 0:t.enabled=i;return;case 1:t.enabled=i&&this._contentIsLargerThanViewport(e);return;default:t.enabled=i;}}_contentIsLargerThanViewport(e){return this._getContentSize(e)>this._getViewportSize(e)}_contentPositionToScrollValue(e){let t=this._getMaxOffset(0),i=this._getMaxOffset(1);return 0===t?gQ.x=0:gQ.x=e.x/t,0===i?gQ.y=0:gQ.y=-(e.y/i),gQ}_getMaxOffset(e,t){t=void 0===t?this._getContentSize(e):t;let i=this._getViewportSize(e);return tMath.abs(s))return 1;let r=Math.min(i/s,1),a=this._toOvershoot(this._scroll[e],t);return 0===a?r:r/(1+Math.abs(a))}_getViewportSize(e){return this._getSize(e,this._viewportEntity)}_getContentSize(e){return this._getSize(e,this._contentEntity)}_getSize(e,t){return t?.element?t.element[this._getCalculatedDimension(e)]:0}_getScrollingEnabled(e){return 0===e?this.horizontal:1===e?this.vertical:void 0}_getScrollbarVisibility(e){return 0===e?this.horizontalScrollbarVisibility:1===e?this.verticalScrollbarVisibility:void 0}_getSign(e){return 0===e?1:-1}_getAxis(e){return 0===e?"x":"y"}_getCalculatedDimension(e){return 0===e?"calculatedWidth":"calculatedHeight"}_destroyDragHelper(){this._contentDragHelper&&this._contentDragHelper.destroy();}onUpdate(){this._contentEntity&&(this._updateVelocity(),this._syncScrollbarEnabledState(0),this._syncScrollbarEnabledState(1));}_updateVelocity(){if(!this._isDragging()){if(1===this.scrollMode&&(this._hasOvershoot("x",0)&&this._setVelocityFromOvershoot(this.scroll.x,"x",0),this._hasOvershoot("y",1)&&this._setVelocityFromOvershoot(this.scroll.y,"y",1)),Math.abs(this._velocity.x)>1e-4||Math.abs(this._velocity.y)>1e-4){let e=this._contentEntity.getLocalPosition();e.x+=this._velocity.x,e.y+=this._velocity.y,this._contentEntity.setLocalPosition(e),this._setScrollFromContentPosition(e);}this._velocity.x*=1-this.friction,this._velocity.y*=1-this.friction;}}_hasOvershoot(e,t){return Math.abs(this._toOvershoot(this.scroll[e],t))>.001}_toOvershoot(e,t){let i=this._getMaxScrollValue(t);return e<0?e:e>i?e-i:0}_setVelocityFromOvershoot(e,t,i){let s=this._toOvershoot(e,i)*this._getMaxOffset(i)*this._getSign(i);Math.abs(s)>0&&(this._velocity[t]=-s/(50*this.bounceAmount+1));}_setVelocityFromContentPositionDelta(e){this._prevContentDragPosition?(this._velocity.sub2(e,this._prevContentDragPosition),this._prevContentDragPosition.copy(e)):(this._velocity.set(0,0,0),this._prevContentDragPosition=e.clone());}_setScrollFromContentPosition(e){let t=this._contentPositionToScrollValue(e);this._isDragging()&&(t=this._applyScrollValueTension(t)),this._onSetScroll(t.x,t.y,false);}_applyScrollValueTension(e){let t=this._getMaxScrollValue(0),i=this._toOvershoot(e.x,0);return i>0?e.x=t+ +Math.log10(1+i):i<0&&(e.x=-1*Math.log10(1-i)),t=this._getMaxScrollValue(1),(i=this._toOvershoot(e.y,1))>0?e.y=t+ +Math.log10(1+i):i<0&&(e.y=-1*Math.log10(1-i)),e}_isDragging(){return this._contentDragHelper&&this._contentDragHelper.isDragging}_setScrollbarComponentsEnabled(e){this._horizontalScrollbarEntity?.scrollbar&&(this._horizontalScrollbarEntity.scrollbar.enabled=e),this._verticalScrollbarEntity?.scrollbar&&(this._verticalScrollbarEntity.scrollbar.enabled=e);}_setContentDraggingEnabled(e){this._contentDragHelper&&(this._contentDragHelper.enabled=e);}_onMouseWheel(e){if(!this.useMouseWheel||!this._contentEntity?.element)return;let t=e.event,i=t.deltaX/this._contentEntity.element.calculatedWidth*this.mouseWheelSensitivity.x,s=t.deltaY/this._contentEntity.element.calculatedHeight*this.mouseWheelSensitivity.y,r=ei.clamp(this._scroll.x+i,0,this._getMaxScrollValue(0)),a=ei.clamp(this._scroll.y+s,0,this._getMaxScrollValue(1));this.scroll=new ef(r,a);}_enableContentInput(){for(;this._disabledContentInputEntities.length;){let e=this._disabledContentInputEntities.pop();e.element&&(e.element.useInput=true);}this._disabledContentInput=false;}_disableContentInput(){let e=t=>{t.element&&t.element.useInput&&(this._disabledContentInputEntities.push(t),t.element.useInput=false);let i=t.children;for(let t=0,s=i.length;t1e-5&&(this.data.value=ei.clamp(i,0,1),this._updateHandlePositionAndSize(),this.fire("set:value",this.data.value));}_onSetHandleSize(e,t,i){Math.abs(i-t)>1e-5&&(this.data.handleSize=ei.clamp(i,0,1),this._updateHandlePositionAndSize());}_onSetHandleAlignment(){this._updateHandlePositionAndSize();}_onSetOrientation(e,t,i){i!==t&&this._handleEntity?.element&&(this._handleEntity.element[this._getOppositeDimension()]=0);}_updateHandlePositionAndSize(){let e=this._handleEntity,t=e?.element;if(e){let t=e.getLocalPosition();t[this._getAxis()]=this._getHandlePosition(),e.setLocalPosition(t);}t&&(t[this._getDimension()]=this._getHandleLength());}_handlePositionToScrollValue(e){return e*this._getSign()/this._getUsableTrackLength()}_scrollValueToHandlePosition(e){return e*this._getSign()*this._getUsableTrackLength()}_getUsableTrackLength(){return Math.max(this._getTrackLength()-this._getHandleLength(),.001)}_getTrackLength(){return this.entity.element?0===this.orientation?this.entity.element.calculatedWidth:this.entity.element.calculatedHeight:0}_getHandleLength(){return this._getTrackLength()*this.handleSize}_getHandlePosition(){return this._scrollValueToHandlePosition(this.value)}_getSign(){return 0===this.orientation?1:-1}_getAxis(){return 0===this.orientation?"x":"y"}_getDimension(){return 0===this.orientation?"width":"height"}_getOppositeDimension(){return 0===this.orientation?"height":"width"}_destroyDragHelper(){this._handleDragHelper&&this._handleDragHelper.destroy();}_setHandleDraggingEnabled(e){this._handleDragHelper&&(this._handleDragHelper.enabled=e);}onEnable(){this._setHandleDraggingEnabled(true);}onDisable(){this._setHandleDraggingEnabled(false);}onRemove(){this._destroyDragHelper(),this._toggleLifecycleListeners("off");}resolveDuplicatedEntityReferenceProperties(e,t){e.handleEntity&&(this.handleEntity=t[e.handleEntity.getGuid()]);}constructor(e,t){super(e,t),this._handleEntity=null,this._evtHandleEntityElementAdd=null,this._evtHandleEntityChanges=[],this._toggleLifecycleListeners("on");}}g3.EVENT_SETVALUE="set:value";class g4{constructor(){this.enabled=true,this.orientation=0,this.value=0,this.handleSize=0,this.handleEntity=null;}}let g5=[{name:"enabled",type:"boolean"},{name:"orientation",type:"number"},{name:"value",type:"number"},{name:"handleSize",type:"number"}];class g6 extends pT{initializeComponentData(e,t,i){super.initializeComponentData(e,t,g5),e.handleEntity=t.handleEntity;}_onAddComponent(e){e.fire("scrollbar:add");}_onRemoveComponent(e,t){t.onRemove();}constructor(e){super(e),this.id="scrollbar",this.ComponentType=g3,this.DataType=g4,this.schema=g5,this.on("add",this._onAddComponent,this),this.on("beforeremove",this._onRemoveComponent,this);}}let g8={volume:0,pitch:0,loop:false,startTime:0,duration:0,position:new ed,maxDistance:0,refDistance:0,rollOffFactor:0,distanceModel:0,onPlay:null,onPause:null,onResume:null,onStop:null,onEnd:null};class g9 extends X{play(){if(this.overlap||this.stop(),!this.isLoaded&&!this._hasAsset())return;let e=this._createInstance();if(this.instances.push(e),this.isLoaded)e.play();else {let t=function(t){let i=e._playWhenLoaded;e.sound=t,i&&e.play();};this.off("load",t),this.once("load",t),this.load();}return e}pause(){let e=false,t=this.instances;for(let i=0,s=t.length;i0?i.duration:null,this._startTime=Math.max(0,Number(i.startTime)||0),this._overlap=!!i.overlap,this._autoPlay=!!i.autoPlay,this._firstNode=null,this._lastNode=null,this._asset=i.asset,this._asset instanceof fX&&(this._asset=this._asset.id),this._onInstancePlayHandler=this._onInstancePlay.bind(this),this._onInstancePauseHandler=this._onInstancePause.bind(this),this._onInstanceResumeHandler=this._onInstanceResume.bind(this),this._onInstanceStopHandler=this._onInstanceStop.bind(this),this._onInstanceEndHandler=this._onInstanceEnd.bind(this);}}g9.EVENT_PLAY="play",g9.EVENT_PAUSE="pause",g9.EVENT_RESUME="resume",g9.EVENT_STOP="stop",g9.EVENT_END="end",g9.EVENT_LOAD="load";class g7 extends px{_updateSoundInstances(e,t,i){let s=this._slots;for(let r in s){let a=s[r];if(!a.overlap){let s=a.instances;for(let r=0,n=s.length;r=0;s--){let t=e[s].isPlaying||e[s].isSuspended,r=e[s].currentTime;t&&e[s].stop();let a=i._createInstance();t&&(a.play(),a.currentTime=r),e.push(a);}}}}get positional(){return this._positional}set slots(e){let t=this._slots;if(t)for(let e in t)t[e].stop();let i={};for(let t in e)e[t]instanceof g9?i[e[t].name]=e[t]:e[t].name&&(i[e[t].name]=new g9(this,e[t].name,e[t]));this._slots=i,this.enabled&&this.entity.enabled&&this.onEnable();}get slots(){return this._slots}onEnable(){if(this.system._inTools)return;let e=this._slots,t=this._playingBeforeDisable;for(let i in e){let s=e[i];s.autoPlay&&s.isStopped?s.play():t[i]?s.resume():s.isLoaded||s.load();}}onDisable(){let e=this._slots,t={};for(let i in e)!e[i].overlap&&e[i].isPlaying&&(e[i].pause(),t[i]=true);this._playingBeforeDisable=t;}onRemove(){this.off();}addSlot(e,t){let i=this._slots;if(i[e])return null;let s=new g9(this,e,t);return i[e]=s,s.autoPlay&&this.enabled&&this.entity.enabled&&s.play(),s}removeSlot(e){let t=this._slots;t[e]&&(t[e].stop(),delete t[e]);}slot(e){return this._slots[e]}_getSlotProperty(e,t){if(!this.enabled||!this.entity.enabled)return;let i=this._slots[e];if(i)return i[t]}isPlaying(e){return this._getSlotProperty(e,"isPlaying")||false}isLoaded(e){return this._getSlotProperty(e,"isLoaded")||false}isPaused(e){return this._getSlotProperty(e,"isPaused")||false}isStopped(e){return this._getSlotProperty(e,"isStopped")||false}play(e){if(!this.enabled||!this.entity.enabled)return null;let t=this._slots[e];return t?t.play():null}pause(e){let t=this._slots;if(e){let i=t[e];if(!i)return;i.pause();}else for(let e in t)t[e].pause();}resume(e){let t=this._slots;if(e){let i=t[e];if(!i)return;i.isPaused&&i.resume();}else for(let e in t)t[e].resume();}stop(e){let t=this._slots;if(e){let i=t[e];if(!i)return;i.stop();}else for(let e in t)t[e].stop();}constructor(...e){super(...e),this._volume=1,this._pitch=1,this._positional=true,this._refDistance=1,this._maxDistance=1e4,this._rollOffFactor=1,this._distanceModel=a1,this._slots={},this._playingBeforeDisable={};}}g7.EVENT_PLAY="play",g7.EVENT_PAUSE="pause",g7.EVENT_RESUME="resume",g7.EVENT_STOP="stop",g7.EVENT_END="end";class ve{constructor(){this.enabled=true;}}let vt=["enabled"];class vi extends pT{set volume(e){this.manager.volume=e;}get volume(){return this.manager.volume}get context(){return a7()?this.manager.context:null}initializeComponentData(e,t,i){i=["volume","pitch","positional","refDistance","maxDistance","rollOffFactor","distanceModel","slots"];for(let s=0;ss||i<0;this._setTime(i);let a=this.frame;(a=this._sprite?Math.floor(this._sprite.frameKeys.length*this._time/s):0)!==this._frame&&this._setFrame(a),r&&(this.loop?(this.fire("loop"),this._component.fire("loop",this)):(this._playing=false,this._paused=false,this.fire("end"),this._component.fire("end",this)));}_setTime(e){this._time=e;let t=this.duration;this._time<0?this.loop?this._time=this._time%t+t:this._time=0:this._time>t&&(this.loop?this._time%=t:this._time=t);}_setFrame(e){this._sprite?this._frame=ei.clamp(e,0,this._sprite.frameKeys.length-1):this._frame=e,this._component.currentClip===this&&this._component._showFrame(this._frame);}_destroy(){if(this._spriteAsset){let e=this._component.system.app.assets;this._unbindSpriteAsset(e.get(this._spriteAsset));}this._sprite&&(this.sprite=null),this._spriteAsset&&(this.spriteAsset=null);}play(){this._playing||(this._playing=true,this._paused=false,this.frame=0,this.fire("play"),this._component.fire("play",this));}pause(){this._playing&&!this._paused&&(this._paused=true,this.fire("pause"),this._component.fire("pause",this));}resume(){this._paused&&(this._paused=false,this.fire("resume"),this._component.fire("resume",this));}stop(){this._playing&&(this._playing=false,this._paused=false,this._time=0,this.frame=0,this.fire("stop"),this._component.fire("stop",this));}constructor(e,t){super(),this._evtSetMeshes=null,this._component=e,this._frame=0,this._sprite=null,this._spriteAsset=null,this.spriteAsset=t.spriteAsset,this.name=t.name,this.fps=t.fps||0,this.loop=t.loop||false,this._playing=false,this._paused=false,this._time=0;}}va.EVENT_PLAY="play",va.EVENT_PAUSE="pause",va.EVENT_RESUME="resume",va.EVENT_STOP="stop",va.EVENT_END="end",va.EVENT_LOOP="loop";let vn="texture_emissiveMap",vo="texture_opacityMap",vl="material_emissive",vh="material_opacity";class vc extends px{set type(e){this._type!==e&&(this._type=e,this._type===vs?(this.stop(),this._currentClip=this._defaultClip,this.enabled&&this.entity.enabled&&(this._currentClip.frame=this.frame,this._currentClip.sprite?this._showModel():this._hideModel())):this._type===vr&&(this.stop(),this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.isPlaying&&this.enabled&&this.entity.enabled?this._showModel():this._hideModel()));}get type(){return this._type}set frame(e){this._currentClip.frame=e;}get frame(){return this._currentClip.frame}set spriteAsset(e){this._defaultClip.spriteAsset=e;}get spriteAsset(){return this._defaultClip._spriteAsset}set sprite(e){this._currentClip.sprite=e;}get sprite(){return this._currentClip.sprite}set material(e){this._material=e,this._meshInstance&&(this._meshInstance.material=e);}get material(){return this._material}set color(e){this._color.r=e.r,this._color.g=e.g,this._color.b=e.b,this._meshInstance&&(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(vl,this._colorUniform));}get color(){return this._color}set opacity(e){this._color.a=e,this._meshInstance&&this._meshInstance.setParameter(vh,e);}get opacity(){return this._color.a}set clips(e){if(!e){for(let e in this._clips)this.removeClip(e);return}for(let t in this._clips){let i=false;for(let s in e)if(e[s].name===t){i=true,this._clips[t].fps=e[s].fps,this._clips[t].loop=e[s].loop,e[s].hasOwnProperty("sprite")?this._clips[t].sprite=e[s].sprite:e[s].hasOwnProperty("spriteAsset")&&(this._clips[t].spriteAsset=e[s].spriteAsset);break}i||this.removeClip(t);}for(let t in e)this._clips[e[t].name]||this.addClip(e[t]);this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.sprite||this._hideModel();}get clips(){return this._clips}get currentClip(){return this._currentClip}set speed(e){this._speed=e;}get speed(){return this._speed}set flipX(e){this._flipX!==e&&(this._flipX=e,this._updateTransform());}get flipX(){return this._flipX}set flipY(e){this._flipY!==e&&(this._flipY=e,this._updateTransform());}get flipY(){return this._flipY}set width(e){e!==this._width&&(this._width=e,this._outerScale.x=this._width,this.sprite&&(2===this.sprite.renderMode||1===this.sprite.renderMode)&&this._updateTransform());}get width(){return this._width}set height(e){e!==this._height&&(this._height=e,this._outerScale.y=this.height,this.sprite&&(2===this.sprite.renderMode||1===this.sprite.renderMode)&&this._updateTransform());}get height(){return this._height}set batchGroupId(e){if(this._batchGroupId===e)return;let t=this._batchGroupId;this._batchGroupId=e,this.entity.enabled&&t>=0&&this.system.app.batcher?.remove(n7.SPRITE,t,this.entity),this.entity.enabled&&e>=0?this.system.app.batcher?.insert(n7.SPRITE,e,this.entity):t>=0&&this._currentClip&&this._currentClip.sprite&&this.enabled&&this.entity.enabled&&this._showModel();}get batchGroupId(){return this._batchGroupId}set autoPlayClip(e){this._autoPlayClip=e instanceof va?e.name:e,this._tryAutoPlay();}get autoPlayClip(){return this._autoPlayClip}set drawOrder(e){this._drawOrder=e,this._meshInstance&&(this._meshInstance.drawOrder=e);}get drawOrder(){return this._drawOrder}set layers(e){this._addedModel&&this._hideModel(),this._layers=e,this._meshInstance&&this.enabled&&this.entity.enabled&&this._showModel();}get layers(){return this._layers}get aabb(){return this._meshInstance?this._meshInstance.aabb:null}onEnable(){let e=this.system.app,t=e.scene,i=t.layers;this._evtLayersChanged=t.on("set:layers",this._onLayersChanged,this),i&&(this._evtLayerAdded=i.on("add",this._onLayerAdded,this),this._evtLayerRemoved=i.on("remove",this._onLayerRemoved,this)),this._showModel(),this._autoPlayClip&&this._tryAutoPlay(),this._batchGroupId>=0&&e.batcher?.insert(n7.SPRITE,this._batchGroupId,this.entity);}onDisable(){let e=this.system.app,t=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.stop(),this._hideModel(),this._batchGroupId>=0&&e.batcher?.remove(n7.SPRITE,this._batchGroupId,this.entity);}onDestroy(){for(let e in this._currentClip=null,this._defaultClip&&(this._defaultClip._destroy(),this._defaultClip=null),this._clips)this._clips[e]._destroy();this._clips=null,this._hideModel(),this._model=null,this._node?.remove(),this._node=null,this._meshInstance&&(this._meshInstance.material=null,this._meshInstance.mesh=null,this._meshInstance=null);}_showModel(){if(this._addedModel||!this._meshInstance)return;let e=[this._meshInstance];for(let t=0,i=this._layers.length;tthis.layers.indexOf(e.id))&&this._addedModel&&this.enabled&&this.entity.enabled&&this._meshInstance&&e.addMeshInstances([this._meshInstance]);}_onLayerRemoved(e){!this._meshInstance||0>this.layers.indexOf(e.id)||e.removeMeshInstances([this._meshInstance]);}removeModelFromLayers(){for(let e=0;e=3&&this.size.set(e[0],e[1],e[2]);}get size(){return this._size}onEnable(){this._checkState();}onDisable(){this._checkState();}_onSetEnabled(e,t,i){this._checkState();}_checkState(){let e=this.enabled&&this.entity.enabled;e!==this._oldState&&(this._oldState=e,this.fire("enable"),this.fire("state",this.enabled));}_onBeforeRemove(){this.fire("remove");}constructor(e,t){super(e,t),this._oldState=true,this._size=new ed,this.on("set_enabled",this._onSetEnabled,this);}}vp.EVENT_ENABLE="enable",vp.EVENT_DISABLE="disable",vp.EVENT_STATE="state",vp.EVENT_REMOVE="remove";class vm{constructor(){this.enabled=true;}}let v_=["enabled"];class vg extends pT{initializeComponentData(e,t,i){e.enabled=!t.hasOwnProperty("enabled")||!!t.enabled,t.size&&(t.size instanceof ed?e.size.copy(t.size):t.size instanceof Array&&t.size.length>=3&&e.size.set(t.size[0],t.size[1],t.size[2]));}cloneComponent(e,t){let i={enabled:e.zone.enabled,size:e.zone.size};return this.addComponent(t,i)}_onBeforeRemove(e,t){t._onBeforeRemove();}constructor(e){super(e),this.id="zone",this.ComponentType=vp,this.DataType=vm,this.schema=v_,this.on("beforeremove",this._onBeforeRemove,this);}}px._buildAccessors(vp.prototype,v_);class vv{constructor(e,t){this.effect=e,this.inputTarget=t,this.outputTarget=null,this.name=e.constructor.name;}}class vS{_allocateColorBuffer(e,t){let i=this.camera.rect,s=this.destinationRenderTarget,r=this.app.graphicsDevice,a=Math.floor(i.z*(s?.width??r.width)),n=Math.floor(i.w*(s?.height??r.height));return ic.createDataTexture2D(r,t,a,n,e)}_createOffscreenTarget(e,t){let i=this.app.graphicsDevice,s=(this.destinationRenderTarget??i.backBuffer).isColorBufferSrgb(0),r=(t&&i.getRenderableHdrFormat([12,14],true))??(s?20:7),a=`${this.camera.entity.name}-posteffect-${this.effects.length}`;return new iG({colorBuffer:this._allocateColorBuffer(r,a),depth:e,stencil:e&&this.app.graphicsDevice.supportsStencil,samples:e?i.samples:1})}_resizeOffscreenTarget(e){let t=e.colorBuffer.format,i=e.colorBuffer.name;e.destroyFrameBuffers(),e.destroyTextureBuffers(),e._colorBuffer=this._allocateColorBuffer(t,i),e._colorBuffers=[e._colorBuffer],e.evaluateDimensions();}_destroyOffscreenTarget(e){e.destroyTextureBuffers(),e.destroy();}addEffect(e){let t=this.effects,i=0===t.length,s=this._createOffscreenTarget(i,e.hdr),r=new vv(e,s);t.push(r),this._sourceTarget=r.inputTarget,t.length>1&&(t[t.length-2].outputTarget=r.inputTarget),this._newPostEffect=e,e.needsDepthBuffer&&this._requestDepthMap(),this.enable(),this._newPostEffect=void 0;}removeEffect(e){let t=-1;for(let i=0,s=this.effects.length;i=0&&(t>0?this.effects[t-1].outputTarget=t+11&&(this.effects[1].inputTarget._depth||(this._destroyOffscreenTarget(this.effects[1].inputTarget),this.effects[1].inputTarget=this._createOffscreenTarget(true,this.effects[1].hdr),this._sourceTarget=this.effects[1].inputTarget),this.camera.renderTarget=this.effects[1].inputTarget),this._destroyOffscreenTarget(this.effects[t].inputTarget),this.effects.splice(t,1)),this.enabled&&e.needsDepthBuffer&&this._releaseDepthMap(),0===this.effects.length&&this.disable();}_requestDepthMaps(){for(let e=0,t=this.effects.length;e{if(this.enabled){let e=null,t=this.effects.length;if(t)for(let i=0;i{let t=i.layers.getLayerById(e);t?.removeCamera(this);}),this._camera.layers=e,this.enabled&&this.entity.enabled&&e.forEach(e=>{let t=i.layers.getLayerById(e);t?.addCamera(this);}),this.fire("set:layers");}get layers(){return this._camera.layers}get layersSet(){return this._camera.layersSet}set jitter(e){this._camera.jitter=e;}get jitter(){return this._camera.jitter}set nearClip(e){this._camera.nearClip=e;}get nearClip(){return this._camera.nearClip}set orthoHeight(e){this._camera.orthoHeight=e;}get orthoHeight(){return this._camera.orthoHeight}get postEffects(){return this._postEffects}get postEffectsEnabled(){return this._postEffects.enabled}set priority(e){this._priority=e,this.dirtyLayerCompositionCameras();}get priority(){return this._priority}set projection(e){this._camera.projection=e;}get projection(){return this._camera.projection}get projectionMatrix(){return this._camera.projectionMatrix}set rect(e){this._camera.rect=e,this.fire("set:rect",this._camera.rect);}get rect(){return this._camera.rect}set renderSceneColorMap(e){e&&!this._sceneColorMapRequested?(this.requestSceneColorMap(true),this._sceneColorMapRequested=true):this._sceneColorMapRequested&&(this.requestSceneColorMap(false),this._sceneColorMapRequested=false);}get renderSceneColorMap(){return this._renderSceneColorMap>0}set renderSceneDepthMap(e){e&&!this._sceneDepthMapRequested?(this.requestSceneDepthMap(true),this._sceneDepthMapRequested=true):this._sceneDepthMapRequested&&(this.requestSceneDepthMap(false),this._sceneDepthMapRequested=false);}get renderSceneDepthMap(){return this._renderSceneDepthMap>0}set renderTarget(e){this._camera.renderTarget=e,this.dirtyLayerCompositionCameras();}get renderTarget(){return this._camera.renderTarget}set scissorRect(e){this._camera.scissorRect=e;}get scissorRect(){return this._camera.scissorRect}set sensitivity(e){this._camera.sensitivity=e;}get sensitivity(){return this._camera.sensitivity}set shutter(e){this._camera.shutter=e;}get shutter(){return this._camera.shutter}get viewMatrix(){return this._camera.viewMatrix}_enableDepthLayer(e){if(this.layers.find(e=>1===e)){let t=this.system.app.scene.layers.getLayerById(1);e?t?.incrementCounter():t?.decrementCounter();}else if(e)return false;return true}requestSceneColorMap(e){this._renderSceneColorMap+=e?1:-1,this._enableDepthLayer(e),this.camera._enableRenderPassColorGrab(this.system.app.graphicsDevice,this.renderSceneColorMap),this.system.app.scene.layers.markDirty();}requestSceneDepthMap(e){this._renderSceneDepthMap+=e?1:-1,this._enableDepthLayer(e),this.camera._enableRenderPassDepthGrab(this.system.app.graphicsDevice,this.system.app.renderer,this.renderSceneDepthMap),this.system.app.scene.layers.markDirty();}dirtyLayerCompositionCameras(){this.system.app.scene.layers._dirty=true;}screenToWorld(e,t,i,s){let{width:r,height:a}=this.system.app.graphicsDevice.clientRect;return this._camera.screenToWorld(e,t,i,r,a,s)}worldToScreen(e,t){let{width:i,height:s}=this.system.app.graphicsDevice.clientRect;return this._camera.worldToScreen(e,i,s,t)}onAppPrerender(){this._camera._viewMatDirty=true,this._camera._viewProjMatDirty=true;}addCameraToLayers(){let e=this.layers;for(let t=0;tthis.layers.indexOf(e.id)||e.addCamera(this);}onLayerRemoved(e){0>this.layers.indexOf(e.id)||e.removeCamera(this);}onEnable(){let e=this.system.app.scene,t=e.layers;this.system.addCamera(this),this._evtLayersChanged?.off(),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved?.off(),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addCameraToLayers(),this.postEffects.enable();}onDisable(){let e=this.system.app.scene.layers;this.postEffects.disable(),this.removeCameraFromLayers(),this._evtLayersChanged?.off(),this._evtLayersChanged=null,e&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.system.removeCamera(this);}onRemove(){this.onDisable(),this.off(),this.camera.destroy();}calculateAspectRatio(e){let t=this.system.app.graphicsDevice,i=e?e.width:t.width,s=e?e.height:t.height;return i*this.rect.z/(s*this.rect.w)}frameUpdate(e){0===this.aspectRatioMode&&(this.aspectRatio=this.calculateAspectRatio(e));}startXr(e,t,i){this.system.app.xr.start(this,e,t,i);}endXr(e){if(!this._camera.xr){e&&e(Error("Camera is not in XR"));return}this._camera.xr.end(e);}copy(e){this.aperture=e.aperture,this.aspectRatio=e.aspectRatio,this.aspectRatioMode=e.aspectRatioMode,this.calculateProjection=e.calculateProjection,this.calculateTransform=e.calculateTransform,this.clearColor=e.clearColor,this.clearColorBuffer=e.clearColorBuffer,this.clearDepthBuffer=e.clearDepthBuffer,this.clearStencilBuffer=e.clearStencilBuffer,this.cullFaces=e.cullFaces,this.disablePostEffectsLayer=e.disablePostEffectsLayer,this.farClip=e.farClip,this.flipFaces=e.flipFaces,this.fov=e.fov,this.frustumCulling=e.frustumCulling,this.horizontalFov=e.horizontalFov,this.layers=e.layers,this.nearClip=e.nearClip,this.orthoHeight=e.orthoHeight,this.priority=e.priority,this.projection=e.projection,this.rect=e.rect,this.renderTarget=e.renderTarget,this.scissorRect=e.scissorRect,this.sensitivity=e.sensitivity,this.shutter=e.shutter;}constructor(e,t){super(e,t),this.onPostprocessing=null,this._renderSceneDepthMap=0,this._renderSceneColorMap=0,this._sceneDepthMapRequested=false,this._sceneColorMapRequested=false,this._priority=0,this._disablePostEffectsLayer=4,this._camera=new oN,this._evtLayersChanged=null,this._evtLayerAdded=null,this._evtLayerRemoved=null,this._camera.node=t,this._postEffects=new vS(e.app,this);}}class vx{constructor(){this.enabled=true;}}let vT=["enabled"];class vE extends pT{initializeComponentData(e,t,i){i=["aspectRatio","aspectRatioMode","calculateProjection","calculateTransform","clearColor","clearColorBuffer","clearDepth","clearDepthBuffer","clearStencilBuffer","renderSceneColorMap","renderSceneDepthMap","cullFaces","farClip","flipFaces","fog","fov","frustumCulling","horizontalFov","layers","renderTarget","nearClip","orthoHeight","projection","priority","rect","scissorRect","aperture","shutter","sensitivity","gammaCorrection","toneMapping"];for(let s=0;s=0&&(this.cameras.splice(t,1),this.cameras.sort(hx));}destroy(){this.app.off("prerender",this.onAppPrerender,this),super.destroy();}constructor(e){super(e),this.cameras=[],this.id="camera",this.ComponentType=vy,this.DataType=vx,this.schema=vT,this.on("beforeremove",this.onBeforeRemove,this),this.app.on("prerender",this.onAppPrerender,this);}}px._buildAccessors(vy.prototype,vT);class vw{constructor(){this.enabled=true,this.type="directional",this.color=new es(1,1,1),this.intensity=1,this.luminance=0,this.shape=0,this.affectSpecularity=true,this.castShadows=false,this.shadowDistance=40,this.shadowIntensity=1,this.shadowResolution=1024,this.shadowBias=.05,this.numCascades=1,this.cascadeBlend=0,this.bakeNumSamples=1,this.bakeArea=0,this.cascadeDistribution=.5,this.normalOffsetBias=0,this.range=10,this.innerConeAngle=40,this.outerConeAngle=45,this.falloffMode=0,this.shadowType=0,this.vsmBlurSize=11,this.vsmBlurMode=1,this.vsmBias=.0025,this.cookieAsset=null,this.cookie=null,this.cookieIntensity=1,this.cookieFalloff=true,this.cookieChannel="rgb",this.cookieAngle=0,this.cookieScale=null,this.cookieOffset=null,this.shadowUpdateMode=2,this.mask=1,this.affectDynamic=true,this.affectLightmapped=false,this.bake=false,this.bakeDir=true,this.isStatic=false,this.layers=[0],this.penumbraSize=1,this.penumbraFalloff=1,this.shadowSamples=16,this.shadowBlockerSamples=16;}}let vb=Object.keys(new vw);class vC extends px{get data(){let e=this.system.store[this.entity.getGuid()];return e?e.data:null}set enabled(e){this._setValue("enabled",e,function(e,t){this.onSetEnabled(null,t,e);});}get enabled(){return this.data.enabled}set light(e){this._setValue("light",e);}get light(){return this.data.light}set type(e){this._setValue("type",e,function(e,t){this.system.changeType(this,t,e),this.refreshProperties();});}get type(){return this.data.type}set color(e){this._setValue("color",e,function(e,t){this.light.setColor(e);},true);}get color(){return this.data.color}set intensity(e){this._setValue("intensity",e,function(e,t){this.light.intensity=e;});}get intensity(){return this.data.intensity}set luminance(e){this._setValue("luminance",e,function(e,t){this.light.luminance=e;});}get luminance(){return this.data.luminance}set shape(e){this._setValue("shape",e,function(e,t){this.light.shape=e;});}get shape(){return this.data.shape}set affectSpecularity(e){this._setValue("affectSpecularity",e,function(e,t){this.light.affectSpecularity=e;});}get affectSpecularity(){return this.data.affectSpecularity}set castShadows(e){this._setValue("castShadows",e,function(e,t){this.light.castShadows=e;});}get castShadows(){return this.data.castShadows}set shadowDistance(e){this._setValue("shadowDistance",e,function(e,t){this.light.shadowDistance=e;});}get shadowDistance(){return this.data.shadowDistance}set shadowIntensity(e){this._setValue("shadowIntensity",e,function(e,t){this.light.shadowIntensity=e;});}get shadowIntensity(){return this.data.shadowIntensity}set shadowResolution(e){this._setValue("shadowResolution",e,function(e,t){this.light.shadowResolution=e;});}get shadowResolution(){return this.data.shadowResolution}set shadowBias(e){this._setValue("shadowBias",e,function(e,t){this.light.shadowBias=-0.01*ei.clamp(e,0,1);});}get shadowBias(){return this.data.shadowBias}set numCascades(e){this._setValue("numCascades",e,function(e,t){this.light.numCascades=ei.clamp(Math.floor(e),1,4);});}get numCascades(){return this.data.numCascades}set cascadeBlend(e){this._setValue("cascadeBlend",e,function(e,t){this.light.cascadeBlend=ei.clamp(e,0,1);});}get cascadeBlend(){return this.data.cascadeBlend}set bakeNumSamples(e){this._setValue("bakeNumSamples",e,function(e,t){this.light.bakeNumSamples=ei.clamp(Math.floor(e),1,255);});}get bakeNumSamples(){return this.data.bakeNumSamples}set bakeArea(e){this._setValue("bakeArea",e,function(e,t){this.light.bakeArea=ei.clamp(e,0,180);});}get bakeArea(){return this.data.bakeArea}set cascadeDistribution(e){this._setValue("cascadeDistribution",e,function(e,t){this.light.cascadeDistribution=ei.clamp(e,0,1);});}get cascadeDistribution(){return this.data.cascadeDistribution}set normalOffsetBias(e){this._setValue("normalOffsetBias",e,function(e,t){this.light.normalOffsetBias=ei.clamp(e,0,1);});}get normalOffsetBias(){return this.data.normalOffsetBias}set range(e){this._setValue("range",e,function(e,t){this.light.attenuationEnd=e;});}get range(){return this.data.range}set innerConeAngle(e){this._setValue("innerConeAngle",e,function(e,t){this.light.innerConeAngle=e;});}get innerConeAngle(){return this.data.innerConeAngle}set outerConeAngle(e){this._setValue("outerConeAngle",e,function(e,t){this.light.outerConeAngle=e;});}get outerConeAngle(){return this.data.outerConeAngle}set falloffMode(e){this._setValue("falloffMode",e,function(e,t){this.light.falloffMode=e;});}get falloffMode(){return this.data.falloffMode}set shadowType(e){this._setValue("shadowType",e,function(e,t){this.light.shadowType=e;});}get shadowType(){return this.data.shadowType}set vsmBlurSize(e){this._setValue("vsmBlurSize",e,function(e,t){this.light.vsmBlurSize=e;});}get vsmBlurSize(){return this.data.vsmBlurSize}set vsmBlurMode(e){this._setValue("vsmBlurMode",e,function(e,t){this.light.vsmBlurMode=e;});}get vsmBlurMode(){return this.data.vsmBlurMode}set vsmBias(e){this._setValue("vsmBias",e,function(e,t){this.light.vsmBias=ei.clamp(e,0,1);});}get vsmBias(){return this.data.vsmBias}set cookieAsset(e){this._setValue("cookieAsset",e,function(e,t){if(!this._cookieAssetId||(!(e instanceof fX)||e.id!==this._cookieAssetId)&&e!==this._cookieAssetId){if(this.onCookieAssetRemove(),this._cookieAssetId=null,e instanceof fX)this.data.cookieAsset=e.id,this._cookieAssetId=e.id,this.onCookieAssetAdd(e);else if("number"==typeof e){this._cookieAssetId=e;let t=this.system.app.assets.get(e);t?this.onCookieAssetAdd(t):(this._cookieAssetAdd=true,this.system.app.assets.on(`add:${this._cookieAssetId}`,this.onCookieAssetAdd,this));}}});}get cookieAsset(){return this.data.cookieAsset}set cookie(e){this._setValue("cookie",e,function(e,t){this.light.cookie=e;});}get cookie(){return this.data.cookie}set cookieIntensity(e){this._setValue("cookieIntensity",e,function(e,t){this.light.cookieIntensity=ei.clamp(e,0,1);});}get cookieIntensity(){return this.data.cookieIntensity}set cookieFalloff(e){this._setValue("cookieFalloff",e,function(e,t){this.light.cookieFalloff=e;});}get cookieFalloff(){return this.data.cookieFalloff}set cookieChannel(e){this._setValue("cookieChannel",e,function(e,t){this.light.cookieChannel=e;});}get cookieChannel(){return this.data.cookieChannel}set cookieAngle(e){this._setValue("cookieAngle",e,function(e,t){if(0!==e||null!==this.cookieScale){this._cookieMatrix||(this._cookieMatrix=new ep);let t=1,i=1;this.cookieScale&&(t=this.cookieScale.x,i=this.cookieScale.y);let s=Math.cos(e*ei.DEG_TO_RAD),r=Math.sin(e*ei.DEG_TO_RAD);this._cookieMatrix.set(s/t,-r/t,r/i,s/i),this.light.cookieTransform=this._cookieMatrix;}else this.light.cookieTransform=null;});}get cookieAngle(){return this.data.cookieAngle}set cookieScale(e){this._setValue("cookieScale",e,function(e,t){if(null!==e||0!==this.cookieAngle){this._cookieMatrix||(this._cookieMatrix=new ep);let t=e.x,i=e.y,s=Math.cos(this.cookieAngle*ei.DEG_TO_RAD),r=Math.sin(this.cookieAngle*ei.DEG_TO_RAD);this._cookieMatrix.set(s/t,-r/t,r/i,s/i),this.light.cookieTransform=this._cookieMatrix;}else this.light.cookieTransform=null;},true);}get cookieScale(){return this.data.cookieScale}set cookieOffset(e){this._setValue("cookieOffset",e,function(e,t){this.light.cookieOffset=e;},true);}get cookieOffset(){return this.data.cookieOffset}set shadowUpdateMode(e){this._setValue("shadowUpdateMode",e,function(e,t){this.light.shadowUpdateMode=e;},true);}get shadowUpdateMode(){return this.data.shadowUpdateMode}set mask(e){this._setValue("mask",e,function(e,t){this.light.mask=e;});}get mask(){return this.data.mask}set affectDynamic(e){this._setValue("affectDynamic",e,function(e,t){e?this.light.mask|=1:this.light.mask&=-2,this.light.layersDirty();});}get affectDynamic(){return this.data.affectDynamic}set affectLightmapped(e){this._setValue("affectLightmapped",e,function(e,t){e?(this.light.mask|=2,this.bake&&(this.light.mask&=-5)):(this.light.mask&=-3,this.bake&&(this.light.mask|=4));});}get affectLightmapped(){return this.data.affectLightmapped}set bake(e){this._setValue("bake",e,function(e,t){e?(this.light.mask|=4,this.affectLightmapped&&(this.light.mask&=-3)):(this.light.mask&=-5,this.affectLightmapped&&(this.light.mask|=2)),this.light.layersDirty();});}get bake(){return this.data.bake}set bakeDir(e){this._setValue("bakeDir",e,function(e,t){this.light.bakeDir=e;});}get bakeDir(){return this.data.bakeDir}set isStatic(e){this._setValue("isStatic",e,function(e,t){this.light.isStatic=e;});}get isStatic(){return this.data.isStatic}set layers(e){this._setValue("layers",e,function(e,t){for(let e=0;e=0&&this.enabled&&this.entity.enabled&&(e.addLight(this),this.light.addLayer(e));}onLayerRemoved(e){this.layers.indexOf(e.id)>=0&&(e.removeLight(this),this.light.removeLayer(e));}refreshProperties(){for(let e=0;e=3&&i.length<=4){for(let e=0;evD(e,t,i,s?s[r]:null)):vD(e,t,i,s)}function vL(e,t,i,s){if(i)for(let r in t){let a=t[r],n=i[r];void 0!==n&&(s[r]=vR(e,a,n,s[r]));}}class vM{add(e,t){if(t&&t.type){if(!(this.index[e]||vM.reservedNames.has(e)))this.index[e]=t,Object.defineProperty(this.scriptType.prototype,e,{get:function(){return this.__attributes[e]},set:function(i){let s="attr",r=`attr:${e}`,a=this.__attributes[e],n=a;if(a&&"json"!==t.type&&"entity"!==t.type&&a.clone&&(this.hasEvent(s)||this.hasEvent(r))&&(n=a.clone()),t.array){if(this.__attributes[e]=[],i)for(let s=0,r=i.length;s{this.initializeAttributes(i);}),i.enabled=!!e[t].enabled),"object"==typeof e[t].attributes)){for(let s in e[t].attributes)if(!vM.reservedNames.has(s)){if(!i.__attributes.hasOwnProperty(s)){let e=this.system.app.scripts.get(t);e&&e.attributes.add(s,{});}i[s]=e[t].attributes[s];}}}}get scripts(){return this._scripts}set enabled(e){let t=this._enabled;this._enabled=e,this.fire("set","enabled",t,e);}get enabled(){return this._enabled}onEnable(){this._beingEnabled=true,this._checkState(),this.entity._beingEnabled||this.onPostStateChange(),this._beingEnabled=false;}onDisable(){this._checkState();}onPostStateChange(){let e=this._beginLooping();for(let e=0,t=this.scripts.length;e{this.initializeAttributes(t);}),t.enabled=t._enabled;}this._endLooping(t);}_onBeforeRemove(){this.fire("remove");let e=this._beginLooping();for(let e=0;et.ind&&(n=t.ind),this._insertScriptInstance(e,n,a),this._scriptsIndex[r]={instance:e,onSwap:function(){i.swap(r);}},this[r]=e,t.preloading||this.initializeAttributes(e),this.fire("create",r,e),this.fire(`create:${r}`,e),this.system.app.scripts.on(`swap:${r}`,this._scriptsIndex[r].onSwap),!t.preloading&&(e.enabled&&!e._initialized&&(e._initialized=true,e.initialize&&this._scriptMethod(e,vO)),e.enabled&&!e._postInitialized&&(e._postInitialized=true,e.postInitialize&&this._scriptMethod(e,vF))),e}}else this._scriptsIndex[r]={awaiting:true,ind:this._scripts.length};return null}destroy(e){let t=e,i=e;"string"==typeof i?i=this.system.app.scripts.get(i):i&&(t=i.__name);let s=this._scriptsIndex[t];if(delete this._scriptsIndex[t],!s)return false;this._attributeDataMap.delete(t);let r=s.instance;if(r&&!r._destroyed)if(r.enabled=false,r._destroyed=true,this._isLoopingThroughScripts)this._destroyedScripts.push(r);else {let e=this._removeScriptInstance(r);e>=0&&this._resetExecutionOrder(e,this._scripts.length);}return this.system.app.scripts.off(`swap:${t}`,s.onSwap),delete this[t],this.fire("destroy",t,r||null),this.fire(`destroy:${t}`,r||null),r&&r.fire("destroy"),true}swap(e){let t=e,i=e;"string"==typeof i?i=this.system.app.scripts.get(i):i&&(t=i.__name);let s=this._scriptsIndex[t];if(!s||!s.instance)return false;let r=s.instance,a=this._scripts.indexOf(r),n=new i({app:this.system.app,entity:this.entity,enabled:r.enabled,attributes:r.__attributes});return !!n.swap&&(this.initializeAttributes(n),this._scripts[a]=n,this._scriptsIndex[t].instance=n,this[t]=n,n.__executionOrder=a,r.update&&this._updateList.remove(r),r.postUpdate&&this._postUpdateList.remove(r),n.update&&this._updateList.insert(n),n.postUpdate&&this._postUpdateList.insert(n),this._scriptMethod(n,"swap",r),this.fire("swap",t,n),this.fire(`swap:${t}`,n),true)}resolveDuplicatedEntityReferenceProperties(e,t){let i=this.entity.script;for(let s in e._scriptsIndex){let r=this.system.app.scripts.get(s);if(!r)continue;let a=e._scriptsIndex[s];if(!a||!a.instance)continue;let n=i[s].__attributesRaw??i._attributeDataMap.get(s),o=i[s].__attributes;if(!n&&!o)continue;let l=!!n,h=a.instance.__attributes??i._attributeDataMap.get(s);for(let e in h){if(!h[e])continue;let i=r.attributes?.get(e)??this.system.app.scripts.getSchema(s)?.attributes?.[e];if(i){if("entity"===i.type)this._resolveEntityScriptAttribute(i,e,h[e],l,n||o,t);else if("json"===i.type&&Array.isArray(i.schema)){let s=h[e],r=n?n[e]:o[e];for(let e=0;e=i||t<0)return false;let s=e,r=e;"string"!=typeof r?r=e.__name:s=null;let a=this._scriptsIndex[r];if(!a||!a.instance)return false;let n=a.instance;if(s&&!(n instanceof s))return false;let o=this._scripts.indexOf(n);return -1!==o&&o!==t&&(this._scripts.splice(t,0,this._scripts.splice(o,1)[0]),this._resetExecutionOrder(0,i),this._updateList.sort(),this._postUpdateList.sort(),this.fire("move",r,n,t,o),this.fire(`move:${r}`,n,t,o),true)}constructor(e,t){super(e,t),this._attributeDataMap=new Map,this._scripts=[],this._updateList=new $({sortBy:"__executionOrder"}),this._postUpdateList=new $({sortBy:"__executionOrder"}),this._scriptsIndex={},this._destroyedScripts=[],this._destroyed=false,this._scriptsData=null,this._oldState=true,this._enabled=true,this._beingEnabled=false,this._isLoopingThroughScripts=false,this._executionOrder=-1,this.on("set_enabled",this._onSetEnabled,this);}}vz.EVENT_CREATE="create",vz.EVENT_DESTROY="destroy",vz.EVENT_ENABLE="enable",vz.EVENT_DISABLE="disable",vz.EVENT_REMOVE="remove",vz.EVENT_STATE="state",vz.EVENT_MOVE="move",vz.EVENT_ERROR="error";class vV{constructor(){this.enabled=true;}}let vG=0;class vH extends pT{initializeComponentData(e,t){if(e._executionOrder=vG++,this._components.append(e),vG>Number.MAX_SAFE_INTEGER&&this._resetExecutionOrder(),e.enabled=!t.hasOwnProperty("enabled")||!!t.enabled,e.enabled&&e.entity.enabled&&this._enabledComponents.append(e),t.hasOwnProperty("order")&&t.hasOwnProperty("scripts")){e._scriptsData=t.scripts;for(let i=0;i=0&&t._onBeforeRemove(),this._removeComponentFromEnabled(t),this._components.remove(t);}destroy(){super.destroy(),this.app.systems.off("initialize",this._onInitialize,this),this.app.systems.off("postInitialize",this._onPostInitialize,this),this.app.systems.off("update",this._onUpdate,this),this.app.systems.off("postUpdate",this._onPostUpdate,this);}constructor(e){super(e),this.id="script",this.ComponentType=vz,this.DataType=vV,this._components=new $({sortBy:"_executionOrder"}),this._enabledComponents=new $({sortBy:"_executionOrder"}),this.preloading=true,this.on("beforeremove",this._onBeforeRemove,this),this.app.systems.on("initialize",this._onInitialize,this),this.app.systems.on("postInitialize",this._onPostInitialize,this),this.app.systems.on("update",this._onUpdate,this),this.app.systems.on("postUpdate",this._onPostUpdate,this);}}let vW=new ef,vX=new Uint32Array(0),vY=[0,0];class vq{destroy(){this.intervals.length=0,this.intervalOffsets.length=0,this.intervalAllocIds.length=0,this.intervalNodeIndices.length=0,this.subDrawTexture?.destroy(),this.subDrawTexture=null,this.subDrawCount=0;}setLayout(e){this.intervalOffsets=e,this.subDrawTexture?.destroy(),this.subDrawTexture=null,this.subDrawCount=0;}ensureSubDrawTexture(e){!this.subDrawTexture&&e>0&&this.updateSubDraws(e);}updateIntervals(e){let t=this.resource;if(this.intervals.length=0,this.intervalAllocIds.length=0,this.intervalNodeIndices.length=0,this.activeSplats=t.numSplats,e.size>0){let t=0,i=0;for(let[s,r]of(this.intervals.length=2*e.size,e))this.intervals[i++]=r.x,this.intervals[i++]=r.y+1,t+=r.y-r.x+1,this.nodeInfos&&(this.intervalAllocIds.push(this.nodeInfos[s].allocId),this.intervalNodeIndices.push(s));this.octreeNodes?(this.activeSplats=t,this.numBoundsEntries=this.octreeNodes.length):t===this.numSplats?this.intervals.length=0:this.activeSplats=t;}else {this.numBoundsEntries=1,this.intervalAllocIds.push(this.allocId);let e=t.maxSplats;e&&this.activeSplats0){let s=Math.min(n,a-l),r=4*t;e[r]=65536|o,e[r+1]=l,e[r+2]=l+s,e[r+3]=i,t++,i+=s,n-=s,o++;}let h=n/a|0;if(h>0){let s=4*t;e[s]=o|h<<16,e[s+1]=0,e[s+2]=a,e[s+3]=i,t++,i+=h*a,n-=h*a,o+=h;}if(n>0){let s=4*t;e[s]=65536|o,e[s+1]=0,e[s+2]=n,e[s+3]=i,t++;}return t}updateSubDraws(e){let t=this.intervals,i=t.length/2;0===i&&(vY[0]=0,vY[1]=this.activeSplats,t=vY,i=1);let s=3*i*4;vX.length0}constructor(e,t,i,s=null,r=null,a=null){this.activeSplats=0,this.intervals=[],this.intervalOffsets=[],this.intervalAllocIds=[],this.intervalNodeIndices=[],this.previousWorldTransform=new ey,this.aabb=new eA,this.subDrawTexture=null,this.subDrawCount=0,this.numBoundsEntries=0,this.boundsBaseIndex=0,this.octreeNodes=null,this.nodeInfos=null,this.colorAccumulatedTranslation=0,this.parameters=null,this.getWorkBufferModifier=null,this.getInstanceStreams=null,this._consumeRenderDirty=null,this.device=e,this.resource=t,this.node=i.node,this.lodIndex=i.lodIndex,this.placementId=i.id,this.allocId=i.allocId,this.parentPlacementId=r&&i.parentPlacement?i.parentPlacement.allocId:i.allocId,this.numSplats=t.numSplats,this.aabb.copy(i.aabb),this.parameters=i.parameters,this.getWorkBufferModifier=()=>i.workBufferModifier,this.getInstanceStreams=()=>i.streams,this._consumeRenderDirty=s,this.octreeNodes=r,this.nodeInfos=a,this.updateIntervals(i.intervals);}}function vj(){let e,t,i,s,r="u">typeof self&&self||require("node:worker_threads").parentPort,a=new Map,n=false,o=false,l=new Float32Array(33),h=new Float32Array(33),c=new GSplatSortBinWeights,d=(e,t,i,s,r,n,o)=>{let{ids:l,intervals:h}=n,c=32/i,d=0;for(let n=0;n0?h[n]:[0,p.length/3];for(let e=0;e{let f=u.data??u;switch(f.command){case "addCenters":a.set(f.id,new Float32Array(f.centers));break;case "removeCenters":a.delete(f.id);break;case "sort":{n=f.radialSorting||false;let a=new Uint32Array(f.order);((e,a,u)=>{let f=performance.now(),{minDist:p,maxDist:m}=n?(e=>{let t=-1/0;for(let i=0;it&&(t=p);}}return t<0&&(t=0),{minDist:0,maxDist:t}})(e):(e=>{let t=1/0,i=-1/0;for(let s=0;s=0?o[0]:l[0],f=c>=0?o[1]:l[1],p=d>=0?o[2]:l[2],m=h>=0?l[0]:o[0],_=c>=0?l[1]:o[1],g=d>=0?l[2]:o[2],v=(u*h+f*c+p*d)*n+a,S=(m*h+_*c+g*d)*n+a,y=Math.min(v,S),x=Math.max(v,S);yi&&(i=x);}return t===1/0&&(t=0,i=0),{minDist:t,maxDist:i}})(e),_=u.totalActiveSplats,g=Math.max(10,Math.min(20,Math.round(Math.log2(_/4)))),v=2**g+1;t?.length!==_&&(t=new Uint32Array(_)),i&&i.length===v?i.fill(0):i=new Uint32Array(v);let S=m-p,y=GSplatSortBinWeights.computeCameraBin(n,p,S);var x=c.compute(y,v);for(let e=0;e<32;e++)l[e]=x[2*e],h[e]=x[2*e+1];(l[32]=l[31]+h[31],h[32]=0,n)?d(e,p,S,t,i,u,(e,t,i,s,r,a,n,o,c,d)=>{let{transformedPosition:u,scale:f}=t,p=u.x,m=u.y,_=u.z;for(let t=i;t>>0,v=l[g]+h[g]*(u-g)>>>0;c[r++]=v,d[v]++;}return r}):d(e,p,S,t,i,u,(e,t,i,s,r,a,n,o,c,d)=>{let{transformedDirection:u,offset:f,scale:p}=t,m=u.x,_=u.y,g=u.z,v=m*p,S=_*p,y=g*p,x=f-n;for(let t=i;t>>0,n=l[s]+h[s]*(i-s)>>>0;c[r++]=n,d[n]++;}return r});var T=i,E=t;for(let e=1;e{let{ids:t,pixelOffsets:i,intervals:r,totalActiveSplats:n}=e;(!s||s.length0?r[e]:[0,n.length/3];for(let e=0;ei){let e=n-i,t=(s-1)*2+1;this.binWeights[t]=Math.max(1,this.binWeights[t]-e);}return this.binWeights}constructor(){this.binWeights=new Float32Array(2*e.NUM_BINS),this.lastCameraBin=-1,this.lastBucketCount=-1;let t=e.NUM_BINS,i=e.WEIGHT_TIERS;this.bitsPerBin=new Float32Array(t),this.weightByDistance=new Float32Array(t);for(let e=0;e=h.fixedTimeStep&&(f=Math.floor(h.simTime/h.fixedTimeStep),h.simTime-=f*h.fixedTimeStep),f){f=Math.min(f,h.maxSubSteps);for(let u=0;ua.skin===t);r&&(r.incRefCount(),s=r.skinInstance)}return s}static addCachedSkinInstance(t,e,s){let i=sn._skinInstanceCache.get(e);i||(i=[],sn._skinInstanceCache.set(e,i));let r=i.find(a=>a.skin===t);r||(r=new ER(t,s),i.push(r)),r.incRefCount()}static removeCachedSkinInstance(t){if(t){let e=t.rootBone;if(e){let s=sn._skinInstanceCache.get(e);if(s){let i=s.findIndex(r=>r.skinInstance===t);if(i>=0){let r=s[i];r.decRefCount(),r.refCount===0&&(s.splice(i,1),s.length||sn._skinInstanceCache.delete(e),t&&(t.destroy(),r.skinInstance=null))}}}}}};n(sn,"_skinInstanceCache",new Map);var Eu=sn;var pa=class{constructor(t,e,s,i,r){n(this,"_evtLoadById",null);n(this,"_evtUnloadById",null);n(this,"_evtAddById",null);n(this,"_evtRemoveById",null);n(this,"_evtLoadByUrl",null);n(this,"_evtAddByUrl",null);n(this,"_evtRemoveByUrl",null);this.propertyName=t,this.parent=e,this._scope=r,this._registry=s,this.id=null,this.url=null,this.asset=null,this._onAssetLoad=i.load,this._onAssetAdd=i.add,this._onAssetRemove=i.remove,this._onAssetUnload=i.unload}set id(t){if(this.url)throw Error("Can't set id and url");this._unbind(),this._id=t,this.asset=this._registry.get(this._id),this._bind()}get id(){return this._id}set url(t){if(this.id)throw Error("Can't set id and url");this._unbind(),this._url=t,this.asset=this._registry.getByUrl(this._url),this._bind()}get url(){return this._url}_bind(){this.id&&(this._onAssetLoad&&(this._evtLoadById=this._registry.on(`load:${this.id}`,this._onLoad,this)),this._onAssetAdd&&(this._evtAddById=this._registry.once(`add:${this.id}`,this._onAdd,this)),this._onAssetRemove&&(this._evtRemoveById=this._registry.on(`remove:${this.id}`,this._onRemove,this)),this._onAssetUnload&&(this._evtUnloadById=this._registry.on(`unload:${this.id}`,this._onUnload,this))),this.url&&(this._onAssetLoad&&(this._evtLoadByUrl=this._registry.on(`load:url:${this.url}`,this._onLoad,this)),this._onAssetAdd&&(this._evtAddByUrl=this._registry.once(`add:url:${this.url}`,this._onAdd,this)),this._onAssetRemove&&(this._evtRemoveByUrl=this._registry.on(`remove:url:${this.url}`,this._onRemove,this)))}_unbind(){this.id&&(this._evtLoadById?.off(),this._evtLoadById=null,this._evtAddById?.off(),this._evtAddById=null,this._evtRemoveById?.off(),this._evtRemoveById=null,this._evtUnloadById?.off(),this._evtUnloadById=null),this.url&&(this._evtLoadByUrl?.off(),this._evtLoadByUrl=null,this._evtAddByUrl?.off(),this._evtAddByUrl=null,this._evtRemoveByUrl?.off(),this._evtRemoveByUrl=null)}_onLoad(t){this._onAssetLoad.call(this._scope,this.propertyName,this.parent,t)}_onAdd(t){this.asset=t,this._onAssetAdd.call(this._scope,this.propertyName,this.parent,t)}_onRemove(t){this._onAssetRemove.call(this._scope,this.propertyName,this.parent,t),this.asset=null}_onUnload(t){this._onAssetUnload.call(this._scope,this.propertyName,this.parent,t)}};var Au=class extends le{constructor(e,s){super(e,s);n(this,"_type","asset");n(this,"_castShadows",!0);n(this,"_receiveShadows",!0);n(this,"_castShadowsLightmap",!0);n(this,"_lightmapped",!1);n(this,"_lightmapSizeMultiplier",1);n(this,"isStatic",!1);n(this,"_batchGroupId",-1);n(this,"_layers",[Os]);n(this,"_renderStyle",Oo);n(this,"_meshInstances",[]);n(this,"_customAabb",null);n(this,"_area",null);n(this,"_assetReference");n(this,"_materialReferences",[]);n(this,"_material");n(this,"_rootBone",null);n(this,"_evtLayersChanged",null);n(this,"_evtLayerAdded",null);n(this,"_evtLayerRemoved",null);n(this,"_evtSetMeshes",null);this._assetReference=new pa("asset",this,e.app.assets,{add:this._onRenderAssetAdded,load:this._onRenderAssetLoad,remove:this._onRenderAssetRemove,unload:this._onRenderAssetUnload},this),this._material=e.defaultMaterial,s.on("remove",this.onRemoveChild,this),s.on("removehierarchy",this.onRemoveChild,this),s.on("insert",this.onInsertChild,this),s.on("inserthierarchy",this.onInsertChild,this)}set renderStyle(e){this._renderStyle!==e&&(this._renderStyle=e,we._prepareRenderStyleForArray(this._meshInstances,e))}get renderStyle(){return this._renderStyle}set customAabb(e){this._customAabb=e;let s=this._meshInstances;if(s)for(let i=0;i=0&&this.system.app.batcher?.remove(pt.RENDER,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(pt.RENDER,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addToLayers(),this._batchGroupId=e)}get batchGroupId(){return this._batchGroupId}set material(e){if(this._material!==e&&(this._material=e,this._meshInstances&&this._type!=="asset"))for(let s=0;se.length){for(let s=e.length;se.id)}set asset(e){let s=e instanceof ae?e.id:e;this._assetReference.id!==s&&(this._assetReference.asset&&this._assetReference.asset.resource&&this._onRenderAssetRemove(),this._assetReference.id=s,this._assetReference.asset&&this._onRenderAssetAdded())}get asset(){return this._assetReference.id}assignAsset(e){let s=e instanceof ae?e.id:e;this._assetReference.id=s}set rootBone(e){if(this._rootBone!==e){let s=typeof e=="string";if(this._rootBone&&s&&this._rootBone.guid===e)return;this._rootBone&&this._clearSkinInstances(),e instanceof Pe?this._rootBone=e:s?(this._rootBone=this.system.app.getEntityFromIndex(e)||null,this._rootBone):this._rootBone=null,this._rootBone&&this._cloneSkinInstances()}}get rootBone(){return this._rootBone}destroyMeshInstances(){let e=this._meshInstances;if(e){this.removeFromLayers(),this._clearSkinInstances();for(let s=0;s=0&&e.batcher?.insert(pt.RENDER,this.batchGroupId,this.entity)}onDisable(){let e=this.system.app,i=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,this._rootBone&&this._clearSkinInstances(),i&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._batchGroupId>=0&&e.batcher?.remove(pt.RENDER,this.batchGroupId,this.entity),this.removeFromLayers()}hide(){if(this._meshInstances)for(let e=0;eo.mesh);i._onSetMeshes(a);for(let o=0;othis._pool.length)for(let e=this._pool.length;e=this._pool.length&&this._resize(this._pool.length*2),this._pool[this._count++]}freeAll(){this._count=0}};var Dr,at,so,Zm,lK=new $,cK=new $,K0=new x,Js=class extends le{constructor(){super(...arguments);n(this,"_angularDamping",0);n(this,"_angularFactor",new x(1,1,1));n(this,"_angularVelocity",new x);n(this,"_body",null);n(this,"_friction",.5);n(this,"_group",2);n(this,"_linearDamping",0);n(this,"_linearFactor",new x(1,1,1));n(this,"_linearVelocity",new x);n(this,"_mask",65533);n(this,"_mass",1);n(this,"_restitution",0);n(this,"_rollingFriction",0);n(this,"_simulationEnabled",!1);n(this,"_type",Sl)}static onLibraryLoaded(){typeof Ammo<"u"&&(Dr=new Ammo.btTransform,at=new Ammo.btVector3,so=new Ammo.btVector3,Zm=new Ammo.btQuaternion)}static onAppDestroy(){Ammo.destroy(Dr),Ammo.destroy(at),Ammo.destroy(so),Ammo.destroy(Zm),Dr=null,at=null,so=null,Zm=null}set angularDamping(e){this._angularDamping!==e&&(this._angularDamping=e,this._body&&this._body.setDamping(this._linearDamping,e))}get angularDamping(){return this._angularDamping}set angularFactor(e){this._angularFactor.equals(e)||(this._angularFactor.copy(e),this._body&&this._type===Ui&&(at.setValue(e.x,e.y,e.z),this._body.setAngularFactor(at)))}get angularFactor(){return this._angularFactor}set angularVelocity(e){this._body&&this._type===Ui&&(this._body.activate(),at.setValue(e.x,e.y,e.z),this._body.setAngularVelocity(at),this._angularVelocity.copy(e))}get angularVelocity(){if(this._body&&this._type===Ui){let e=this._body.getAngularVelocity();this._angularVelocity.set(e.x(),e.y(),e.z())}return this._angularVelocity}set body(e){this._body!==e&&(this._body=e,e&&this._simulationEnabled&&e.activate())}get body(){return this._body}set friction(e){this._friction!==e&&(this._friction=e,this._body&&this._body.setFriction(e))}get friction(){return this._friction}set group(e){this._group!==e&&(this._group=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}get group(){return this._group}set linearDamping(e){this._linearDamping!==e&&(this._linearDamping=e,this._body&&this._body.setDamping(e,this._angularDamping))}get linearDamping(){return this._linearDamping}set linearFactor(e){this._linearFactor.equals(e)||(this._linearFactor.copy(e),this._body&&this._type===Ui&&(at.setValue(e.x,e.y,e.z),this._body.setLinearFactor(at)))}get linearFactor(){return this._linearFactor}set linearVelocity(e){this._body&&this._type===Ui&&(this._body.activate(),at.setValue(e.x,e.y,e.z),this._body.setLinearVelocity(at),this._linearVelocity.copy(e))}get linearVelocity(){if(this._body&&this._type===Ui){let e=this._body.getLinearVelocity();this._linearVelocity.set(e.x(),e.y(),e.z())}return this._linearVelocity}set mask(e){this._mask!==e&&(this._mask=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}get mask(){return this._mask}set mass(e){if(this._mass!==e&&(this._mass=e,this._body&&this._type===Ui)){let s=this.enabled&&this.entity.enabled;s&&this.disableSimulation(),this._body.getCollisionShape().calculateLocalInertia(e,at),this._body.setMassProps(e,at),this._body.updateInertiaTensor(),s&&this.enableSimulation()}}get mass(){return this._mass}set restitution(e){this._restitution!==e&&(this._restitution=e,this._body&&this._body.setRestitution(e))}get restitution(){return this._restitution}set rollingFriction(e){this._rollingFriction!==e&&(this._rollingFriction=e,this._body&&this._body.setRollingFriction(e))}get rollingFriction(){return this._rollingFriction}set type(e){if(this._type!==e){switch(this._type=e,this.disableSimulation(),e){case Ui:this._group=1,this._mask=65535;break;case tn:this._group=4,this._mask=65535;break;case Sl:default:this._group=2,this._mask=65533;break}this.createBody()}}get type(){return this._type}createBody(){let e=this.entity,s;if(e.collision&&(s=e.collision.shape,e.trigger&&(e.trigger.destroy(),delete e.trigger)),s){this._body&&(this.system.removeBody(this._body),this.system.destroyBody(this._body),this._body=null);let i=this._type===Ui?this._mass:0;this._getEntityTransform(Dr);let r=this.system.createBody(i,s,Dr);if(r.setRestitution(this._restitution),r.setFriction(this._friction),r.setRollingFriction(this._rollingFriction),r.setDamping(this._linearDamping,this._angularDamping),this._type===Ui){let a=this._linearFactor;at.setValue(a.x,a.y,a.z),r.setLinearFactor(at);let o=this._angularFactor;at.setValue(o.x,o.y,o.z),r.setAngularFactor(at)}else this._type===tn&&(r.setCollisionFlags(r.getCollisionFlags()|2),r.setActivationState(4));r.entity=e,this.body=r,this.enabled&&e.enabled&&this.enableSimulation()}}isActive(){return this._body?this._body.isActive():!1}activate(){this._body&&this._body.activate()}enableSimulation(){let e=this.entity;if(e.collision&&e.collision.enabled&&!this._simulationEnabled){let s=this._body;if(s){switch(this.system.addBody(s,this._group,this._mask),this._type){case Ui:this.system._dynamic.push(this),s.forceActivationState(1),this.syncEntityToBody();break;case tn:this.system._kinematic.push(this),s.forceActivationState(4);break;case Sl:s.forceActivationState(1),this.syncEntityToBody();break}e.collision.type==="compound"&&this.system._compounds.push(e.collision),s.activate(),this._simulationEnabled=!0}}}disableSimulation(){let e=this._body;if(e&&this._simulationEnabled){let s=this.system,i=s._compounds.indexOf(this.entity.collision);i>-1&&s._compounds.splice(i,1),i=s._dynamic.indexOf(this),i>-1&&s._dynamic.splice(i,1),i=s._kinematic.indexOf(this),i>-1&&s._kinematic.splice(i,1),s.removeBody(e),e.forceActivationState(5),this._simulationEnabled=!1}}applyForce(e,s,i,r,a,o){let l=this._body;l&&(l.activate(),e instanceof x?at.setValue(e.x,e.y,e.z):at.setValue(e,s,i),s instanceof x?so.setValue(s.x,s.y,s.z):r!==void 0?so.setValue(r,a,o):so.setValue(0,0,0),l.applyForce(at,so))}applyTorque(e,s,i){let r=this._body;r&&(r.activate(),e instanceof x?at.setValue(e.x,e.y,e.z):at.setValue(e,s,i),r.applyTorque(at))}applyImpulse(e,s,i,r,a,o){let l=this._body;l&&(l.activate(),e instanceof x?at.setValue(e.x,e.y,e.z):at.setValue(e,s,i),s instanceof x?so.setValue(s.x,s.y,s.z):r!==void 0?so.setValue(r,a,o):so.setValue(0,0,0),l.applyImpulse(at,so))}applyTorqueImpulse(e,s,i){let r=this._body;r&&(r.activate(),e instanceof x?at.setValue(e.x,e.y,e.z):at.setValue(e,s,i),r.applyTorqueImpulse(at))}isStatic(){return this._type===Sl}isStaticOrKinematic(){return this._type===Sl||this._type===tn}isKinematic(){return this._type===tn}_getEntityTransform(e){let s=this.entity,i=s.collision;if(i){let r=i.getShapePosition(),a=i.getShapeRotation();at.setValue(r.x,r.y,r.z),Zm.setValue(a.x,a.y,a.z,a.w)}else{let r=s.getPosition(),a=s.getRotation();at.setValue(r.x,r.y,r.z),Zm.setValue(a.x,a.y,a.z,a.w)}e.setOrigin(at),e.setRotation(Zm)}syncEntityToBody(){let e=this._body;if(e){if(this._getEntityTransform(Dr),e.setWorldTransform(Dr),this._type===tn){let s=e.getMotionState();s&&s.setWorldTransform(Dr)}e.activate()}}_updateDynamic(){let e=this._body;if(e.isActive()){let s=e.getMotionState();if(s){let i=this.entity;s.getWorldTransform(Dr);let r=Dr.getOrigin(),a=Dr.getRotation(),o=i.collision;if(o&&o._hasOffset){let l=o.data.linearOffset,h=o.data.angularOffset,f=cK.copy(h).invert(),u=lK.set(a.x(),a.y(),a.z(),a.w()).mul(f);u.transformVector(l,K0),i.setPosition(r.x()-K0.x,r.y()-K0.y,r.z()-K0.z),i.setRotation(u)}else i.setPosition(r.x(),r.y(),r.z()),i.setRotation(a.x(),a.y(),a.z(),a.w())}}}_updateKinematic(){let e=this._body.getMotionState();e&&(this._getEntityTransform(Dr),e.setWorldTransform(Dr))}teleport(e,s,i,r,a,o){e instanceof x?this.entity.setPosition(e):this.entity.setPosition(e,s,i),s instanceof $?this.entity.setRotation(s):s instanceof x?this.entity.setEulerAngles(s):r!==void 0&&this.entity.setEulerAngles(r,a,o),this.syncEntityToBody()}onEnable(){this._body||this.createBody(),this.enableSimulation()}onDisable(){this.disableSimulation()}};n(Js,"EVENT_CONTACT","contact"),n(Js,"EVENT_COLLISIONSTART","collisionstart"),n(Js,"EVENT_COLLISIONEND","collisionend"),n(Js,"EVENT_TRIGGERENTER","triggerenter"),n(Js,"EVENT_TRIGGERLEAVE","triggerleave"),n(Js,"order",-1);var j0=class{constructor(){n(this,"enabled",!0)}};var yl,El,Qm=class{constructor(t,e,s,i){n(this,"entity");n(this,"point");n(this,"normal");n(this,"hitFraction");this.entity=t,this.point=e,this.normal=s,this.hitFraction=i}},YS=class{constructor(t,e,s){n(this,"a");n(this,"b");n(this,"impulse");n(this,"localPointA");n(this,"localPointB");n(this,"pointA");n(this,"pointB");n(this,"normal");arguments.length!==0?(this.a=t,this.b=e,this.impulse=s.impulse,this.localPointA=s.localPoint,this.localPointB=s.localPointOther,this.pointA=s.point,this.pointB=s.pointOther,this.normal=s.normal):(this.a=null,this.b=null,this.impulse=0,this.localPointA=new x,this.localPointB=new x,this.pointA=new x,this.pointB=new x,this.normal=new x)}},KS=class{constructor(t=new x,e=new x,s=new x,i=new x,r=new x,a=0){n(this,"localPoint");n(this,"localPointOther");n(this,"point");n(this,"pointOther");n(this,"normal");n(this,"impulse");this.localPoint=t,this.localPointOther=e,this.point=s,this.pointOther=i,this.normal=r,this.impulse=a}},jS=class{constructor(t,e){n(this,"other");n(this,"contacts");this.other=t,this.contacts=e}},_k=["enabled"],Al=class extends Fe{constructor(e){super(e);n(this,"maxSubSteps",10);n(this,"fixedTimeStep",1/60);n(this,"gravity",new x(0,-9.81,0));n(this,"_gravityFloat32",new Float32Array(3));n(this,"_dynamic",[]);n(this,"_kinematic",[]);n(this,"_triggers",[]);n(this,"_compounds",[]);this.id="rigidbody",this._stats=e.stats.frame,this.ComponentType=Js,this.DataType=j0,this.contactPointPool=null,this.contactResultPool=null,this.singleContactResultPool=null,this.schema=_k,this.collisions={},this.frameCollisions={},this.on("beforeremove",this.onBeforeRemove,this)}onLibraryLoaded(){if(typeof Ammo<"u"){if(this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.overlappingPairCache=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.dynamicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.overlappingPairCache,this.solver,this.collisionConfiguration),this.dynamicsWorld.setInternalTickCallback){let e=Ammo.addFunction(this._checkForCollisions.bind(this),"vif");this.dynamicsWorld.setInternalTickCallback(e)}yl=new Ammo.btVector3,El=new Ammo.btVector3,Js.onLibraryLoaded(),this.contactPointPool=new $m(KS,1),this.contactResultPool=new $m(jS,1),this.singleContactResultPool=new $m(YS,1),this.app.systems.on("update",this.onUpdate,this)}else this.app.systems.off("update",this.onUpdate,this)}initializeComponentData(e,s,i){let r=["mass","linearDamping","angularDamping","linearFactor","angularFactor","friction","rollingFriction","restitution","type","group","mask"];for(let a of r)if(s.hasOwnProperty(a)){let o=s[a];Array.isArray(o)?e[a]=new x(o[0],o[1],o[2]):e[a]=o}super.initializeComponentData(e,s,["enabled"])}cloneComponent(e,s){let i=e.rigidbody,r={enabled:i.enabled,mass:i.mass,linearDamping:i.linearDamping,angularDamping:i.angularDamping,linearFactor:[i.linearFactor.x,i.linearFactor.y,i.linearFactor.z],angularFactor:[i.angularFactor.x,i.angularFactor.y,i.angularFactor.z],friction:i.friction,rollingFriction:i.rollingFriction,restitution:i.restitution,type:i.type,group:i.group,mask:i.mask};return this.addComponent(s,r)}onBeforeRemove(e,s){s.enabled&&(s.enabled=!1),s.body&&(this.destroyBody(s.body),s.body=null)}addBody(e,s,i){s!==void 0&&i!==void 0?this.dynamicsWorld.addRigidBody(e,s,i):this.dynamicsWorld.addRigidBody(e)}removeBody(e){this.dynamicsWorld.removeRigidBody(e)}createBody(e,s,i){let r=new Ammo.btVector3(0,0,0);e!==0&&s.calculateLocalInertia(e,r);let a=new Ammo.btDefaultMotionState(i),o=new Ammo.btRigidBodyConstructionInfo(e,a,s,r),l=new Ammo.btRigidBody(o);return Ammo.destroy(o),Ammo.destroy(r),l}destroyBody(e){let s=e.getMotionState();s&&Ammo.destroy(s),Ammo.destroy(e)}raycastFirst(e,s,i={}){if(i.filterTags||i.filterCallback)return i.sort=!0,this.raycastAll(e,s,i)[0]||null;let r=null;yl.setValue(e.x,e.y,e.z),El.setValue(s.x,s.y,s.z);let a=new Ammo.ClosestRayResultCallback(yl,El);if(typeof i.filterCollisionGroup=="number"&&a.set_m_collisionFilterGroup(i.filterCollisionGroup),typeof i.filterCollisionMask=="number"&&a.set_m_collisionFilterMask(i.filterCollisionMask),this.dynamicsWorld.rayTest(yl,El,a),a.hasHit()){let o=a.get_m_collisionObject(),l=Ammo.castObject(o,Ammo.btRigidBody);if(l){let h=a.get_m_hitPointWorld(),f=a.get_m_hitNormalWorld();r=new Qm(l.entity,new x(h.x(),h.y(),h.z()),new x(f.x(),f.y(),f.z()),a.get_m_closestHitFraction())}}return Ammo.destroy(a),r}raycastAll(e,s,i={}){let r=[];yl.setValue(e.x,e.y,e.z),El.setValue(s.x,s.y,s.z);let a=new Ammo.AllHitsRayResultCallback(yl,El);if(typeof i.filterCollisionGroup=="number"&&a.set_m_collisionFilterGroup(i.filterCollisionGroup),typeof i.filterCollisionMask=="number"&&a.set_m_collisionFilterMask(i.filterCollisionMask),this.dynamicsWorld.rayTest(yl,El,a),a.hasHit()){let o=a.get_m_collisionObjects(),l=a.get_m_hitPointWorld(),h=a.get_m_hitNormalWorld(),f=a.get_m_hitFractions(),u=o.size();for(let d=0;dd.hitFraction-p.hitFraction)}return Ammo.destroy(a),r}_storeCollision(e,s){let i=!1,r=e.guid;return this.collisions[r]=this.collisions[r]||{others:[],entity:e},this.collisions[r].others.indexOf(s)<0&&(this.collisions[r].others.push(s),i=!0),this.frameCollisions[r]=this.frameCollisions[r]||{others:[],entity:e},this.frameCollisions[r].others.push(s),i}_createContactPointFromAmmo(e){let s=e.get_m_localPointA(),i=e.get_m_localPointB(),r=e.getPositionWorldOnA(),a=e.getPositionWorldOnB(),o=e.get_m_normalWorldOnB(),l=this.contactPointPool.allocate();return l.localPoint.set(s.x(),s.y(),s.z()),l.localPointOther.set(i.x(),i.y(),i.z()),l.point.set(r.x(),r.y(),r.z()),l.pointOther.set(a.x(),a.y(),a.z()),l.normal.set(o.x(),o.y(),o.z()),l.impulse=e.getAppliedImpulse(),l}_createReverseContactPointFromAmmo(e){let s=e.get_m_localPointA(),i=e.get_m_localPointB(),r=e.getPositionWorldOnA(),a=e.getPositionWorldOnB(),o=e.get_m_normalWorldOnB(),l=this.contactPointPool.allocate();return l.localPointOther.set(s.x(),s.y(),s.z()),l.localPoint.set(i.x(),i.y(),i.z()),l.pointOther.set(r.x(),r.y(),r.z()),l.point.set(a.x(),a.y(),a.z()),l.normal.set(o.x(),o.y(),o.z()),l.impulse=e.getAppliedImpulse(),l}_createSingleContactResult(e,s,i){let r=this.singleContactResultPool.allocate();return r.a=e,r.b=s,r.localPointA=i.localPoint,r.localPointB=i.localPointOther,r.pointA=i.point,r.pointB=i.pointOther,r.normal=i.normal,r.impulse=i.impulse,r}_createContactResult(e,s){let i=this.contactResultPool.allocate();return i.other=e,i.contacts=s,i}_cleanOldCollisions(){for(let e in this.collisions)if(this.collisions.hasOwnProperty(e)){let s=this.frameCollisions[e],i=this.collisions[e],r=i.entity,a=r.collision,o=r.rigidbody,l=i.others,f=l.length;for(;f--;){let u=l[f];(!s||s.others.indexOf(u)<0)&&(l.splice(f,1),r.trigger?(a&&a.fire("triggerleave",u),u.rigidbody&&u.rigidbody.fire("triggerleave",r)):u.trigger||(o&&o.fire("collisionend",u),a&&a.fire("collisionend",u)))}l.length===0&&delete this.collisions[e]}}_hasContactEvent(e){let s=e.collision;if(s&&(s.hasEvent("collisionstart")||s.hasEvent("collisionend")||s.hasEvent("contact")))return!0;let i=e.rigidbody;return i&&(i.hasEvent("collisionstart")||i.hasEvent("collisionend")||i.hasEvent("contact"))}_checkForCollisions(e,s){let r=Ammo.wrapPointer(e,Ammo.btDynamicsWorld).getDispatcher(),a=r.getNumManifolds();this.frameCollisions={};for(let o=0;o0)if(_&4||S&4){let E=p.collision&&(p.collision.hasEvent("triggerenter")||p.collision.hasEvent("triggerleave")),y=m.collision&&(m.collision.hasEvent("triggerenter")||m.collision.hasEvent("triggerleave")),P=p.rigidbody&&(p.rigidbody.hasEvent("triggerenter")||p.rigidbody.hasEvent("triggerleave")),A=m.rigidbody&&(m.rigidbody.hasEvent("triggerenter")||m.rigidbody.hasEvent("triggerleave"));E&&(v=this._storeCollision(p,m),v&&!(S&4)&&p.collision.fire("triggerenter",m)),y&&(v=this._storeCollision(m,p),v&&!(_&4)&&m.collision.fire("triggerenter",p)),P&&(v||(v=this._storeCollision(m,p)),v&&p.rigidbody.fire("triggerenter",m)),A&&(v||(v=this._storeCollision(p,m)),v&&m.rigidbody.fire("triggerenter",p))}else{let E=this._hasContactEvent(p),y=this._hasContactEvent(m),P=this.hasEvent("contact");if(P||E||y){for(let A=0;A=0&&r!==e.element.drawOrder&&this.system.app.batcher?.markGroupDirty(e.element._batchGroupId)}e.particlesystem&&(e.particlesystem.drawOrder=s++);let i=e.children;for(let r=0;re._onScreenRemove()),this._elements.clear(),this.off()}set resolution(e){this._screenSpace?this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height):this._resolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:resolution",this._resolution),this._elements.forEach(s=>s._onScreenResize(this._resolution))}get resolution(){return this._resolution}set referenceResolution(e){this._referenceResolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:referenceresolution",this._resolution),this._elements.forEach(s=>s._onScreenResize(this._resolution))}get referenceResolution(){return this._scaleMode===fh?this._resolution:this._referenceResolution}set screenSpace(e){this._screenSpace=e,this._screenSpace&&this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height),this.resolution=this._resolution,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:screenspace",this._screenSpace),this._elements.forEach(s=>s._onScreenSpaceChange())}get screenSpace(){return this._screenSpace}set scaleMode(e){e!==fh&&e!==CR&&(e=fh),!this._screenSpace&&e!==fh&&(e=fh),this._scaleMode=e,this.resolution=this._resolution,this.fire("set:scalemode",this._scaleMode)}get scaleMode(){return this._scaleMode}set scaleBlend(e){this._scaleBlend=e,this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:scaleblend",this._scaleBlend),this._elements.forEach(s=>s._onScreenResize(this._resolution))}get scaleBlend(){return this._scaleBlend}set priority(e){e=R.clamp(e,0,127),this._priority!==e&&(this._priority=e,this.syncDrawOrder())}get priority(){return this._priority}};var q0=class{constructor(){n(this,"enabled",!0)}};var PR=["enabled"],Jm=class extends Fe{constructor(t){super(t),this.id="screen",this.ComponentType=Pu,this.DataType=q0,this.schema=PR,this.windowResolution=new B,this._drawOrderSyncQueue=new sd,this.app.graphicsDevice.on("resizecanvas",this._onResize,this),this.app.systems.on("update",this._onUpdate,this),this.on("beforeremove",this.onRemoveComponent,this)}initializeComponentData(t,e,s){e.priority!==void 0&&(t.priority=e.priority),e.screenSpace!==void 0&&(t.screenSpace=e.screenSpace),t.cull=t.screenSpace,e.scaleMode!==void 0&&(t.scaleMode=e.scaleMode),e.scaleBlend!==void 0&&(t.scaleBlend=e.scaleBlend),e.resolution!==void 0&&(e.resolution instanceof B?t._resolution.copy(e.resolution):t._resolution.set(e.resolution[0],e.resolution[1]),t.resolution=t._resolution),e.referenceResolution!==void 0&&(e.referenceResolution instanceof B?t._referenceResolution.copy(e.referenceResolution):t._referenceResolution.set(e.referenceResolution[0],e.referenceResolution[1]),t.referenceResolution=t._referenceResolution),this._updateDescendantElements(t.entity,t.entity),t.syncDrawOrder(),super.initializeComponentData(t,e,PR)}_updateDescendantElements(t,e){let s=t.children;for(let i=0;ithis.dragThreshold||Math.abs(i)>this.dragThreshold)&&this._disableContentInput()}}_horizontalScrollbarEntitySubscribe(){this._evtHorizontalScrollbarAdd=this._horizontalScrollbarEntity.on("scrollbar:add",this._onHorizontalScrollbarGain,this),this._horizontalScrollbarEntity.scrollbar&&this._onHorizontalScrollbarGain()}_verticalScrollbarEntitySubscribe(){this._evtVerticalScrollbarAdd=this._verticalScrollbarEntity.on("scrollbar:add",this._onVerticalScrollbarGain,this),this._verticalScrollbarEntity.scrollbar&&this._onVerticalScrollbarGain()}_horizontalScrollbarEntityUnsubscribe(){this._evtHorizontalScrollbarAdd?.off(),this._evtHorizontalScrollbarAdd=null,this._horizontalScrollbarEntity.scrollbar&&this._onHorizontalScrollbarLose()}_verticalScrollbarEntityUnsubscribe(){this._evtVerticalScrollbarAdd?.off(),this._evtVerticalScrollbarAdd=null,this._verticalScrollbarEntity.scrollbar&&this._onVerticalScrollbarLose()}_onSetHorizontalScrollbarValue(e){!this._scrollbarUpdateFlags[Ge]&&this.enabled&&this.entity.enabled&&this._onSetScroll(e,null)}_onSetVerticalScrollbarValue(e){!this._scrollbarUpdateFlags[dt]&&this.enabled&&this.entity.enabled&&this._onSetScroll(null,e)}_onHorizontalScrollbarGain(){let e=this._horizontalScrollbarEntity?.scrollbar;this._evtHorizontalScrollbarRemove=e.on("beforeremove",this._onHorizontalScrollbarLose,this),this._evtHorizontalScrollbarValue=e.on("set:value",this._onSetHorizontalScrollbarValue,this),this._syncScrollbarEnabledState(Ge),this._syncScrollbarPosition(Ge)}_onVerticalScrollbarGain(){let e=this._verticalScrollbarEntity?.scrollbar;this._evtVerticalScrollbarRemove=e.on("beforeremove",this._onVerticalScrollbarLose,this),this._evtVerticalScrollbarValue=e.on("set:value",this._onSetVerticalScrollbarValue,this),this._syncScrollbarEnabledState(dt),this._syncScrollbarPosition(dt)}_onHorizontalScrollbarLose(){this._evtHorizontalScrollbarRemove?.off(),this._evtHorizontalScrollbarRemove=null,this._evtHorizontalScrollbarValue?.off(),this._evtHorizontalScrollbarValue=null}_onVerticalScrollbarLose(){this._evtVerticalScrollbarRemove?.off(),this._evtVerticalScrollbarRemove=null,this._evtVerticalScrollbarValue?.off(),this._evtVerticalScrollbarValue=null}_onSetScroll(e,s,i){i!==!1&&this._velocity.set(0,0,0);let r=this._updateAxis(e,"x",Ge),a=this._updateAxis(s,"y",dt);(r||a)&&this.fire("set:scroll",this._scroll)}_updateAxis(e,s,i){let r=e!==null&&Math.abs(e-this._scroll[s])>1e-5;return(r||this._isDragging()||e===0)&&(this._scroll[s]=this._determineNewScrollValue(e,s,i),this._syncContentPosition(i),this._syncScrollbarPosition(i)),r}_determineNewScrollValue(e,s,i){if(!this._getScrollingEnabled(i))return this._scroll[s];switch(this.scrollMode){case 0:return R.clamp(e,0,this._getMaxScrollValue(i));case 1:return this._setVelocityFromOvershoot(e,s,i),e;case 2:return e;default:return e}}_syncAll(){this._syncContentPosition(Ge),this._syncContentPosition(dt),this._syncScrollbarPosition(Ge),this._syncScrollbarPosition(dt),this._syncScrollbarEnabledState(Ge),this._syncScrollbarEnabledState(dt)}_syncContentPosition(e){if(!this._contentEntity)return;let s=this._getAxis(e),i=this._getSign(e),r=this._prevContentSizes[e],a=this._getContentSize(e);if(r!==null&&Math.abs(r-a)>1e-4){let h=this._getMaxOffset(e,r),f=this._getMaxOffset(e,a);f===0?this._scroll[s]=1:this._scroll[s]=R.clamp(this._scroll[s]*h/f,0,1)}let o=this._scroll[s]*this._getMaxOffset(e),l=this._contentEntity.getLocalPosition();l[s]=o*i,this._contentEntity.setLocalPosition(l),this._prevContentSizes[e]=a}_syncScrollbarPosition(e){let s=this._scrollbarEntities[e];if(!s?.scrollbar)return;let i=this._getAxis(e);this._scrollbarUpdateFlags[e]=!0,s.scrollbar.value=this._scroll[i],s.scrollbar.handleSize=this._getScrollbarHandleSize(i,e),this._scrollbarUpdateFlags[e]=!1}_syncScrollbarEnabledState(e){let s=this._scrollbarEntities[e];if(!s)return;let i=this._getScrollingEnabled(e);switch(this._getScrollbarVisibility(e)){case 0:s.enabled=i;return;case 1:s.enabled=i&&this._contentIsLargerThanViewport(e);return;default:s.enabled=i}}_contentIsLargerThanViewport(e){return this._getContentSize(e)>this._getViewportSize(e)}_contentPositionToScrollValue(e){let s=this._getMaxOffset(Ge),i=this._getMaxOffset(dt);return s===0?$S.x=0:$S.x=e.x/s,i===0?$S.y=0:$S.y=e.y/-i,$S}_getMaxOffset(e,s){s=s===void 0?this._getContentSize(e):s;let i=this._getViewportSize(e);return s1e-4||Math.abs(this._velocity.y)>1e-4){let e=this._contentEntity.getLocalPosition();e.x+=this._velocity.x,e.y+=this._velocity.y,this._contentEntity.setLocalPosition(e),this._setScrollFromContentPosition(e)}this._velocity.x*=1-this.friction,this._velocity.y*=1-this.friction}}_hasOvershoot(e,s){return Math.abs(this._toOvershoot(this.scroll[e],s))>.001}_toOvershoot(e,s){let i=this._getMaxScrollValue(s);return e<0?e:e>i?e-i:0}_setVelocityFromOvershoot(e,s,i){let a=this._toOvershoot(e,i)*this._getMaxOffset(i)*this._getSign(i);Math.abs(a)>0&&(this._velocity[s]=-a/(this.bounceAmount*50+1))}_setVelocityFromContentPositionDelta(e){this._prevContentDragPosition?(this._velocity.sub2(e,this._prevContentDragPosition),this._prevContentDragPosition.copy(e)):(this._velocity.set(0,0,0),this._prevContentDragPosition=e.clone())}_setScrollFromContentPosition(e){let s=this._contentPositionToScrollValue(e);this._isDragging()&&(s=this._applyScrollValueTension(s)),this._onSetScroll(s.x,s.y,!1)}_applyScrollValueTension(e){let i=this._getMaxScrollValue(Ge),r=this._toOvershoot(e.x,Ge);return r>0?e.x=i+1*Math.log10(1+r):r<0&&(e.x=-1*Math.log10(1-r)),i=this._getMaxScrollValue(dt),r=this._toOvershoot(e.y,dt),r>0?e.y=i+1*Math.log10(1+r):r<0&&(e.y=-1*Math.log10(1-r)),e}_isDragging(){return this._contentDragHelper&&this._contentDragHelper.isDragging}_setScrollbarComponentsEnabled(e){this._horizontalScrollbarEntity?.scrollbar&&(this._horizontalScrollbarEntity.scrollbar.enabled=e),this._verticalScrollbarEntity?.scrollbar&&(this._verticalScrollbarEntity.scrollbar.enabled=e)}_setContentDraggingEnabled(e){this._contentDragHelper&&(this._contentDragHelper.enabled=e)}_onMouseWheel(e){if(!this.useMouseWheel||!this._contentEntity?.element)return;let s=e.event,i=s.deltaX/this._contentEntity.element.calculatedWidth*this.mouseWheelSensitivity.x,r=s.deltaY/this._contentEntity.element.calculatedHeight*this.mouseWheelSensitivity.y,a=R.clamp(this._scroll.x+i,0,this._getMaxScrollValue(Ge)),o=R.clamp(this._scroll.y+r,0,this._getMaxScrollValue(dt));this.scroll=new B(a,o)}_enableContentInput(){for(;this._disabledContentInputEntities.length;){let e=this._disabledContentInputEntities.pop();e.element&&(e.element.useInput=!0)}this._disabledContentInput=!1}_disableContentInput(){let e=s=>{s.element&&s.element.useInput&&(this._disabledContentInputEntities.push(s),s.element.useInput=!1);let i=s.children;for(let r=0,a=i.length;r1e-5&&(this._value=R.clamp(e,0,1),this._updateHandlePositionAndSize(),this.fire("set:value",this._value))}get value(){return this._value}set handleSize(e){Math.abs(e-this._handleSize)>1e-5&&(this._handleSize=R.clamp(e,0,1),this._updateHandlePositionAndSize())}get handleSize(){return this._handleSize}set handleEntity(e){let s;e instanceof Pe?s=e:typeof e=="string"?s=this.system.app.getEntityFromIndex(e)??null:s=null,this._handleEntity!==s&&(this._handleEntity&&this._handleEntityUnsubscribe(),this._handleEntity=s,s&&this._handleEntitySubscribe())}get handleEntity(){return this._handleEntity}_handleEntitySubscribe(){this._evtHandleEntityElementAdd=this._handleEntity.on("element:add",this._onHandleElementGain,this),this._handleEntity.element&&this._onHandleElementGain()}_handleEntityUnsubscribe(){this._evtHandleEntityElementAdd?.off(),this._evtHandleEntityElementAdd=null,this._handleEntity?.element&&this._onHandleElementLose()}_handleEntityElementSubscribe(){let e=this._handleEntity.element,s=this._evtHandleEntityChanges;s.push(e.once("beforeremove",this._onHandleElementLose,this)),s.push(e.on("set:anchor",this._updateHandlePositionAndSize,this)),s.push(e.on("set:margin",this._updateHandlePositionAndSize,this)),s.push(e.on("set:pivot",this._updateHandlePositionAndSize,this))}_handleEntityElementUnsubscribe(){for(let e=0;e0?i.duration:null,this._startTime=Math.max(0,Number(i.startTime)||0),this._overlap=!!i.overlap,this._autoPlay=!!i.autoPlay,this._firstNode=null,this._lastNode=null,this._asset=i.asset,this._asset instanceof ae&&(this._asset=this._asset.id),this._onInstancePlayHandler=this._onInstancePlay.bind(this),this._onInstancePauseHandler=this._onInstancePause.bind(this),this._onInstanceResumeHandler=this._onInstanceResume.bind(this),this._onInstanceStopHandler=this._onInstanceStop.bind(this),this._onInstanceEndHandler=this._onInstanceEnd.bind(this)}play(){if(this.overlap||this.stop(),!this.isLoaded&&!this._hasAsset())return;let e=this._createInstance();if(this.instances.push(e),this.isLoaded)e.play();else{let s=function(i){let r=e._playWhenLoaded;e.sound=i,r&&e.play()};this.off("load",s),this.once("load",s),this.load()}return e}pause(){let e=!1,s=this.instances;for(let i=0,r=s.length;i=0;l--){let h=a[l].isPlaying||a[l].isSuspended,f=a[l].currentTime;h&&a[l].stop();let u=r._createInstance();h&&(u.play(),u.currentTime=f),a.push(u)}}}}get positional(){return this._positional}set slots(e){let s=this._slots;if(s)for(let r in s)s[r].stop();let i={};for(let r in e)e[r]instanceof ir?i[e[r].name]=e[r]:e[r].name&&(i[e[r].name]=new ir(this,e[r].name,e[r]));this._slots=i,this.enabled&&this.entity.enabled&&this.onEnable()}get slots(){return this._slots}onEnable(){if(this.system._inTools)return;let e=this._slots,s=this._playingBeforeDisable;for(let i in e){let r=e[i];r.autoPlay&&r.isStopped?r.play():s[i]?r.resume():r.isLoaded||r.load()}}onDisable(){let e=this._slots,s={};for(let i in e)e[i].overlap||e[i].isPlaying&&(e[i].pause(),s[i]=!0);this._playingBeforeDisable=s}onRemove(){this.off()}addSlot(e,s){let i=this._slots;if(i[e])return null;let r=new ir(this,e,s);return i[e]=r,r.autoPlay&&this.enabled&&this.entity.enabled&&r.play(),r}removeSlot(e){let s=this._slots;s[e]&&(s[e].stop(),delete s[e])}slot(e){return this._slots[e]}_getSlotProperty(e,s){if(!this.enabled||!this.entity.enabled)return;let i=this._slots[e];if(i)return i[s]}isPlaying(e){return this._getSlotProperty(e,"isPlaying")||!1}isLoaded(e){return this._getSlotProperty(e,"isLoaded")||!1}isPaused(e){return this._getSlotProperty(e,"isPaused")||!1}isStopped(e){return this._getSlotProperty(e,"isStopped")||!1}play(e){if(!this.enabled||!this.entity.enabled)return null;let s=this._slots[e];return s?s.play():null}pause(e){let s=this._slots;if(e){let i=s[e];if(!i)return;i.pause()}else for(let i in s)s[i].pause()}resume(e){let s=this._slots;if(e){let i=s[e];if(!i)return;i.isPaused&&i.resume()}else for(let i in s)s[i].resume()}stop(e){let s=this._slots;if(e){let i=s[e];if(!i)return;i.stop()}else for(let i in s)s[i].stop()}};n(ma,"EVENT_PLAY","play"),n(ma,"EVENT_PAUSE","pause"),n(ma,"EVENT_RESUME","resume"),n(ma,"EVENT_STOP","stop"),n(ma,"EVENT_END","end");var Q0=class{constructor(){n(this,"enabled",!0)}};var Ak=["enabled"],s_=class extends Fe{constructor(t){super(t),this.id="sound",this.ComponentType=ma,this.DataType=Q0,this.schema=Ak,this.manager=t.soundManager,this.app.systems.on("update",this.onUpdate,this),this.on("beforeremove",this.onBeforeRemove,this)}set volume(t){this.manager.volume=t}get volume(){return this.manager.volume}get context(){return this.manager.context}initializeComponentData(t,e,s){s=["volume","pitch","positional","refDistance","maxDistance","rollOffFactor","distanceModel","slots"];for(let i=0;ir||i<0;this._setTime(i);let o=this.frame;this._sprite?o=Math.floor(this._sprite.frameKeys.length*this._time/r):o=0,o!==this._frame&&this._setFrame(o),a&&(this.loop?(this.fire("loop"),this._component.fire("loop",this)):(this._playing=!1,this._paused=!1,this.fire("end"),this._component.fire("end",this)))}_setTime(e){this._time=e;let s=this.duration;this._time<0?this.loop?this._time=this._time%s+s:this._time=0:this._time>s&&(this.loop?this._time%=s:this._time=s)}_setFrame(e){this._sprite?this._frame=R.clamp(e,0,this._sprite.frameKeys.length-1):this._frame=e,this._component.currentClip===this&&this._component._showFrame(this._frame)}_destroy(){if(this._spriteAsset){let e=this._component.system.app.assets;this._unbindSpriteAsset(e.get(this._spriteAsset))}this._sprite&&(this.sprite=null),this._spriteAsset&&(this.spriteAsset=null)}play(){this._playing||(this._playing=!0,this._paused=!1,this.frame=0,this.fire("play"),this._component.fire("play",this))}pause(){!this._playing||this._paused||(this._paused=!0,this.fire("pause"),this._component.fire("pause",this))}resume(){this._paused&&(this._paused=!1,this.fire("resume"),this._component.fire("resume",this))}stop(){this._playing&&(this._playing=!1,this._paused=!1,this._time=0,this.frame=0,this.fire("stop"),this._component.fire("stop",this))}};n(rr,"EVENT_PLAY","play"),n(rr,"EVENT_PAUSE","pause"),n(rr,"EVENT_RESUME","resume"),n(rr,"EVENT_STOP","stop"),n(rr,"EVENT_END","end"),n(rr,"EVENT_LOOP","loop");var Ck="texture_emissiveMap",Pk="texture_opacityMap",wk="material_emissive",Ik="material_opacity",gK="innerOffset",SK="outerScale",xK="atlasRect",Lr=class extends le{constructor(e,s){super(e,s);n(this,"_evtLayersChanged",null);n(this,"_evtLayerAdded",null);n(this,"_evtLayerRemoved",null);n(this,"_type",J0);n(this,"_material",null);n(this,"_color",new F(1,1,1,1));n(this,"_colorUniform",new Float32Array(3));n(this,"_speed",1);n(this,"_flipX",!1);n(this,"_flipY",!1);n(this,"_width",1);n(this,"_height",1);n(this,"_drawOrder",0);n(this,"_layers",[Os]);n(this,"_outerScale",new B(1,1));n(this,"_outerScaleUniform",new Float32Array(2));n(this,"_innerOffset",new Q);n(this,"_innerOffsetUniform",new Float32Array(4));n(this,"_atlasRect",new Q);n(this,"_atlasRectUniform",new Float32Array(4));n(this,"_batchGroupId",-1);n(this,"_node",new Pe);n(this,"_meshInstance",null);n(this,"_updateAabbFunc",null);n(this,"_inLayers",!1);n(this,"_autoPlayClip",null);n(this,"_clips",{});n(this,"_defaultClip",null);n(this,"_currentClip",null);this._material=e.defaultMaterial,s.addChild(this._node),this._updateAabbFunc=this._updateAabb.bind(this),this._defaultClip=new rr(this,{name:this.entity.name,fps:0,loop:!1,spriteAsset:null}),this._currentClip=this._defaultClip}set type(e){this._type!==e&&(this._type=e,this._type===J0?(this.stop(),this._currentClip=this._defaultClip,this.enabled&&this.entity.enabled&&(this._currentClip.frame=this.frame,this._currentClip.sprite?this.addToLayers():this.removeFromLayers())):this._type===eE&&(this.stop(),this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.isPlaying&&this.enabled&&this.entity.enabled?this.addToLayers():this.removeFromLayers()))}get type(){return this._type}set frame(e){this._currentClip.frame=e}get frame(){return this._currentClip.frame}set spriteAsset(e){this._defaultClip.spriteAsset=e}get spriteAsset(){return this._defaultClip._spriteAsset}set sprite(e){this._currentClip.sprite=e}get sprite(){return this._currentClip.sprite}set material(e){this._material=e,this._meshInstance&&(this._meshInstance.material=e)}get material(){return this._material}set color(e){this._color.r=e.r,this._color.g=e.g,this._color.b=e.b,this._meshInstance&&(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(wk,this._colorUniform))}get color(){return this._color}set opacity(e){this._color.a=e,this._meshInstance&&this._meshInstance.setParameter(Ik,e)}get opacity(){return this._color.a}set clips(e){if(!e){for(let s in this._clips)this.removeClip(s);return}for(let s in this._clips){let i=!1;for(let r in e)if(e[r].name===s){i=!0,this._clips[s].fps=e[r].fps,this._clips[s].loop=e[r].loop,e[r].hasOwnProperty("sprite")?this._clips[s].sprite=e[r].sprite:e[r].hasOwnProperty("spriteAsset")&&(this._clips[s].spriteAsset=e[r].spriteAsset);break}i||this.removeClip(s)}for(let s in e)this._clips[e[s].name]||this.addClip(e[s]);this._autoPlayClip&&this._tryAutoPlay(),(!this._currentClip||!this._currentClip.sprite)&&this.removeFromLayers()}get clips(){return this._clips}get currentClip(){return this._currentClip}set speed(e){this._speed=e}get speed(){return this._speed}set flipX(e){this._flipX!==e&&(this._flipX=e,this._updateTransform())}get flipX(){return this._flipX}set flipY(e){this._flipY!==e&&(this._flipY=e,this._updateTransform())}get flipY(){return this._flipY}set width(e){e!==this._width&&(this._width=e,this._outerScale.x=this._width,this.sprite&&(this.sprite.renderMode===Rt||this.sprite.renderMode===It)&&this._updateTransform())}get width(){return this._width}set height(e){e!==this._height&&(this._height=e,this._outerScale.y=this.height,this.sprite&&(this.sprite.renderMode===Rt||this.sprite.renderMode===It)&&this._updateTransform())}get height(){return this._height}set batchGroupId(e){if(this._batchGroupId===e)return;let s=this._batchGroupId;this._batchGroupId=e,this.entity.enabled&&s>=0&&this.system.app.batcher?.remove(pt.SPRITE,s,this.entity),this.entity.enabled&&e>=0?this.system.app.batcher?.insert(pt.SPRITE,e,this.entity):s>=0&&this._currentClip&&this._currentClip.sprite&&this.enabled&&this.entity.enabled&&this.addToLayers()}get batchGroupId(){return this._batchGroupId}set autoPlayClip(e){this._autoPlayClip=e instanceof rr?e.name:e,this._tryAutoPlay()}get autoPlayClip(){return this._autoPlayClip}set drawOrder(e){this._drawOrder=e,this._meshInstance&&(this._meshInstance.drawOrder=e)}get drawOrder(){return this._drawOrder}set layers(e){this._inLayers&&this.removeFromLayers(),this._layers=e,this._meshInstance&&this.enabled&&this.entity.enabled&&this.addToLayers()}get layers(){return this._layers}get aabb(){return this._meshInstance?this._meshInstance.aabb:null}onEnable(){let e=this.system.app,s=e.scene,i=s.layers;this._evtLayersChanged=s.on("set:layers",this._onLayersChanged,this),i&&(this._evtLayerAdded=i.on("add",this._onLayerAdded,this),this._evtLayerRemoved=i.on("remove",this._onLayerRemoved,this)),this.addToLayers(),this._autoPlayClip&&this._tryAutoPlay(),this._batchGroupId>=0&&e.batcher?.insert(pt.SPRITE,this._batchGroupId,this.entity)}onDisable(){let e=this.system.app,i=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,i&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.stop(),this.removeFromLayers(),this._batchGroupId>=0&&e.batcher?.remove(pt.SPRITE,this._batchGroupId,this.entity)}onDestroy(){this._currentClip=null,this._defaultClip&&(this._defaultClip._destroy(),this._defaultClip=null);for(let e in this._clips)this._clips[e]._destroy();this._clips=null,this.removeFromLayers(),this._node?.remove(),this._node=null,this._meshInstance&&(this._meshInstance.material=null,this._meshInstance.mesh=null,this._meshInstance=null)}addToLayers(){if(this._inLayers||!this._meshInstance)return;let e=[this._meshInstance];for(let s=0,i=this._layers.length;s=3&&this.size.set(e[0],e[1],e[2])}get size(){return this._size}onEnable(){this._checkState()}onDisable(){this._checkState()}_onSetEnabled(e,s,i){this._checkState()}_checkState(){let e=this.enabled&&this.entity.enabled;e!==this._oldState&&(this._oldState=e,this.fire("enable"),this.fire("state",this.enabled))}_onBeforeRemove(){this.fire("remove")}};n(ro,"EVENT_ENABLE","enable"),n(ro,"EVENT_DISABLE","disable"),n(ro,"EVENT_STATE","state"),n(ro,"EVENT_REMOVE","remove");var sE=class{constructor(){n(this,"enabled",!0)}};var bk=["enabled"],r_=class extends Fe{constructor(t){super(t),this.id="zone",this.ComponentType=ro,this.DataType=sE,this.schema=bk,this.on("beforeremove",this._onBeforeRemove,this)}initializeComponentData(t,e,s){t.enabled=e.hasOwnProperty("enabled")?!!e.enabled:!0,e.size&&(e.size instanceof x?t.size.copy(e.size):e.size instanceof Array&&e.size.length>=3&&t.size.set(e.size[0],e.size[1],e.size[2]))}cloneComponent(t,e){let s={enabled:t.zone.enabled,size:t.zone.size};return this.addComponent(e,s)}_onBeforeRemove(t,e){e._onBeforeRemove()}};le._buildAccessors(ro.prototype,bk);var RR=class{constructor(t,e){this.effect=t,this.inputTarget=e,this.outputTarget=null,this.name=t.constructor.name}},a_=class{constructor(t,e){this.app=t,this.camera=e,this.destinationRenderTarget=null,this.effects=[],this.enabled=!1,this.depthTarget=null,e.on("set:rect",this.onCameraRectChanged,this)}_allocateColorBuffer(t,e){let s=this.camera.rect,i=this.destinationRenderTarget,r=this.app.graphicsDevice,a=Math.floor(s.z*(i?.width??r.width)),o=Math.floor(s.w*(i?.height??r.height));return Z.createDataTexture2D(r,e,a,o,t)}_createOffscreenTarget(t,e){let s=this.app.graphicsDevice,r=(this.destinationRenderTarget??s.backBuffer).isColorBufferSrgb(0),a=(e&&s.getRenderableHdrFormat([Me,ke],!0))??(r?st:ce),o=`${this.camera.entity.name}-posteffect-${this.effects.length}`,l=this._allocateColorBuffer(a,o);return new me({colorBuffer:l,depth:t,stencil:t&&this.app.graphicsDevice.supportsStencil,samples:t?s.samples:1})}_resizeOffscreenTarget(t){let e=t.colorBuffer.format,s=t.colorBuffer.name;t.destroyFrameBuffers(),t.destroyTextureBuffers(),t._colorBuffer=this._allocateColorBuffer(e,s),t._colorBuffers=[t._colorBuffer],t.evaluateDimensions()}_destroyOffscreenTarget(t){t.destroyTextureBuffers(),t.destroy()}addEffect(t){let e=this.effects,s=e.length===0,i=this._createOffscreenTarget(s,t.hdr),r=new RR(t,i);e.push(r),this._sourceTarget=r.inputTarget,e.length>1&&(e[e.length-2].outputTarget=r.inputTarget),this._newPostEffect=t,t.needsDepthBuffer&&this._requestDepthMap(),this.enable(),this._newPostEffect=void 0}removeEffect(t){let e=-1;for(let s=0,i=this.effects.length;s=0&&(e>0?this.effects[e-1].outputTarget=e+11&&(this.effects[1].inputTarget._depth||(this._destroyOffscreenTarget(this.effects[1].inputTarget),this.effects[1].inputTarget=this._createOffscreenTarget(!0,this.effects[1].hdr),this._sourceTarget=this.effects[1].inputTarget),this.camera.renderTarget=this.effects[1].inputTarget),this._destroyOffscreenTarget(this.effects[e].inputTarget),this.effects.splice(e,1)),this.enabled&&t.needsDepthBuffer&&this._releaseDepthMap(),this.effects.length===0&&this.disable()}_requestDepthMaps(){for(let t=0,e=this.effects.length;t{if(this.enabled){let t=null,e=this.effects.length;if(e)for(let s=0;s{i.layers.getLayerById(r)?.removeCamera(this)}),this._camera.layers=e,this.enabled&&this.entity.enabled&&e.forEach(r=>{i.layers.getLayerById(r)?.addCamera(this)}),this.fire("set:layers")}get layers(){return this._camera.layers}get layersSet(){return this._camera.layersSet}set jitter(e){this._camera.jitter=e}get jitter(){return this._camera.jitter}set nearClip(e){this._camera.nearClip=e}get nearClip(){return this._camera.nearClip}set orthoHeight(e){this._camera.orthoHeight=e}get orthoHeight(){return this._camera.orthoHeight}get postEffects(){return this._postEffects}get postEffectsEnabled(){return this._postEffects.enabled}set priority(e){this._priority=e,this.dirtyLayerCompositionCameras()}get priority(){return this._priority}set projection(e){this._camera.projection=e}get projection(){return this._camera.projection}get projectionMatrix(){return this._camera.projectionMatrix}set rect(e){this._camera.rect=e,this.fire("set:rect",this._camera.rect)}get rect(){return this._camera.rect}set renderSceneColorMap(e){e&&!this._sceneColorMapRequested?(this.requestSceneColorMap(!0),this._sceneColorMapRequested=!0):!e&&this._sceneColorMapRequested&&(this.requestSceneColorMap(!1),this._sceneColorMapRequested=!1)}get renderSceneColorMap(){return this._renderSceneColorMap>0}set renderSceneDepthMap(e){e&&!this._sceneDepthMapRequested?(this.requestSceneDepthMap(!0),this._sceneDepthMapRequested=!0):!e&&this._sceneDepthMapRequested&&(this.requestSceneDepthMap(!1),this._sceneDepthMapRequested=!1)}get renderSceneDepthMap(){return this._renderSceneDepthMap>0}set renderTarget(e){this._camera.renderTarget=e,this.dirtyLayerCompositionCameras()}get renderTarget(){return this._camera.renderTarget}set scissorRect(e){this._camera.scissorRect=e}get scissorRect(){return this._camera.scissorRect}set sensitivity(e){this._camera.sensitivity=e}get sensitivity(){return this._camera.sensitivity}set shutter(e){this._camera.shutter=e}get shutter(){return this._camera.shutter}get viewMatrix(){return this._camera.viewMatrix}_enableDepthLayer(e){if(this.layers.find(i=>i===Zt)){let i=this.system.app.scene.layers.getLayerById(Zt);e?i?.incrementCounter():i?.decrementCounter()}else if(e)return!1;return!0}requestSceneColorMap(e){this._renderSceneColorMap+=e?1:-1;let s=this._enableDepthLayer(e);this.camera._enableRenderPassColorGrab(this.system.app.graphicsDevice,this.renderSceneColorMap),this.system.app.scene.layers.markDirty()}requestSceneDepthMap(e){this._renderSceneDepthMap+=e?1:-1;let s=this._enableDepthLayer(e);this.camera._enableRenderPassDepthGrab(this.system.app.graphicsDevice,this.system.app.renderer,this.renderSceneDepthMap),this.system.app.scene.layers.markDirty()}dirtyLayerCompositionCameras(){let e=this.system.app.scene.layers;e._dirty=!0}screenToWorld(e,s,i,r){let a=this.system.app.graphicsDevice,{width:o,height:l}=a.clientRect;return this._camera.screenToWorld(e,s,i,o,l,r)}worldToScreen(e,s){let i=this.system.app.graphicsDevice,{width:r,height:a}=i.clientRect;return this._camera.worldToScreen(e,r,a,s)}onAppPrerender(){this._camera._viewMatDirty=!0,this._camera._viewProjMatDirty=!0}addCameraToLayers(){let e=this.layers;for(let s=0;s=0&&(this.cameras.splice(s,1),Uc(this.cameras))}destroy(){this.app.off("prerender",this.onAppPrerender,this),super.destroy()}};le._buildAccessors(ar.prototype,Dk);var Iu=["type","color","intensity","luminance","shape","affectSpecularity","castShadows","shadowDistance","shadowIntensity","shadowResolution","shadowBias","numCascades","cascadeBlend","bakeNumSamples","bakeArea","cascadeDistribution","normalOffsetBias","range","innerConeAngle","outerConeAngle","falloffMode","shadowType","vsmBlurSize","vsmBlurMode","vsmBias","cookieAsset","cookie","cookieIntensity","cookieFalloff","cookieChannel","cookieAngle","cookieScale","cookieOffset","shadowUpdateMode","mask","affectDynamic","affectLightmapped","bake","bakeDir","isStatic","layers","penumbraSize","penumbraFalloff","shadowSamples","shadowBlockerSamples"],Ru=class extends le{constructor(e,s){super(e,s);n(this,"_light");n(this,"_evtLayersChanged",null);n(this,"_evtLayerAdded",null);n(this,"_evtLayerRemoved",null);n(this,"_cookieAsset",null);n(this,"_cookieAssetId",null);n(this,"_cookieAssetAdd",!1);n(this,"_cookieMatrix",null);n(this,"_shadowBias",.05);n(this,"_cookieAngle",0);n(this,"_cookieScale",null);n(this,"_castShadows",!1);n(this,"_affectSpecularity",!0);n(this,"_affectDynamic",!0);n(this,"_affectLightmapped",!1);n(this,"_bake",!1);n(this,"_layers",[Os]);n(this,"_type","directional");this._light=new kc(e.app.graphicsDevice,e.app.scene.clusteredLightingEnabled),this._light._node=s,this._light.setColor(1,1,1)}get light(){return this._light}set type(e){this._type!==e&&(this.removeLightFromLayers(),this._type=e,this._light.type=ly[e],this.refreshProperties())}get type(){return this._type}set color(e){this._light.setColor(e)}get color(){return this._light.getColor()}set intensity(e){this._light.intensity=e}get intensity(){return this._light.intensity}set luminance(e){this._light.luminance=e}get luminance(){return this._light.luminance}set shape(e){this._light.shape=e}get shape(){return this._light.shape}set affectSpecularity(e){this._affectSpecularity=e,this._light.affectSpecularity=e}get affectSpecularity(){return this._affectSpecularity}set castShadows(e){this._castShadows=e,this._light.castShadows=e}get castShadows(){return this._castShadows}set shadowDistance(e){this._light.shadowDistance=e}get shadowDistance(){return this._light.shadowDistance}set shadowIntensity(e){this._light.shadowIntensity=e}get shadowIntensity(){return this._light.shadowIntensity}set shadowResolution(e){this._light.shadowResolution=e}get shadowResolution(){return this._light.shadowResolution}set shadowBias(e){this._shadowBias=e,this._light.shadowBias=-.01*R.clamp(e,0,1)}get shadowBias(){return this._shadowBias}set numCascades(e){this._light.numCascades=R.clamp(Math.floor(e),1,4)}get numCascades(){return this._light.numCascades}set cascadeBlend(e){this._light.cascadeBlend=R.clamp(e,0,1)}get cascadeBlend(){return this._light.cascadeBlend}set bakeNumSamples(e){this._light.bakeNumSamples=R.clamp(Math.floor(e),1,255)}get bakeNumSamples(){return this._light.bakeNumSamples}set bakeArea(e){this._light.bakeArea=R.clamp(e,0,180)}get bakeArea(){return this._light.bakeArea}set cascadeDistribution(e){this._light.cascadeDistribution=R.clamp(e,0,1)}get cascadeDistribution(){return this._light.cascadeDistribution}set normalOffsetBias(e){this._light.normalOffsetBias=R.clamp(e,0,1)}get normalOffsetBias(){return this._light.normalOffsetBias}set range(e){this._light.attenuationEnd=e}get range(){return this._light.attenuationEnd}set innerConeAngle(e){this._light.innerConeAngle=e}get innerConeAngle(){return this._light.innerConeAngle}set outerConeAngle(e){this._light.outerConeAngle=e}get outerConeAngle(){return this._light.outerConeAngle}set falloffMode(e){this._light.falloffMode=e}get falloffMode(){return this._light.falloffMode}set shadowType(e){this._light.shadowType=e}get shadowType(){return this._light.shadowType}set vsmBlurSize(e){this._light.vsmBlurSize=e}get vsmBlurSize(){return this._light.vsmBlurSize}set vsmBlurMode(e){this._light.vsmBlurMode=e}get vsmBlurMode(){return this._light.vsmBlurMode}set vsmBias(e){this._light.vsmBias=R.clamp(e,0,1)}get vsmBias(){return this._light.vsmBias}set cookieAsset(e){if(!(this._cookieAssetId&&(e instanceof ae&&e.id===this._cookieAssetId||e===this._cookieAssetId))){if(this.onCookieAssetRemove(),this._cookieAssetId=null,e instanceof ae)this._cookieAssetId=e.id,this.onCookieAssetAdd(e);else if(typeof e=="number"){this._cookieAssetId=e;let s=this.system.app.assets.get(e);s?this.onCookieAssetAdd(s):(this._cookieAssetAdd=!0,this.system.app.assets.on(`add:${this._cookieAssetId}`,this.onCookieAssetAdd,this))}}}get cookieAsset(){return this._cookieAssetId}set cookie(e){this._light.cookie=e}get cookie(){return this._light.cookie}set cookieIntensity(e){this._light.cookieIntensity=R.clamp(e,0,1)}get cookieIntensity(){return this._light.cookieIntensity}set cookieFalloff(e){this._light.cookieFalloff=e}get cookieFalloff(){return this._light.cookieFalloff}set cookieChannel(e){this._light.cookieChannel=e}get cookieChannel(){return this._light.cookieChannel}set cookieAngle(e){if(this._cookieAngle!==e)if(this._cookieAngle=e,e!==0||this._cookieScale!==null){this._cookieMatrix||(this._cookieMatrix=new Q);let s=1,i=1;this._cookieScale&&(s=this._cookieScale.x,i=this._cookieScale.y);let r=Math.cos(e*R.DEG_TO_RAD),a=Math.sin(e*R.DEG_TO_RAD);this._cookieMatrix.set(r/s,-a/s,a/i,r/i),this._light.cookieTransform=this._cookieMatrix}else this._light.cookieTransform=null}get cookieAngle(){return this._cookieAngle}set cookieScale(e){if(this._cookieScale=e,e!==null||this._cookieAngle!==0){this._cookieMatrix||(this._cookieMatrix=new Q);let s=e?e.x:1,i=e?e.y:1,r=Math.cos(this._cookieAngle*R.DEG_TO_RAD),a=Math.sin(this._cookieAngle*R.DEG_TO_RAD);this._cookieMatrix.set(r/s,-a/s,a/i,r/i),this._light.cookieTransform=this._cookieMatrix}else this._light.cookieTransform=null}get cookieScale(){return this._cookieScale}set cookieOffset(e){this._light.cookieOffset=e}get cookieOffset(){return this._light.cookieOffset}set shadowUpdateMode(e){this._light.shadowUpdateMode=e}get shadowUpdateMode(){return this._light.shadowUpdateMode}set mask(e){this._light.mask=e}get mask(){return this._light.mask}set affectDynamic(e){this._affectDynamic!==e&&(this._affectDynamic=e,e?this._light.mask|=cs:this._light.mask&=~cs,this._light.layersDirty())}get affectDynamic(){return this._affectDynamic}set affectLightmapped(e){this._affectLightmapped!==e&&(this._affectLightmapped=e,e?(this._light.mask|=xi,this._bake&&(this._light.mask&=~vi)):(this._light.mask&=~xi,this._bake&&(this._light.mask|=vi)))}get affectLightmapped(){return this._affectLightmapped}set bake(e){this._bake!==e&&(this._bake=e,e?(this._light.mask|=vi,this._affectLightmapped&&(this._light.mask&=~xi)):(this._light.mask&=~vi,this._affectLightmapped&&(this._light.mask|=xi)),this._light.layersDirty())}get bake(){return this._bake}set bakeDir(e){this._light.bakeDir=e}get bakeDir(){return this._light.bakeDir}set isStatic(e){this._light.isStatic=e}get isStatic(){return this._light.isStatic}set layers(e){let s=this._layers;for(let i=0;i=0&&this.enabled&&this.entity.enabled&&(e.addLight(this),this._light.addLayer(e))}onLayerRemoved(e){this._layers.indexOf(e.id)>=0&&(e.removeLight(this),this._light.removeLayer(e))}refreshProperties(){for(let e=0;e=3&&e.length<=4){for(let i=0;ic_(c,t,i,s?s[r]:null)):c_(c,t,e,s)}function bR(c,t,e,s){if(e)for(let i in t){let r=t[i],a=e[i];a!==void 0&&(s[i]=Mk(c,r,a,s[i]))}}var l_=class l_{constructor(t){this.scriptType=t,this.index={}}add(t,e){e&&e.type&&(this.index[t]||l_.reservedNames.has(t)||(this.index[t]=e,Object.defineProperty(this.scriptType.prototype,t,{get:function(){return this.__attributes[t]},set:function(s){let i="attr",r=`attr:${t}`,a=this.__attributes[t],o=a;if(a&&e.type!=="json"&&e.type!=="entity"&&a.clone&&(this.hasEvent(i)||this.hasEvent(r))&&(o=a.clone()),e.array){if(this.__attributes[t]=[],s)for(let l=0,h=s.length;l{this.initializeAttributes(i)}),i.enabled=!!e[s].enabled),typeof e[s].attributes=="object")){for(let r in e[s].attributes)if(!ao.reservedNames.has(r)){if(!i.__attributes.hasOwnProperty(r)){let a=this.system.app.scripts.get(s);a&&a.attributes.add(r,{})}i[r]=e[s].attributes[r]}}}}get scripts(){return this._scripts}set enabled(e){let s=this._enabled;this._enabled=e,this.fire("set","enabled",s,e)}get enabled(){return this._enabled}onEnable(){this._beingEnabled=!0,this._checkState(),this.entity._beingEnabled||this.onPostStateChange(),this._beingEnabled=!1}onDisable(){this._checkState()}onPostStateChange(){let e=this._beginLooping();for(let s=0,i=this.scripts.length;s{this.initializeAttributes(a)}),a.enabled=a._enabled}this._endLooping(s)}_onBeforeRemove(){this.fire("remove");let e=this._beginLooping();for(let s=0;ss.ind&&(h=s.ind),this._insertScriptInstance(o,h,l),this._scriptsIndex[a]={instance:o,onSwap:function(){i.swap(a)}},this[a]=o,s.preloading||this.initializeAttributes(o),this.fire("create",a,o),this.fire(`create:${a}`,o),this.system.app.scripts.on(`swap:${a}`,this._scriptsIndex[a].onSwap),s.preloading||(o.enabled&&!o._initialized&&(o._initialized=!0,o.initialize&&this._scriptMethod(o,IS)),o.enabled&&!o._postInitialized&&(o._postInitialized=!0,o.postInitialize&&this._scriptMethod(o,RS))),o}}else this._scriptsIndex[a]={awaiting:!0,ind:this._scripts.length};return null}destroy(e){let s=e,i=e;typeof i=="string"?i=this.system.app.scripts.get(i):i&&(s=i.__name);let r=this._scriptsIndex[s];if(delete this._scriptsIndex[s],!r)return!1;this._attributeDataMap.delete(s);let a=r.instance;if(a&&!a._destroyed)if(a.enabled=!1,a._destroyed=!0,this._isLoopingThroughScripts)this._destroyedScripts.push(a);else{let o=this._removeScriptInstance(a);o>=0&&this._resetExecutionOrder(o,this._scripts.length)}return this.system.app.scripts.off(`swap:${s}`,r.onSwap),delete this[s],this.fire("destroy",s,a||null),this.fire(`destroy:${s}`,a||null),a&&a.fire("destroy"),!0}swap(e){let s=e,i=e;typeof i=="string"?i=this.system.app.scripts.get(i):i&&(s=i.__name);let r=this._scriptsIndex[s];if(!r||!r.instance)return!1;let a=r.instance,o=this._scripts.indexOf(a),l=new i({app:this.system.app,entity:this.entity,enabled:a.enabled,attributes:a.__attributes});return l.swap?(this.initializeAttributes(l),this._scripts[o]=l,this._scriptsIndex[s].instance=l,this[s]=l,l.__executionOrder=o,a.update&&this._updateList.remove(a),a.postUpdate&&this._postUpdateList.remove(a),l.update&&this._updateList.insert(l),l.postUpdate&&this._postUpdateList.insert(l),this._scriptMethod(l,w2,a),this.fire("swap",s,l),this.fire(`swap:${s}`,l),!0):!1}resolveDuplicatedEntityReferenceProperties(e,s){let i=this.entity.script;for(let r in e._scriptsIndex){let a=this.system.app.scripts.get(r);if(!a)continue;let o=e._scriptsIndex[r];if(!o||!o.instance)continue;let l=i[r].__attributesRaw??i._attributeDataMap.get(r),h=i[r].__attributes;if(!l&&!h)continue;let f=!!l,u=o.instance.__attributes??i._attributeDataMap.get(r);for(let d in u){if(!u[d])continue;let p=a.attributes?.get(d)??this.system.app.scripts.getSchema(r)?.attributes?.[d];if(p){if(p.type==="entity")this._resolveEntityScriptAttribute(p,d,u[d],f,l||h,s);else if(p.type==="json"&&Array.isArray(p.schema)){let m=u[d],_=l?l[d]:h[d];for(let S=0;S=i||s<0)return!1;let r=e,a=e;typeof a!="string"?a=e.__name:r=null;let o=this._scriptsIndex[a];if(!o||!o.instance)return!1;let l=o.instance;if(r&&!(l instanceof r))return!1;let h=this._scripts.indexOf(l);return h===-1||h===s?!1:(this._scripts.splice(s,0,this._scripts.splice(h,1)[0]),this._resetExecutionOrder(0,i),this._updateList.sort(),this._postUpdateList.sort(),this.fire("move",a,l,s,h),this.fire(`move:${a}`,l,s,h),!0)}};n(or,"EVENT_CREATE","create"),n(or,"EVENT_DESTROY","destroy"),n(or,"EVENT_ENABLE","enable"),n(or,"EVENT_DISABLE","disable"),n(or,"EVENT_REMOVE","remove"),n(or,"EVENT_STATE","state"),n(or,"EVENT_MOVE","move"),n(or,"EVENT_ERROR","error");var aE=class{constructor(){n(this,"enabled",!0)}};var yK="_onInitializeAttributes",EK="_onInitialize",AK="_onPostInitialize",CK="_onUpdate",PK="_onPostUpdate",oE=0,h_=class extends Fe{constructor(t){super(t),this.id="script",this.ComponentType=or,this.DataType=aE,this._components=new po({sortBy:"_executionOrder"}),this._enabledComponents=new po({sortBy:"_executionOrder"}),this.preloading=!0,this.on("beforeremove",this._onBeforeRemove,this),this.app.systems.on("initialize",this._onInitialize,this),this.app.systems.on("postInitialize",this._onPostInitialize,this),this.app.systems.on("update",this._onUpdate,this),this.app.systems.on("postUpdate",this._onPostUpdate,this)}initializeComponentData(t,e){if(t._executionOrder=oE++,this._components.append(t),oE>Number.MAX_SAFE_INTEGER&&this._resetExecutionOrder(),t.enabled=e.hasOwnProperty("enabled")?!!e.enabled:!0,t.enabled&&t.entity.enabled&&this._enabledComponents.append(t),e.hasOwnProperty("order")&&e.hasOwnProperty("scripts")){t._scriptsData=e.scripts;for(let s=0;s=0&&e._onBeforeRemove(),this._removeComponentFromEnabled(e),this._components.remove(e)}destroy(){super.destroy(),this.app.systems.off("initialize",this._onInitialize,this),this.app.systems.off("postInitialize",this._onPostInitialize,this),this.app.systems.off("update",this._onUpdate,this),this.app.systems.off("postUpdate",this._onPostUpdate,this)}};var wK=new B,DR=new Uint32Array(0),LR=[0,0],ZS=class{constructor(t,e,s,i=null,r=null,a=null){n(this,"device");n(this,"resource");n(this,"node");n(this,"lodIndex");n(this,"placementId");n(this,"allocId");n(this,"parentPlacementId");n(this,"numSplats");n(this,"activeSplats",0);n(this,"intervals",[]);n(this,"intervalOffsets",[]);n(this,"intervalAllocIds",[]);n(this,"intervalNodeIndices",[]);n(this,"previousWorldTransform",new W);n(this,"aabb",new ge);n(this,"subDrawTexture",null);n(this,"subDrawCount",0);n(this,"numBoundsEntries",0);n(this,"boundsBaseIndex",0);n(this,"octreeNodes",null);n(this,"nodeInfos",null);n(this,"colorAccumulatedTranslation",0);n(this,"parameters",null);n(this,"getWorkBufferModifier",null);n(this,"getInstanceStreams",null);n(this,"_consumeRenderDirty",null);this.device=t,this.resource=e,this.node=s.node,this.lodIndex=s.lodIndex,this.placementId=s.id,this.allocId=s.allocId,this.parentPlacementId=r&&s.parentPlacement?s.parentPlacement.allocId:s.allocId,this.numSplats=e.numSplats,this.aabb.copy(s.aabb),this.parameters=s.parameters,this.getWorkBufferModifier=()=>s.workBufferModifier,this.getInstanceStreams=()=>s.streams,this._consumeRenderDirty=i,this.octreeNodes=r,this.nodeInfos=a,this.updateIntervals(s.intervals)}destroy(){this.intervals.length=0,this.intervalOffsets.length=0,this.intervalAllocIds.length=0,this.intervalNodeIndices.length=0,this.subDrawTexture?.destroy(),this.subDrawTexture=null,this.subDrawCount=0}setLayout(t){this.intervalOffsets=t,this.subDrawTexture?.destroy(),this.subDrawTexture=null,this.subDrawCount=0}ensureSubDrawTexture(t){!this.subDrawTexture&&t>0&&this.updateSubDraws(t)}updateIntervals(t){let e=this.resource;if(this.intervals.length=0,this.intervalAllocIds.length=0,this.intervalNodeIndices.length=0,this.activeSplats=e.numSplats,t.size>0){let s=0,i=0;this.intervals.length=t.size*2;for(let[r,a]of t)this.intervals[i++]=a.x,this.intervals[i++]=a.y+1,s+=a.y-a.x+1,this.nodeInfos&&(this.intervalAllocIds.push(this.nodeInfos[r].allocId),this.intervalNodeIndices.push(r));this.octreeNodes?(this.activeSplats=s,this.numBoundsEntries=this.octreeNodes.length):s===this.numSplats?this.intervals.length=0:this.activeSplats=s}else{this.numBoundsEntries=1,this.intervalAllocIds.push(this.allocId);let s=e.maxSplats;s&&this.activeSplats0){let u=Math.min(o,a-h),d=e*4;t[d]=l|65536,t[d+1]=h,t[d+2]=h+u,t[d+3]=s,e++,s+=u,o-=u,l++}let f=o/a|0;if(f>0){let u=e*4;t[u]=l|f<<16,t[u+1]=0,t[u+2]=a,t[u+3]=s,e++,s+=f*a,o-=f*a,l+=f}if(o>0){let u=e*4;t[u]=l|65536,t[u+1]=0,t[u+2]=o,t[u+3]=s,e++}return e}updateSubDraws(t){let e=this.intervals,s=e.length/2;s===0&&(LR[0]=0,LR[1]=this.activeSplats,e=LR,s=1);let r=s*3*4;DR.length0}};function Ok(){let c=typeof self<"u"&&self||EC("node:worker_threads").parentPort,t=new Map,e,s,i,r,a=!1,o=!1,l=32,h=new Float32Array(l+1),f=new Float32Array(l+1),u=new GSplatSortBinWeights,d=E=>{for(let y=0;y{let{ids:O,intervals:G}=I,M=l/P,H=0;for(let U=0;U0?G[U]:[0,N.length/3];for(let z=0;z{p(E,y,P,A,w,I,(D,O,G,M,H,U,L,b,N,k)=>{let{transformedDirection:z,offset:V,scale:q}=O,re=z.x,te=z.y,j=z.z,oe=re*q,be=te*q,qe=j*q,ot=V-L;for(let Ve=G;Ve>>0,de=h[Qu]+f[Qu]*(di-Qu)>>>0;N[H++]=de,k[de]++}return H})},_=(E,y,P,A,w,I)=>{p(E,y,P,A,w,I,(D,O,G,M,H,U,L,b,N,k)=>{let{transformedPosition:z,scale:V}=O,q=z.x,re=z.y,te=z.z;for(let j=G;j>>0,Cs=h[ds]+f[ds]*(Vs-ds)>>>0;N[H++]=Cs,k[Cs]++}return H})},S=(E,y,P,A,w)=>{for(let D=1;D{let y=1/0,P=-1/0;for(let A=0;A=0?G[0]:M[0],N=U>=0?G[1]:M[1],k=L>=0?G[2]:M[2],z=H>=0?M[0]:G[0],V=U>=0?M[1]:G[1],q=L>=0?M[2]:G[2],re=b*H+N*U+k*L,te=z*H+V*U+q*L,j=re*O+D,oe=te*O+D,be=Math.min(j,oe),qe=Math.max(j,oe);beP&&(P=qe)}return y===1/0&&(y=0,P=0),{minDist:y,maxDist:P}},T=E=>{let y=-1/0;for(let A=0;Ay&&(y=te)}}let P=0;return y<0&&(y=0),{minDist:P,maxDist:y}},C=(E,y,P)=>{let A=performance.now(),{minDist:w,maxDist:I}=a?T(E):g(E),D=P.totalActiveSplats,G=2**Math.max(10,Math.min(20,Math.round(Math.log2(D/4))))+1;s?.length!==D&&(s=new Uint32Array(D)),!i||i.length!==G?i=new Uint32Array(G):i.fill(0);let M=I-w,H=GSplatSortBinWeights.computeCameraBin(a,w,M),U=u.compute(H,G);d(U),a?_(E,w,M,s,i,P):m(E,w,M,s,i,P),S(G,i,D,s,y);let L=D,b=performance.now()-A,N=[y.buffer],k={order:y.buffer,count:L,version:P.version,sortTime:b};c.postMessage(k,N)},v=E=>{let{ids:y,pixelOffsets:P,intervals:A,totalActiveSplats:w}=E;(!r||r.length0?A[D]:[0,O.length/3];for(let H=0;H{let y=E.data??E;switch(y.command){case"addCenters":{t.set(y.id,new Float32Array(y.centers));break}case"removeCenters":{t.delete(y.id);break}case"sort":{a=y.radialSorting||!1;let P=new Uint32Array(y.order);C(y.sortParams,P,e);break}case"intervals":{e=y,v(e);break}}})}var Cl=class c{static get NUM_BINS(){return 32}static get WEIGHT_TIERS(){return[{maxDistance:0,weight:40},{maxDistance:2,weight:20},{maxDistance:5,weight:8},{maxDistance:10,weight:3},{maxDistance:1/0,weight:1}]}constructor(){let t=c.NUM_BINS,e=c.WEIGHT_TIERS;this.binWeights=new Float32Array(t*2),this.bitsPerBin=new Float32Array(t),this.weightByDistance=new Float32Array(t);for(let s=0;se){let o=a-e,l=(s-1)*2+1;this.binWeights[l]=Math.max(1,this.binWeights[l]-o)}return this.binWeights}};var MR=new Set,nE=class extends J{constructor(e){super();n(this,"worker");n(this,"bufferLength",0);n(this,"availableOrderData",[]);n(this,"jobsInFlight",0);n(this,"hasNewVersion",!1);n(this,"pendingSorted",null);n(this,"centersSet",new Set);n(this,"_destroyed",!1);n(this,"scene",null);this.scene=e??null;let s=` + const GSplatSortBinWeights = ${Cl.toString()}; + (${Ok.toString()})() + `;ue.environment==="node"?(this.worker=new Worker(s,{eval:!0}),this.worker.on("message",this.onSorted.bind(this))):(this.worker=new Worker(URL.createObjectURL(new Blob([s],{type:"application/javascript"}))),this.worker.addEventListener("message",this.onSorted.bind(this)))}onSorted(e){if(this._destroyed)return;let s=e.data??e;this.scene&&s.sortTime!==void 0&&this.scene.fire("gsplat:sorted",s.sortTime);let i=new Uint32Array(s.order);this.jobsInFlight--,this.pendingSorted&&this.releaseOrderData(this.pendingSorted.orderData),this.pendingSorted={count:s.count,version:s.version,orderData:i}}applyPendingSorted(){if(this.pendingSorted){let{count:e,version:s,orderData:i}=this.pendingSorted;this.pendingSorted=null,this.fire("sorted",e,s,i),this.releaseOrderData(i)}}releaseOrderData(e){e.length===this.bufferLength&&this.availableOrderData.push(e)}destroy(){this._destroyed=!0,this.pendingSorted=null,this.worker.terminate(),this.worker=null}setCenters(e,s){if(s){if(!this.centersSet.has(e)){this.centersSet.add(e);let i=s.buffer.slice();this.worker.postMessage({command:"addCenters",id:e,centers:i},[i])}}else this.centersSet.has(e)&&(this.centersSet.delete(e),this.worker.postMessage({command:"removeCenters",id:e}))}updateCentersForSplats(e){for(let s of e){let i=s.resource.id;MR.add(i),this.centersSet.has(i)||this.setCenters(i,s.resource.centers)}for(let s of this.centersSet)MR.has(s)||this.setCenters(s,null);MR.clear()}setSortParameters(e){this.hasNewVersion=!0;let{textureSize:s}=e,i=s*s;i!==this.bufferLength&&(this.bufferLength=i,this.availableOrderData.length=0),this.worker.postMessage(e)}setSortParams(e,s){if(this.hasNewVersion||this.jobsInFlight===0){let i=this.availableOrderData.pop();i||(i=new Uint32Array(this.bufferLength)),this.jobsInFlight++,this.hasNewVersion=!1,this.worker.postMessage({command:"sort",sortParams:e,radialSorting:s,order:i.buffer},[i.buffer])}}};var lE=` #include "tonemappingPS" #include "decodePS" #include "gammaPS" @@ -13731,7 +14075,7 @@ fn prepareOutputFromGamma(gammaColor: vec3f, depth: f32) -> vec3f { #endif return color; } -`;class vJ{destroy(){}setRenderMode(e){this.renderMode=e;}get material(){return null}setDataSource(e){this.workBuffer=e,this.onWorkBufferFormatChanged();}onWorkBufferFormatChanged(){}update(e,t){}setGpuSortedRendering(e,t,i,s){}setCpuSortedRendering(){}setOrderData(){}frameUpdate(e,t,i){}updateOverdrawMode(e){}_createTonemapIncludes(e){for(let t of(e.set("gsplatOutputVS",vQ),["tonemappingPS","tonemappingNonePS","tonemappingLinearPS","tonemappingFilmicPS","tonemappingHejlPS","tonemappingAcesPS","tonemappingAces2PS","tonemappingNeutralPS","decodePS","gammaPS"]))e.set(t,pr[t]);}constructor(e,t,i,s,r){this._workBufferFormatVersion=-1,this.fisheyeProj=new cQ,this.device=e,this.node=t,this.cameraNode=i,this.layer=s,this.workBuffer=r,this._workBufferFormatVersion=r?.format.extraStreamsVersion??-1;}}class v0 extends vJ{setRenderMode(e){let t=this.renderMode??0,i=(1&t)!=0,s=(2&t)!=0,r=(1&e)!=0,a=(2&e)!=0;this.meshInstance.castShadow=a,i&&!r&&this.layer.removeMeshInstances([this.meshInstance],true),s&&!a&&this.layer.removeShadowCasters([this.meshInstance]),!i&&r&&this.layer.addMeshInstances([this.meshInstance],true),!s&&a&&this.layer.addShadowCasters([this.meshInstance]),super.setRenderMode(e);}destroy(){this.renderMode&&(1&this.renderMode&&this.layer.removeMeshInstances([this.meshInstance],true),2&this.renderMode&&this.layer.removeShadowCasters([this.meshInstance])),this._material.destroy(),this.meshInstance.destroy(),super.destroy();}get material(){return this._material}onWorkBufferFormatChanged(){this.configureMaterial();}configureMaterial(){let{workBuffer:e}=this;this._injectFormatChunks(),this._material.setDefine("SH_BANDS","0"),this._material.setDefine("GSPLAT_SEPARATE_OPACITY","");let t=e.format.getStream("dataColor");t&&47!==t.format&&this._material.setDefine("GSPLAT_COLOR_FLOAT",""),this._updateIdDefines(),this._bindWorkBufferTextures(),this._material.setParameter("numSplats",0),this.setOrderData(),this._material.setDefine("DITHER_NONE",""),this._material.cull=0,this._material.blendType=4,this._material.depthWrite=false,this._material.update();}_bindWorkBufferTextures(){let{workBuffer:e}=this;for(let t of e.format.resourceStreams){let i=e.getTexture(t.name);i&&this._material.setParameter(t.name,i);}}_injectFormatChunks(){let e=this.device.isWebGPU?this._material.shaderChunks.wgsl:this._material.shaderChunks.glsl,t=this.workBuffer.format;e.set("gsplatDeclarationsVS",t.getInputDeclarations()),e.set("gsplatReadVS",t.getReadCode());}update(e,t){this.meshInstance.instancingCount=Math.ceil(e/uj.instanceSize),this._material.setParameter("numSplats",e),this._material.setParameter("splatTextureSize",t),this.meshInstance.visible=e>0;}setGpuSortedRendering(e,t,i,s){this.meshInstance.setIndirect(null,e,1),this._material.setParameter("compactedSplatIds",t),this._material.setParameter("numSplatsStorage",i),this._material.getDefine("GSPLAT_INDIRECT_DRAW")||(this._material.setDefine("GSPLAT_INDIRECT_DRAW",true),this._material.update()),this._material.setParameter("splatTextureSize",s),this.meshInstance.visible=true,this.meshInstance.instancingCount<=0&&(this.meshInstance.instancingCount=1);}setCpuSortedRendering(){this.meshInstance.setIndirect(null,-1),this._material.getDefine("GSPLAT_INDIRECT_DRAW")&&(this._material.setDefine("GSPLAT_INDIRECT_DRAW",false),this._material.update()),this.setOrderData(),this.meshInstance.visible=false;}setOrderData(){this.device.isWebGPU?this._material.setParameter("splatOrder",this.workBuffer.orderBuffer):this._material.setParameter("splatOrder",this.workBuffer.orderTexture);}frameUpdate(e){e.colorRamp&&this._material.setParameter("colorRampIntensity",e.colorRampIntensity);let t=this.cameraNode.camera;this.fisheyeProj.update(e.fisheye,t.fov,t.projectionMatrix);let i=this.fisheyeProj.enabled;if(i!==this._lastFisheyeEnabled&&(this._lastFisheyeEnabled=i,this._material.setDefine("GSPLAT_FISHEYE",i),this._material.update()),i){let e=this.fisheyeProj;this._material.setParameter("fisheye_k",e.k),this._material.setParameter("fisheye_inv_k",e.invK),this._material.setParameter("fisheye_projMat00",e.projMat00),this._material.setParameter("fisheye_projMat11",e.projMat11);}let s=!e.useFog;s!==this._lastNoFog&&(this._lastNoFog=s,this._material.setDefine("GSPLAT_NO_FOG",s),this._material.update()),this._syncWithWorkBufferFormat(),(this.forceCopyMaterial||e.material.dirty)&&(this.copyMaterialSettings(e.material),this.forceCopyMaterial=false);}_updateIdDefines(){let e=!!this.workBuffer.format.getStream("pcId");this._material.setDefine("GSPLAT_UNIFIED_ID",e),this._material.setDefine("PICK_CUSTOM_ID",e);}_syncWithWorkBufferFormat(){let e=this.workBuffer.format;this._workBufferFormatVersion!==e.extraStreamsVersion&&(this._workBufferFormatVersion=e.extraStreamsVersion,this.workBuffer.syncWithFormat(),this._injectFormatChunks(),this._bindWorkBufferTextures(),this._updateIdDefines(),this._material.update());}copyMaterialSettings(e){let t=[];this._material.defines.forEach((e,i)=>{this._internalDefines.has(i)||t.push(i);}),t.forEach(e=>this._material.defines.delete(e)),e.defines.forEach((e,t)=>{this._material.defines.set(t,e);});let i=e.parameters;for(let e in i)i.hasOwnProperty(e)&&this._material.setParameter(e,i[e].data);e.hasShaderChunks&&this._material.shaderChunks.copy(e.shaderChunks),this._injectFormatChunks(),this._material.update();}updateOverdrawMode(e){let t=!!e.colorRamp,i=this._material.getDefine("GSPLAT_OVERDRAW");t&&(this._material.setParameter("colorRamp",e.colorRamp),this._material.setParameter("colorRampIntensity",e.colorRampIntensity)),t!==i&&(this._material.setDefine("GSPLAT_OVERDRAW",t),t?(this.originalBlendType=this._material.blendType,this._material.blendType=1):this._material.blendType=this.originalBlendType,this._material.update());}createMeshInstance(){let e=new oS(uj.createMesh(this.device),this._material);e.node=this.node,e.setInstancing(true,true),e.instancingCount=0;let t=this.cameraNode.camera;return e.isVisibleFunc=e=>{let i=this.renderMode??0;return t.camera===e&&!!(1&i)||!!(2&i)&&e.node?.name===nU},e}constructor(e,t,i,s,r){super(e,t,i,s,r),this.originalBlendType=1,this._internalDefines=new Set,this.forceCopyMaterial=true,this._lastFisheyeEnabled=false,this._material=new cT({uniqueName:"UnifiedSplatMaterial",vertexGLSL:'#include "gsplatVS"',fragmentGLSL:'#include "gsplatPS"',vertexWGSL:'#include "gsplatVS"',fragmentWGSL:'#include "gsplatPS"',attributes:{vertex_position:e8}}),this._material.setDefine("{GSPLAT_INSTANCE_SIZE}",uj.instanceSize),this.configureMaterial(),this._material.defines.forEach((e,t)=>{this._internalDefines.add(t);}),this._internalDefines.add("{GSPLAT_INSTANCE_SIZE}"),this._internalDefines.add("GSPLAT_UNIFIED_ID"),this._internalDefines.add("PICK_CUSTOM_ID"),this._internalDefines.add("GSPLAT_INDIRECT_DRAW"),this._internalDefines.add("GSPLAT_SEPARATE_OPACITY"),this._internalDefines.add("GSPLAT_FISHEYE"),this.meshInstance=this.createMeshInstance();}}class v1 extends an{frameUpdate(){let e=this.renderer,t=e.cameraNode.camera,i=t.renderTarget,s=i?i.width:this.device.width,r=i?i.height:this.device.height,a=t.rect,n=Math.floor(s*a.z),o=Math.floor(r*a.w);e.resizeOutputTexture(n,o);}execute(){this.renderer.dispatch();}constructor(e){super(e.device),this.renderer=e,this.name="FramePassGSplatComputeLocal";}}let v2=` +`;var mh=class{constructor(t,e,s,i,r){n(this,"device");n(this,"node");n(this,"cameraNode");n(this,"layer");n(this,"workBuffer");n(this,"renderMode");n(this,"_workBufferFormatVersion",-1);n(this,"fisheyeProj",new Yp);this.device=t,this.node=e,this.cameraNode=s,this.layer=i,this.workBuffer=r,this._workBufferFormatVersion=r?.format.extraStreamsVersion??-1}destroy(){}setRenderMode(t){this.renderMode=t}get material(){return null}setDataSource(t){this.workBuffer=t,this.onWorkBufferFormatChanged()}onWorkBufferFormatChanged(){}update(t,e){}setGpuSortedRendering(t,e,s,i){}setCpuSortedRendering(){}setOrderData(){}frameUpdate(t,e,s){}updateOverdrawMode(t){}_createTonemapIncludes(t){t.set("gsplatOutputVS",lE);let e=["tonemappingPS","tonemappingNonePS","tonemappingLinearPS","tonemappingFilmicPS","tonemappingHejlPS","tonemappingAcesPS","tonemappingAces2PS","tonemappingNeutralPS","decodePS","gammaPS"];for(let s of e)t.set(s,eh[s])}};var cE=class extends mh{constructor(e,s,i,r,a){super(e,s,i,r,a);n(this,"_material");n(this,"meshInstance");n(this,"originalBlendType",ea);n(this,"_internalDefines",new Set);n(this,"forceCopyMaterial",!0);n(this,"_lastFisheyeEnabled",!1);n(this,"_lastSourceChunksKey","");this._material=new ct({uniqueName:"UnifiedSplatMaterial",vertexGLSL:'#include "gsplatVS"',fragmentGLSL:'#include "gsplatPS"',vertexWGSL:'#include "gsplatVS"',fragmentWGSL:'#include "gsplatPS"',attributes:{vertex_position:ee}}),this._material.setDefine("{GSPLAT_INSTANCE_SIZE}",rt.instanceSize),this.configureMaterial(),this._material.defines.forEach((o,l)=>{this._internalDefines.add(l)}),this._internalDefines.add("{GSPLAT_INSTANCE_SIZE}"),this._internalDefines.add("GSPLAT_UNIFIED_ID"),this._internalDefines.add("PICK_CUSTOM_ID"),this._internalDefines.add("GSPLAT_INDIRECT_DRAW"),this._internalDefines.add("GSPLAT_SEPARATE_OPACITY"),this._internalDefines.add("GSPLAT_FISHEYE"),this.meshInstance=this.createMeshInstance()}setRenderMode(e){let s=this.renderMode??0,i=(s&Fs)!==0,r=(s&el)!==0,a=(e&Fs)!==0,o=(e&el)!==0;this.meshInstance.castShadow=o,i&&!a&&this.layer.removeMeshInstances([this.meshInstance],!0),r&&!o&&this.layer.removeShadowCasters([this.meshInstance]),!i&&a&&this.layer.addMeshInstances([this.meshInstance],!0),!r&&o&&this.layer.addShadowCasters([this.meshInstance]),super.setRenderMode(e)}destroy(){this.renderMode&&(this.renderMode&Fs&&this.layer.removeMeshInstances([this.meshInstance],!0),this.renderMode&el&&this.layer.removeShadowCasters([this.meshInstance])),this._material.destroy(),this.meshInstance.destroy(),super.destroy()}get material(){return this._material}onWorkBufferFormatChanged(){this.configureMaterial()}configureMaterial(){let{workBuffer:e}=this;this._injectFormatChunks(),this._material.setDefine("SH_BANDS","0"),this._material.setDefine("GSPLAT_SEPARATE_OPACITY","");let s=e.format.getStream("dataColor");s&&s.format!==Rs&&this._material.setDefine("GSPLAT_COLOR_FLOAT",""),this._updateIdDefines(),this._bindWorkBufferTextures();let i=!1;this._material.setParameter("numSplats",0),this.setOrderData(),this._material.setDefine(`DITHER_${i?"BLUENOISE":"NONE"}`,""),this._material.cull=0,this._material.blendType=i?wt:Ms,this._material.depthWrite=!!i,this._material.update()}_bindWorkBufferTextures(){let{workBuffer:e}=this;for(let s of e.format.resourceStreams){let i=e.getTexture(s.name);i&&this._material.setParameter(s.name,i)}}_injectFormatChunks(){let e=this.device.isWebGPU?this._material.shaderChunks.wgsl:this._material.shaderChunks.glsl,s=this.workBuffer.format;e.set("gsplatDeclarationsVS",s.getInputDeclarations()),e.set("gsplatReadVS",s.getReadCode())}update(e,s){this.meshInstance.instancingCount=Math.ceil(e/rt.instanceSize),this._material.setParameter("numSplats",e),this._material.setParameter("splatTextureSize",s),this.meshInstance.visible=e>0}setGpuSortedRendering(e,s,i,r){this.meshInstance.setIndirect(null,e,1),this._material.setParameter("compactedSplatIds",s),this._material.setParameter("numSplatsStorage",i),this._material.getDefine("GSPLAT_INDIRECT_DRAW")||(this._material.setDefine("GSPLAT_INDIRECT_DRAW",!0),this._material.update()),this._material.setParameter("splatTextureSize",r),this.meshInstance.visible=!0,this.meshInstance.instancingCount<=0&&(this.meshInstance.instancingCount=1)}setCpuSortedRendering(){this.meshInstance.setIndirect(null,-1),this._material.getDefine("GSPLAT_INDIRECT_DRAW")&&(this._material.setDefine("GSPLAT_INDIRECT_DRAW",!1),this._material.update()),this.setOrderData(),this.meshInstance.visible=!1}setOrderData(){this.device.isWebGPU?this._material.setParameter("splatOrder",this.workBuffer.orderBuffer):this._material.setParameter("splatOrder",this.workBuffer.orderTexture)}frameUpdate(e){e.colorRamp&&this._material.setParameter("colorRampIntensity",e.colorRampIntensity);let s=this.cameraNode.camera;this.fisheyeProj.update(e.fisheye,s.fov,s.projectionMatrix);let i=this.fisheyeProj.enabled;if(i!==this._lastFisheyeEnabled&&(this._lastFisheyeEnabled=i,this._material.setDefine("GSPLAT_FISHEYE",i),this._material.update()),i){let a=this.fisheyeProj;this._material.setParameter("fisheye_k",a.k),this._material.setParameter("fisheye_inv_k",a.invK),this._material.setParameter("fisheye_projMat00",a.projMat00),this._material.setParameter("fisheye_projMat11",a.projMat11)}let r=!e.useFog;r!==this._lastNoFog&&(this._lastNoFog=r,this._material.setDefine("GSPLAT_NO_FOG",r),this._material.update()),this._syncWithWorkBufferFormat(),(this.forceCopyMaterial||e.material.dirty)&&(this.copyMaterialSettings(e.material),this.forceCopyMaterial=!1)}_updateIdDefines(){let e=!!this.workBuffer.format.getStream("pcId");this._material.setDefine("GSPLAT_UNIFIED_ID",e),this._material.setDefine("PICK_CUSTOM_ID",e)}_syncWithWorkBufferFormat(){let e=this.workBuffer.format;this._workBufferFormatVersion!==e.extraStreamsVersion&&(this._workBufferFormatVersion=e.extraStreamsVersion,this.workBuffer.syncWithFormat(),this._injectFormatChunks(),this._bindWorkBufferTextures(),this._updateIdDefines(),this._material.update())}copyMaterialSettings(e){let s=[];this._material.defines.forEach((r,a)=>{!this._internalDefines.has(a)&&!e.defines.has(a)&&s.push(a)}),s.forEach(r=>this._material.setDefine(r,void 0)),e.defines.forEach((r,a)=>{this._material.setDefine(a,r)});let i=e.parameters;for(let r in i)i.hasOwnProperty(r)&&this._material.setParameter(r,i[r].data);if(e.hasShaderChunks){let r=e.shaderChunks.key;r!==this._lastSourceChunksKey&&(this._material.shaderChunks.copy(e.shaderChunks),this._injectFormatChunks(),this._lastSourceChunksKey=r)}this._material.update()}updateOverdrawMode(e){let s=!!e.colorRamp,i=this._material.getDefine("GSPLAT_OVERDRAW");s&&(this._material.setParameter("colorRamp",e.colorRamp),this._material.setParameter("colorRampIntensity",e.colorRampIntensity)),s!==i&&(this._material.setDefine("GSPLAT_OVERDRAW",s),s?(this.originalBlendType=this._material.blendType,this._material.blendType=ea):this._material.blendType=this.originalBlendType,this._material.update())}createMeshInstance(){let e=rt.createMesh(this.device),s=new we(e,this._material);s.node=this.node,s.setInstancing(!0,!0),s.instancingCount=0;let i=this.cameraNode.camera;return s.isVisibleFunc=r=>{let a=this.renderMode??0;return i.camera===r&&a&Fs?!0:a&el?r.node?.name===Gf:!1},s}};var Fk=new W,IK=new W,hE=class extends mh{constructor(e,s,i,r,a){super(e,s,i,r,a);n(this,"_material");n(this,"meshInstance");n(this,"_pickMaterial",null);n(this,"_pickMeshInstance",null);n(this,"_clipToViewZ",new Float32Array(4));n(this,"_clipToViewZPick",null);n(this,"originalBlendType",ea);n(this,"_internalDefines",new Set);n(this,"forceCopyMaterial",!0);this._material=new ct({uniqueName:"UnifiedSplatHybridMaterial",vertexWGSL:'#include "gsplatHybridVS"',fragmentWGSL:'#include "gsplatPS"',attributes:{vertex_position:ee}}),this._material.setDefine("{GSPLAT_INSTANCE_SIZE}",rt.instanceSize),this._material.setDefine("{CACHE_STRIDE}",8),this.configureMaterial(),this._material.defines.forEach((o,l)=>{this._internalDefines.add(l)}),this._internalDefines.add("{GSPLAT_INSTANCE_SIZE}"),this._internalDefines.add("{CACHE_STRIDE}"),this._internalDefines.add("GSPLAT_UNIFIED_ID"),this._internalDefines.add("PICK_CUSTOM_ID"),this._internalDefines.add("GSPLAT_OVERDRAW"),this._internalDefines.add("GSPLAT_NO_FOG"),this.meshInstance=this.createMeshInstance()}setRenderMode(e){let i=((this.renderMode??0)&Fs)!==0,r=(e&Fs)!==0;i&&!r&&this.layer.removeMeshInstances([this.meshInstance],!0),!i&&r&&this.layer.addMeshInstances([this.meshInstance],!0),super.setRenderMode(e)}destroy(){this.renderMode&&this.renderMode&Fs&&this.layer.removeMeshInstances([this.meshInstance],!0),this._material.destroy(),this._pickMaterial?.destroy(),this.meshInstance.destroy(),this._pickMeshInstance?.destroy(),super.destroy()}get material(){return this._material}onWorkBufferFormatChanged(){this.configureMaterial()}configureMaterial(){this._material.setDefine("SH_BANDS","0"),this._material.setDefine("GSPLAT_INDIRECT_DRAW",!0),this._updateIdDefines(this._material);let e=!1;this._material.setDefine(`DITHER_${e?"BLUENOISE":"NONE"}`,""),this._material.cull=0,this._material.blendType=e?wt:Ms,this._material.depthWrite=!!e,this._material.update()}update(e,s){this.meshInstance.instancingCount<=0&&(this.meshInstance.instancingCount=1),this.meshInstance.visible=e>0}setHybridSortedRendering(e,s,i,r){this.meshInstance.setIndirect(null,e,1),this._material.setParameter("sortedIndices",s),this._material.setParameter("projCache",i),this._material.setParameter("numSplatsStorage",r),this._computeClipToViewZ(this.cameraNode,this._clipToViewZ),this._material.setParameter("clipToViewZ",this._clipToViewZ),this.meshInstance.visible=!0,this.meshInstance.instancingCount<=0&&(this.meshInstance.instancingCount=1)}prepareForPicking(e,s,i,r,a,o,l){if(this._pickMaterial)this._updateIdDefines(this._pickMaterial)&&this._pickMaterial.update();else{this._pickMaterial=new ct({uniqueName:"UnifiedSplatHybridPickMaterial",vertexWGSL:'#include "gsplatHybridVS"',fragmentWGSL:'#include "gsplatPS"',attributes:{vertex_position:ee}}),this._pickMaterial.setDefine("{GSPLAT_INSTANCE_SIZE}",rt.instanceSize),this._pickMaterial.setDefine("{CACHE_STRIDE}",8),this._pickMaterial.setDefine("SH_BANDS","0"),this._pickMaterial.setDefine("GSPLAT_INDIRECT_DRAW",!0),this._pickMaterial.setDefine("DITHER_NONE",""),this._updateIdDefines(this._pickMaterial),this._pickMaterial.cull=0,this._pickMaterial.blendType=wt,this._pickMaterial.depthWrite=!1,this._pickMaterial.update();let u=rt.createMesh(this.device);this._pickMeshInstance=new we(u,this._pickMaterial),this._pickMeshInstance.node=this.node,this._pickMeshInstance.setInstancing(!0,!0),this._pickMeshInstance.instancingCount=1}let h=this._pickMaterial,f=this._pickMeshInstance;return f.setIndirect(null,e,1),h.setParameter("sortedIndices",s),h.setParameter("projCache",i),h.setParameter("numSplatsStorage",r),h.setParameter("alphaClip",a),h.setParameter("alphaClipForward",o),this._clipToViewZPick??(this._clipToViewZPick=new Float32Array(4)),this._computeClipToViewZ(l,this._clipToViewZPick),h.setParameter("clipToViewZ",this._clipToViewZPick),f}_computeClipToViewZ(e,s){let i=e.camera,r=i.camera;if(this.fisheyeProj.enabled){let l=r.nearClip,h=r.farClip;s[0]=0,s[1]=0,s[2]=h-l,s[3]=l;return}let a=!!i.renderTarget?.flipY;Fk.copy(Bs.applyShaderProjectionTransform(r.projectionMatrix,IK,a,this.device.isWebGPU)).invert();let o=Fk.data;s[0]=-o[2],s[1]=-o[6],s[2]=-o[10],s[3]=-o[14]}setCpuSortedRendering(){this.meshInstance.setIndirect(null,-1),this.meshInstance.visible=!1}setOrderData(){}frameUpdate(e){this._material.setParameter("alphaClip",e.alphaClip),this._material.setParameter("alphaClipForward",e.alphaClipForward),this._pickMaterial?.setParameter("alphaClip",e.alphaClip),this._pickMaterial?.setParameter("alphaClipForward",e.alphaClipForward),e.colorRamp&&this._material.setParameter("colorRampIntensity",e.colorRampIntensity);let s=!e.useFog;s!==this._lastNoFog&&(this._lastNoFog=s,this._material.setDefine("GSPLAT_NO_FOG",s),this._material.update())}_updateIdDefines(e){let s=!!this.workBuffer.format.getStream("pcId"),i=e.getDefine("GSPLAT_UNIFIED_ID")!==s||e.getDefine("PICK_CUSTOM_ID")!==s;return e.setDefine("GSPLAT_UNIFIED_ID",s),e.setDefine("PICK_CUSTOM_ID",s),i}updateOverdrawMode(e){let s=!!e.colorRamp,i=this._material.getDefine("GSPLAT_OVERDRAW");s&&(this._material.setParameter("colorRamp",e.colorRamp),this._material.setParameter("colorRampIntensity",e.colorRampIntensity)),s!==i&&(this._material.setDefine("GSPLAT_OVERDRAW",s),s?(this.originalBlendType=this._material.blendType,this._material.blendType=ea):this._material.blendType=this.originalBlendType,this._material.update())}createMeshInstance(){let e=rt.createMesh(this.device),s=new we(e,this._material);s.node=this.node,s.setInstancing(!0,!0),s.instancingCount=0,s.pick=!1;let i=this.cameraNode.camera;return s.isVisibleFunc=r=>{let a=this.renderMode??0;return i.camera===r&&a&Fs?!0:(r.node?.name===Gf,!1)},s}};var fE=class extends Nt{constructor(e){super(e.device);n(this,"renderer");this.renderer=e,this.name="FramePassGSplatComputeLocal"}frameUpdate(){let e=this.renderer,s=e.cameraNode.camera,i=s.renderTarget,r=i?i.width:this.device.width,a=i?i.height:this.device.height,o=s.rect,l=Math.floor(r*o.z),h=Math.floor(a*o.w);e.resizeOutputTexture(l,h)}execute(){this.renderer.dispatch()}};var Nk=` @group(0) @binding(0) var sortElementCount: array; @group(0) @binding(1) var dispatchArgs: array; @compute @workgroup_size(1) @@ -13761,7 +14105,7 @@ fn main() { } dispatchArgs[5] = 1u; } -`,v3=` +`;var Bk=` @group(0) @binding(0) var countersBuffer: array; @group(0) @binding(1) var dispatchArgs: array; @group(0) @binding(2) var largeSplatIds: array; @@ -13780,10 +14124,9 @@ fn main() { } dispatchArgs[2] = 1u; } -`,v4=` +`;var Uk=` #include "gsplatCommonCS" #include "gsplatTileIntersectCS" -const CACHE_STRIDE: u32 = 7u; const MAX_TILE_ENTRIES: u32 = 0xFFFFu; const BITMASK_W: u32 = 8u; const BITMASK_H: u32 = 4u; @@ -13825,6 +14168,7 @@ struct Uniforms { #include "gsplatComputeSplatCS" #include "gsplatFormatDeclCS" #include "gsplatFormatReadCS" +#include "gsplatProjectCommonCS" @compute @workgroup_size(256) fn main( @builtin(global_invocation_id) gid: vec3u, @@ -13832,44 +14176,41 @@ fn main( ) { let threadIdx = gid.y * (numWorkgroups.x * 256u) + gid.x; let numVisible = sortElementCount[0]; - if (threadIdx >= numVisible) { - return; - } - let splatId = compactedSplatIds[threadIdx]; - setSplat(splatId); - let center = getCenter(); - let opacity = getOpacity(); - if (opacity < uniforms.alphaClip) { - projCache[threadIdx * CACHE_STRIDE + 6u] = 0u; - splatPairStart[threadIdx] = 0u; - splatPairCount[threadIdx] = 0u; - return; - } - let rotation = half4(getRotation()); - let scale = half3(getScale()); - let proj = computeSplatCov( - center, rotation, scale, - uniforms.viewMatrix, uniforms.viewProj, - uniforms.focal, uniforms.viewportWidth, uniforms.viewportHeight, - uniforms.nearClip, uniforms.farClip, opacity, uniforms.minPixelSize, - uniforms.isOrtho, uniforms.alphaClip, uniforms.minContribution, + let projected = projectSplatCommon( + threadIdx, + numVisible, + uniforms.alphaClip, + uniforms.minPixelSize, + uniforms.minContribution, + uniforms.viewMatrix, + uniforms.viewProj, + uniforms.focal, + uniforms.viewportWidth, + uniforms.viewportHeight, + uniforms.nearClip, + uniforms.farClip, + uniforms.isOrtho, #ifdef GSPLAT_FISHEYE uniforms.fisheye_k, uniforms.fisheye_inv_k, uniforms.fisheye_projMat00, uniforms.fisheye_projMat11, #endif ); - if (!proj.valid) { - projCache[threadIdx * CACHE_STRIDE + 6u] = 0u; - splatPairStart[threadIdx] = 0u; - splatPairCount[threadIdx] = 0u; + if (!projected.valid) { + if (threadIdx < numVisible) { + projCache[threadIdx * {CACHE_STRIDE}u + 6u] = 0u; + splatPairStart[threadIdx] = 0u; + splatPairCount[threadIdx] = 0u; + } return; } + let opacity = projected.opacity; + let proj = projected.proj; let det = proj.a * proj.c - proj.b * proj.b; let invDet = 1.0 / det; let cx = 4.0 * proj.c * invDet; let cy = -4.0 * proj.b * invDet; let cz = 4.0 * proj.a * invDet; - let base = threadIdx * CACHE_STRIDE; + let base = threadIdx * {CACHE_STRIDE}u; projCache[base + 0u] = bitcast(proj.screen.x); projCache[base + 1u] = bitcast(proj.screen.y); projCache[base + 2u] = bitcast(cx); @@ -13891,6 +14232,7 @@ fn main( uniforms.viewportWidth, uniforms.viewportHeight, uniforms.alphaClip); let radiusFactor = eval.radiusFactor; + projCache[base + 7u] = bitcast(-0.5 * radiusFactor); let minTileX = max(0i, i32(floor(eval.splatMin.x / f32(TILE_SIZE)))); let maxTileX = min(i32(uniforms.numTilesX) - 1i, i32(floor(eval.splatMax.x / f32(TILE_SIZE)))); let minTileY = max(0i, i32(floor(eval.splatMin.y / f32(TILE_SIZE)))); @@ -13968,10 +14310,9 @@ fn main( splatPairCount[threadIdx] = j; } } -`,v5=` +`;var kk=` #include "gsplatCommonCS" #include "gsplatTileIntersectCS" -const CACHE_STRIDE: u32 = 7u; const WG_SIZE: u32 = 256u; const MAX_TILE_ENTRIES: u32 = 0xFFFFu; @group(0) @binding(0) var projCache: array; @@ -14015,7 +14356,7 @@ fn main( var radiusFactor = 0.0f; if (isActive) { threadIdx = largeSplatIds[largeSplatIdx]; - let cacheBase = threadIdx * CACHE_STRIDE; + let cacheBase = threadIdx * {CACHE_STRIDE}u; screen = vec2f(bitcast(projCache[cacheBase + 0u]), bitcast(projCache[cacheBase + 1u])); cx = bitcast(projCache[cacheBase + 2u]); cy = bitcast(projCache[cacheBase + 3u]); @@ -14094,7 +14435,7 @@ fn main( } } } -`,v6=` +`;var zk=` @group(0) @binding(0) var pairBuffer: array; @group(0) @binding(1) var splatPairStart: array; @group(0) @binding(2) var splatPairCount: array; @@ -14128,7 +14469,7 @@ fn main(@builtin(global_invocation_id) gid: vec3u, @builtin(num_workgroups) numW } } } -`,v8=` +`;var Gk=` const WG_SIZE: u32 = 256u; @group(0) @binding(0) var pairBuffer: array; @group(0) @binding(1) var splatPairStart: array; @@ -14168,7 +14509,7 @@ fn main( } } } -`,v9=` +`;var Vk=` #include "gsplatLocalBitonicCS" @group(0) @binding(0) var tileEntries: array; @group(0) @binding(1) var tileSplatCounts: array; @@ -14191,7 +14532,7 @@ fn main( let count = tEnd - tStart; bitonicSortRange(localIdx, tStart, count); } -`;var v7=` +`;var _h=` fn calcDispatch2D(count: u32, maxDim: u32) -> vec2u { if (count <= maxDim) { return vec2u(count, 1u); @@ -14200,9 +14541,9 @@ fn calcDispatch2D(count: u32, maxDim: u32) -> vec2u { let x = (count + y - 1u) / y; return vec2u(x, y); } -`;let Se=` -${ps} -${v7} +`;var Hk=` +${Jc} +${_h} const MAX_TILE_ENTRIES: u32 = 4096u; const CLASSIFY_WORKGROUP: u32 = 256u; @group(0) @binding(0) var tileSplatCounts: array; @@ -14266,7 +14607,7 @@ fn main(@builtin(local_invocation_index) localIdx: u32) { indirectDrawArgs[uniforms.drawSlot] = DrawIndirectArgs(rasterizeCount * 6u, 1u, 0u, 0u, 0u); } } -`,St=` +`;var Wk=` const NUM_BUCKETS: u32 = 128u; const MAX_CHUNK_SIZE: u32 = 4096u; const WG_SIZE: u32 = 256u; @@ -14386,7 +14727,7 @@ fn main( } } } -`,Si=` +`;var Xk=` #include "gsplatLocalBitonicCS" @group(0) @binding(0) var tileEntries: array; @group(0) @binding(1) var depthBuffer: array; @@ -14410,8 +14751,8 @@ fn main( let count = chunkRanges[chunkIdx * 2u + 1u]; bitonicSortRange(localIdx, tStart, count); } -`,Ss=` -${v7} +`;var Yk=` +${_h} @group(0) @binding(0) var totalChunks: array; @group(0) @binding(1) var chunkSortIndirect: array; struct Uniforms { @@ -14427,7 +14768,7 @@ fn main() { chunkSortIndirect[1] = dim.y; chunkSortIndirect[2] = 1u; } -`,Sr=` +`;var Kk=` const MAX_TILE_ENTRIES: u32 = 4096u; const INDEX_BITS: u32 = 12u; const INDEX_MASK: u32 = 0xFFFu; @@ -14510,7 +14851,74 @@ fn bitonicSortRange(localIdx: u32, tStart: u32, count: u32) { tileEntries[tStart + i] = sData[i]; } } -`,Sa=` +`;var uE=` +struct ProjectedSplatCommon { + valid: bool, + splatId: u32, + center: vec3f, + opacity: f32, + proj: SplatCov2D +} +fn invalidProjectedSplatCommon() -> ProjectedSplatCommon { + var cov: SplatCov2D; + cov.screen = vec2f(0.0); + cov.a = 0.0; + cov.b = 0.0; + cov.c = 0.0; + cov.viewDepth = 0.0; + cov.valid = false; + return ProjectedSplatCommon(false, 0u, vec3f(0.0), 0.0, cov); +} +fn projectSplatCommon( + threadIdx: u32, + numVisible: u32, + alphaClip: f32, + minPixelSize: f32, + minContribution: f32, + viewMatrix: mat4x4f, + viewProj: mat4x4f, + focal: f32, + viewportWidth: f32, + viewportHeight: f32, + nearClip: f32, + farClip: f32, + isOrtho: u32, + #ifdef GSPLAT_FISHEYE + fisheye_k: f32, + fisheye_inv_k: f32, + fisheye_projMat00: f32, + fisheye_projMat11: f32, + #endif +) -> ProjectedSplatCommon { + if (threadIdx >= numVisible) { + return invalidProjectedSplatCommon(); + } + let splatId = compactedSplatIds[threadIdx]; + setSplat(splatId); + let center = getCenter(); + let opacity = getOpacity(); + if (opacity <= alphaClip) { + return invalidProjectedSplatCommon(); + } + let rotation = half4(getRotation()); + let scale = half3(getScale()); + let proj = computeSplatCov( + center, rotation, scale, + viewMatrix, viewProj, + focal, viewportWidth, viewportHeight, + nearClip, farClip, opacity, minPixelSize, + isOrtho, alphaClip, minContribution, + #ifdef GSPLAT_FISHEYE + fisheye_k, fisheye_inv_k, + fisheye_projMat00, fisheye_projMat11, + #endif + ); + if (!proj.valid) { + return invalidProjectedSplatCommon(); + } + return ProjectedSplatCommon(true, splatId, center, opacity, proj); +} +`;var dE=` #include "halfTypesCS" const TILE_SIZE: u32 = 16u; fn quatToMat3(r: half4) -> half3x3 { @@ -14532,6 +14940,9 @@ struct SplatCov2D { c: f32, viewDepth: f32, valid: bool, + #if GSPLAT_AA + aaFactor: f32, + #endif } fn computeSplatCov( worldCenter: vec3f, @@ -14623,13 +15034,19 @@ fn computeSplatCov( #endif let b0 = M * tt0; let b1 = M * tt1; - let a = dot(b0, b0) + 0.3; + let aRaw = dot(b0, b0); let b = dot(b0, b1); - let c = dot(b1, b1) + 0.3; + let cRaw = dot(b1, b1); + let a = aRaw + 0.3; + let c = cRaw + 0.3; let det = a * c - b * b; if (det <= 0.0) { return result; } + #if GSPLAT_AA + let detOrig = aRaw * cRaw - b * b; + result.aaFactor = sqrt(max(detOrig / det, 0.0)); + #endif let totalContribution = opacity * 6.283185 * sqrt(det); if (totalContribution < minContribution) { return result; @@ -14663,7 +15080,7 @@ fn computeSplatCov( result.valid = true; return result; } -`,Sn=` +`;var pE=` struct SplatTileEval { radiusFactor: f32, splatMin: vec2f, @@ -14727,7 +15144,7 @@ fn tileIntersectsEllipse( } return false; } -`;class So{destroy(){this._material.destroy(),this._mesh.destroy(),this._meshInstance.destroy(),this._pickMaterial?.destroy(),this._pickMeshInstance?.destroy();}get material(){return this._material}get meshInstance(){return this._meshInstance}update(e,t,i,s,r,a){this._meshInstance.setIndirect(null,e,1),this._material.setParameter("source",t),this._material.setParameter("rasterizeTileList",i),this._material.setParameter("numTilesX",s),this._material.setParameter("screenWidth",r),this._material.setParameter("screenHeight",a);}prepareForPicking(e,t,i,s,r,a,n){this._pickMaterial||(this._pickMaterial=new cT({uniqueName:"GSplatTileCompositePick",vertexWGSL:'#include "gsplatTileCompositeVS"',fragmentWGSL:'#include "gsplatTileCompositePS"'}),this._pickMaterial.setDefine("PICK_MODE",true),this._pickMaterial.cull=0,this._pickMaterial.depthWrite=false,this._pickMaterial.update(),this._pickMeshInstance=new oS(this._mesh,this._pickMaterial),this._pickMeshInstance.node=this._node,this._pickMeshInstance.instancingCount=1);let o=this._pickMeshInstance,l=this._pickMaterial;return o.setIndirect(null,e,1),l.setParameter("pickIdTexture",t),l.setParameter("pickDepthTexture",i),l.setParameter("rasterizeTileList",s),l.setParameter("numTilesX",r),l.setParameter("screenWidth",a),l.setParameter("screenHeight",n),o}constructor(e,t,i){this._pickMaterial=null,this._pickMeshInstance=null,this.device=e,this._node=t,this._material=new cT({uniqueName:"GSplatTileComposite",vertexWGSL:'#include "gsplatTileCompositeVS"',fragmentWGSL:'#include "gsplatTileCompositePS"'}),this._material.blendType=4,this._material.cull=0,this._material.depthWrite=false,this._material.update(),this._mesh=new on(e),this._mesh.primitive[0].type=4,this._mesh.primitive[0].base=0,this._mesh.primitive[0].count=0,this._mesh.primitive[0].indexed=false,this._meshInstance=new oS(this._mesh,this._material),this._meshInstance.node=t,this._meshInstance.instancingCount=1,this._meshInstance.isVisibleFunc=i,this._meshInstance.pick=false;}}let Sl=` +`;var mE=class{constructor(t,e,s){n(this,"device");n(this,"_material");n(this,"_mesh");n(this,"_meshInstance");n(this,"_pickMaterial",null);n(this,"_pickMeshInstance",null);n(this,"_node");this.device=t,this._node=e,this._material=new ct({uniqueName:"GSplatTileComposite",vertexWGSL:'#include "gsplatTileCompositeVS"',fragmentWGSL:'#include "gsplatTileCompositePS"'}),this._material.blendType=Ms,this._material.cull=0,this._material.depthWrite=!1,this._material.update(),this._mesh=new _e(t),this._mesh.primitive[0].type=Yt,this._mesh.primitive[0].base=0,this._mesh.primitive[0].count=0,this._mesh.primitive[0].indexed=!1,this._meshInstance=new we(this._mesh,this._material),this._meshInstance.node=e,this._meshInstance.instancingCount=1,this._meshInstance.isVisibleFunc=s,this._meshInstance.pick=!1}destroy(){this._material.destroy(),this._mesh.destroy(),this._meshInstance.destroy(),this._pickMaterial?.destroy(),this._pickMeshInstance?.destroy()}get material(){return this._material}get meshInstance(){return this._meshInstance}update(t,e,s,i,r,a){this._meshInstance.setIndirect(null,t,1),this._material.setParameter("source",e),this._material.setParameter("rasterizeTileList",s),this._material.setParameter("numTilesX",i),this._material.setParameter("screenWidth",r),this._material.setParameter("screenHeight",a)}prepareForPicking(t,e,s,i,r,a,o){this._pickMaterial||(this._pickMaterial=new ct({uniqueName:"GSplatTileCompositePick",vertexWGSL:'#include "gsplatTileCompositeVS"',fragmentWGSL:'#include "gsplatTileCompositePS"'}),this._pickMaterial.setDefine("PICK_MODE",!0),this._pickMaterial.cull=0,this._pickMaterial.depthWrite=!1,this._pickMaterial.update(),this._pickMeshInstance=new we(this._mesh,this._pickMaterial),this._pickMeshInstance.node=this._node,this._pickMeshInstance.instancingCount=1);let l=this._pickMeshInstance,h=this._pickMaterial;return l.setIndirect(null,t,1),h.setParameter("pickIdTexture",e),h.setParameter("pickDepthTexture",s),h.setParameter("rasterizeTileList",i),h.setParameter("numTilesX",r),h.setParameter("screenWidth",a),h.setParameter("screenHeight",o),l}};var jk=` #include "halfTypesCS" #ifndef PICK_MODE #include "decodePS" @@ -14736,7 +15153,6 @@ fn tileIntersectsEllipse( #include "gammaPS" #endif #endif -const CACHE_STRIDE: u32 = 7u; const BATCH_SIZE: u32 = 64u; const ALPHA_THRESHOLD: half = half(1.0) / half(255.0); const EXP4: half = exp(half(-4.0)); @@ -14773,6 +15189,7 @@ struct Uniforms { #endif var sharedCenterScreen: array; var sharedCoeffs: array; +var sharedPowerCutoff: array; #ifdef HEATMAP_MODE var sharedHeatCount: atomic; #endif @@ -14888,7 +15305,7 @@ fn main( let batchOffset = batch * BATCH_SIZE + localIdx; if (batchOffset < tileCount) { let cacheIdx = tileEntries[tStart + batchOffset]; - let base = cacheIdx * CACHE_STRIDE; + let base = cacheIdx * {CACHE_STRIDE}u; sharedCenterScreen[localIdx] = vec2f( bitcast(projCache[base + 0u]), bitcast(projCache[base + 1u]) @@ -14897,6 +15314,7 @@ fn main( let cy = bitcast(projCache[base + 3u]); let cz = bitcast(projCache[base + 4u]); sharedCoeffs[localIdx] = vec3f(cx * -0.5, cz * -0.5, -cy); + sharedPowerCutoff[localIdx] = bitcast(projCache[base + 7u]); #ifdef PICK_MODE sharedPickId[localIdx] = projCache[base + 5u]; sharedOpacity[localIdx] = half(unpack2x16float(projCache[base + 6u]).y); @@ -14934,6 +15352,13 @@ fn main( let splatOpacity = sharedOpacity[i]; let splatPickId = sharedPickId[i]; let splatDepth = sharedViewDepth[i]; + let d = p00 - center; + let dxV = vec4f(d.x, d.x + 1.0, d.x, d.x + 1.0); + let dyV = vec4f(d.y, d.y, d.y + 1.0, d.y + 1.0); + let power4 = coeffs.x * dxV * dxV + coeffs.z * dxV * dyV + coeffs.y * dyV * dyV; + if (all(power4 <= vec4f(sharedPowerCutoff[i]))) { + continue; + } evalSplatPick(p00, center, coeffs.x, coeffs.y, coeffs.z, splatOpacity, splatPickId, splatDepth, clipH, &pickId00, &dAcc00, &wAcc00, &T00); evalSplatPick(p10, center, coeffs.x, coeffs.y, coeffs.z, splatOpacity, splatPickId, splatDepth, clipH, &pickId10, &dAcc10, &wAcc10, &T10); evalSplatPick(p01, center, coeffs.x, coeffs.y, coeffs.z, splatOpacity, splatPickId, splatDepth, clipH, &pickId01, &dAcc01, &wAcc01, &T01); @@ -14955,6 +15380,9 @@ fn main( let dxV = vec4f(d.x, d.x + 1.0, d.x, d.x + 1.0); let dyV = vec4f(d.y, d.y, d.y + 1.0, d.y + 1.0); let power4 = coeffs.x * dxV * dxV + coeffs.z * dxV * dyV + coeffs.y * dyV * dyV; + if (all(power4 <= vec4f(sharedPowerCutoff[i]))) { + continue; + } let gauss4 = (half4(exp(power4)) - half4(EXP4)) * half4(INV_EXP4); let alpha4 = min(half4(0.99), half4(splatColor.a) * gauss4); let newT = T * (half4(1.0) - alpha4); @@ -15035,7 +15463,7 @@ fn main( } #endif } -`;class Sh{resizeOutputTextures(e,t){this.pickMode?(this.pickIdTexture?.resize(e,t),this.pickDepthTexture?.resize(e,t)):this.outputTexture?.resize(e,t);}ensureTileBuffers(e){let t=e+1;t<=this._allocatedTileCapacity||(this._tileSplatCountsBuffer?.destroy(),this._smallTileListBuffer?.destroy(),this._largeTileListBuffer?.destroy(),this._largeTileOverflowBasesBuffer?.destroy(),this._rasterizeTileListBuffer?.destroy(),this._tileListCountsBuffer?.destroy(),this._chunkRangesBuffer?.destroy(),this._totalChunksBuffer?.destroy(),this._chunkSortIndirectBuffer?.destroy(),this._allocatedTileCapacity=t,this._tileSplatCountsBuffer=new rO(this.device,4*t,12),this._smallTileListBuffer=new rO(this.device,4*e),this._largeTileListBuffer=new rO(this.device,4*e),this._largeTileOverflowBasesBuffer=new rO(this.device,4*e),this._rasterizeTileListBuffer=new rO(this.device,4*e),this._tileListCountsBuffer=new rO(this.device,16,12),this._chunkRangesBuffer=new rO(this.device,8*e*8),this._totalChunksBuffer=new rO(this.device,4,8),this._chunkSortIndirectBuffer=new rO(this.device,12,264),this.prefixSumKernel.destroyPasses());}getCountCompute(e,t){if(e){if(!this._countComputeFisheye){let{shader:e,bindGroupFormat:i}=t(this.pickMode,true);this._countShaderFisheye=e,this._countBindGroupFormatFisheye=i;let s=this.pickMode?"GSplatPickTileCountFisheye":"GSplatLocalTileCountFisheye";this._countComputeFisheye=new ar(this.device,e,s);}return this._countComputeFisheye}if(!this._countCompute){let{shader:e,bindGroupFormat:i}=t(this.pickMode,false);this._countShader=e,this._countBindGroupFormat=i;let s=this.pickMode?"GSplatPickTileCount":"GSplatLocalTileCount";this._countCompute=new ar(this.device,e,s);}return this._countCompute}destroyCountResources(){this._countShader?.destroy(),this._countBindGroupFormat?.destroy(),this._countCompute?.destroy(),this._countShaderFisheye?.destroy(),this._countBindGroupFormatFisheye?.destroy(),this._countComputeFisheye?.destroy(),this._countShader=null,this._countBindGroupFormat=null,this._countCompute=null,this._countShaderFisheye=null,this._countBindGroupFormatFisheye=null,this._countComputeFisheye=null;}getRasterizeCompute(e,t,i="none",s=false){let r=e?"pick":"color";t&&(r+="-depth"),"none"!==i&&(r+=`-fog-${i}`),s&&(r+="-heatmap");let a=this._rasterizeVariants.get(r);if(!a){let{shader:n,bindGroupFormat:o}=this._createRasterizeShaderAndFormat(e,t,i,s),l=new ar(this.device,n,`GSplatRasterize-${r}`);a={shader:n,bindGroupFormat:o,compute:l},this._rasterizeVariants.set(r,a);}return a.compute}_createRasterizeShaderAndFormat(e,t=false,i="none",s=false){let r=this.device,a="none"!==i,n=[new s_("screenWidth",26),new s_("screenHeight",26),new s_("numTilesX",26),new s_("nearClip",2),new s_("farClip",2),new s_("alphaClip",2)];a&&n.push(new s_("fog_color",4),new s_("fog_start",2),new s_("fog_end",2),new s_("fog_density",2));let o=new sg(r,n),l=new ii(r,[new t9("uniforms",4),new t7("tileEntries",4,true),new t7("tileSplatCounts",4,true),new t7("projCache",4,true),new t7("rasterizeTileList",4,true),new t7("tileListCounts",4,true),new t7("depthBuffer",4,true),...e?[new it("pickIdTexture",37),new it("pickDepthTexture",12)]:[new it("outputTexture",12)],...t?[new ie("sceneDepthMap",4,"2d",1,false)]:[]]),h=new Map;e&&h.set("PICK_MODE",""),t&&h.set("DEPTH_TEST",""),s&&h.set("HEATMAP_MODE",""),h.set("GAMMA","SRGB"),h.set("FOG",a?i.toUpperCase():"NONE");let c=e?void 0:new Map([["decodePS",pr.decodePS]]);a&&c&&(c.set("fogMathPS",pr.fogMathPS),c.set("gammaPS",pr.gammaPS));let d="GSplatLocalRasterize";return e?d="GSplatLocalRasterizePick":t&&(d="GSplatLocalRasterizeDepth"),{shader:new r_(r,{name:d,shaderLanguage:tV,cshader:Sl,cdefines:h.size>0?h:void 0,cincludes:c,computeBindGroupFormat:l,computeUniformBufferFormats:{uniforms:o}}),bindGroupFormat:l}}destroy(){for(let{shader:e,bindGroupFormat:t,compute:i}of(this.destroyCountResources(),this._rasterizeVariants.values()))i.destroy(),e.destroy(),t.destroy();this._tileSplatCountsBuffer?.destroy(),this._smallTileListBuffer?.destroy(),this._largeTileListBuffer?.destroy(),this._largeTileOverflowBasesBuffer?.destroy(),this._rasterizeTileListBuffer?.destroy(),this._tileListCountsBuffer?.destroy(),this._chunkRangesBuffer?.destroy(),this._totalChunksBuffer?.destroy(),this._chunkSortIndirectBuffer?.destroy(),this.prefixSumKernel.destroy(),this.outputTexture?.destroy(),this.pickIdTexture?.destroy(),this.pickDepthTexture?.destroy();}constructor(e,t){this._countShader=null,this._countBindGroupFormat=null,this._countCompute=null,this._countShaderFisheye=null,this._countBindGroupFormatFisheye=null,this._countComputeFisheye=null,this._rasterizeVariants=new Map,this._tileSplatCountsBuffer=null,this._smallTileListBuffer=null,this._largeTileListBuffer=null,this._largeTileOverflowBasesBuffer=null,this._rasterizeTileListBuffer=null,this._tileListCountsBuffer=null,this._chunkRangesBuffer=null,this._totalChunksBuffer=null,this._chunkSortIndirectBuffer=null,this._allocatedTileCapacity=0,this.outputTexture=null,this.pickIdTexture=null,this.pickDepthTexture=null,this.device=e,this.pickMode=t,this.prefixSumKernel=new dN(e),t?(this.pickIdTexture=new ic(e,{name:"GSplatLocalPickId",width:4,height:4,format:37,mipmaps:false,minFilter:0,magFilter:0,storage:true}),this.pickDepthTexture=new ic(e,{name:"GSplatLocalPickDepth",width:4,height:4,format:12,mipmaps:false,minFilter:0,magFilter:0,storage:true})):this.outputTexture=new ic(e,{name:"GSplatLocalComputeOutput",width:4,height:4,format:12,mipmaps:false,minFilter:0,magFilter:0,storage:true});}}var Sc=` +`;var f_=.00392156862745098,u_=8,rn=64;var RK=8,_E=class{constructor(t,e){n(this,"device");n(this,"pickMode");n(this,"_countShader",null);n(this,"_countBindGroupFormat",null);n(this,"_countCompute",null);n(this,"_countShaderFisheye",null);n(this,"_countBindGroupFormatFisheye",null);n(this,"_countComputeFisheye",null);n(this,"placeEntriesCompute");n(this,"largeSplatCompute");n(this,"largePlaceEntriesCompute");n(this,"classifyCompute");n(this,"sortCompute");n(this,"bucketSortCompute");n(this,"copyCompute");n(this,"chunkSortCompute");n(this,"_rasterizeVariants",new Map);n(this,"prefixSumKernel");n(this,"_tileSplatCountsBuffer",null);n(this,"_smallTileListBuffer",null);n(this,"_largeTileListBuffer",null);n(this,"_largeTileOverflowBasesBuffer",null);n(this,"_rasterizeTileListBuffer",null);n(this,"_tileListCountsBuffer",null);n(this,"_chunkRangesBuffer",null);n(this,"_totalChunksBuffer",null);n(this,"_chunkSortIndirectBuffer",null);n(this,"_allocatedTileCapacity",0);n(this,"outputTexture",null);n(this,"pickIdTexture",null);n(this,"pickDepthTexture",null);this.device=t,this.pickMode=e,this.prefixSumKernel=new Wc(t),e?(this.pickIdTexture=new Z(t,{name:"GSplatLocalPickId",width:4,height:4,format:zt,mipmaps:!1,minFilter:0,magFilter:0,storage:!0}),this.pickDepthTexture=new Z(t,{name:"GSplatLocalPickDepth",width:4,height:4,format:Me,mipmaps:!1,minFilter:0,magFilter:0,storage:!0})):this.outputTexture=new Z(t,{name:"GSplatLocalComputeOutput",width:4,height:4,format:Me,mipmaps:!1,minFilter:0,magFilter:0,storage:!0})}resizeOutputTextures(t,e){this.pickMode?(this.pickIdTexture?.resize(t,e),this.pickDepthTexture?.resize(t,e)):this.outputTexture?.resize(t,e)}ensureTileBuffers(t){let e=t+1;if(e<=this._allocatedTileCapacity)return;this._tileSplatCountsBuffer?.destroy(),this._smallTileListBuffer?.destroy(),this._largeTileListBuffer?.destroy(),this._largeTileOverflowBasesBuffer?.destroy(),this._rasterizeTileListBuffer?.destroy(),this._tileListCountsBuffer?.destroy(),this._chunkRangesBuffer?.destroy(),this._totalChunksBuffer?.destroy(),this._chunkSortIndirectBuffer?.destroy(),this._allocatedTileCapacity=e,this._tileSplatCountsBuffer=new Ee(this.device,e*4,12),this._smallTileListBuffer=new Ee(this.device,t*4),this._largeTileListBuffer=new Ee(this.device,t*4),this._largeTileOverflowBasesBuffer=new Ee(this.device,t*4),this._rasterizeTileListBuffer=new Ee(this.device,t*4),this._tileListCountsBuffer=new Ee(this.device,16,12);let s=t*RK;this._chunkRangesBuffer=new Ee(this.device,s*8),this._totalChunksBuffer=new Ee(this.device,4,8),this._chunkSortIndirectBuffer=new Ee(this.device,12,264),this.prefixSumKernel.destroyPasses()}getCountCompute(t,e){if(t){if(!this._countComputeFisheye){let{shader:s,bindGroupFormat:i}=e(this.pickMode,!0);this._countShaderFisheye=s,this._countBindGroupFormatFisheye=i;let r=this.pickMode?"GSplatPickTileCountFisheye":"GSplatLocalTileCountFisheye";this._countComputeFisheye=new Ye(this.device,s,r)}return this._countComputeFisheye}if(!this._countCompute){let{shader:s,bindGroupFormat:i}=e(this.pickMode,!1);this._countShader=s,this._countBindGroupFormat=i;let r=this.pickMode?"GSplatPickTileCount":"GSplatLocalTileCount";this._countCompute=new Ye(this.device,s,r)}return this._countCompute}destroyCountResources(){this._countShader?.destroy(),this._countBindGroupFormat?.destroy(),this._countCompute?.destroy(),this._countShaderFisheye?.destroy(),this._countBindGroupFormatFisheye?.destroy(),this._countComputeFisheye?.destroy(),this._countShader=null,this._countBindGroupFormat=null,this._countCompute=null,this._countShaderFisheye=null,this._countBindGroupFormatFisheye=null,this._countComputeFisheye=null}getRasterizeCompute(t,e,s="none",i=!1){let r=t?"pick":"color";e&&(r+="-depth"),s!=="none"&&(r+=`-fog-${s}`),i&&(r+="-heatmap");let a=this._rasterizeVariants.get(r);if(!a){let{shader:o,bindGroupFormat:l}=this._createRasterizeShaderAndFormat(t,e,s,i),h=new Ye(this.device,o,`GSplatRasterize-${r}`);a={shader:o,bindGroupFormat:l,compute:h},this._rasterizeVariants.set(r,a)}return a.compute}_createRasterizeShaderAndFormat(t,e=!1,s="none",i=!1){let r=this.device,a=s!=="none",o=[new Y("screenWidth",pe),new Y("screenHeight",pe),new Y("numTilesX",pe),new Y("nearClip",Te),new Y("farClip",Te),new Y("alphaClip",Te)];a&&o.push(new Y("fog_color",Kt),new Y("fog_start",Te),new Y("fog_end",Te),new Y("fog_density",Te));let l=new Xe(r,o),h=[new Qe("uniforms",X),new K("tileEntries",X,!0),new K("tileSplatCounts",X,!0),new K("projCache",X,!0),new K("rasterizeTileList",X,!0),new K("tileListCounts",X,!0),new K("depthBuffer",X,!0)],f=t?[new Xn("pickIdTexture",zt),new Xn("pickDepthTexture",Me)]:[new Xn("outputTexture",Me)],u=e?[new Ki("sceneDepthMap",X,Ds,Vi,!1)]:[],d=new Ue(r,[...h,...f,...u]),p=new Map;p.set("{CACHE_STRIDE}",u_.toString()),t&&p.set("PICK_MODE",""),e&&p.set("DEPTH_TEST",""),i&&p.set("HEATMAP_MODE",""),p.set("GAMMA","SRGB"),p.set("FOG",a?s.toUpperCase():"NONE");let m=t?void 0:new Map([["decodePS",eh.decodePS]]);a&&m&&(m.set("fogMathPS",eh.fogMathPS),m.set("gammaPS",eh.gammaPS));let _="GSplatLocalRasterize";return t?_="GSplatLocalRasterizePick":e&&(_="GSplatLocalRasterizeDepth"),{shader:new Be(r,{name:_,shaderLanguage:se,cshader:jk,cdefines:p.size>0?p:void 0,cincludes:m,computeBindGroupFormat:d,computeUniformBufferFormats:{uniforms:l}}),bindGroupFormat:d}}destroy(){this.destroyCountResources();for(let{shader:t,bindGroupFormat:e,compute:s}of this._rasterizeVariants.values())s.destroy(),t.destroy(),e.destroy();this._tileSplatCountsBuffer?.destroy(),this._smallTileListBuffer?.destroy(),this._largeTileListBuffer?.destroy(),this._largeTileOverflowBasesBuffer?.destroy(),this._rasterizeTileListBuffer?.destroy(),this._tileListCountsBuffer?.destroy(),this._chunkRangesBuffer?.destroy(),this._totalChunksBuffer?.destroy(),this._chunkSortIndirectBuffer?.destroy(),this.prefixSumKernel.destroy(),this.outputTexture?.destroy(),this.pickIdTexture?.destroy(),this.pickDepthTexture?.destroy()}};var gE=` struct Splat { index: u32, uv: vec2i @@ -15045,89 +15473,210 @@ fn setSplat(idx: u32) { splat.index = idx; splat.uv = vec2i(i32(idx % uniforms.splatTextureSize), i32(idx / uniforms.splatTextureSize)); } -`;let Sd=new ey,Su=new Float32Array(16),Sf=new Float32Array(16),Sp=new es,Sm=new Float32Array(3);class S_ extends vJ{setDataSource(e){this._dataSource=e;}destroy(){this._unregisterFramePass(),this.renderMode&&1&this.renderMode&&this.layer.removeMeshInstances([this.tileComposite.meshInstance],true),this._mainSet.destroy(),this._pickSet?.destroy(),this._placeEntriesShader.destroy(),this._placeEntriesBindGroupFormat.destroy(),this._placeEntryPrepShader.destroy(),this._placeEntryPrepBindGroupFormat.destroy(),this._placeEntryPrepDispatchBuffer?.destroy(),this._largeSplatShader.destroy(),this._largeSplatBindGroupFormat.destroy(),this._largeSplatPrepShader.destroy(),this._largeSplatPrepBindGroupFormat.destroy(),this._largeSplatDispatchBuffer?.destroy(),this._largePlaceEntriesShader.destroy(),this._largePlaceEntriesBindGroupFormat.destroy(),this._classifyShader.destroy(),this._classifyBindGroupFormat.destroy(),this._sortShader.destroy(),this._sortBindGroupFormat.destroy(),this._bucketSortShader.destroy(),this._bucketSortBindGroupFormat.destroy(),this._copyShader.destroy(),this._copyBindGroupFormat.destroy(),this._chunkSortShader.destroy(),this._chunkSortBindGroupFormat.destroy(),this._projCacheBuffer?.destroy(),this._depthBuffer?.destroy(),this._tileEntriesBuffer?.destroy(),this._pairBuffer?.destroy(),this._countersBuffer?.destroy(),this._splatPairStartBuffer?.destroy(),this._splatPairCountBuffer?.destroy(),this._largeSplatIdsBuffer?.destroy(),this.tileComposite.destroy(),super.destroy();}get material(){return this.tileComposite.material}setRenderMode(e){let t=((this.renderMode??0)&1)!=0,i=(1&e)!=0;!t&&i&&(this.layer.addMeshInstances([this.tileComposite.meshInstance],true),this._registerFramePass()),t&&!i&&(this.layer.removeMeshInstances([this.tileComposite.meshInstance],true),this._unregisterFramePass()),super.setRenderMode(e);}frameUpdate(e,t,i){this._needsFramePassRegister&&this._registerFramePass(),this._minPixelSize=e.minPixelSize,this._minContribution=e.minContribution,this._alphaClip=e.alphaClip,this._exposure=t??1,this._fisheye=e.fisheye,this._fogParams=i??null,this._debugMode=e.debug;let s=this._dataSource.format.hash;s!==this._formatHash&&(this._formatHash=s,this._invalidateCountCompute());}setCompactedData(e,t,i,s){this._compactedSplatIds=e,this._sortElementCountBuffer=t,this._textureSize=i,this._numSplats=s;}_registerFramePass(){let e=this.cameraNode.camera?.camera;e?(e.beforePasses.includes(this.framePass)||e.beforePasses.push(this.framePass),this._needsFramePassRegister=false):this._needsFramePassRegister=true;}_unregisterFramePass(){this._needsFramePassRegister=false;let e=this.cameraNode.camera?.camera;if(e){let t=e.beforePasses.indexOf(this.framePass);-1!==t&&e.beforePasses.splice(t,1);}}resizeOutputTexture(e,t){this._mainSet.resizeOutputTextures(e,t);}_ensureSharedBuffers(e){let t=this.device,i=t.submitVersion!==this._lastBufferSubmitVersion,s=this._lastReadbackEntryCount;if(-1!==s){this._lastReadbackEntryCount=-1;let t=this._allocatedEntryCapacity;if(t>0&&s=200&&e>0){let t=Math.max(2.5,s/e*2);this._tileEntryMultiplier=Math.max(t,.9*this._tileEntryMultiplier),this._shrinkFrameCount=0;}}if(!i)return;e>this._allocatedSplatCapacity&&(this._projCacheBuffer?.destroy(),this._depthBuffer?.destroy(),this._splatPairStartBuffer?.destroy(),this._splatPairCountBuffer?.destroy(),this._allocatedSplatCapacity=e,this._projCacheBuffer=new rO(t,7*e*4),this._depthBuffer=new rO(t,4*e),this._splatPairStartBuffer=new rO(t,4*e),this._splatPairCountBuffer=new rO(t,4*e)),this._countersBuffer||(this._countersBuffer=new rO(t,8,12)),this._largeSplatIdsCapacity>this._allocatedLargeSplatCapacity&&(this._largeSplatIdsBuffer?.destroy(),this._allocatedLargeSplatCapacity=this._largeSplatIdsCapacity,this._largeSplatIdsBuffer=new rO(t,4*this._largeSplatIdsCapacity));let r=Math.ceil(e*this._tileEntryMultiplier),a=r>this._allocatedEntryCapacity,n=this._allocatedEntryCapacity>0&&2*r65535){let e=Math.sqrt(65535/(n*o));n=Math.max(1,Math.floor(n*e)),o=Math.max(1,Math.floor(o*e));}let l=n*o;this._ensureSharedBuffers(r),e.ensureTileBuffers(l);let h=this._allocatedEntryCapacity,c=this._dataSource,d=this.cameraNode.camera,u=d.camera,f=u.viewMatrix,p=u.projectionMatrix;Sd.mul2(p,f),Su.set(Sd.data),Sf.set(f.data);let m=t*p.data[0],_=s?this._alphaClip:1/255;this.fisheyeProj.update(this._fisheye,d.fov,p);let g=this.fisheyeProj.enabled,v=(e,t)=>this._createCountShaderAndFormat(e,t),S=e.getCountCompute(g,v);for(let t of(this._placeEntryPrepCompute.setParameter("sortElementCount",this._sortElementCountBuffer),this._placeEntryPrepCompute.setParameter("dispatchArgs",this._placeEntryPrepDispatchBuffer),this._placeEntryPrepCompute.setupDispatch(1,1,1),a.computeDispatch([this._placeEntryPrepCompute],"GSplatLocalDispatchPrep"),e._tileSplatCountsBuffer.clear(),this._countersBuffer.clear(),S.setParameter("compactedSplatIds",this._compactedSplatIds),S.setParameter("sortElementCount",this._sortElementCountBuffer),S.setParameter("projCache",this._projCacheBuffer),S.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),S.setParameter("pairBuffer",this._pairBuffer),S.setParameter("countersBuffer",this._countersBuffer),S.setParameter("splatPairStart",this._splatPairStartBuffer),S.setParameter("splatPairCount",this._splatPairCountBuffer),S.setParameter("largeSplatIds",this._largeSplatIdsBuffer),S.setParameter("depthBuffer",this._depthBuffer),c.format.streams))S.setParameter(t.name,c.getTexture(t.name));for(let e of c.format.extraStreams)S.setParameter(e.name,c.getTexture(e.name));if(S.setParameter("splatTextureSize",this._textureSize),S.setParameter("numTilesX",n),S.setParameter("numTilesY",o),S.setParameter("viewProj",Su),S.setParameter("viewMatrix",Sf),S.setParameter("focal",m),S.setParameter("viewportWidth",t),S.setParameter("viewportHeight",i),S.setParameter("nearClip",u.nearClip),S.setParameter("farClip",u.farClip),S.setParameter("minPixelSize",.5*this._minPixelSize),S.setParameter("isOrtho",+(1===u.projection)),S.setParameter("exposure",this._exposure),S.setParameter("alphaClip",_),S.setParameter("minContribution",this._minContribution),g){let e=this.fisheyeProj;S.setParameter("fisheye_k",e.k),S.setParameter("fisheye_inv_k",e.invK),S.setParameter("fisheye_projMat00",e.projMat00),S.setParameter("fisheye_projMat11",e.projMat11);}S.setupIndirectDispatch(0,this._placeEntryPrepDispatchBuffer),a.computeDispatch([S],s?"GSplatPickTileCount":"GSplatLocalTileCount"),this._largeSplatPrepCompute.setParameter("countersBuffer",this._countersBuffer),this._largeSplatPrepCompute.setParameter("dispatchArgs",this._largeSplatDispatchBuffer),this._largeSplatPrepCompute.setParameter("largeSplatIds",this._largeSplatIdsBuffer),this._largeSplatPrepCompute.setupDispatch(1,1,1),a.computeDispatch([this._largeSplatPrepCompute],s?"GSplatPickLargeSplatPrep":"GSplatLocalLargeSplatPrep"),e.largeSplatCompute.setParameter("projCache",this._projCacheBuffer),e.largeSplatCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.largeSplatCompute.setParameter("pairBuffer",this._pairBuffer),e.largeSplatCompute.setParameter("countersBuffer",this._countersBuffer),e.largeSplatCompute.setParameter("splatPairStart",this._splatPairStartBuffer),e.largeSplatCompute.setParameter("splatPairCount",this._splatPairCountBuffer),e.largeSplatCompute.setParameter("largeSplatIds",this._largeSplatIdsBuffer),e.largeSplatCompute.setParameter("numTilesX",n),e.largeSplatCompute.setParameter("numTilesY",o),e.largeSplatCompute.setParameter("viewportWidth",t),e.largeSplatCompute.setParameter("viewportHeight",i),e.largeSplatCompute.setParameter("alphaClip",_),e.largeSplatCompute.setupIndirectDispatch(0,this._largeSplatDispatchBuffer),a.computeDispatch([e.largeSplatCompute],s?"GSplatPickLargeTileCount":"GSplatLocalLargeTileCount"),e.prefixSumKernel.resize(e._tileSplatCountsBuffer,l+1),e.prefixSumKernel.dispatch(a),e.placeEntriesCompute.setParameter("pairBuffer",this._pairBuffer),e.placeEntriesCompute.setParameter("splatPairStart",this._splatPairStartBuffer),e.placeEntriesCompute.setParameter("splatPairCount",this._splatPairCountBuffer),e.placeEntriesCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.placeEntriesCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.placeEntriesCompute.setParameter("sortElementCount",this._sortElementCountBuffer),e.placeEntriesCompute.setupIndirectDispatch(1,this._placeEntryPrepDispatchBuffer),a.computeDispatch([e.placeEntriesCompute],s?"GSplatPickPlaceEntries":"GSplatLocalPlaceEntries"),e.largePlaceEntriesCompute.setParameter("pairBuffer",this._pairBuffer),e.largePlaceEntriesCompute.setParameter("splatPairStart",this._splatPairStartBuffer),e.largePlaceEntriesCompute.setParameter("splatPairCount",this._splatPairCountBuffer),e.largePlaceEntriesCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.largePlaceEntriesCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.largePlaceEntriesCompute.setParameter("largeSplatIds",this._largeSplatIdsBuffer),e.largePlaceEntriesCompute.setParameter("countersBuffer",this._countersBuffer),e.largePlaceEntriesCompute.setupIndirectDispatch(0,this._largeSplatDispatchBuffer),a.computeDispatch([e.largePlaceEntriesCompute],s?"GSplatPickLargePlaceEntries":"GSplatLocalLargePlaceEntries"),e._tileListCountsBuffer.clear(),e._totalChunksBuffer.clear(),e._chunkSortIndirectBuffer.clear();let y=a.getIndirectDispatchSlot(3),x=a.getIndirectDrawSlot(1);e.classifyCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.classifyCompute.setParameter("smallTileList",e._smallTileListBuffer),e.classifyCompute.setParameter("largeTileList",e._largeTileListBuffer),e.classifyCompute.setParameter("rasterizeTileList",e._rasterizeTileListBuffer),e.classifyCompute.setParameter("tileListCounts",e._tileListCountsBuffer),e.classifyCompute.setParameter("indirectDispatchArgs",a.indirectDispatchBuffer),e.classifyCompute.setParameter("largeTileOverflowBases",e._largeTileOverflowBasesBuffer),e.classifyCompute.setParameter("indirectDrawArgs",a.indirectDrawBuffer),e.classifyCompute.setParameter("numTiles",l),e.classifyCompute.setParameter("dispatchSlotOffset",3*y),e.classifyCompute.setParameter("bufferCapacity",h),e.classifyCompute.setParameter("maxWorkgroupsPerDim",a.limits.maxComputeWorkgroupsPerDimension||65535),e.classifyCompute.setParameter("drawSlot",x),e.classifyCompute.setupDispatch(1,1,1),a.computeDispatch([e.classifyCompute],s?"GSplatPickClassify":"GSplatLocalClassify"),e.bucketSortCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.bucketSortCompute.setParameter("largeTileOverflowBases",e._largeTileOverflowBasesBuffer),e.bucketSortCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.bucketSortCompute.setParameter("depthBuffer",this._depthBuffer),e.bucketSortCompute.setParameter("largeTileList",e._largeTileListBuffer),e.bucketSortCompute.setParameter("chunkRanges",e._chunkRangesBuffer),e.bucketSortCompute.setParameter("totalChunks",e._totalChunksBuffer),e.bucketSortCompute.setParameter("tileListCounts",e._tileListCountsBuffer),e.bucketSortCompute.setParameter("bufferCapacity",h),e.bucketSortCompute.setParameter("maxChunks",8*l),e.bucketSortCompute.setupIndirectDispatch(y+1),a.computeDispatch([e.bucketSortCompute],s?"GSplatPickBucketSort":"GSplatLocalBucketSort"),e.copyCompute.setParameter("totalChunks",e._totalChunksBuffer),e.copyCompute.setParameter("chunkSortIndirect",e._chunkSortIndirectBuffer),e.copyCompute.setParameter("maxChunks",8*l),e.copyCompute.setParameter("maxWorkgroupsPerDim",a.limits.maxComputeWorkgroupsPerDimension||65535),e.copyCompute.setupDispatch(1,1,1),a.computeDispatch([e.copyCompute],s?"GSplatPickCopy":"GSplatLocalCopy"),e.sortCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.sortCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.sortCompute.setParameter("depthBuffer",this._depthBuffer),e.sortCompute.setParameter("smallTileList",e._smallTileListBuffer),e.sortCompute.setParameter("tileListCounts",e._tileListCountsBuffer),e.sortCompute.setupIndirectDispatch(y),a.computeDispatch([e.sortCompute],s?"GSplatPickTileSort":"GSplatLocalTileSort"),e.chunkSortCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.chunkSortCompute.setParameter("depthBuffer",this._depthBuffer),e.chunkSortCompute.setParameter("chunkRanges",e._chunkRangesBuffer),e.chunkSortCompute.setParameter("totalChunks",e._totalChunksBuffer),e.chunkSortCompute.setParameter("maxChunks",8*l),e.chunkSortCompute.setupIndirectDispatch(0,e._chunkSortIndirectBuffer),a.computeDispatch([e.chunkSortCompute],s?"GSplatPickChunkSort":"GSplatLocalChunkSort");let T=u.shaderParams.sceneDepthMapLinear?a.scope.resolve("uSceneDepthMap").value:null,E=!s&&T,w=this._fogParams,b=w&&w.type!==ns?w.type:"none",C=!s&&3===this._debugMode,A=e.getRasterizeCompute(s,E,b,C);A.setParameter("screenWidth",t),A.setParameter("screenHeight",i),A.setParameter("numTilesX",n),A.setParameter("nearClip",u.nearClip),A.setParameter("farClip",u.farClip),A.setParameter("alphaClip",_),"none"!==b&&(Sp.linear(w.color),Sm[0]=Sp.r,Sm[1]=Sp.g,Sm[2]=Sp.b,A.setParameter("fog_color",Sm),A.setParameter("fog_start",w.start),A.setParameter("fog_end",w.end),A.setParameter("fog_density",w.density)),A.setParameter("tileEntries",this._tileEntriesBuffer),A.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),A.setParameter("projCache",this._projCacheBuffer),A.setParameter("rasterizeTileList",e._rasterizeTileListBuffer),A.setParameter("tileListCounts",e._tileListCountsBuffer),A.setParameter("depthBuffer",this._depthBuffer),s?(A.setParameter("pickIdTexture",e.pickIdTexture),A.setParameter("pickDepthTexture",e.pickDepthTexture)):(A.setParameter("outputTexture",e.outputTexture),E&&A.setParameter("sceneDepthMap",T)),A.setupIndirectDispatch(y+2),a.computeDispatch([A],s?"GSplatPickRasterize":"GSplatLocalRasterize"),this._lastDrawSlot=x,this._lastNumTilesX=n,this._scheduleReadback(r,l,e);}_scheduleReadback(e,t,i){0===e||Promise.all([i._tileSplatCountsBuffer.read(4*t,4),i._tileListCountsBuffer.read(12,4),this._countersBuffer.read(4,4)]).then(([t,i,s])=>{let r=new Uint32Array(t.buffer,t.byteOffset,1)[0]+new Uint32Array(i.buffer,i.byteOffset,1)[0];e>0&&(this._tileEntryMultiplier=Math.max(this._tileEntryMultiplier,r/e*2),this._tileEntryMultiplier=Math.max(this._tileEntryMultiplier,2.5)),this._lastReadbackEntryCount=r;let a=new Uint32Array(s.buffer,s.byteOffset,1)[0];a>this._largeSplatIdsCapacity&&(this._largeSplatIdsCapacity=Math.ceil(1.2*a));}).catch(()=>{});}_invalidateCountCompute(){this._mainSet.destroyCountResources(),this._pickSet?.destroyCountResources();}_createCommonIncludes(){let e=new Map;return e.set("gsplatCommonCS",Sa),e.set("gsplatTileIntersectCS",Sn),e}_createBitonicIncludes(){let e=new Map;return e.set("gsplatLocalBitonicCS",Sr),e}_createSharedShaders(){let e=this.device;this._placeEntriesBindGroupFormat=new ii(e,[new t7("pairBuffer",4,true),new t7("splatPairStart",4,true),new t7("splatPairCount",4,true),new t7("tileSplatCounts",4,true),new t7("tileEntries",4),new t7("sortElementCount",4,true)]),this._placeEntriesShader=new r_(e,{name:"GSplatLocalPlaceEntries",shaderLanguage:tV,cshader:v6,computeBindGroupFormat:this._placeEntriesBindGroupFormat});{let t=e.limits.maxComputeWorkgroupsPerDimension||65535,i=new Map;i.set("{MAX_DIM}",t.toString()),i.set("{SPLATS_PER_WG}","256"),i.set("{SPLATS_PER_WG_MINUS_1}","255"),this._placeEntryPrepBindGroupFormat=new ii(e,[new t7("sortElementCount",4,true),new t7("dispatchArgs",4)]),this._placeEntryPrepShader=new r_(e,{name:"GSplatLocalPlaceEntryPrep",shaderLanguage:tV,cshader:v2,cdefines:i,computeBindGroupFormat:this._placeEntryPrepBindGroupFormat}),this._placeEntryPrepDispatchBuffer=new rO(e,24,256),this._placeEntryPrepCompute=new ar(e,this._placeEntryPrepShader);}{let t=this._createCommonIncludes(),i=new sg(e,[new s_("numTilesX",26),new s_("numTilesY",26),new s_("viewportWidth",2),new s_("viewportHeight",2),new s_("alphaClip",2)]);this._largeSplatBindGroupFormat=new ii(e,[new t7("projCache",4,true),new t7("tileSplatCounts",4),new t7("pairBuffer",4),new t7("countersBuffer",4),new t7("splatPairStart",4),new t7("splatPairCount",4),new t7("largeSplatIds",4,true),new t9("uniforms",4)]),this._largeSplatShader=new r_(e,{name:"GSplatLocalTileCountLarge",shaderLanguage:tV,cshader:v5,cincludes:t,computeBindGroupFormat:this._largeSplatBindGroupFormat,computeUniformBufferFormats:{uniforms:i}});}{let t=e.limits.maxComputeWorkgroupsPerDimension||65535,i=new Map;i.set("{MAX_DIM}",t.toString()),this._largeSplatPrepBindGroupFormat=new ii(e,[new t7("countersBuffer",4,true),new t7("dispatchArgs",4),new t7("largeSplatIds",4,true)]),this._largeSplatPrepShader=new r_(e,{name:"GSplatLocalLargeSplatPrep",shaderLanguage:tV,cshader:v3,cdefines:i,computeBindGroupFormat:this._largeSplatPrepBindGroupFormat}),this._largeSplatDispatchBuffer=new rO(e,12,256),this._largeSplatPrepCompute=new ar(e,this._largeSplatPrepShader);}this._largePlaceEntriesBindGroupFormat=new ii(e,[new t7("pairBuffer",4,true),new t7("splatPairStart",4,true),new t7("splatPairCount",4,true),new t7("tileSplatCounts",4,true),new t7("tileEntries",4),new t7("largeSplatIds",4,true),new t7("countersBuffer",4,true)]),this._largePlaceEntriesShader=new r_(e,{name:"GSplatLocalPlaceEntriesLarge",shaderLanguage:tV,cshader:v8,computeBindGroupFormat:this._largePlaceEntriesBindGroupFormat});{let t=new sg(e,[new s_("numTiles",26),new s_("dispatchSlotOffset",26),new s_("bufferCapacity",26),new s_("maxWorkgroupsPerDim",26),new s_("drawSlot",26)]);this._classifyBindGroupFormat=new ii(e,[new t7("tileSplatCounts",4,true),new t7("smallTileList",4),new t7("largeTileList",4),new t7("rasterizeTileList",4),new t7("tileListCounts",4),new t7("indirectDispatchArgs",4),new t7("largeTileOverflowBases",4),new t9("uniforms",4),new t7("indirectDrawArgs",4)]),this._classifyShader=new r_(e,{name:"GSplatLocalClassify",shaderLanguage:tV,cshader:Se,computeBindGroupFormat:this._classifyBindGroupFormat,computeUniformBufferFormats:{uniforms:t}});}this._sortBindGroupFormat=new ii(e,[new t7("tileEntries",4),new t7("tileSplatCounts",4,true),new t7("depthBuffer",4,true),new t7("smallTileList",4,true),new t7("tileListCounts",4,true)]),this._sortShader=new r_(e,{name:"GSplatLocalTileSort",shaderLanguage:tV,cshader:v9,cincludes:this._createBitonicIncludes(),computeBindGroupFormat:this._sortBindGroupFormat});{let t=new sg(e,[new s_("bufferCapacity",26),new s_("maxChunks",26)]);this._bucketSortBindGroupFormat=new ii(e,[new t7("tileEntries",4),new t7("largeTileOverflowBases",4,true),new t7("tileSplatCounts",4,true),new t7("depthBuffer",4,true),new t7("largeTileList",4,true),new t7("chunkRanges",4),new t7("totalChunks",4),new t7("tileListCounts",4,true),new t9("uniforms",4)]),this._bucketSortShader=new r_(e,{name:"GSplatLocalBucketSort",shaderLanguage:tV,cshader:St,computeBindGroupFormat:this._bucketSortBindGroupFormat,computeUniformBufferFormats:{uniforms:t}});}{let t=new sg(e,[new s_("maxChunks",26),new s_("maxWorkgroupsPerDim",26)]);this._copyBindGroupFormat=new ii(e,[new t7("totalChunks",4,true),new t7("chunkSortIndirect",4),new t9("uniforms",4)]),this._copyShader=new r_(e,{name:"GSplatLocalCopy",shaderLanguage:tV,cshader:Ss,computeBindGroupFormat:this._copyBindGroupFormat,computeUniformBufferFormats:{uniforms:t}});}{let t=new sg(e,[new s_("maxChunks",26)]);this._chunkSortBindGroupFormat=new ii(e,[new t7("tileEntries",4),new t7("depthBuffer",4,true),new t7("chunkRanges",4,true),new t7("totalChunks",4,true),new t9("uniforms",4)]),this._chunkSortShader=new r_(e,{name:"GSplatLocalChunkSort",shaderLanguage:tV,cshader:Si,cincludes:this._createBitonicIncludes(),computeBindGroupFormat:this._chunkSortBindGroupFormat,computeUniformBufferFormats:{uniforms:t}});}}_createCountShaderAndFormat(e,t){let i=this.device,s=[new s_("splatTextureSize",26),new s_("numTilesX",26),new s_("numTilesY",26),new s_("viewProj",14),new s_("viewMatrix",14),new s_("focal",2),new s_("viewportWidth",2),new s_("viewportHeight",2),new s_("nearClip",2),new s_("farClip",2),new s_("minPixelSize",2),new s_("isOrtho",26),new s_("exposure",2),new s_("alphaClip",2),new s_("minContribution",2)];t&&s.push(new s_("fisheye_k",2),new s_("fisheye_inv_k",2),new s_("fisheye_projMat00",2),new s_("fisheye_projMat11",2));let r=new sg(i,s),a=this._dataSource.format,n=[new t7("compactedSplatIds",4,true),new t7("sortElementCount",4,true),new t7("projCache",4),new t7("tileSplatCounts",4),new t9("uniforms",4),new t7("pairBuffer",4),new t7("countersBuffer",4),new t7("splatPairStart",4),new t7("splatPairCount",4),new t7("largeSplatIds",4),new t7("depthBuffer",4)],o=new ii(i,[...n,...a.getComputeBindFormats()]),l=this._createCommonIncludes();l.set("gsplatComputeSplatCS",Sc),l.set("gsplatFormatDeclCS",a.getComputeInputDeclarations(n.length)),l.set("gsplatFormatReadCS",a.getReadCode());let h=new Map;t&&h.set("GSPLAT_FISHEYE",""),e&&h.set("PICK_MODE","");let c=a.getStream("dataColor");c&&47!==c.format&&h.set("GSPLAT_COLOR_FLOAT","");let d=t?"Fisheye":"";return {shader:new r_(i,{name:e?`GSplatLocalTileCountPick${d}`:`GSplatLocalTileCount${d}`,shaderLanguage:tV,cshader:v4,cincludes:l,cdefines:h,computeBindGroupFormat:o,computeUniformBufferFormats:{uniforms:r}}),bindGroupFormat:o}}_createDispatchSet(e){let t=this.device,i=new Sh(t,e);return i.placeEntriesCompute=new ar(t,this._placeEntriesShader,e?"GSplatPickPlaceEntries":"GSplatLocalPlaceEntries"),i.largeSplatCompute=new ar(t,this._largeSplatShader,e?"GSplatPickLargeTileCount":"GSplatLocalLargeTileCount"),i.largePlaceEntriesCompute=new ar(t,this._largePlaceEntriesShader,e?"GSplatPickLargePlaceEntries":"GSplatLocalLargePlaceEntries"),i.classifyCompute=new ar(t,this._classifyShader,e?"GSplatPickClassify":"GSplatLocalClassify"),i.sortCompute=new ar(t,this._sortShader,e?"GSplatPickTileSort":"GSplatLocalTileSort"),i.bucketSortCompute=new ar(t,this._bucketSortShader,e?"GSplatPickBucketSort":"GSplatLocalBucketSort"),i.copyCompute=new ar(t,this._copyShader,e?"GSplatPickCopy":"GSplatLocalCopy"),i.chunkSortCompute=new ar(t,this._chunkSortShader,e?"GSplatPickChunkSort":"GSplatLocalChunkSort"),i}constructor(e,t,i,s,r){super(e,t,i,s,r),this._pickSet=null,this._needsFramePassRegister=false,this._textureSize=0,this._minPixelSize=2,this._minContribution=3,this._alphaClip=.3,this._exposure=1,this._numSplats=0,this._compactedSplatIds=null,this._sortElementCountBuffer=null,this._projCacheBuffer=null,this._tileEntriesBuffer=null,this._pairBuffer=null,this._countersBuffer=null,this._splatPairStartBuffer=null,this._splatPairCountBuffer=null,this._largeSplatIdsBuffer=null,this._largeSplatIdsCapacity=16384,this._allocatedLargeSplatCapacity=0,this._allocatedSplatCapacity=0,this._allocatedEntryCapacity=0,this._tileEntryMultiplier=2.5,this._lastBufferSubmitVersion=-1,this._lastReadbackEntryCount=-1,this._shrinkFrameCount=0,this._fisheye=0,this._placeEntryPrepDispatchBuffer=null,this._placeEntryPrepCompute=null,this._largeSplatDispatchBuffer=null,this._largeSplatPrepCompute=null,this._lastDrawSlot=0,this._lastNumTilesX=0,this._dataSource=r,this._createSharedShaders(),this._mainSet=this._createDispatchSet(false),this.framePass=new v1(this);let a=i.camera;this.tileComposite=new So(e,t,e=>{let t=this.renderMode??0;return a.camera===e&&(1&t)!=0&&null!==this._mainSet._rasterizeTileListBuffer});}}let Sg=new oc;class Sv{set lodBaseDistance(e){this._lodBaseDistance!==e&&(this._lodBaseDistance=e,this.lodDirty=true);}get lodBaseDistance(){return this._lodBaseDistance}set lodMultiplier(e){this._lodMultiplier!==e&&(this._lodMultiplier=e,this.lodDirty=true);}get lodMultiplier(){return this._lodMultiplier}destroy(){this._streams?.destroy(),this._streams=null,this.intervals.clear(),this.resource=null;}set workBufferModifier(e){this._workBufferModifier=e,this.renderDirty=true;}get workBufferModifier(){return this.parentPlacement?.workBufferModifier??this._workBufferModifier}consumeRenderDirty(){let e=this.resource?.format;e&&this._lastFormatVersion!==e.extraStreamsVersion&&(this._lastFormatVersion=e.extraStreamsVersion,this.renderDirty=true),2===this.workBufferUpdate?this.renderDirty=true:1===this.workBufferUpdate&&(this.renderDirty=true,this.workBufferUpdate=0);let t=this.renderDirty;return this.renderDirty=false,t}set aabb(e){this._aabb=e?.clone()??null;}get aabb(){return this._aabb??this.resource?.aabb}getLodDistance(e){return this.lodBaseDistance*Math.pow(this.lodMultiplier,e)}getInstanceTexture(e,t){let i=this.resource;if(i?.format)return !this._streams&&i.format.instanceStreams.length>0&&(this._streams=new uV(t,true),this._streams.textureDimensions.copy(i.streams.textureDimensions),this._streams.syncWithFormat(i.format)),this._streams?.getTexture(e)}get streams(){return this.parentPlacement?.streams??this._streams}ensureInstanceStreams(e){let t=this.resource;t?.format&&!this._streams&&t.format.instanceStreams.length>0&&(this._streams=new uV(e,true),this._streams.textureDimensions.copy(t.streams.textureDimensions),this._streams.syncWithFormat(t.format));}constructor(e,t,i=0,s=null,r=null,a=null){this.intervals=new Map,this.id=0,this.allocId=Sg.get(),this.lodIndex=0,this._lodBaseDistance=5,this._lodMultiplier=3,this._aabb=null,this.parameters=null,this._streams=null,this.lodDirty=false,this.renderDirty=false,this.workBufferUpdate=0,this._lastFormatVersion=-1,this._workBufferModifier=null,this.parentPlacement=null,this.id=a??r?.id??0,this.resource=e,this.node=t,this.lodIndex=i,this.parameters=s??r?.parameters??null,this.parentPlacement=r;}}let SS=new ey,Sy=new ed,Sx=new ed,ST=new ed,SE=[];new eA;let Sw=Math.tan(22.5*ei.DEG_TO_RAD);new es(1,0,0),new es(0,1,0),new es(0,0,1),new es(1,1,0),new es(1,0,1);class Sb{resetLod(){this.currentLod=-1,this.optimalLod=-1;}constructor(){this.currentLod=-1,this.optimalLod=-1,this.worldDistance=0,this.colorAccumulatedTranslation=0,this.inst=null,this.lods=null,this.allocId=Sg.get();}}class SC{get pendingLoadCount(){let e=this.pending.size+this.prefetchPending.size;return this.octree.environmentUrl&&!this.environmentPlacement&&e++,e}destroy(e=false){if(!e&&this.octree&&!this.octree.destroyed){for(let e of this.getFileDecrements())this.octree.decRefCount(e,0);for(let e of this.pending)this.filePlacements[e]||this.octree.unloadResource(e);for(let e of this.prefetchPending)this.filePlacements[e]||this.octree.unloadResource(e);this.environmentPlacement&&this.octree.decEnvironmentRefCount();}this.pending.clear(),this.pendingDecrements.clear(),this.filePlacements.length=0,this.environmentPlacement&&(this.activePlacements.delete(this.environmentPlacement),this.environmentPlacement=null),this._deviceLostEvent?.off(),this._deviceLostEvent=null;}_onDeviceLost(){for(let e=0;e0){let r=Math.min(i,t+s);for(let i=t;i<=r;i++){let t=e.lods[i].fileIndex;if(-1!==t&&this.octree.getFileResource(t))return i}for(let i=r;i>=t;i--)if(-1!==e.lods[i].fileIndex)return i}return t}prefetchNextLod(e,t,i){if(-1===t||-1===i)return;if(t===i){let t=e.lods[i].fileIndex;-1!==t&&(this.octree.ensureFileResource(t),this.octree.getFileResource(t)||this.prefetchPending.add(t));return}let s=Math.max(i,t-1);for(let t=s;t>=i;t--){let i=e.lods[t].fileIndex;if(-1!==i){this.octree.ensureFileResource(i),this.octree.getFileResource(i)||this.prefetchPending.add(i);break}}}updateLod(e,t){let i=this.octree.lodLevels-1,{lodBaseDistance:s,lodMultiplier:r}=this.placement,{lodRangeMin:a,lodRangeMax:n}=t,o=Math.max(0,Math.min(a??0,i)),l=Math.max(o,Math.min(n??i,i)),h=this.placement.node.getWorldTransform().getScale().x;this.evaluateNodeLods(e,i,s,r,o,l,t,h),this.applyLodChanges(i,t);}evaluateNodeLods(e,t,i,s,r,a,n,o){let{lodBehindPenalty:l}=n,h=e.camera,c=Math.tan(.5*h.fov*ei.DEG_TO_RAD);h.horizontalFov&&(c/=h.aspectRatio);let d=c*h.aspectRatio,u=Math.min(c,d)/Sw,f=1/Math.log(s),p=e.getPosition(),m=this.placement.node.getWorldTransform();SS.copy(m).invert();let _=SS.transformPoint(p,Sy),g=e.forward,v=SS.transformVector(g,Sx).normalize(),S=this.octree.nodes,y=this.nodeInfos,x=0;for(let e=0;e1&&c>.01){let e=v.dot(ST)/c;e<0&&(d=c*(1+-e*(l-1)));}let p=d*u;(s=pa&&(s=a),h.optimalLod=s,h.worldDistance=p*o;let m=S[e].lods[s];m&&m.count&&(x+=m.count);}return x}evaluateOptimalLods(e,t,i=1){let s=this.octree.lodLevels-1,{lodBaseDistance:r,lodMultiplier:a}=this.placement,{lodRangeMin:n,lodRangeMax:o}=t,l=Math.max(0,Math.min(n??0,s)),h=Math.max(l,Math.min(o??s,s));this.rangeMin=l,this.rangeMax=h;let c=this.placement.node.getWorldTransform().getScale().x,d=Math.max(1.2,a*Math.pow(i,-0.2));return this.evaluateNodeLods(e,s,r*i,d,l,h,t,c)}applyLodChanges(e,t){let i=this.octree.nodes,{lodUnderfillLimit:s=0}=t;for(let t=0;t=0?r.lods[o].fileIndex:-1,i=l>=0?r.lods[l].fileIndex:-1,s=-1!==e,n=-1!==i,h=this.pendingDecrements.get(t);if(h&&h.newFileIndex!==i&&(this.filePlacements[h.newFileIndex]&&this.decrementFileRef(h.newFileIndex,t),s&&n?this.pendingDecrements.set(t,{oldFileIndex:h.oldFileIndex,newFileIndex:i}):this.pendingDecrements.delete(t)),!s&&n){let e=this.pendingVisibleAdds.get(t);void 0!==e&&e!==i&&(this.decrementFileRef(e,t),this.pendingVisibleAdds.delete(t)),this.incrementFileRef(i,t,l);let s=this.filePlacements[i];s?.resource?(a.currentLod=l,this.pendingVisibleAdds.delete(t)):this.pendingVisibleAdds.set(t,i);}else if(s&&!n){let i=this.pendingDecrements.get(t);i&&(this.decrementFileRef(i.newFileIndex,t),this.pendingDecrements.delete(t)),this.decrementFileRef(e,t),a.currentLod=-1,this.pendingVisibleAdds.delete(t);}else if(s&&n){this.incrementFileRef(i,t,l);let s=this.filePlacements[i];s?.resource?(this.decrementFileRef(e,t),this.pendingDecrements.delete(t),a.currentLod=l):this.pendingDecrements.set(t,{oldFileIndex:e,newFileIndex:i}),this.pendingVisibleAdds.delete(t);}}this.prefetchNextLod(r,l,n);}}incrementFileRef(e,t,i){if(-1===e)return;let s=this.filePlacements[e];!s&&(s=new Sv(null,this.placement.node,i,null,this.placement),this.filePlacements[e]=s,this.removedCandidates.delete(e)||this.octree.incRefCount(e),this.addFilePlacement(e)||(this.octree.ensureFileResource(e),this.pending.add(e)));let r=this.octree.nodes[t].lods[i],a=new ef(r.offset,r.offset+r.count-1);s.intervals.set(t,a),this.dirtyModifiedPlacements=true;}decrementFileRef(e,t){if(-1===e)return;let i=this.filePlacements[e];i&&i&&(i.intervals.delete(t),this.dirtyModifiedPlacements=true,0===i.intervals.size&&(i.resource&&(this.activePlacements.delete(i),0===this.activePlacements.size&&(this.dirtyPlacementSetChanged=true)),this.removedCandidates.add(e),this.filePlacements[e]=null,this.pending.delete(e)));}addFilePlacement(e){let t=this.octree.getFileResource(e);if(t){let i=this.filePlacements[e];if(i)return i.resource=t,0===this.activePlacements.size&&(this.dirtyPlacementSetChanged=true),this.activePlacements.add(i),this.dirtyModifiedPlacements=true,this.removedCandidates.delete(e),true}return false}testMoved(e){return this.placement.node.getPosition().distance(this.previousPosition)>e}updateMoved(){this.previousPosition.copy(this.placement.node.getPosition());}update(){if(this.placement.lodDirty&&(this.placement.lodDirty=false,this.needsLodUpdate=true),this.pending.size){for(let e of this.pending)if(this.octree.ensureFileResource(e),this.addFilePlacement(e)){for(let[t,{oldFileIndex:i,newFileIndex:s}]of(SE.push(e),this.pendingDecrements))if(s===e){this.decrementFileRef(i,t),this.pendingDecrements.delete(t);let e=0,r=this.octree.nodes[t].lods;for(let t=0;t0&&(this.needsLodUpdate=true),SE))this.pending.delete(e);SE.length=0;}if(this.pollPrefetchCompletions(),this.octree.environmentUrl&&!this.environmentPlacement){this.octree.ensureEnvironmentResource();let e=this.octree.environmentResource;e&&(this.environmentPlacement=new Sv(e,this.placement.node,0,null,this.placement),this.environmentPlacement.aabb.copy(e.aabb),this.activePlacements.add(this.environmentPlacement),this.dirtyModifiedPlacements=true,this.dirtyPlacementSetChanged=true);}let e=this.dirtyModifiedPlacements;return this.dirtyModifiedPlacements=false,e}consumePlacementSetChanged(){let e=this.dirtyPlacementSetChanged;return this.dirtyPlacementSetChanged=false,e}debugRender(e){}consumeNeedsLodUpdate(){let e=this.needsLodUpdate;return this.needsLodUpdate=false,e}pollPrefetchCompletions(){if(this.prefetchPending.size){for(let e of this.prefetchPending)this.octree.ensureFileResource(e),this.octree.getFileResource(e)&&SE.push(e);for(let e of(SE.length>0&&(this.needsLodUpdate=true),SE))this.prefetchPending.delete(e);SE.length=0;}}constructor(e,t,i){this.activePlacements=new Set,this.dirtyModifiedPlacements=false,this.dirtyPlacementSetChanged=false,this.pending=new Set,this.pendingDecrements=new Map,this.removedCandidates=new Set,this.rangeMin=0,this.rangeMax=0,this.previousPosition=new ed,this.needsLodUpdate=false,this.prefetchPending=new Set,this.pendingVisibleAdds=new Map,this.environmentPlacement=null,this._deviceLostEvent=null,this.device=e,this.octree=t,this.placement=i,this.nodeInfos=Array(t.nodes.length);for(let e=0;e0&&(this.cooldowns.forEach((e,t)=>{e<=1?(0===this.fileRefCounts[t]&&this.unloadResource(t),SD.push(t)):this.cooldowns.set(t,e-1);}),SD.forEach(e=>this.cooldowns.delete(e)),SD.length=0);}ensureFileResource(e){if(this.fileResources.has(e))return;let t=this.files[e].url,i=this.assetLoader?.getResource(t);if(i){this.fileResources.set(e,i),0===this.fileRefCounts[e]&&this.cooldowns.set(e,this.cooldownTicks),this._traceLodCounts();return}this.assetLoader?.load(t);}incEnvironmentRefCount(){this.environmentRefCount++;}decEnvironmentRefCount(){this.environmentRefCount--,0===this.environmentRefCount&&this.unloadEnvironmentResource();}ensureEnvironmentResource(){if(!this.assetLoader||!this.environmentUrl||this.environmentResource)return;let e=this.assetLoader.getResource(this.environmentUrl);if(e){this.environmentResource=e,0===this.environmentRefCount&&this.unloadEnvironmentResource();return}this.assetLoader.load(this.environmentUrl);}unloadEnvironmentResource(){this.assetLoader&&this.environmentResource&&this.environmentUrl&&(this.assetLoader.unload(this.environmentUrl),this.environmentResource=null);}constructor(e,t){this.fileResources=new Map,this.cooldowns=new Map,this.environmentUrl=null,this.environmentResource=null,this.environmentRefCount=0,this.assetLoader=null,this.destroyed=false,this.cooldownTicks=100,this.lodLevels=t.lodLevels,this.assetFileUrl=e;let i=P.getDirectory(e);this.files=t.filenames.map(e=>({url:P.isRelativePath(e)?P.join(i,e):e,lodLevel:-1})),this.fileRefCounts=new Int32Array(this.files.length),t.environment&&(this.environmentUrl=P.isRelativePath(t.environment)?P.join(i,t.environment):t.environment);let s=[];this._extractLeafNodes(t.tree,s),this.nodes=s.map(e=>{let t=[];for(let i=0;ie.destroy()),this.splats.length=0,this.needsUpload.length=0,this.needsUploadIds.clear(),this.allocIdToSplat.clear(),this.boundsGroups.length=0;}computeAllocationDiff(e,t){for(let i=0;i0&&r.length===n)for(let e=0;e0&&(SO.push(e),SF.push(t))):t>0&&(SO.push(e),SF.push(t));}applyAllocations(e,t,i){let s=false;if(SN.length>0||SF.length>0){s=t.updateAllocation(SN,SF);for(let e=0;e.3){let e=t.defrag(r);if(e.size>0)for(let[t,s]of i)e.has(s)&&SO.push(t);}let a=t.capacity;this.textureSize=a>0?Math.ceil(Math.sqrt(a)):1;let n=SO.length>0?new Set(SO):null;return SM.clear(),SO.length=0,SF.length=0,SN.length=0,{fullRebuild:s,changedAllocIds:n}}assignSplatOffsets(e,t,i,s){let r=0,a=0;for(let n=0;n0?c:1;let d=i,u=[];if(c>0&&l.length===c)for(let e=0;e0&&(o.setLayout(u),d)&&(this.needsUpload.push(o),i))for(let e=0;e; -@group(0) @binding(1) var sortKeys: array; -struct SortKeyUniforms { - cameraPosition: vec3f, - elementCount: u32, - cameraDirection: vec3f, - numBits: u32, - textureSize: u32, - minDist: f32, - invRange: f32, - numWorkgroupsX: u32, - numBins: u32 -}; -@group(0) @binding(2) var uniforms: SortKeyUniforms; +`;var FR=2.5,qk=2,bK=200,DK=16384,$k=16,Zk=65535,NR=8,Qk=new W,Jk=new Float32Array(16),ez=new Float32Array(16),tz=new W,SE=new F,xE=new Float32Array(3),vE=class extends mh{constructor(e,s,i,r,a){super(e,s,i,r,a);n(this,"_mainSet");n(this,"_pickSet",null);n(this,"framePass");n(this,"tileComposite");n(this,"_needsFramePassRegister",!1);n(this,"_textureSize",0);n(this,"_minPixelSize",2);n(this,"_minContribution",3);n(this,"_alphaClip",.3);n(this,"_alphaClipForward",f_);n(this,"_exposure",1);n(this,"_numSplats",0);n(this,"_compactedSplatIds",null);n(this,"_sortElementCountBuffer",null);n(this,"_projCacheBuffer",null);n(this,"_tileEntriesBuffer",null);n(this,"_pairBuffer",null);n(this,"_countersBuffer",null);n(this,"_splatPairStartBuffer",null);n(this,"_splatPairCountBuffer",null);n(this,"_largeSplatIdsBuffer",null);n(this,"_largeSplatIdsCapacity",DK);n(this,"_allocatedLargeSplatCapacity",0);n(this,"_allocatedSplatCapacity",0);n(this,"_allocatedEntryCapacity",0);n(this,"_tileEntryMultiplier",FR);n(this,"_lastBufferSubmitVersion",-1);n(this,"_lastReadbackEntryCount",-1);n(this,"_shrinkFrameCount",0);n(this,"_fisheye",0);n(this,"_dataSource");n(this,"_placeEntriesShader");n(this,"_placeEntriesBindGroupFormat");n(this,"_placeEntryPrepShader");n(this,"_placeEntryPrepBindGroupFormat");n(this,"_placeEntryPrepDispatchBuffer",null);n(this,"_placeEntryPrepCompute",null);n(this,"_largeSplatShader");n(this,"_largeSplatBindGroupFormat");n(this,"_largeSplatPrepShader");n(this,"_largeSplatPrepBindGroupFormat");n(this,"_largeSplatDispatchBuffer",null);n(this,"_largeSplatPrepCompute",null);n(this,"_largePlaceEntriesShader");n(this,"_largePlaceEntriesBindGroupFormat");n(this,"_classifyShader");n(this,"_classifyBindGroupFormat");n(this,"_sortShader");n(this,"_sortBindGroupFormat");n(this,"_bucketSortShader");n(this,"_bucketSortBindGroupFormat");n(this,"_copyShader");n(this,"_copyBindGroupFormat");n(this,"_chunkSortShader");n(this,"_chunkSortBindGroupFormat");n(this,"_lastDrawSlot",0);n(this,"_lastNumTilesX",0);this._dataSource=a,this._createSharedShaders(),this._mainSet=this._createDispatchSet(!1),this.framePass=new fE(this);let o=i.camera;this.tileComposite=new mE(e,s,l=>{let h=this.renderMode??0;return o.camera===l&&(h&Fs)!==0&&this._mainSet._rasterizeTileListBuffer!==null})}setDataSource(e){this._dataSource=e}destroy(){this._unregisterFramePass(),this.renderMode&&this.renderMode&Fs&&this.layer.removeMeshInstances([this.tileComposite.meshInstance],!0),this._mainSet.destroy(),this._pickSet?.destroy(),this._placeEntriesShader.destroy(),this._placeEntriesBindGroupFormat.destroy(),this._placeEntryPrepShader.destroy(),this._placeEntryPrepBindGroupFormat.destroy(),this._placeEntryPrepDispatchBuffer?.destroy(),this._largeSplatShader.destroy(),this._largeSplatBindGroupFormat.destroy(),this._largeSplatPrepShader.destroy(),this._largeSplatPrepBindGroupFormat.destroy(),this._largeSplatDispatchBuffer?.destroy(),this._largePlaceEntriesShader.destroy(),this._largePlaceEntriesBindGroupFormat.destroy(),this._classifyShader.destroy(),this._classifyBindGroupFormat.destroy(),this._sortShader.destroy(),this._sortBindGroupFormat.destroy(),this._bucketSortShader.destroy(),this._bucketSortBindGroupFormat.destroy(),this._copyShader.destroy(),this._copyBindGroupFormat.destroy(),this._chunkSortShader.destroy(),this._chunkSortBindGroupFormat.destroy(),this._projCacheBuffer?.destroy(),this._depthBuffer?.destroy(),this._tileEntriesBuffer?.destroy(),this._pairBuffer?.destroy(),this._countersBuffer?.destroy(),this._splatPairStartBuffer?.destroy(),this._splatPairCountBuffer?.destroy(),this._largeSplatIdsBuffer?.destroy(),this.tileComposite.destroy(),super.destroy()}get material(){return this.tileComposite.material}setRenderMode(e){let i=((this.renderMode??0)&Fs)!==0,r=(e&Fs)!==0;!i&&r&&(this.layer.addMeshInstances([this.tileComposite.meshInstance],!0),this._registerFramePass()),i&&!r&&(this.layer.removeMeshInstances([this.tileComposite.meshInstance],!0),this._unregisterFramePass()),super.setRenderMode(e)}frameUpdate(e,s,i){this._needsFramePassRegister&&this._registerFramePass(),this._minPixelSize=e.minPixelSize,this._minContribution=e.minContribution,this._alphaClip=e.alphaClip,this._alphaClipForward=e.alphaClipForward,this._exposure=s??1,this._fisheye=e.fisheye,this._fogParams=i??null,this._debugMode=e.debug;let r=this._dataSource.format.hash;r!==this._formatHash&&(this._formatHash=r,this._invalidateCountCompute())}setCompactedData(e,s,i,r){this._compactedSplatIds=e,this._sortElementCountBuffer=s,this._textureSize=i,this._numSplats=r}_registerFramePass(){let e=this.cameraNode.camera?.camera;e?(e.beforePasses.includes(this.framePass)||e.beforePasses.push(this.framePass),this._needsFramePassRegister=!1):this._needsFramePassRegister=!0}_unregisterFramePass(){this._needsFramePassRegister=!1;let e=this.cameraNode.camera?.camera;if(e){let s=e.beforePasses.indexOf(this.framePass);s!==-1&&e.beforePasses.splice(s,1)}}resizeOutputTexture(e,s){this._mainSet.resizeOutputTextures(e,s)}_ensureSharedBuffers(e){let s=this.device,i=s.submitVersion!==this._lastBufferSubmitVersion,r=this._lastReadbackEntryCount;if(r!==-1){this._lastReadbackEntryCount=-1;let h=this._allocatedEntryCapacity;if(h>0&&r=bK&&e>0){let f=Math.max(FR,r/e*qk);this._tileEntryMultiplier=Math.max(f,this._tileEntryMultiplier*.9),this._shrinkFrameCount=0}}if(!i)return;e>this._allocatedSplatCapacity&&(this._projCacheBuffer?.destroy(),this._depthBuffer?.destroy(),this._splatPairStartBuffer?.destroy(),this._splatPairCountBuffer?.destroy(),this._allocatedSplatCapacity=e,this._projCacheBuffer=new Ee(s,e*u_*4),this._depthBuffer=new Ee(s,e*4),this._splatPairStartBuffer=new Ee(s,e*4),this._splatPairCountBuffer=new Ee(s,e*4)),this._countersBuffer||(this._countersBuffer=new Ee(s,8,12)),this._largeSplatIdsCapacity>this._allocatedLargeSplatCapacity&&(this._largeSplatIdsBuffer?.destroy(),this._allocatedLargeSplatCapacity=this._largeSplatIdsCapacity,this._largeSplatIdsBuffer=new Ee(s,this._largeSplatIdsCapacity*4));let a=Math.ceil(e*this._tileEntryMultiplier),o=a>this._allocatedEntryCapacity,l=this._allocatedEntryCapacity>0&&a*2Zk){let U=Math.sqrt(Zk/(l*h));l=Math.max(1,Math.floor(l*U)),h=Math.max(1,Math.floor(h*U))}let f=l*h;this._ensureSharedBuffers(a),e.ensureTileBuffers(f);let u=this._allocatedEntryCapacity,d=this._dataSource,p=this.cameraNode.camera,m=p.camera,_=m.viewMatrix,S=!!p.renderTarget?.flipY,g=o.isWebGPU;Qk.mul2(Bs.applyShaderProjectionTransform(m.projectionMatrix,tz,S,g),_),Jk.set(Qk.data),ez.set(_.data);let T=s*tz.data[0],C=r?this._alphaClip:Math.max(f_,this._alphaClipForward);this.fisheyeProj.update(this._fisheye,p.fov,m.projectionMatrix);let v=this.fisheyeProj.enabled,E=(U,L)=>this._createCountShaderAndFormat(U,L),y=e.getCountCompute(v,E);this._placeEntryPrepCompute.setParameter("sortElementCount",this._sortElementCountBuffer),this._placeEntryPrepCompute.setParameter("dispatchArgs",this._placeEntryPrepDispatchBuffer),this._placeEntryPrepCompute.setupDispatch(1,1,1),o.computeDispatch([this._placeEntryPrepCompute],"GSplatLocalDispatchPrep"),e._tileSplatCountsBuffer.clear(),this._countersBuffer.clear(),y.setParameter("compactedSplatIds",this._compactedSplatIds),y.setParameter("sortElementCount",this._sortElementCountBuffer),y.setParameter("projCache",this._projCacheBuffer),y.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),y.setParameter("pairBuffer",this._pairBuffer),y.setParameter("countersBuffer",this._countersBuffer),y.setParameter("splatPairStart",this._splatPairStartBuffer),y.setParameter("splatPairCount",this._splatPairCountBuffer),y.setParameter("largeSplatIds",this._largeSplatIdsBuffer),y.setParameter("depthBuffer",this._depthBuffer);for(let U of d.format.streams)y.setParameter(U.name,d.getTexture(U.name));for(let U of d.format.extraStreams)y.setParameter(U.name,d.getTexture(U.name));if(y.setParameter("splatTextureSize",this._textureSize),y.setParameter("numTilesX",l),y.setParameter("numTilesY",h),y.setParameter("viewProj",Jk),y.setParameter("viewMatrix",ez),y.setParameter("focal",T),y.setParameter("viewportWidth",s),y.setParameter("viewportHeight",i),y.setParameter("nearClip",m.nearClip),y.setParameter("farClip",m.farClip),y.setParameter("minPixelSize",this._minPixelSize*.5),y.setParameter("isOrtho",m.projection===ni?1:0),y.setParameter("exposure",this._exposure),y.setParameter("alphaClip",C),y.setParameter("minContribution",this._minContribution),v){let U=this.fisheyeProj;y.setParameter("fisheye_k",U.k),y.setParameter("fisheye_inv_k",U.invK),y.setParameter("fisheye_projMat00",U.projMat00),y.setParameter("fisheye_projMat11",U.projMat11)}y.setupIndirectDispatch(0,this._placeEntryPrepDispatchBuffer),o.computeDispatch([y],r?"GSplatPickTileCount":"GSplatLocalTileCount"),this._largeSplatPrepCompute.setParameter("countersBuffer",this._countersBuffer),this._largeSplatPrepCompute.setParameter("dispatchArgs",this._largeSplatDispatchBuffer),this._largeSplatPrepCompute.setParameter("largeSplatIds",this._largeSplatIdsBuffer),this._largeSplatPrepCompute.setupDispatch(1,1,1),o.computeDispatch([this._largeSplatPrepCompute],r?"GSplatPickLargeSplatPrep":"GSplatLocalLargeSplatPrep"),e.largeSplatCompute.setParameter("projCache",this._projCacheBuffer),e.largeSplatCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.largeSplatCompute.setParameter("pairBuffer",this._pairBuffer),e.largeSplatCompute.setParameter("countersBuffer",this._countersBuffer),e.largeSplatCompute.setParameter("splatPairStart",this._splatPairStartBuffer),e.largeSplatCompute.setParameter("splatPairCount",this._splatPairCountBuffer),e.largeSplatCompute.setParameter("largeSplatIds",this._largeSplatIdsBuffer),e.largeSplatCompute.setParameter("numTilesX",l),e.largeSplatCompute.setParameter("numTilesY",h),e.largeSplatCompute.setParameter("viewportWidth",s),e.largeSplatCompute.setParameter("viewportHeight",i),e.largeSplatCompute.setParameter("alphaClip",C),e.largeSplatCompute.setupIndirectDispatch(0,this._largeSplatDispatchBuffer),o.computeDispatch([e.largeSplatCompute],r?"GSplatPickLargeTileCount":"GSplatLocalLargeTileCount"),e.prefixSumKernel.resize(e._tileSplatCountsBuffer,f+1),e.prefixSumKernel.dispatch(o),e.placeEntriesCompute.setParameter("pairBuffer",this._pairBuffer),e.placeEntriesCompute.setParameter("splatPairStart",this._splatPairStartBuffer),e.placeEntriesCompute.setParameter("splatPairCount",this._splatPairCountBuffer),e.placeEntriesCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.placeEntriesCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.placeEntriesCompute.setParameter("sortElementCount",this._sortElementCountBuffer),e.placeEntriesCompute.setupIndirectDispatch(1,this._placeEntryPrepDispatchBuffer),o.computeDispatch([e.placeEntriesCompute],r?"GSplatPickPlaceEntries":"GSplatLocalPlaceEntries"),e.largePlaceEntriesCompute.setParameter("pairBuffer",this._pairBuffer),e.largePlaceEntriesCompute.setParameter("splatPairStart",this._splatPairStartBuffer),e.largePlaceEntriesCompute.setParameter("splatPairCount",this._splatPairCountBuffer),e.largePlaceEntriesCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.largePlaceEntriesCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.largePlaceEntriesCompute.setParameter("largeSplatIds",this._largeSplatIdsBuffer),e.largePlaceEntriesCompute.setParameter("countersBuffer",this._countersBuffer),e.largePlaceEntriesCompute.setupIndirectDispatch(0,this._largeSplatDispatchBuffer),o.computeDispatch([e.largePlaceEntriesCompute],r?"GSplatPickLargePlaceEntries":"GSplatLocalLargePlaceEntries"),e._tileListCountsBuffer.clear(),e._totalChunksBuffer.clear(),e._chunkSortIndirectBuffer.clear();let P=o.getIndirectDispatchSlot(3),A=o.getIndirectDrawSlot(1);e.classifyCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.classifyCompute.setParameter("smallTileList",e._smallTileListBuffer),e.classifyCompute.setParameter("largeTileList",e._largeTileListBuffer),e.classifyCompute.setParameter("rasterizeTileList",e._rasterizeTileListBuffer),e.classifyCompute.setParameter("tileListCounts",e._tileListCountsBuffer),e.classifyCompute.setParameter("indirectDispatchArgs",o.indirectDispatchBuffer),e.classifyCompute.setParameter("largeTileOverflowBases",e._largeTileOverflowBasesBuffer),e.classifyCompute.setParameter("indirectDrawArgs",o.indirectDrawBuffer),e.classifyCompute.setParameter("numTiles",f),e.classifyCompute.setParameter("dispatchSlotOffset",P*3),e.classifyCompute.setParameter("bufferCapacity",u),e.classifyCompute.setParameter("maxWorkgroupsPerDim",o.limits.maxComputeWorkgroupsPerDimension||65535),e.classifyCompute.setParameter("drawSlot",A),e.classifyCompute.setupDispatch(1,1,1),o.computeDispatch([e.classifyCompute],r?"GSplatPickClassify":"GSplatLocalClassify"),e.bucketSortCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.bucketSortCompute.setParameter("largeTileOverflowBases",e._largeTileOverflowBasesBuffer),e.bucketSortCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.bucketSortCompute.setParameter("depthBuffer",this._depthBuffer),e.bucketSortCompute.setParameter("largeTileList",e._largeTileListBuffer),e.bucketSortCompute.setParameter("chunkRanges",e._chunkRangesBuffer),e.bucketSortCompute.setParameter("totalChunks",e._totalChunksBuffer),e.bucketSortCompute.setParameter("tileListCounts",e._tileListCountsBuffer),e.bucketSortCompute.setParameter("bufferCapacity",u),e.bucketSortCompute.setParameter("maxChunks",f*NR),e.bucketSortCompute.setupIndirectDispatch(P+1),o.computeDispatch([e.bucketSortCompute],r?"GSplatPickBucketSort":"GSplatLocalBucketSort"),e.copyCompute.setParameter("totalChunks",e._totalChunksBuffer),e.copyCompute.setParameter("chunkSortIndirect",e._chunkSortIndirectBuffer),e.copyCompute.setParameter("maxChunks",f*NR),e.copyCompute.setParameter("maxWorkgroupsPerDim",o.limits.maxComputeWorkgroupsPerDimension||65535),e.copyCompute.setupDispatch(1,1,1),o.computeDispatch([e.copyCompute],r?"GSplatPickCopy":"GSplatLocalCopy"),e.sortCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.sortCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.sortCompute.setParameter("depthBuffer",this._depthBuffer),e.sortCompute.setParameter("smallTileList",e._smallTileListBuffer),e.sortCompute.setParameter("tileListCounts",e._tileListCountsBuffer),e.sortCompute.setupIndirectDispatch(P),o.computeDispatch([e.sortCompute],r?"GSplatPickTileSort":"GSplatLocalTileSort"),e.chunkSortCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.chunkSortCompute.setParameter("depthBuffer",this._depthBuffer),e.chunkSortCompute.setParameter("chunkRanges",e._chunkRangesBuffer),e.chunkSortCompute.setParameter("totalChunks",e._totalChunksBuffer),e.chunkSortCompute.setParameter("maxChunks",f*NR),e.chunkSortCompute.setupIndirectDispatch(0,e._chunkSortIndirectBuffer),o.computeDispatch([e.chunkSortCompute],r?"GSplatPickChunkSort":"GSplatLocalChunkSort");let I=m.shaderParams.sceneDepthMapLinear?o.scope.resolve("uSceneDepthMap").value:null,D=!r&&I,O=this._fogParams,G=O&&O.type!==Mi?O.type:"none",M=!r&&this._debugMode===Ep,H=e.getRasterizeCompute(r,D,G,M);H.setParameter("screenWidth",s),H.setParameter("screenHeight",i),H.setParameter("numTilesX",l),H.setParameter("nearClip",m.nearClip),H.setParameter("farClip",m.farClip),H.setParameter("alphaClip",C),G!=="none"&&(SE.linear(O.color),xE[0]=SE.r,xE[1]=SE.g,xE[2]=SE.b,H.setParameter("fog_color",xE),H.setParameter("fog_start",O.start),H.setParameter("fog_end",O.end),H.setParameter("fog_density",O.density)),H.setParameter("tileEntries",this._tileEntriesBuffer),H.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),H.setParameter("projCache",this._projCacheBuffer),H.setParameter("rasterizeTileList",e._rasterizeTileListBuffer),H.setParameter("tileListCounts",e._tileListCountsBuffer),H.setParameter("depthBuffer",this._depthBuffer),r?(H.setParameter("pickIdTexture",e.pickIdTexture),H.setParameter("pickDepthTexture",e.pickDepthTexture)):(H.setParameter("outputTexture",e.outputTexture),D&&H.setParameter("sceneDepthMap",I)),H.setupIndirectDispatch(P+2),o.computeDispatch([H],r?"GSplatPickRasterize":"GSplatLocalRasterize"),this._lastDrawSlot=A,this._lastNumTilesX=l,this._scheduleReadback(a,f,e)}_scheduleReadback(e,s,i){if(e===0)return;let r=e,a=i._tileSplatCountsBuffer.read(s*4,4),o=i._tileListCountsBuffer.read(12,4),l=this._countersBuffer.read(4,4);Promise.all([a,o,l]).then(([h,f,u])=>{let d=new Uint32Array(h.buffer,h.byteOffset,1)[0],p=new Uint32Array(f.buffer,f.byteOffset,1)[0],m=d+p;r>0&&(this._tileEntryMultiplier=Math.max(this._tileEntryMultiplier,m/r*qk),this._tileEntryMultiplier=Math.max(this._tileEntryMultiplier,FR)),this._lastReadbackEntryCount=m;let _=new Uint32Array(u.buffer,u.byteOffset,1)[0];_>this._largeSplatIdsCapacity&&(this._largeSplatIdsCapacity=Math.ceil(_*1.2))}).catch(()=>{})}_invalidateCountCompute(){this._mainSet.destroyCountResources(),this._pickSet?.destroyCountResources()}_createCommonIncludes(){let e=new Map;return e.set("gsplatCommonCS",dE),e.set("gsplatTileIntersectCS",pE),e}_createBitonicIncludes(){let e=new Map;return e.set("gsplatLocalBitonicCS",Kk),e}_createSharedShaders(){let e=this.device;this._placeEntriesBindGroupFormat=new Ue(e,[new K("pairBuffer",X,!0),new K("splatPairStart",X,!0),new K("splatPairCount",X,!0),new K("tileSplatCounts",X,!0),new K("tileEntries",X),new K("sortElementCount",X,!0)]),this._placeEntriesShader=new Be(e,{name:"GSplatLocalPlaceEntries",shaderLanguage:se,cshader:zk,computeBindGroupFormat:this._placeEntriesBindGroupFormat});{let s=e.limits.maxComputeWorkgroupsPerDimension||65535,i=new Map;i.set("{MAX_DIM}",s.toString()),i.set("{SPLATS_PER_WG}","256"),i.set("{SPLATS_PER_WG_MINUS_1}","255"),this._placeEntryPrepBindGroupFormat=new Ue(e,[new K("sortElementCount",X,!0),new K("dispatchArgs",X)]),this._placeEntryPrepShader=new Be(e,{name:"GSplatLocalPlaceEntryPrep",shaderLanguage:se,cshader:Nk,cdefines:i,computeBindGroupFormat:this._placeEntryPrepBindGroupFormat}),this._placeEntryPrepDispatchBuffer=new Ee(e,24,256),this._placeEntryPrepCompute=new Ye(e,this._placeEntryPrepShader)}{let s=this._createCommonIncludes(),i=new Xe(e,[new Y("numTilesX",pe),new Y("numTilesY",pe),new Y("viewportWidth",Te),new Y("viewportHeight",Te),new Y("alphaClip",Te)]);this._largeSplatBindGroupFormat=new Ue(e,[new K("projCache",X,!0),new K("tileSplatCounts",X),new K("pairBuffer",X),new K("countersBuffer",X),new K("splatPairStart",X),new K("splatPairCount",X),new K("largeSplatIds",X,!0),new Qe("uniforms",X)]);let r=new Map;r.set("{CACHE_STRIDE}",u_.toString()),this._largeSplatShader=new Be(e,{name:"GSplatLocalTileCountLarge",shaderLanguage:se,cshader:kk,cincludes:s,cdefines:r,computeBindGroupFormat:this._largeSplatBindGroupFormat,computeUniformBufferFormats:{uniforms:i}})}{let s=e.limits.maxComputeWorkgroupsPerDimension||65535,i=new Map;i.set("{MAX_DIM}",s.toString()),this._largeSplatPrepBindGroupFormat=new Ue(e,[new K("countersBuffer",X,!0),new K("dispatchArgs",X),new K("largeSplatIds",X,!0)]),this._largeSplatPrepShader=new Be(e,{name:"GSplatLocalLargeSplatPrep",shaderLanguage:se,cshader:Bk,cdefines:i,computeBindGroupFormat:this._largeSplatPrepBindGroupFormat}),this._largeSplatDispatchBuffer=new Ee(e,12,256),this._largeSplatPrepCompute=new Ye(e,this._largeSplatPrepShader)}this._largePlaceEntriesBindGroupFormat=new Ue(e,[new K("pairBuffer",X,!0),new K("splatPairStart",X,!0),new K("splatPairCount",X,!0),new K("tileSplatCounts",X,!0),new K("tileEntries",X),new K("largeSplatIds",X,!0),new K("countersBuffer",X,!0)]),this._largePlaceEntriesShader=new Be(e,{name:"GSplatLocalPlaceEntriesLarge",shaderLanguage:se,cshader:Gk,computeBindGroupFormat:this._largePlaceEntriesBindGroupFormat});{let s=new Xe(e,[new Y("numTiles",pe),new Y("dispatchSlotOffset",pe),new Y("bufferCapacity",pe),new Y("maxWorkgroupsPerDim",pe),new Y("drawSlot",pe)]);this._classifyBindGroupFormat=new Ue(e,[new K("tileSplatCounts",X,!0),new K("smallTileList",X),new K("largeTileList",X),new K("rasterizeTileList",X),new K("tileListCounts",X),new K("indirectDispatchArgs",X),new K("largeTileOverflowBases",X),new Qe("uniforms",X),new K("indirectDrawArgs",X)]),this._classifyShader=new Be(e,{name:"GSplatLocalClassify",shaderLanguage:se,cshader:Hk,computeBindGroupFormat:this._classifyBindGroupFormat,computeUniformBufferFormats:{uniforms:s}})}this._sortBindGroupFormat=new Ue(e,[new K("tileEntries",X),new K("tileSplatCounts",X,!0),new K("depthBuffer",X,!0),new K("smallTileList",X,!0),new K("tileListCounts",X,!0)]),this._sortShader=new Be(e,{name:"GSplatLocalTileSort",shaderLanguage:se,cshader:Vk,cincludes:this._createBitonicIncludes(),computeBindGroupFormat:this._sortBindGroupFormat});{let s=new Xe(e,[new Y("bufferCapacity",pe),new Y("maxChunks",pe)]);this._bucketSortBindGroupFormat=new Ue(e,[new K("tileEntries",X),new K("largeTileOverflowBases",X,!0),new K("tileSplatCounts",X,!0),new K("depthBuffer",X,!0),new K("largeTileList",X,!0),new K("chunkRanges",X),new K("totalChunks",X),new K("tileListCounts",X,!0),new Qe("uniforms",X)]),this._bucketSortShader=new Be(e,{name:"GSplatLocalBucketSort",shaderLanguage:se,cshader:Wk,computeBindGroupFormat:this._bucketSortBindGroupFormat,computeUniformBufferFormats:{uniforms:s}})}{let s=new Xe(e,[new Y("maxChunks",pe),new Y("maxWorkgroupsPerDim",pe)]);this._copyBindGroupFormat=new Ue(e,[new K("totalChunks",X,!0),new K("chunkSortIndirect",X),new Qe("uniforms",X)]),this._copyShader=new Be(e,{name:"GSplatLocalCopy",shaderLanguage:se,cshader:Yk,computeBindGroupFormat:this._copyBindGroupFormat,computeUniformBufferFormats:{uniforms:s}})}{let s=new Xe(e,[new Y("maxChunks",pe)]);this._chunkSortBindGroupFormat=new Ue(e,[new K("tileEntries",X),new K("depthBuffer",X,!0),new K("chunkRanges",X,!0),new K("totalChunks",X,!0),new Qe("uniforms",X)]),this._chunkSortShader=new Be(e,{name:"GSplatLocalChunkSort",shaderLanguage:se,cshader:Xk,cincludes:this._createBitonicIncludes(),computeBindGroupFormat:this._chunkSortBindGroupFormat,computeUniformBufferFormats:{uniforms:s}})}}_createCountShaderAndFormat(e,s){let i=this.device,r=[new Y("splatTextureSize",pe),new Y("numTilesX",pe),new Y("numTilesY",pe),new Y("viewProj",as),new Y("viewMatrix",as),new Y("focal",Te),new Y("viewportWidth",Te),new Y("viewportHeight",Te),new Y("nearClip",Te),new Y("farClip",Te),new Y("minPixelSize",Te),new Y("isOrtho",pe),new Y("exposure",Te),new Y("alphaClip",Te),new Y("minContribution",Te)];s&&r.push(new Y("fisheye_k",Te),new Y("fisheye_inv_k",Te),new Y("fisheye_projMat00",Te),new Y("fisheye_projMat11",Te));let a=new Xe(i,r),o=this._dataSource.format,l=[new K("compactedSplatIds",X,!0),new K("sortElementCount",X,!0),new K("projCache",X),new K("tileSplatCounts",X),new Qe("uniforms",X),new K("pairBuffer",X),new K("countersBuffer",X),new K("splatPairStart",X),new K("splatPairCount",X),new K("largeSplatIds",X),new K("depthBuffer",X)],h=new Ue(i,[...l,...o.getComputeBindFormats()]),f=this._createCommonIncludes();f.set("gsplatComputeSplatCS",gE),f.set("gsplatFormatDeclCS",o.getComputeInputDeclarations(l.length)),f.set("gsplatFormatReadCS",o.getReadCode()),f.set("gsplatProjectCommonCS",uE);let u=new Map;u.set("{CACHE_STRIDE}",u_.toString()),s&&u.set("GSPLAT_FISHEYE",""),e&&u.set("PICK_MODE","");let d=o.getStream("dataColor");d&&d.format!==Rs&&u.set("GSPLAT_COLOR_FLOAT","");let p=s?"Fisheye":"";return{shader:new Be(i,{name:e?`GSplatLocalTileCountPick${p}`:`GSplatLocalTileCount${p}`,shaderLanguage:se,cshader:Uk,cincludes:f,cdefines:u,computeBindGroupFormat:h,computeUniformBufferFormats:{uniforms:a}}),bindGroupFormat:h}}_createDispatchSet(e){let s=this.device,i=new _E(s,e);return i.placeEntriesCompute=new Ye(s,this._placeEntriesShader,e?"GSplatPickPlaceEntries":"GSplatLocalPlaceEntries"),i.largeSplatCompute=new Ye(s,this._largeSplatShader,e?"GSplatPickLargeTileCount":"GSplatLocalLargeTileCount"),i.largePlaceEntriesCompute=new Ye(s,this._largePlaceEntriesShader,e?"GSplatPickLargePlaceEntries":"GSplatLocalLargePlaceEntries"),i.classifyCompute=new Ye(s,this._classifyShader,e?"GSplatPickClassify":"GSplatLocalClassify"),i.sortCompute=new Ye(s,this._sortShader,e?"GSplatPickTileSort":"GSplatLocalTileSort"),i.bucketSortCompute=new Ye(s,this._bucketSortShader,e?"GSplatPickBucketSort":"GSplatLocalBucketSort"),i.copyCompute=new Ye(s,this._copyShader,e?"GSplatPickCopy":"GSplatLocalCopy"),i.chunkSortCompute=new Ye(s,this._chunkSortShader,e?"GSplatPickChunkSort":"GSplatLocalChunkSort"),i}};var sz=` +#include "gsplatCommonCS" +#include "gsplatTileIntersectCS" +@group(0) @binding(0) var compactedSplatIds: array; +@group(0) @binding(1) var sortElementCount: array; +@group(0) @binding(2) var projCache: array; +@group(0) @binding(3) var sortKeys: array; +@group(0) @binding(4) var renderCounter: array>; struct BinWeight { base: f32, divider: f32 -}; -@group(0) @binding(3) var binWeights: array; -#ifdef USE_INDIRECT_SORT - @group(0) @binding(4) var compactedSplatIds: array; - @group(0) @binding(5) var sortElementCountBuf: array; -#endif -@compute @workgroup_size({WORKGROUP_SIZE_X}, {WORKGROUP_SIZE_Y}, 1) -fn main( - @builtin(global_invocation_id) global_id: vec3u, - @builtin(workgroup_id) w_id: vec3u, - @builtin(num_workgroups) w_dim: vec3u, - @builtin(local_invocation_index) TID: u32 -) { - #ifdef USE_INDIRECT_SORT - let WORKGROUP_ID = w_id.x + w_id.y * w_dim.x; - let gid = WORKGROUP_ID * ({WORKGROUP_SIZE_X}u * {WORKGROUP_SIZE_Y}u) + TID; - #else - let gid = global_id.x + global_id.y * ({WORKGROUP_SIZE_X} * uniforms.numWorkgroupsX); - #endif - - if (gid >= uniforms.elementCount) { - return; - } - #ifdef USE_INDIRECT_SORT - let visibleCount = sortElementCountBuf[0]; - if (gid >= visibleCount) { - return; - } - let splatId = compactedSplatIds[gid]; - #else - let splatId = gid; - #endif - - let textureSize = uniforms.textureSize; - let uv = vec2i(i32(splatId % textureSize), i32(splatId / textureSize)); - - let packed = textureLoad(dataTransformA, uv, 0); - let worldCenter = vec3f( - bitcast(packed.r), - bitcast(packed.g), - bitcast(packed.b) - ); - - var dist: f32; - - #ifdef RADIAL_SORT - let delta = worldCenter - uniforms.cameraPosition; - let radialDist = length(delta); - dist = (1.0 / uniforms.invRange) - radialDist - uniforms.minDist; - #else - let toSplat = worldCenter - uniforms.cameraPosition; - dist = dot(toSplat, uniforms.cameraDirection) - uniforms.minDist; - #endif - - let numBins = uniforms.numBins; - let d = dist * uniforms.invRange * f32(numBins); - let binFloat = clamp(d, 0.0, f32(numBins) - 0.001); - let bin = u32(binFloat); - let binFrac = binFloat - f32(bin); - - let sortKey = u32(binWeights[bin].base + binWeights[bin].divider * binFrac); - - sortKeys[gid] = sortKey; } -`,Sz=new ed,SV=new ef;class SG{destroy(){this.keysBuffer?.destroy(),this.binWeightsBuffer?.destroy(),this.compute?.shader?.destroy(),this.bindGroupFormat?.destroy(),this.bindGroupFormatIndirect?.destroy(),this.keysBuffer=null,this.binWeightsBuffer=null,this.compute=null,this.bindGroupFormat=null,this.bindGroupFormatIndirect=null,this.uniformBufferFormat=null;}_getCompute(e,t=false){if(!this.compute||this.computeRadialSort!==e||this.computeUseIndirectSort!==t){this.compute?.shader?.destroy();let i=`GSplatSortKeyCompute-${e?"Radial":"Linear"}${t?"-Indirect":""}`,s=new Map([["{WORKGROUP_SIZE_X}","16"],["{WORKGROUP_SIZE_Y}","16"]]);e&&s.set("RADIAL_SORT",""),t&&s.set("USE_INDIRECT_SORT","");let r=t?this.bindGroupFormatIndirect:this.bindGroupFormat,a=new r_(this.device,{name:i,shaderLanguage:tV,cshader:SU,cdefines:s,computeBindGroupFormat:r,computeUniformBufferFormats:{uniforms:this.uniformBufferFormat}});this.compute=new ar(this.device,a,i),this.computeRadialSort=e,this.computeUseIndirectSort=t;}return this.compute}_createBindGroupFormat(){let e=this.device;this.uniformBufferFormat=new sg(e,[new s_("cameraPosition",4),new s_("elementCount",26),new s_("cameraDirection",4),new s_("numBits",26),new s_("textureSize",26),new s_("minDist",2),new s_("invRange",2),new s_("numWorkgroupsX",26),new s_("numBins",26)]),this.bindGroupFormat=new ii(e,[new ie("dataTransformA",4,void 0,4,false),new t7("sortKeys",4,false),new t9("uniforms",4),new t7("binWeights",4,true)]),this.bindGroupFormatIndirect=new ii(e,[new ie("dataTransformA",4,void 0,4,false),new t7("sortKeys",4,false),new t9("uniforms",4),new t7("binWeights",4,true),new t7("compactedSplatIds",4,true),new t7("sortElementCountBuf",4,true)]);}_ensureCapacity(e){e>this.allocatedCount&&(this.keysBuffer?.destroy(),this.allocatedCount=e,this.keysBuffer=new rO(this.device,4*e,4));}generate(e,t,i,s,r,a,n){this._ensureCapacity(s);let o=Math.ceil(s/256);ar.calcDispatchSize(o,SV,this.device.limits.maxComputeWorkgroupsPerDimension||65535);let l=this._getCompute(i),h=t.getPosition(),c=t.getWorldTransform().getZ(Sz).normalize(),d=n-a,u=vK.computeCameraBin(i,a,d),f=this.binWeightsUtil.compute(u,1<0?1/d:1),l.setParameter("numWorkgroupsX",SV.x),l.setParameter("numBins",vK.NUM_BINS),l.setupDispatch(SV.x,SV.y,1),this.device.computeDispatch([l],"GSplatSortKeyCompute"),this.keysBuffer}generateIndirect(e,t,i,s,r,a,n,o,l,h){this._ensureCapacity(s);let c=this._getCompute(i,true),d=t.getPosition(),u=t.getWorldTransform().getZ(Sz).normalize(),f=n-a,p=vK.computeCameraBin(i,a,f),m=this.binWeightsUtil.compute(p,1<0?1/f:1);let _=Math.ceil(s/256);return ar.calcDispatchSize(_,SV,this.device.limits.maxComputeWorkgroupsPerDimension||65535),c.setParameter("numWorkgroupsX",SV.x),c.setParameter("numBins",vK.NUM_BINS),c.setupIndirectDispatch(h),this.device.computeDispatch([c],"GSplatSortKeyCompute-Indirect"),this.keysBuffer}constructor(e){this.allocatedCount=0,this.keysBuffer=null,this.binWeightsBuffer=null,this.compute=null,this.computeRadialSort=false,this.computeUseIndirectSort=false,this.bindGroupFormat=null,this.bindGroupFormatIndirect=null,this.uniformBufferFormat=null,this.cameraPositionData=new Float32Array(3),this.cameraDirectionData=new Float32Array(3),this.device=e,this.binWeightsUtil=new vK,this.binWeightsBuffer=new rO(e,2*vK.NUM_BINS*4,12),this._createBindGroupFormat();}}let SH=` +@group(0) @binding(5) var binWeights: array; +struct ProjectorUniforms { + splatTextureSize: u32, + numBins: u32, + isOrtho: u32, + pad0: u32, + viewProj: mat4x4f, + viewMatrix: mat4x4f, + cameraPosition: vec3f, + minPixelSize: f32, + cameraDirection: vec3f, + focal: f32, + viewportWidth: f32, + viewportHeight: f32, + nearClip: f32, + farClip: f32, + alphaClip: f32, + minContribution: f32, + minDist: f32, + invRange: f32, + #ifdef GSPLAT_FISHEYE + fisheye_k: f32, + fisheye_inv_k: f32, + fisheye_projMat00: f32, + fisheye_projMat11: f32, + #endif +} +@group(0) @binding(6) var uniforms: ProjectorUniforms; +#include "gsplatComputeSplatCS" +#include "gsplatFormatDeclCS" +#include "gsplatFormatReadCS" +#include "gsplatProjectCommonCS" +var wgCount: atomic; +var wgBase: u32; +@compute @workgroup_size(256) +fn main( + @builtin(global_invocation_id) gid: vec3u, + @builtin(num_workgroups) numWorkgroups: vec3u, + @builtin(local_invocation_index) localIdx: u32 +) { + if (localIdx == 0u) { + atomicStore(&wgCount, 0u); + } + workgroupBarrier(); + let threadIdx = gid.y * (numWorkgroups.x * 256u) + gid.x; + let numVisible = sortElementCount[0]; + var valid = false; + var clipPos: vec4f = vec4f(0.0); + var v1: vec2f = vec2f(0.0); + var v2: vec2f = vec2f(0.0); + var rgb: vec3f = vec3f(0.0); + var alpha: f32 = 0.0; + var pcId: u32 = 0u; + var sortKey: u32 = 0u; + let projected = projectSplatCommon( + threadIdx, + numVisible, + uniforms.alphaClip, + uniforms.minPixelSize, + uniforms.minContribution, + uniforms.viewMatrix, + uniforms.viewProj, + uniforms.focal, + uniforms.viewportWidth, + uniforms.viewportHeight, + uniforms.nearClip, + uniforms.farClip, + uniforms.isOrtho, + #ifdef GSPLAT_FISHEYE + uniforms.fisheye_k, + uniforms.fisheye_inv_k, + uniforms.fisheye_projMat00, + uniforms.fisheye_projMat11, + #endif + ); + if (projected.valid) { + let center = projected.center; + let opacity = projected.opacity; + let proj = projected.proj; + let mid = 0.5 * (proj.a + proj.c); + let radius = length(vec2f(0.5 * (proj.a - proj.c), proj.b)); + let lambda1 = mid + radius; + let lambda2 = max(mid - radius, 0.1); + let vmin = min(1024.0, min(uniforms.viewportWidth, uniforms.viewportHeight)); + let l1 = 2.0 * min(sqrt(2.0 * lambda1), vmin); + let l2 = 2.0 * min(sqrt(2.0 * lambda2), vmin); + let dir = normalize(vec2f(proj.b, lambda1 - proj.a)); + v1 = l1 * dir; + v2 = l2 * vec2f(dir.y, -dir.x); + #ifdef GSPLAT_FISHEYE + let viewCenter = uniforms.viewMatrix * vec4f(center, 1.0); + let neg_z = -viewCenter.z; + let ndcX = proj.screen.x / uniforms.viewportWidth * 2.0 - 1.0; + let ndcY = proj.screen.y / uniforms.viewportHeight * 2.0 - 1.0; + let depthNdc = clamp( + (neg_z - uniforms.nearClip) / (uniforms.farClip - uniforms.nearClip), + 0.0, 1.0 + ); + clipPos = vec4f(ndcX, ndcY, depthNdc, 1.0); + #else + clipPos = uniforms.viewProj * vec4f(center, 1.0); + clipPos.z = clamp(clipPos.z, 0.0, abs(clipPos.w)); + #endif + #ifdef RADIAL_SORT + let delta = center - uniforms.cameraPosition; + let radialDist = length(delta); + let dist = (1.0 / uniforms.invRange) - radialDist - uniforms.minDist; + #else + let toSplat = center - uniforms.cameraPosition; + let dist = dot(toSplat, uniforms.cameraDirection) - uniforms.minDist; + #endif + let d = dist * uniforms.invRange * f32(uniforms.numBins); + let binFloat = clamp(d, 0.0, f32(uniforms.numBins) - 0.001); + let bin = u32(binFloat); + let binFrac = binFloat - f32(bin); + sortKey = u32(binWeights[bin].base + binWeights[bin].divider * binFrac); + #ifdef PICK_MODE + pcId = loadPcId().r; + alpha = opacity; + #else + let color = getColor(); + rgb = max(color, vec3f(0.0)); + #if GSPLAT_AA + alpha = opacity * proj.aaFactor; + #else + alpha = opacity; + #endif + #endif + valid = true; + } + var localDst: u32 = 0u; + if (valid) { + localDst = atomicAdd(&wgCount, 1u); + } + workgroupBarrier(); + if (localIdx == 0u) { + let total = atomicLoad(&wgCount); + wgBase = atomicAdd(&renderCounter[0], total); + } + workgroupBarrier(); + if (valid) { + let dst = wgBase + localDst; + let base = dst * {CACHE_STRIDE}u; + projCache[base + 0u] = bitcast(clipPos.x); + projCache[base + 1u] = bitcast(clipPos.y); + projCache[base + 2u] = bitcast(clipPos.z); + projCache[base + 3u] = bitcast(clipPos.w); + projCache[base + 4u] = pack2x16float(v1); + projCache[base + 5u] = pack2x16float(v2); + #ifdef PICK_MODE + projCache[base + 6u] = pcId; + projCache[base + 7u] = pack2x16float(vec2f(0.0, alpha)); + #else + projCache[base + 6u] = pack2x16float(vec2f(rgb.x, rgb.y)); + projCache[base + 7u] = pack2x16float(vec2f(rgb.z, alpha)); + #endif + sortKeys[dst] = sortKey; + } +} +`;var iz=` +${Jc} +${_h} +${vm} +@group(0) @binding(0) var renderCounter: array; +@group(0) @binding(1) var indirectDrawArgs: array; +@group(0) @binding(2) var numSplatsBuf: array; +@group(0) @binding(3) var indirectDispatchArgs: array; +@group(0) @binding(4) var sortElementCountBuf: array; +struct WriteArgsUniforms { + drawSlot: u32, + indexCount: u32, + sortSlotBase: u32, + pad0: u32, + sortIndirectInfo: vec4 +}; +@group(0) @binding(5) var uniforms: WriteArgsUniforms; +@compute @workgroup_size(1) +fn main() { + let count = renderCounter[0]; + let instanceCount = (count + {INSTANCE_SIZE}u - 1u) / {INSTANCE_SIZE}u; + indirectDrawArgs[uniforms.drawSlot] = DrawIndexedIndirectArgs( + uniforms.indexCount, + instanceCount, + 0u, + 0, + 0u + ); + numSplatsBuf[0] = count; + sortElementCountBuf[0] = count; + writeSortIndirectArgs(uniforms.sortSlotBase, count, uniforms.sortIndirectInfo); +} +`;var LK=6*rt.instanceSize,MK=256,OK=new x,BR=new B,rz=new W,az=new Float32Array(16),oz=new Float32Array(16),nz=new W,TE=class{constructor(t){n(this,"device");n(this,"projCache",null);n(this,"sortKeys",null);n(this,"renderCounter",null);n(this,"binWeightsBuffer",null);n(this,"binWeightsUtil");n(this,"_projectorComputes",new Map);n(this,"_projectorBindGroupFormat",null);n(this,"_projectorUniformBufferFormat",null);n(this,"_projectorUniformBufferFormatFisheye",null);n(this,"_writeIndirectArgsCompute",null);n(this,"_writeArgsBindGroupFormat",null);n(this,"_writeArgsUniformBufferFormat",null);n(this,"_formatVersion",-1);n(this,"_allocatedCacheCount",0);n(this,"cameraPositionData",new Float32Array(3));n(this,"cameraDirectionData",new Float32Array(3));this.device=t,this.binWeightsUtil=new Cl,this.binWeightsBuffer=new Ee(t,Cl.NUM_BINS*2*4,12),this.renderCounter=new Ee(t,4,12),this._createUniformBufferFormats(),this._createWriteIndirectArgsCompute()}destroy(){this.projCache?.destroy(),this.sortKeys?.destroy(),this.renderCounter?.destroy(),this.binWeightsBuffer?.destroy();for(let t of this._projectorComputes.values())t.shader?.destroy();this._projectorComputes.clear(),this._projectorBindGroupFormat?.destroy(),this._writeIndirectArgsCompute?.shader?.destroy(),this._writeArgsBindGroupFormat?.destroy(),this.projCache=null,this.sortKeys=null,this.renderCounter=null,this.binWeightsBuffer=null,this._projectorBindGroupFormat=null,this._projectorUniformBufferFormat=null,this._projectorUniformBufferFormatFisheye=null,this._writeIndirectArgsCompute=null,this._writeArgsBindGroupFormat=null,this._writeArgsUniformBufferFormat=null}_createUniformBufferFormats(){let t=this.device,e=[new Y("splatTextureSize",pe),new Y("numBins",pe),new Y("isOrtho",pe),new Y("pad0",pe),new Y("viewProj",as),new Y("viewMatrix",as),new Y("cameraPosition",Kt),new Y("minPixelSize",Te),new Y("cameraDirection",Kt),new Y("focal",Te),new Y("viewportWidth",Te),new Y("viewportHeight",Te),new Y("nearClip",Te),new Y("farClip",Te),new Y("alphaClip",Te),new Y("minContribution",Te),new Y("minDist",Te),new Y("invRange",Te)];this._projectorUniformBufferFormat=new Xe(t,e),this._projectorUniformBufferFormatFisheye=new Xe(t,[...e.map(s=>new Y(s.name,s.type)),new Y("fisheye_k",Te),new Y("fisheye_inv_k",Te),new Y("fisheye_projMat00",Te),new Y("fisheye_projMat11",Te)]),this._writeArgsUniformBufferFormat=new Xe(t,[new Y("drawSlot",pe),new Y("indexCount",pe),new Y("sortSlotBase",pe),new Y("pad0",pe),new Y("sortIndirectInfo",Li)])}_createWriteIndirectArgsCompute(){let t=this.device;this._writeArgsBindGroupFormat=new Ue(t,[new K("renderCounter",X,!0),new K("indirectDrawArgs",X,!1),new K("numSplatsBuf",X,!1),new K("indirectDispatchArgs",X,!1),new K("sortElementCountBuf",X,!1),new Qe("uniforms",X)]);let e=new Map([["{INSTANCE_SIZE}",rt.instanceSize.toString()]]),s=new Be(t,{name:"GSplatProjectorWriteIndirectArgs",shaderLanguage:se,cshader:iz,cdefines:e,computeBindGroupFormat:this._writeArgsBindGroupFormat,computeUniformBufferFormats:{uniforms:this._writeArgsUniformBufferFormat}});this._writeIndirectArgsCompute=new Ye(t,s,"GSplatProjectorWriteIndirectArgs")}_destroyProjectorComputes(){for(let t of this._projectorComputes.values())t.shader?.destroy();this._projectorComputes.clear(),this._projectorBindGroupFormat?.destroy(),this._projectorBindGroupFormat=null}_projectorKey(t,e,s,i){return`${t?"r":"l"}${e?"p":""}${s?"f":""}${i?"a":""}`}_createProjectorCompute(t,e,s,i,r){let a=this.device,o=t.format,l=[new K("compactedSplatIds",X,!0),new K("sortElementCount",X,!0),new K("projCache",X),new K("sortKeys",X),new K("renderCounter",X),new K("binWeights",X,!0),new Qe("uniforms",X)];this._projectorBindGroupFormat||(this._projectorBindGroupFormat=new Ue(a,[...l,...o.getComputeBindFormats()]));let h=new Map;h.set("gsplatCommonCS",dE),h.set("gsplatTileIntersectCS",pE),h.set("gsplatComputeSplatCS",gE),h.set("gsplatFormatDeclCS",o.getComputeInputDeclarations(l.length)),h.set("gsplatFormatReadCS",o.getReadCode()),h.set("gsplatProjectCommonCS",uE);let f=new Map;f.set("{CACHE_STRIDE}",8 .toString()),e&&f.set("RADIAL_SORT",""),s&&f.set("PICK_MODE",""),i&&f.set("GSPLAT_FISHEYE",""),r&&f.set("GSPLAT_AA","");let u=o.getStream("dataColor");u&&u.format!==Rs&&f.set("GSPLAT_COLOR_FLOAT","");let d=`GSplatProjector${e?"Radial":"Linear"}${s?"Pick":""}${i?"Fisheye":""}${r?"Aa":""}`,p=i?this._projectorUniformBufferFormatFisheye:this._projectorUniformBufferFormat,m=new Be(a,{name:d,shaderLanguage:se,cshader:sz,cincludes:h,cdefines:f,computeBindGroupFormat:this._projectorBindGroupFormat,computeUniformBufferFormats:{uniforms:p}});return new Ye(a,m,d)}_getProjectorCompute(t,e,s=!1,i=!1,r=!1){let a=t.format;this._formatVersion!==a.extraStreamsVersion&&(this._destroyProjectorComputes(),this._formatVersion=a.extraStreamsVersion);let o=this._projectorKey(e,s,i,r),l=this._projectorComputes.get(o);return l||(l=this._createProjectorCompute(t,e,s,i,r),this._projectorComputes.set(o,l)),l}_ensureCapacity(t){t>this._allocatedCacheCount&&(this.projCache?.destroy(),this.sortKeys?.destroy(),this._allocatedCacheCount=t,this.projCache=new Ee(this.device,t*8*4),this.sortKeys=new Ee(this.device,t*4,4))}dispatch(t){let{workBuffer:e,cameraNode:s,compactedSplatIds:i,sortElementCountBuffer:r,totalCapacity:a,radialSort:o,numBits:l,minDist:h,maxDist:f,alphaClip:u,minPixelSize:d,minContribution:p,viewportWidth:m,viewportHeight:_,flipY:S,pickMode:g=!1,fisheyeProj:T,antiAlias:C=!1}=t,v=!!T?.enabled,E=C&&!g;this._ensureCapacity(a),this.renderCounter.clear();let y=this._getProjectorCompute(e,o,g,v,E),P=s.getPosition(),w=s.getWorldTransform().getZ(OK).normalize(),I=f-h,D=I>0?1/I:1,O=1<0&&(this._streams=new dl(e,!0),this._streams.textureDimensions.copy(s.streams.textureDimensions),this._streams.syncWithFormat(s.format)),this._streams?.getTexture(t)}get streams(){return this.parentPlacement?.streams??this._streams}ensureInstanceStreams(t){let e=this.resource;e?.format&&!this._streams&&e.format.instanceStreams.length>0&&(this._streams=new dl(t,!0),this._streams.textureDimensions.copy(e.streams.textureDimensions),this._streams.syncWithFormat(e.format))}};var UR=new W,FK=new x,NK=new x,gh=[],Lqe=new ge,BK=Math.tan(22.5*R.DEG_TO_RAD),Mqe=[new F(1,0,0),new F(0,1,0),new F(0,0,1),new F(1,1,0),new F(1,0,1)],kR=class{constructor(){n(this,"currentLod",-1);n(this,"optimalLod",-1);n(this,"worldDistance",0);n(this,"colorAccumulatedTranslation",0);n(this,"inst",null);n(this,"lods",null);n(this,"budgetBucket",0);n(this,"allocId",yE.get())}resetLod(){this.currentLod=-1,this.optimalLod=-1}},EE=class{constructor(t,e,s){n(this,"octree");n(this,"placement");n(this,"activePlacements",new Set);n(this,"dirtyModifiedPlacements",!1);n(this,"dirtyPlacementSetChanged",!1);n(this,"device");n(this,"nodeInfos");n(this,"filePlacements");n(this,"pending",new Set);n(this,"pendingDecrements",new Map);n(this,"removedCandidates",new Set);n(this,"rangeMin",0);n(this,"rangeMax",0);n(this,"previousPosition",new x);n(this,"needsLodUpdate",!1);n(this,"prefetchPending",new Set);n(this,"pendingVisibleAdds",new Map);n(this,"environmentPlacement",null);n(this,"_deviceLostEvent",null);n(this,"_lodMinDistThresholds",null);this.device=t,this.octree=e,this.placement=s,this.nodeInfos=new Array(e.nodes.length);for(let r=0;r0){let r=Math.min(s,e+i);for(let a=e;a<=r;a++){let o=t.lods[a].fileIndex;if(o!==-1&&this.octree.getFileResource(o))return a}for(let a=r;a>=e;a--)if(t.lods[a].fileIndex!==-1)return a}return e}prefetchNextLod(t,e,s){if(e===-1||s===-1)return;if(e===s){let r=t.lods[s].fileIndex;r!==-1&&(this.octree.ensureFileResource(r),this.octree.getFileResource(r)||this.prefetchPending.add(r));return}let i=Math.max(s,e-1);for(let r=i;r>=s;r--){let a=t.lods[r].fileIndex;if(a!==-1){this.octree.ensureFileResource(a),this.octree.getFileResource(a)||this.prefetchPending.add(a);break}}}updateLod(t,e){let s=this.octree.lodLevels-1,{lodBaseDistance:i,lodMultiplier:r}=this.placement,{lodRangeMin:a,lodRangeMax:o}=e,l=Math.max(0,Math.min(a??0,s)),h=Math.max(l,Math.min(o??s,s)),f=this.placement.node.getWorldTransform().getScale().x;this.evaluateNodeLods(t,s,i,r,l,h,e,f,!1),this.applyLodChanges(s,e)}_ensureLodMinDistThresholds(t,e,s){let i=t+1,r=this._lodMinDistThresholds;(!r||r.length=1&&(H=this._ensureLodMinDistThresholds(e,s,i));let U=f>0?rn/Math.sqrt(f):0;for(let L=0;LV&&(k=V);let q=w,re=P[N+1],te=P[N+4];qte&&(q=te);let j=I,oe=P[N+2],be=P[N+5];jbe&&(j=be);let qe=k-A,ot=q-w,Ve=j-I,Lt=Math.sqrt(qe*qe+ot*ot+Ve*Ve),Vs=Lt;if(u>1&&Lt>.01){let di=(D*qe+O*ot+G*Ve)/Lt;if(di<0){let de=1+-di*(u-1);Vs=Lt*de}}let ds=Vs*_,Cs;if(e===0||ds1&&dsa&&(Cs=a),b.optimalLod=Cs,b.worldDistance=ds*l,U>0&&Cs>=0){let di=Math.sqrt(b.worldDistance)*U>>>0;b.budgetBucket=di=0?a.lods[h].fileIndex:-1,d=f>=0?a.lods[f].fileIndex:-1,p=u!==-1,m=d!==-1,_=this.pendingDecrements.get(r);if(_&&_.newFileIndex!==d&&(this.filePlacements[_.newFileIndex]&&this.decrementFileRef(_.newFileIndex,r),p&&m?this.pendingDecrements.set(r,{oldFileIndex:_.oldFileIndex,newFileIndex:d}):this.pendingDecrements.delete(r)),!p&&m){let S=this.pendingVisibleAdds.get(r);S!==void 0&&S!==d&&(this.decrementFileRef(S,r),this.pendingVisibleAdds.delete(r)),this.incrementFileRef(d,r,f),this.filePlacements[d]?.resource?(o.currentLod=f,this.pendingVisibleAdds.delete(r)):this.pendingVisibleAdds.set(r,d)}else if(p&&!m){let S=this.pendingDecrements.get(r);S&&(this.decrementFileRef(S.newFileIndex,r),this.pendingDecrements.delete(r)),this.decrementFileRef(u,r),o.currentLod=-1,this.pendingVisibleAdds.delete(r)}else p&&m&&(this.incrementFileRef(d,r,f),this.filePlacements[d]?.resource?(this.decrementFileRef(u,r),this.pendingDecrements.delete(r),o.currentLod=f,this.pendingVisibleAdds.delete(r)):(this.pendingDecrements.set(r,{oldFileIndex:u,newFileIndex:d}),this.pendingVisibleAdds.delete(r)))}this.prefetchNextLod(a,f,l)}}incrementFileRef(t,e,s){if(t===-1)return;let i=this.filePlacements[t];i||(i=new bu(null,this.placement.node,s,null,this.placement),this.filePlacements[t]=i,this.removedCandidates.delete(t)||this.octree.incRefCount(t),this.addFilePlacement(t)||(this.octree.ensureFileResource(t),this.pending.add(t)));let o=this.octree.nodes[e].lods[s],l=new B(o.offset,o.offset+o.count-1);i.intervals.set(e,l),this.dirtyModifiedPlacements=!0}decrementFileRef(t,e){if(t===-1)return;let s=this.filePlacements[t];s&&s&&(s.intervals.delete(e),this.dirtyModifiedPlacements=!0,s.intervals.size===0&&(s.resource&&(this.activePlacements.delete(s),this.activePlacements.size===0&&(this.dirtyPlacementSetChanged=!0)),this.removedCandidates.add(t),this.filePlacements[t]=null,this.pending.delete(t)))}addFilePlacement(t){let e=this.octree.getFileResource(t);if(e){let s=this.filePlacements[t];if(s)return s.resource=e,this.activePlacements.size===0&&(this.dirtyPlacementSetChanged=!0),this.activePlacements.add(s),this.dirtyModifiedPlacements=!0,this.removedCandidates.delete(t),!0}return!1}testMoved(t){return this.placement.node.getPosition().distance(this.previousPosition)>t}updateMoved(){this.previousPosition.copy(this.placement.node.getPosition())}update(){if(this.placement.lodDirty&&(this.placement.lodDirty=!1,this.needsLodUpdate=!0),this.pending.size){for(let e of this.pending)if(this.octree.ensureFileResource(e),this.addFilePlacement(e)){gh.push(e);for(let[s,{oldFileIndex:i,newFileIndex:r}]of this.pendingDecrements)if(r===e){this.decrementFileRef(i,s),this.pendingDecrements.delete(s);let a=0,o=this.octree.nodes[s].lods;for(let l=0;l0&&(this.needsLodUpdate=!0);for(let e of gh)this.pending.delete(e);gh.length=0}if(this.pollPrefetchCompletions(),this.octree.environmentUrl&&!this.environmentPlacement){this.octree.ensureEnvironmentResource();let e=this.octree.environmentResource;e&&(this.environmentPlacement=new bu(e,this.placement.node,0,null,this.placement),this.environmentPlacement.aabb.copy(e.aabb),this.activePlacements.add(this.environmentPlacement),this.dirtyModifiedPlacements=!0,this.dirtyPlacementSetChanged=!0,e.releaseTextureSources?.())}let t=this.dirtyModifiedPlacements;return this.dirtyModifiedPlacements=!1,t}consumePlacementSetChanged(){let t=this.dirtyPlacementSetChanged;return this.dirtyPlacementSetChanged=!1,t}debugRender(t){}consumeNeedsLodUpdate(){let t=this.needsLodUpdate;return this.needsLodUpdate=!1,t}pollPrefetchCompletions(){if(this.prefetchPending.size){for(let t of this.prefetchPending)this.octree.ensureFileResource(t),this.octree.getFileResource(t)&&gh.push(t);gh.length>0&&(this.needsLodUpdate=!0);for(let t of gh)this.prefetchPending.delete(t);gh.length=0}}};var lz=new x,cz=new x,AE=class{constructor(t,e){n(this,"lods");n(this,"bounds",new ge);n(this,"boundingSphere",new Q);this.lods=t,lz.set(e.min[0],e.min[1],e.min[2]),cz.set(e.max[0],e.max[1],e.max[2]),this.bounds.setMinMax(lz,cz);let s=this.bounds.center,i=this.bounds.halfExtents,r=Math.sqrt(i.x*i.x+i.y*i.y+i.z*i.z);this.boundingSphere.set(s.x,s.y,s.z,r)}};var zR=[],CE=class{constructor(t,e){n(this,"nodes");n(this,"nodeBoundsMinMax");n(this,"files");n(this,"lodLevels");n(this,"assetFileUrl");n(this,"fileResources",new Map);n(this,"fileRefCounts");n(this,"cooldowns",new Map);n(this,"environmentUrl",null);n(this,"environmentResource",null);n(this,"environmentRefCount",0);n(this,"assetLoader",null);n(this,"destroyed",!1);n(this,"cooldownTicks",100);this.lodLevels=e.lodLevels,this.assetFileUrl=t;let s=xe.getDirectory(t);this.files=e.filenames.map(o=>({url:xe.isRelativePath(o)?xe.join(s,o):o,lodLevel:-1})),this.fileRefCounts=new Int32Array(this.files.length),e.environment&&(this.environmentUrl=xe.isRelativePath(e.environment)?xe.join(s,e.environment):e.environment);let i=[];this._extractLeafNodes(e.tree,i),this.nodes=i.map(o=>{let l=[];for(let h=0;h0&&(this.cooldowns.forEach((e,s)=>{e<=1?(this.fileRefCounts[s]===0&&this.unloadResource(s),zR.push(s)):this.cooldowns.set(s,e-1)}),zR.forEach(e=>this.cooldowns.delete(e)),zR.length=0)}ensureFileResource(t){if(this.fileResources.has(t))return;let e=this.files[t].url,s=this.assetLoader?.getResource(e);if(s){this.fileResources.set(t,s),s.releaseTextureSources?.(),this.fileRefCounts[t]===0&&this.cooldowns.set(t,this.cooldownTicks),this._traceLodCounts();return}this.assetLoader?.load(e)}incEnvironmentRefCount(){this.environmentRefCount++}decEnvironmentRefCount(){this.environmentRefCount--,this.environmentRefCount===0&&this.unloadEnvironmentResource()}ensureEnvironmentResource(){if(!this.assetLoader||!this.environmentUrl||this.environmentResource)return;let t=this.assetLoader.getResource(this.environmentUrl);if(t){this.environmentResource=t,this.environmentRefCount===0&&this.unloadEnvironmentResource();return}this.assetLoader.load(this.environmentUrl)}unloadEnvironmentResource(){this.assetLoader&&this.environmentResource&&this.environmentUrl&&(this.assetLoader.unload(this.environmentUrl),this.environmentResource=null)}};var d_=class{constructor(t,e,s){n(this,"aabb",new ge);n(this,"centersVersion",0);n(this,"octree");n(this,"data");this.octree=new CE(t,e),this.octree.assetLoader=s,this.aabb.setMinMax(new x(e.tree.bound.min),new x(e.tree.bound.max)),this.data=e,this.data.tree=null}destroy(){this.octree?.destroy(),this.octree=null}};var GR=new Set,Pl=[],p_=[],m_=[],PE=class{constructor(t,e,s,i,r){n(this,"version",0);n(this,"sortParametersSet",!1);n(this,"sortedBefore",!1);n(this,"splats",[]);n(this,"textureSize",0);n(this,"totalActiveSplats",0);n(this,"totalIntervals",0);n(this,"boundsGroups",[]);n(this,"pendingReleases",[]);n(this,"needsUpload",[]);n(this,"needsUploadIds",new Set);n(this,"allocIdToSplat",new Map);n(this,"fullRebuild",!1);if(this.version=e,this.splats=s,s.length===0){for(let[,l]of r)i.free(l);r.clear(),this.totalActiveSplats=0,this.totalIntervals=0,this.textureSize=1;return}this.computeAllocationDiff(s,r);let{fullRebuild:a,changedAllocIds:o}=this.applyAllocations(t,i,r);this.assignSplatOffsets(s,r,a,o),this.buildBoundsGroups(s)}destroy(){this.splats.forEach(t=>t.destroy()),this.splats.length=0,this.needsUpload.length=0,this.needsUploadIds.clear(),this.allocIdToSplat.clear(),this.boundsGroups.length=0}computeAllocationDiff(t,e){for(let s=0;s0&&r.length===o)for(let l=0;l0&&(Pl.push(t),p_.push(e))):e>0&&(Pl.push(t),p_.push(e))}applyAllocations(t,e,s){let i=!1;if(m_.length>0||p_.length>0){i=e.updateAllocation(m_,p_);for(let h=0;h.3){let h=e.defrag(a);if(h.size>0)for(let[f,u]of s)h.has(u)&&Pl.push(f)}let o=e.capacity;this.textureSize=o>0?Math.ceil(Math.sqrt(o)):1;let l=Pl.length>0?new Set(Pl):null;return GR.clear(),Pl.length=0,p_.length=0,m_.length=0,{fullRebuild:i,changedAllocIds:l}}assignSplatOffsets(t,e,s,i){let r=0,a=0;for(let o=0;o0?u:1;let d=s,p=[];if(u>0&&h.length===u)for(let m=0;m0&&(l.setLayout(p),d&&(this.needsUpload.push(l),s)))for(let m=0;m prefixSumBuffer: array; @group(0) @binding(1) var indirectDrawArgs: array; @group(0) @binding(2) var numSplatsBuf: array; @@ -15247,8 +15797,9 @@ ${v7} struct WriteArgsUniforms { drawSlot: u32, indexCount: u32, - dispatchSlotOffset: u32, - totalSplats: u32 + dispatchSlotBase: u32, + totalSplats: u32, + sortIndirectInfo: vec4 }; @group(0) @binding(5) var uniforms: WriteArgsUniforms; @compute @workgroup_size(1) @@ -15263,20 +15814,17 @@ fn main(@builtin(global_invocation_id) gid: vec3u) { 0u ); numSplatsBuf[0] = count; - let dispatchOffset = uniforms.dispatchSlotOffset; + let keygenSlot = uniforms.dispatchSlotBase; + let keygenOffset = keygenSlot * 3u; let keygenWorkgroupCount = (count + {KEYGEN_THREADS_PER_WORKGROUP}u - 1u) / {KEYGEN_THREADS_PER_WORKGROUP}u; let keygenDim = calcDispatch2D(keygenWorkgroupCount, {MAX_WORKGROUPS_PER_DIM}u); - indirectDispatchArgs[dispatchOffset + 0u] = keygenDim.x; - indirectDispatchArgs[dispatchOffset + 1u] = keygenDim.y; - indirectDispatchArgs[dispatchOffset + 2u] = 1u; - let sortWorkgroupCount = (count + {SORT_ELEMENTS_PER_WORKGROUP}u - 1u) / {SORT_ELEMENTS_PER_WORKGROUP}u; - let sortDim = calcDispatch2D(sortWorkgroupCount, {MAX_WORKGROUPS_PER_DIM}u); - indirectDispatchArgs[dispatchOffset + 3u] = sortDim.x; - indirectDispatchArgs[dispatchOffset + 4u] = sortDim.y; - indirectDispatchArgs[dispatchOffset + 5u] = 1u; + indirectDispatchArgs[keygenOffset + 0u] = keygenDim.x; + indirectDispatchArgs[keygenOffset + 1u] = keygenDim.y; + indirectDispatchArgs[keygenOffset + 2u] = 1u; + writeSortIndirectArgs(keygenSlot + 1u, count, uniforms.sortIndirectInfo); sortElementCountBuf[0] = count; } -`,SY=6*uj.instanceSize;class Sq{destroy(){this.compactedSplatIds?.destroy(),this.intervalsBuffer?.destroy(),this.countBuffer?.destroy(),this.prefixSumKernel?.destroy(),this.numSplatsBuffer?.destroy(),this.sortElementCountBuffer?.destroy(),this._destroyCullPass(),this._scatterCompute?.shader?.destroy(),this._scatterBindGroupFormat?.destroy(),this._writeIndirectArgsCompute?.shader?.destroy(),this._writeArgsBindGroupFormat?.destroy(),this.compactedSplatIds=null,this.intervalsBuffer=null,this.countBuffer=null,this.prefixSumKernel=null,this.numSplatsBuffer=null,this.sortElementCountBuffer=null,this._scatterCompute=null,this._scatterBindGroupFormat=null,this._writeIndirectArgsCompute=null,this._writeArgsBindGroupFormat=null,this._scatterUniformBufferFormat=null,this._writeArgsUniformBufferFormat=null;}_destroyCullPass(){this._cullComputePerspective?.shader?.destroy(),this._cullBindGroupFormatPerspective?.destroy(),this._cullComputePerspective=null,this._cullBindGroupFormatPerspective=null,this._cullComputeFisheye?.shader?.destroy(),this._cullBindGroupFormatFisheye?.destroy(),this._cullComputeFisheye=null,this._cullBindGroupFormatFisheye=null;}_createUniformBufferFormats(){let e=this.device;this._scatterUniformBufferFormat=new sg(e,[new s_("numIntervals",26),new s_("pad0",26),new s_("pad1",26),new s_("pad2",26)]),this._writeArgsUniformBufferFormat=new sg(e,[new s_("drawSlot",26),new s_("indexCount",26),new s_("dispatchSlotOffset",26),new s_("totalSplats",26)]);}_createCullPass(e){let t=this.device,i=e?"Fisheye":"",s=new ii(t,[new t9("uniforms",4),new t7("intervals",4,true),new t7("countBuffer",4,false),new t7("boundsBuffer",4,true),new t7("transformsBuffer",4,true)]),r=new Map([["{WORKGROUP_SIZE}","256"]]);e&&r.set("GSPLAT_FISHEYE","");let a=e?new sg(t,[new s_("cameraWorldPos",4),new s_("maxTheta",2),new s_("cameraForward",4),new s_("numIntervals",26)]):new sg(t,[new s_("frustumPlanes",5,6),new s_("numIntervals",26)]),n=new r_(t,{name:`GSplatIntervalCull${i}`,shaderLanguage:tV,cshader:SH,cdefines:r,computeBindGroupFormat:s,computeUniformBufferFormats:{uniforms:a}});return {compute:new ar(t,n,`GSplatIntervalCull${i}`),bindGroupFormat:s}}_getCullCompute(e){if(e){if(!this._cullComputeFisheye){let{compute:e,bindGroupFormat:t}=this._createCullPass(true);this._cullComputeFisheye=e,this._cullBindGroupFormatFisheye=t;}return this._cullComputeFisheye}if(!this._cullComputePerspective){let{compute:e,bindGroupFormat:t}=this._createCullPass(false);this._cullComputePerspective=e,this._cullBindGroupFormatPerspective=t;}return this._cullComputePerspective}_createScatterCompute(){let e=this.device;this._scatterBindGroupFormat=new ii(e,[new t9("uniforms",4),new t7("intervals",4,true),new t7("prefixSumBuffer",4,true),new t7("compactedOutput",4,false)]);let t=new r_(e,{name:"GSplatIntervalScatter",shaderLanguage:tV,cshader:SW,cdefines:new Map([["{WORKGROUP_SIZE}","256"]]),computeBindGroupFormat:this._scatterBindGroupFormat,computeUniformBufferFormats:{uniforms:this._scatterUniformBufferFormat}});this._scatterCompute=new ar(e,t,"GSplatIntervalScatter");}_createWriteIndirectArgsCompute(){let e=this.device;this._writeArgsBindGroupFormat=new ii(e,[new t7("prefixSumBuffer",4,true),new t7("indirectDrawArgs",4,false),new t7("numSplatsBuf",4,false),new t7("indirectDispatchArgs",4,false),new t7("sortElementCountBuf",4,false),new t9("uniforms",4)]);let t=new Map([["{INSTANCE_SIZE}",uj.instanceSize],["{KEYGEN_THREADS_PER_WORKGROUP}",256],["{SORT_ELEMENTS_PER_WORKGROUP}",dU],["{MAX_WORKGROUPS_PER_DIM}",e.limits.maxComputeWorkgroupsPerDimension||65535]]),i=new r_(e,{name:"GSplatIntervalWriteIndirectArgs",shaderLanguage:tV,cshader:SX,cdefines:t,computeBindGroupFormat:this._writeArgsBindGroupFormat,computeUniformBufferFormats:{uniforms:this._writeArgsUniformBufferFormat}});this._writeIndirectArgsCompute=new ar(e,i,"GSplatIntervalWriteIndirectArgs");}_ensureCapacity(e,t){t>this.allocatedCompactedCount&&(this.compactedSplatIds?.destroy(),this.allocatedCompactedCount=t,this.compactedSplatIds=new rO(this.device,4*t,4));let i=e+1;i>this.allocatedCountBufferSize&&(this.countBuffer?.destroy(),this.allocatedCountBufferSize=i,this.countBuffer=new rO(this.device,4*i),this.prefixSumKernel&&this.prefixSumKernel.destroyPasses());}uploadIntervals(e){if(e.version===this._uploadedVersion)return;this._uploadedVersion=e.version;let t=e.splats,i=e.totalIntervals;if(0===i)return;i>this.allocatedIntervalCount&&(this.intervalsBuffer?.destroy(),this.allocatedIntervalCount=i,this.intervalsBuffer=new rO(this.device,4*i*4,8));let s=new Uint32Array(4*i),r=0;for(let e=0;e0){let e=i.intervalNodeIndices;for(let t=0;t0?e[t/2]:0),s[r++]=0;}}else s[r++]=i.intervalOffsets[0],s[r++]=i.activeSplats,s[r++]=i.boundsBaseIndex,s[r++]=0;}this.intervalsBuffer.write(0,s,0,4*i);}dispatchCompact(e,t,i,s){if(0===t)return;this._ensureCapacity(t,i);let r=this._getCullCompute(s);r.setParameter("intervals",this.intervalsBuffer),r.setParameter("countBuffer",this.countBuffer),r.setParameter("boundsBuffer",e.boundsBuffer),r.setParameter("transformsBuffer",e.transformsBuffer),s?(r.setParameter("cameraWorldPos",e.fisheyeCameraPos),r.setParameter("maxTheta",e.fisheyeMaxTheta),r.setParameter("cameraForward",e.fisheyeCameraForward)):r.setParameter("frustumPlanes[0]",e.frustumPlanes),r.setParameter("numIntervals",t);let a=Math.ceil(t/256);r.setupDispatch(a),this.device.computeDispatch([r],"GSplatIntervalCull");let n=t+1;this.prefixSumKernel.resize(this.countBuffer,n),this.prefixSumKernel.dispatch(this.device);let o=this._scatterCompute;o.setParameter("intervals",this.intervalsBuffer),o.setParameter("prefixSumBuffer",this.countBuffer),o.setParameter("compactedOutput",this.compactedSplatIds),o.setParameter("numIntervals",t),o.setParameter("pad0",0),o.setParameter("pad1",0),o.setParameter("pad2",0),o.setupDispatch(t),this.device.computeDispatch([o],"GSplatIntervalScatter");}writeIndirectArgs(e,t,i){let s=this._writeIndirectArgsCompute;s.setParameter("prefixSumBuffer",this.countBuffer),s.setParameter("indirectDrawArgs",this.device.indirectDrawBuffer),s.setParameter("numSplatsBuf",this.numSplatsBuffer),s.setParameter("indirectDispatchArgs",this.device.indirectDispatchBuffer),s.setParameter("sortElementCountBuf",this.sortElementCountBuffer),s.setParameter("drawSlot",e),s.setParameter("indexCount",SY),s.setParameter("dispatchSlotOffset",3*t),s.setParameter("totalSplats",i),s.setupDispatch(1),this.device.computeDispatch([s],"GSplatIntervalWriteIndirectArgs");}constructor(e){this.compactedSplatIds=null,this.intervalsBuffer=null,this.countBuffer=null,this.prefixSumKernel=null,this.numSplatsBuffer=null,this.sortElementCountBuffer=null,this.allocatedCompactedCount=0,this.allocatedIntervalCount=0,this.allocatedCountBufferSize=0,this._uploadedVersion=-1,this._cullComputePerspective=null,this._cullComputeFisheye=null,this._scatterCompute=null,this._writeIndirectArgsCompute=null,this._cullBindGroupFormatPerspective=null,this._cullBindGroupFormatFisheye=null,this._scatterBindGroupFormat=null,this._writeArgsBindGroupFormat=null,this._scatterUniformBufferFormat=null,this._writeArgsUniformBufferFormat=null,this.device=e,this.numSplatsBuffer=new rO(e,4,12),this.sortElementCountBuffer=new rO(e,4,12),this.prefixSumKernel=new dN(e),this._createUniformBufferFormats(),this._createScatterCompute(),this._createWriteIndirectArgsCompute();}}class Sj{_initBuckets(){if(!this._buckets){this._buckets=Array(64);for(let e=0;e<64;e++)this._buckets[e]=[];}}balance(e,t,i){this._initBuckets();for(let e=0;e<64;e++)this._buckets[e].length=0;let s=64/Math.sqrt(i),r=0;for(let[,t]of e){let e=t.octree.nodes,i=t.nodeInfos;for(let t=0,a=e.length;t>>0,h=l<64?l:63;this._buckets[h].push(a),r+=o[n].count;}}let a=r;if(a===t)return;let n=a>t,o=false;for(;!o&&(n?a>t:a=0&&!o;i--){let s=this._buckets[i];for(let i=0,r=s.length;ir.inst.rangeMin){let i=r.lods,s=r.optimalLod,n=i[s-1].count-i[s].count;if(a+n<=t){if(r.optimalLod=s-1,e=true,(a+=n)>=t){o=true;break}}else {o=true;break}}}}if(!e)break}}constructor(){this._buckets=null;}}class SK{get offset(){return this._offset}get size(){return this._size}constructor(){this._offset=0,this._size=0,this._free=true,this._prev=null,this._next=null,this._prevFree=null,this._nextFree=null,this._bucket=-1;}}class S${get capacity(){return this._capacity}get usedSize(){return this._usedSize}get freeSize(){return this._freeSize}get fragmentation(){return this._freeSize>0?1-1/this._freeRegionCount:0}_bucketFor(e){return 31-Math.clz32(e)}_addToBucket(e){let t=this._bucketFor(e._size);for(e._bucket=t;t>=this._freeBucketHeads.length;)this._freeBucketHeads.push(null);e._prevFree=null,e._nextFree=this._freeBucketHeads[t],this._freeBucketHeads[t]&&(this._freeBucketHeads[t]._prevFree=e),this._freeBucketHeads[t]=e,this._freeRegionCount++;}_removeFromBucket(e){let t=e._bucket;e._prevFree?e._prevFree._nextFree=e._nextFree:this._freeBucketHeads[t]=e._nextFree,e._nextFree&&(e._nextFree._prevFree=e._prevFree),e._prevFree=null,e._nextFree=null,e._bucket=-1,this._freeRegionCount--;}_rebucket(e){this._bucketFor(e._size)!==e._bucket&&(this._removeFromBucket(e),this._addToBucket(e));}_obtain(e,t,i){let s;return (s=this._pool.length>0?this._pool.pop():new SK)._offset=e,s._size=t,s._free=i,s._prev=null,s._next=null,s._prevFree=null,s._nextFree=null,s._bucket=-1,s}_release(e){e._prev=null,e._next=null,e._prevFree=null,e._nextFree=null,e._bucket=-1,this._pool.push(e);}_insertAfterInMainList(e,t){null===t?(e._prev=null,e._next=this._headAll,this._headAll&&(this._headAll._prev=e),this._headAll=e,this._tailAll||(this._tailAll=e)):(e._prev=t,e._next=t._next,t._next&&(t._next._prev=e),t._next=e,this._tailAll===t&&(this._tailAll=e));}_removeFromMainList(e){e._prev?e._prev._next=e._next:this._headAll=e._next,e._next?e._next._prev=e._prev:this._tailAll=e._prev,e._prev=null,e._next=null;}_findFreeBlock(e){let t=this._bucketFor(e),i=this._freeBucketHeads.length;if(t=e)||i&&!(s._size0){let e=this._obtain(t,s,true);this._insertAfterInMainList(e,this._tailAll),this._addToBucket(e);}}_defragIncremental(e,t){let i=Math.ceil(e/2),s=e-i;for(let e=0;e=e._offset)break;this._moveBlock(e,i),t.add(e);}let r=this._headAll;for(let e=0;ethis._capacity&&this.grow(r),this.defrag(0);for(let i=e;i0){this._capacity=e,this._freeSize=e;let t=this._obtain(0,e,true);this._headAll=t,this._tailAll=t,this._addToBucket(t);}}}let SZ=new ed,SQ=new ed,SJ=new ed,S0=new ed,S1=new ey,S2=new Set,S3=new Set,S4=[],S5=[],S6=new Set,S8={translationDelta:0},S9=new ed,S7=new ed,ye=new Set,yt=new Set,yi=[[1,0,0],[0,1,0],[0,0,1],[1,1,0],[1,0,1],[0,1,1],[1,.5,0],[.5,0,1]];new es(1,0,0),new es(0,1,0),new es(0,0,1),new es(1,1,0),new es(1,0,1),new es(0,1,1),new es(1,.5,0),new es(.5,0,1);let ys=null;class yr{destroy(){for(let[,e]of(this._destroyed=true,this.worldStates)){for(let t of e.splats)t.resource.decRefCount();e.destroy();}for(let[,e]of(this.worldStates.clear(),this.octreeInstances))e.destroy();for(let e of(this.octreeInstances.clear(),this.octreeInstancesToDestroy))e.destroy();this.octreeInstancesToDestroy.length=0,this.destroyGpuSorting(),this.destroyCpuSorting(),this.workBuffer.destroy(),this.renderer.destroy();}destroyGpuSorting(){this.keyGenerator?.destroy(),this.keyGenerator=null,this.gpuSorter?.destroy(),this.gpuSorter=null,this.renderer.setCpuSortedRendering(),this.destroyIntervalCompaction(false);}destroyIntervalCompaction(e=true){this.intervalCompaction&&(e&&this.renderer.setCpuSortedRendering(),this.intervalCompaction.destroy(),this.intervalCompaction=null);}destroyCpuSorting(){this.cpuSorter?.destroy(),this.cpuSorter=null;}initGpuSorting(){this.keyGenerator||(this.keyGenerator=new SG(this.device)),this.gpuSorter||(this.gpuSorter=new dz(this.device));}initCpuSorting(){this.cpuSorter||(this.cpuSorter=this.createSorter());let e=this.worldStates.get(this.sortedVersion);e&&(e.sortParametersSet=false,e.sortedBefore=false,this.cpuSorter.updateCentersForSplats(e.splats)),this.renderer.setCpuSortedRendering();}get material(){return this.renderer.material}prepareForPicking(e,t,i){return 3!==this.activeRenderer?null:this.renderer.dispatchPick(e,t,i)}createSorter(){let e=new vZ(this.scene);return e.on("sorted",(e,t,i)=>{this.onSorted(e,t,i);}),e}setRenderMode(e){this.renderMode=e,this.renderer.setRenderMode(e);}get canCull(){return 1!==this.activeRenderer&&this.workBuffer.frustumCuller.totalBoundsEntries>0}_createRenderer(e){3===e?this.renderer=new S_(this.device,this.node,this.cameraNode,this.layer,this.workBuffer):(this.renderer=new v0(this.device,this.node,this.cameraNode,this.layer,this.workBuffer),2===e?this.initGpuSorting():this.initCpuSorting()),this.activeRenderer=e;}prepareRendererMode(){let e=this.scene.gsplat.currentRenderer;e!==this.activeRenderer&&(this.destroyGpuSorting(),this.destroyCpuSorting(),this.renderer.destroy(),this._createRenderer(e),this.renderer.setRenderMode(this.renderMode),this._workBufferRebuildRequired=true,this.sortNeeded=true);}reconcile(e){for(let t of(S2.clear(),e))t.resource instanceof SL?(this.octreeInstances.has(t)||(this.octreeInstances.set(t,new SC(this.device,t.resource.octree,t)),this.hasNewOctreeInstances=true),S3.add(t)):S2.add(t);for(let[e,t]of this.octreeInstances)S3.has(e)||(this.octreeInstances.delete(e),this.layerPlacementsDirty=true,this._placementSetChanged=true,this.octreeInstancesToDestroy.push(t));if(this.layerPlacementsDirty||(this.layerPlacementsDirty=this.layerPlacements.length!==S2.size),!this.layerPlacementsDirty)for(let e=0;e{if(i.resource){i.ensureInstanceStreams(this.device);let s=i.intervals.size>0?t.octree.nodes:null,r=s?t.nodeInfos:null,a=new vq(this.device,i.resource,i,i.consumeRenderDirty.bind(i),s,r);e.push(a);}});if(this.cpuSorter)for(let t of e){let e=t.resource;this._centersVersions.get(e.id)!==e.centersVersion&&(this._centersVersions.set(e.id,e.centersVersion),this.cpuSorter.setCenters(e.id,null),this.cpuSorter.setCenters(e.id,e.centers));}this.cpuSorter?.updateCentersForSplats(e);let t=new SB(this.device,this.lastWorldStateVersion,e,this._allocator,this._allocationMap);for(let e of t.splats)e.resource.incRefCount();for(let[,e]of this.octreeInstances)if(e.removedCandidates&&e.removedCandidates.size){for(let i of e.removedCandidates)t.pendingReleases.push([e.octree,i]);e.removedCandidates.clear();}if(this.octreeInstancesToDestroy.length){for(let e of this.octreeInstancesToDestroy){if(e.removedCandidates&&e.removedCandidates.size){for(let i of e.removedCandidates)t.pendingReleases.push([e.octree,i]);e.removedCandidates.clear();}for(let i of e.getFileDecrements())t.pendingReleases.push([e.octree,i]);e.destroy(true);}this.octreeInstancesToDestroy.length=0;}this._placementSetChanged&&(t.fullRebuild=true),this.worldStates.set(this.lastWorldStateVersion,t),this.layerPlacementsDirty=false,this._placementSetChanged=false,this.sortNeeded=true;}}onSorted(e,t,i){this.cleanupOldWorldStates(t),this.sortedVersion=t;let s=this.worldStates.get(t);s&&(s.sortedBefore||(s.sortedBefore=true,this.rebuildWorkBuffer(s,e)),this.workBuffer.setOrderData(i),this.renderer.setOrderData());}rebuildWorkBuffer(e,t,i=false){let s=e.textureSize;s!==this.workBuffer.textureSize&&this.workBuffer.resize(s),1!==this.activeRenderer&&(this.workBuffer.frustumCuller.updateBoundsData(e.boundsGroups),this.workBuffer.frustumCuller.updateTransformsData(e.boundsGroups));let r=i||e.fullRebuild,a=r?e.splats:e.needsUpload,n=r?null:e.needsUploadIds;if(a.length>0){let t=this._allocationMap.size,i=r?t:e.needsUploadIds.size;this.bufferCopyUploaded+=i,this.bufferCopyTotal=t,this.workBuffer.render(a,this.cameraNode,this.getDebugColors(),n);}for(let t=0;t0,n=0;e.splats.forEach(e=>{if(e.update()){if(S4.push(e),n+=e.intervalAllocIds.length,e.nodeInfos)for(let t of e.intervalNodeIndices)e.nodeInfos[t].colorAccumulatedTranslation=0;else e.colorAccumulatedTranslation=0;this.sortNeeded=true;}else if(a&&e.hasSphericalHarmonics)if(S5.push(e),e.nodeInfos){let t=e.intervalNodeIndices;for(let s=0;s=o&&(S6.add(e.intervalAllocIds[s]),a.colorAccumulatedTranslation=0,n++);}}else {e.colorAccumulatedTranslation+=r,S1.copy(e.node.getWorldTransform()).invert(),S1.transformPoint(s,S9),e.aabb.closestPoint(S9,S7);let t=i*Math.max(1,S9.distance(S7)*e.node.getWorldTransform().getScale().x);e.colorAccumulatedTranslation>=t&&(S6.add(e.allocId),n+=e.intervalAllocIds.length,e.colorAccumulatedTranslation=0);}}),this.bufferCopyUploaded+=n,this.bufferCopyTotal=this._allocationMap.size,S4.length>0&&(this.workBuffer.render(S4,this.cameraNode,this.getDebugColors()),S4.length=0),S6.size>0&&(this.workBuffer.renderColor(S5,this.cameraNode,this.getDebugColors(),S6),S6.clear()),S5.length=0;}testCameraMovedForLod(){let e=this.scene.gsplat.lodUpdateDistance,t=this.cameraNode.getPosition(),i=this.lastLodCameraPos.distance(t)>e;if(i)return true;let s=false,r=this.scene.gsplat.lodUpdateAngle;if(r>0)if(Number.isFinite(this.lastLodCameraFwd.x)){let e=this.cameraNode.forward;s=Math.acos(Math.min(1,Math.max(-1,this.lastLodCameraFwd.dot(e))))>r*ei.DEG_TO_RAD;}else s=true;let a=this.cameraNode.camera.fov,n=this.lastLodCameraFov<0||Math.abs(a-this.lastLodCameraFov)>.02*this.lastLodCameraFov;return i||s||n}testCameraMovedForSort(){if(this.scene.gsplat.radialSorting){let e=this.cameraNode.getPosition();return this.lastSortCameraPos.distance(e)>.001}if(Number.isFinite(this.lastSortCameraFwd.x)){let e=this.cameraNode.forward;return Math.acos(Math.min(1,Math.max(-1,this.lastSortCameraFwd.dot(e))))>.001}return true}testFrustumChanged(){if(!this.lastCullingProjMat.equals(this.cameraNode.camera.projectionMatrix))return true;let e=this.cameraNode.forward;return Math.acos(Math.min(1,Math.max(-1,this.lastCullingCameraFwd.dot(e))))>.001}updateColorCameraTracking(){this.lastColorUpdateCameraPos.copy(this.cameraNode.getPosition());}getDebugColors(){let e=this.scene.gsplat.debug;if(2===e){ys??(ys=[]);let e=Math.random(),s=Math.random(),r=Math.random();for(let a=0;ae&&(e=a);}return Math.max(e,1)}_enforceBudget(e){let t=this.workBuffer.textureSize,i=0,s=0;for(let e of this.layerPlacements){let r=e.resource;if(r){let e=r.numSplats??0;i+=e,s+=(t-e%t)%t;}}let r=Math.max(1,e-i),a=this.computeGlobalMaxDistance(),n=0;for(let[,e]of this.octreeInstances)for(let i of(n+=e.evaluateOptimalLods(this.cameraNode,this.scene.gsplat,this._budgetScale),e.activePlacements)){let e=i.resource;s+=(t-(e?.numSplats??0)%t)%t;}let o=Math.max(1,r-s);if(n>0){let e=n/o;if(e>1.4||e<.6){let t=1/Math.sqrt(e);this._budgetScale*=1+(t-1)*.3,this._budgetScale=Math.max(.01,Math.min(this._budgetScale,100));}}for(let[,e]of(this._budgetBalancer.balance(this.octreeInstances,o,a),this.octreeInstances)){let t=e.octree.lodLevels-1;e.applyLodChanges(t,this.scene.gsplat);}}handleFormatChange(){let e=this.scene.gsplat.format;this.workBuffer.format!==e&&(this.workBuffer.destroy(),this.workBuffer=new uW(this.device,e),this.renderer.setDataSource(this.workBuffer),this._workBufferFormatVersion=this.workBuffer.format.extraStreamsVersion,this._workBufferRebuildRequired=true,this.sortNeeded=true);}update(){this.bufferCopyUploaded=0,this.bufferCopyTotal=0,this.handleFormatChange();let e=this.workBuffer.format.extraStreamsVersion;this._workBufferFormatVersion!==e&&(this._workBufferFormatVersion=e,this.workBuffer.syncWithFormat(),this._workBufferRebuildRequired=true,this.sortNeeded=true),this.prepareRendererMode(),this.cpuSorter&&this.cpuSorter.applyPendingSorted();let t=1!==this.activeRenderer||this.cpuSorter&&this.cpuSorter.jobsInFlight<3,i=false;this.framesTillFullUpdate--,this.framesTillFullUpdate<=0&&(this.framesTillFullUpdate=10,t&&(i=true));let s=this.hasNewOctreeInstances&&t;s&&(this.hasNewOctreeInstances=false);let r=false,a=false,n=false;if(i){for(let[,e]of this.octreeInstances){let t=e.update();this.layerPlacementsDirty||(this.layerPlacementsDirty=t),this._placementSetChanged||(this._placementSetChanged=e.consumePlacementSetChanged());let i=e.consumeNeedsLodUpdate();r||(r=i);}let e=this.scene.gsplat.lodUpdateDistance;for(let[,t]of this.octreeInstances){let i=t.testMoved(e);a||(a=i);}n=this.testCameraMovedForLod(),this._awaitingLodUpdate=false;}if(this.testCameraMovedForSort()&&(this.sortNeeded=true),this.intervalCompaction&&!this.sortNeeded&&this.testFrustumChanged()&&(this.lastCullingCameraFwd.copy(this.cameraNode.forward),this.lastCullingProjMat.copy(this.cameraNode.camera.projectionMatrix),this.sortNeeded=true),this.scene.gsplat.dirty&&(this.layerPlacementsDirty=true,this.renderer.updateOverdrawMode(this.scene.gsplat),this._workBufferRebuildRequired=true,this.sortNeeded=true,this.octreeInstances.size>0&&(this._awaitingLodUpdate=true)),n||a||this.scene.gsplat.dirty||r||s){for(let[,e]of this.octreeInstances)e.updateMoved();let e=this.cameraNode;this.lastLodCameraPos.copy(e.getPosition()),this.lastLodCameraFwd.copy(e.forward),this.lastLodCameraFov=e.camera.fov;let t=this.scene.gsplat.splatBudget;if(t>0)this._enforceBudget(t);else for(let[,e]of(this._budgetScale=1,this.octreeInstances))e.updateLod(this.cameraNode,this.scene.gsplat);}this.updateWorldState();let o=this.worldStates.get(this.lastWorldStateVersion);if(o&&this.cpuSorter&&!o.sortParametersSet){o.sortParametersSet=true;let e=this.prepareSortParameters(o);this.cpuSorter.setSortParameters(e);}let l=this.worldStates.get(this.sortedVersion);if(l?.sortedBefore)if(this._workBufferRebuildRequired){let e=l.totalActiveSplats;this.rebuildWorkBuffer(l,e,true),this._workBufferRebuildRequired=false,this.renderer.setOrderData(),this.intervalCompaction&&(this.intervalCompaction._uploadedVersion=-1);}else this.applyWorkBufferUpdates(l);let h=false;this.sortNeeded&&o&&(3===this.activeRenderer?(this.compactGpu(o),h=true):2===this.activeRenderer?(this.sortGpu(o),h=true):this.sortCpu(o),this.sortNeeded=false,this.lastSortCameraPos.copy(this.cameraNode.getPosition()),this.lastSortCameraFwd.copy(this.cameraNode.forward),this.lastCullingCameraFwd.copy(this.cameraNode.forward),this.lastCullingProjMat.copy(this.cameraNode.camera.projectionMatrix)),3!==this.activeRenderer&&this.intervalCompaction&&!h&&this.refreshIndirectDraw();let c=this.scene.gsplat.useFog?this.cameraNode.camera.fogParams??this.scene.fog:null;if(this.renderer.frameUpdate(this.scene.gsplat,this.scene.exposure,c),l?.sortedBefore&&this.updateColorCameraTracking(),this.octreeInstances.size){let e=this.scene.gsplat.cooldownTicks;for(let[,t]of this.octreeInstances){let i=t.octree;ye.has(i)||(ye.add(i),i.updateCooldownTick(e));}ye.clear();}if(this.fireFrameReadyEvent(),this.scene.gsplat.dirty)for(let[,e]of this.octreeInstances)e.needsLodUpdate=true;return l?l.totalActiveSplats:0}sortGpu(e){let t=this.keyGenerator,i=this.gpuSorter;if(!t||!i)return;let s=e.totalActiveSplats;if(0===s)return;if(this.intervalCompaction||(this.intervalCompaction=new Sq(this.device)),e.sortedBefore||(e.sortedBefore=true,this.cleanupOldWorldStates(e.version),this.sortedVersion=e.version,this.rebuildWorkBuffer(e,s)),this.intervalCompaction.uploadIntervals(e),this.canCull){let e=this.worldStates.get(this.sortedVersion);e&&this._runFrustumCulling(e);}let r=e.totalIntervals,a=e.totalActiveSplats;this.intervalCompaction.dispatchCompact(this.workBuffer.frustumCuller,r,a,this.renderer.fisheyeProj.enabled),this.allocateAndWriteIntervalIndirectArgs(r);let n=this.intervalCompaction.compactedSplatIds,o=4*Math.ceil(Math.max(10,Math.min(20,Math.round(Math.log2(s/4))))/4),{minDist:l,maxDist:h}=this.computeDistanceRange(e),c=this.dispatchGpuSort(s,o,l,h,n);this.applyGpuSortResults(e,c);}compactGpu(e){this.intervalCompaction||(this.intervalCompaction=new Sq(this.device));let t=e.totalActiveSplats;if(0===t)return;if(e.sortedBefore||(e.sortedBefore=true,this.cleanupOldWorldStates(e.version),this.sortedVersion=e.version,this.rebuildWorkBuffer(e,t)),this.intervalCompaction.uploadIntervals(e),this.canCull){let e=this.worldStates.get(this.sortedVersion);e&&this._runFrustumCulling(e);}let i=e.totalIntervals,s=e.totalActiveSplats;this.intervalCompaction.dispatchCompact(this.workBuffer.frustumCuller,i,s,this.renderer.fisheyeProj.enabled),this.allocateAndWriteIntervalIndirectArgs(i);let r=this.intervalCompaction;this.renderer.setCompactedData(r.compactedSplatIds,r.sortElementCountBuffer,e.textureSize,s);}allocateAndWriteIntervalIndirectArgs(e){this.indirectDrawSlot=this.device.getIndirectDrawSlot(1),this.indirectDispatchSlot=this.device.getIndirectDispatchSlot(2),this.intervalCompaction.writeIndirectArgs(this.indirectDrawSlot,this.indirectDispatchSlot,e),this.lastCompactedNumIntervals=e;}dispatchGpuSort(e,t,i,s,r){let a=this.keyGenerator,n=this.gpuSorter,o=this.intervalCompaction,l=a.generateIndirect(this.workBuffer,this.cameraNode,this.scene.gsplat.radialSorting,e,t,i,s,r,o.sortElementCountBuffer,this.indirectDispatchSlot);return n.sortIndirect(l,e,t,this.indirectDispatchSlot+1,o.sortElementCountBuffer,r,true)}applyGpuSortResults(e,t){let i=this.intervalCompaction;this.renderer.setGpuSortedRendering(this.indirectDrawSlot,t,i.numSplatsBuffer,e.textureSize);}_runFrustumCulling(e){this.workBuffer.frustumCuller.updateTransformsData(e.boundsGroups);let t=this.cameraNode.camera;this.workBuffer.frustumCuller.computeFrustumPlanes(t.projectionMatrix,t.viewMatrix);let i=this.scene.gsplat,s=this.renderer.fisheyeProj;s.update(i.fisheye,t.fov,t.projectionMatrix),s.enabled&&this.workBuffer.frustumCuller.setFisheyeData(this.cameraNode.getPosition(),this.cameraNode.forward,s.maxTheta);}refreshIndirectDraw(){let e=this.worldStates.get(this.sortedVersion);if(!e||!this.intervalCompaction)return;this.allocateAndWriteIntervalIndirectArgs(this.lastCompactedNumIntervals);let t=this.gpuSorter,i=this.intervalCompaction;this.renderer.setGpuSortedRendering(this.indirectDrawSlot,t.sortedIndices,i.numSplatsBuffer,e.textureSize);}computeDistanceRange(e){let t=this.cameraNode.getWorldTransform();t.getTranslation(SZ),t.getZ(SQ).normalize();let i=this.scene.gsplat.radialSorting,s=i?0:1/0,r=i?0:-1/0;for(let t of e.splats){let e=t.node.getWorldTransform(),a=t.aabb.getMin(),n=t.aabb.getMax();for(let t=0;t<8;t++)if(S0.x=1&t?n.x:a.x,S0.y=2&t?n.y:a.y,S0.z=4&t?n.z:a.z,e.transformPoint(S0,S0),i){let e=S0.distance(SZ);e>r&&(r=e);}else {let e=S0.sub(SZ).dot(SQ);er&&(r=e);}}return 0===r||r===-1/0?{minDist:0,maxDist:1}:{minDist:s,maxDist:r}}sortCpu(e){if(!this.cpuSorter)return;let t=this.cameraNode.getWorldTransform();t.getTranslation(SZ),t.getZ(SQ).normalize();let i=[];e.splats.forEach(e=>{let t=e.node.getWorldTransform();S1.copy(t).invert();let s=t.getScale().x,r=S1.transformVector(SQ).normalize(),a=S1.transformPoint(SZ);t.getTranslation(SJ);let n=SJ.sub(SZ).dot(SQ),o=e.aabb.getMin(),l=e.aabb.getMax();i.push({transformedDirection:r,transformedPosition:a,offset:n,scale:s,modelMat:t.data.slice(),aabbMin:[o.x,o.y,o.z],aabbMax:[l.x,l.y,l.z]});}),this.cpuSorter.setSortParams(i,this.scene.gsplat.radialSorting);}prepareSortParameters(e){return {command:"intervals",textureSize:e.textureSize,totalActiveSplats:e.totalActiveSplats,version:e.version,ids:e.splats.map(e=>e.resource.id),pixelOffsets:e.splats.map(e=>e.intervalOffsets),intervals:e.splats.map(e=>e.intervals)}}constructor(e,t,i,s){this.node=new oJ("GSplatManager"),this.worldStates=new Map,this.lastWorldStateVersion=0,this.cpuSorter=null,this.keyGenerator=null,this.gpuSorter=null,this.intervalCompaction=null,this.indirectDrawSlot=-1,this.indirectDispatchSlot=-1,this.lastCompactedNumIntervals=0,this.sortedVersion=0,this._awaitingLodUpdate=false,this._workBufferFormatVersion=-1,this._workBufferRebuildRequired=false,this.bufferCopyUploaded=0,this.bufferCopyTotal=0,this._stateTracker=new Sk,this._centersVersions=new Map,this.framesTillFullUpdate=0,this.lastLodCameraPos=new ed(1/0,1/0,1/0),this.lastLodCameraFwd=new ed(1/0,1/0,1/0),this.lastLodCameraFov=-1,this.lastSortCameraPos=new ed(1/0,1/0,1/0),this.lastSortCameraFwd=new ed(1/0,1/0,1/0),this.lastCullingCameraFwd=new ed(1/0,1/0,1/0),this.lastCullingProjMat=new ey,this.sortNeeded=true,this._budgetBalancer=new Sj,this._budgetScale=1,this._allocationMap=new Map,this.lastColorUpdateCameraPos=new ed(1/0,1/0,1/0),this.layerPlacements=[],this.layerPlacementsDirty=false,this._placementSetChanged=false,this.octreeInstances=new Map,this.octreeInstancesToDestroy=[],this.hasNewOctreeInstances=false,this.device=e,this.scene=t.scene,this.director=t,this.cameraNode=s;let r=this.scene.gsplat.splatBudget;this._allocator=new S$(r>0?Math.ceil(1.15*r):0,1.15),this.workBuffer=new uW(e,this.scene.gsplat.format),this.layer=i,this._createRenderer(this.scene.gsplat.currentRenderer),this._workBufferFormatVersion=this.workBuffer.format.extraStreamsVersion;}}class ya{static equals(e,t){if(e.size!==t.size)return false;for(let i of e)if(!t.has(i))return false;return true}}let yn=[];class yo{createManager(e,t,i,s,r,a){let n=new yr(e,t,i,s);return n.setRenderMode(a),t.eventHandler&&t.eventHandler.fire("material:created",n.material,r,i),n}updateConfiguration(e,t,i,s){let r=s.node,a=i.gsplatPlacements.length>0,n=i.gsplatShadowCasters.length>0,o=ya.equals(i.gsplatPlacementsSet,i.gsplatShadowCastersSet)&&a,l=o?3:+!!a,h=o?0:2*!!n;l?this.gsplatManager?this.gsplatManager.setRenderMode(l):this.gsplatManager=this.createManager(e,t,i,r,s,l):this.gsplatManager&&(this.gsplatManager.destroy(),this.gsplatManager=null),h?this.gsplatManagerShadow?this.gsplatManagerShadow.setRenderMode(h):this.gsplatManagerShadow=this.createManager(e,t,i,r,s,h):this.gsplatManagerShadow&&(this.gsplatManagerShadow.destroy(),this.gsplatManagerShadow=null);}destroy(){this.gsplatManager?.destroy(),this.gsplatManager=null,this.gsplatManagerShadow?.destroy(),this.gsplatManagerShadow=null;}constructor(e,t,i,s){this.gsplatManager=null,this.gsplatManagerShadow=null,this.updateConfiguration(e,t,i,s);}}class yl{destroy(){this.layersMap.forEach(e=>e.destroy()),this.layersMap.clear();}removeLayerData(e){let t=this.layersMap.get(e);t&&(t.destroy(),this.layersMap.delete(e));}getLayerData(e,t,i,s){let r=this.layersMap.get(i);return r||(r=new yo(e,t,i,s),this.layersMap.set(i,r)),r}constructor(){this.layersMap=new Map;}}class yh{destroy(){this.camerasMap.forEach(e=>e.destroy()),this.camerasMap.clear();}getCameraData(e){let t=this.camerasMap.get(e);return t||(t=new yl,this.camerasMap.set(e,t)),t}prepareForPicking(e,t,i,s){let r=this.camerasMap.get(e);if(!r)return null;let a=r.layersMap.get(s);return a?.gsplatManager?a.gsplatManager.prepareForPicking(e,t,i):null}update(e){uX.process(this.device),this.camerasMap.forEach((t,i)=>{if(e.camerasSet.has(i)){t.layersMap.forEach((e,t)=>{i.layersSet.has(t.id)&&t.enabled||yn.push(t);});for(let e=0;e0,t=i.gsplatShadowCasters.length>0;if(e||t){o??(o=this.getCameraData(n));let e=o.getLayerData(this.device,this,i,n);e.updateConfiguration(this.device,this,i,n),e.gsplatManager&&e.gsplatManager.reconcile(i.gsplatPlacements),e.gsplatManagerShadow&&e.gsplatManagerShadow.reconcile(i.gsplatShadowCasters);}else o&&o.removeLayerData(i);}}if(o)for(let e of o.layersMap.values())e.gsplatManager&&(t+=e.gsplatManager.update(),i+=e.gsplatManager.bufferCopyUploaded,s+=e.gsplatManager.bufferCopyTotal),e.gsplatManagerShadow&&(t+=e.gsplatManagerShadow.update(),i+=e.gsplatManagerShadow.bufferCopyUploaded,s+=e.gsplatManagerShadow.bufferCopyTotal);}this.renderer._gsplatCount=t,this.renderer._gsplatBufferCopy=s>0?i/s*100:0,this.scene.gsplat.frameEnd();for(let t=0;t0&&(this.lodBaseDistance=e[0],this.lodMultiplier=3);}get lodDistances(){return []}set splatBudget(e){}get splatBudget(){return 0}set unified(e){this._unified!==e&&(this._unified=e,this._onGSplatAssetAdded());}get unified(){return this._unified}get id(){return this._id}set workBufferUpdate(e){this._workBufferUpdate=e,this._placement&&(this._placement.workBufferUpdate=e);}get workBufferUpdate(){return this._workBufferUpdate}setWorkBufferModifier(e){if(e){let t=(this.system.app.graphicsDevice.isWebGPU?e.wgsl:e.glsl)??null;this._workBufferModifier=t?{code:t,hash:iL(t)}:null;}else this._workBufferModifier=null;this._placement&&(this._placement.workBufferModifier=this._workBufferModifier);}set layers(e){this.removeFromLayers(),this._layers.length=0;for(let t=0;tthis.layers.indexOf(e.id)||!this.unified&&this._instance&&e.addMeshInstances(this._instance.meshInstance);}onLayerRemoved(e){0>this.layers.indexOf(e.id)||!this.unified&&this._instance&&e.removeMeshInstances(this._instance.meshInstance);}onEnable(){let e=this.system.app.scene,t=e.layers;this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this._instance||this._placement?this.addToLayers():this.asset?this._onGSplatAssetAdded():this._resource&&this._onGSplatAssetLoad();}onDisable(){let e=this.system.app.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,e&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.removeFromLayers();}hide(){this._instance&&(this._instance.meshInstance.visible=false);}show(){this._instance&&(this._instance.meshInstance.visible=true);}setParameter(e,t){let i=this.system.app.graphicsDevice.scope.resolve(e);this._parameters.set(e,{scopeId:i,data:t}),this._placement&&(this._placement.renderDirty=true);}getParameter(e){return this._parameters.get(e)?.data}deleteParameter(e){this._parameters.delete(e),this._placement&&(this._placement.renderDirty=true);}getInstanceTexture(e){return this._placement?this._placement.getInstanceTexture(e,this.system.app.graphicsDevice)??null:null}_onGSplatAssetAdded(){this._assetReference.asset&&(this._assetReference.asset.resource?this._onGSplatAssetLoad():this.enabled&&this.entity.enabled&&this.system.app.assets.load(this._assetReference.asset));}_onGSplatAssetLoad(){this.destroyInstance();let e=this._resource??this._assetReference.asset?.resource;e&&(this.unified?(this._placement=null,this._placement=new Sv(e,this.entity,0,this._parameters,null,this._id),this._placement.lodBaseDistance=this._lodBaseDistance,this._placement.lodMultiplier=this._lodMultiplier,this._placement.workBufferUpdate=this._workBufferUpdate,this._placement.workBufferModifier=this._workBufferModifier,this.enabled&&this.entity.enabled&&this.addToLayers()):(this.instance=new fv(e,{material:this._materialTmp,highQualitySH:this._highQualitySH,scene:this.system.app.scene}),this._materialTmp=null));}_onGSplatAssetUnload(){this.destroyInstance();}_onGSplatAssetRemove(){this._onGSplatAssetUnload();}constructor(e,t){super(e,t),this._layers=[0],this._instance=null,this._placement=null,this._id=od.get(),this._materialTmp=null,this._highQualitySH=true,this._lodBaseDistance=5,this._lodMultiplier=3,this._customAabb=null,this._resource=null,this._evtLayersChanged=null,this._evtLayerAdded=null,this._evtLayerRemoved=null,this._castShadows=false,this._unified=false,this._parameters=new Map,this._workBufferUpdate=0,this._workBufferModifier=null,this._assetReference=new gv("asset",this,e.app.assets,{add:this._onGSplatAssetAdded,load:this._onGSplatAssetLoad,remove:this._onGSplatAssetRemove,unload:this._onGSplatAssetUnload},this),t.on("remove",this.onRemoveChild,this),t.on("removehierarchy",this.onRemoveChild,this),t.on("insert",this.onInsertChild,this),t.on("inserthierarchy",this.onInsertChild,this);}}class yd{constructor(){this.enabled=true;}}let yu={gsplatCenterVS:` +`;var VR=256,UK=6*rt.instanceSize,HR=4,QS=class{constructor(t){n(this,"device");n(this,"compactedSplatIds",null);n(this,"intervalsBuffer",null);n(this,"countBuffer",null);n(this,"prefixSumKernel",null);n(this,"numSplatsBuffer",null);n(this,"sortElementCountBuffer",null);n(this,"allocatedCompactedCount",0);n(this,"allocatedIntervalCount",0);n(this,"allocatedCountBufferSize",0);n(this,"_uploadedVersion",-1);n(this,"_cullComputePerspective",null);n(this,"_cullComputeFisheye",null);n(this,"_scatterCompute",null);n(this,"_writeIndirectArgsCompute",null);n(this,"_cullBindGroupFormatPerspective",null);n(this,"_cullBindGroupFormatFisheye",null);n(this,"_scatterBindGroupFormat",null);n(this,"_writeArgsBindGroupFormat",null);n(this,"_scatterUniformBufferFormat",null);n(this,"_writeArgsUniformBufferFormat",null);this.device=t,this.numSplatsBuffer=new Ee(t,4,12),this.sortElementCountBuffer=new Ee(t,4,12),this.prefixSumKernel=new Wc(t),this._createUniformBufferFormats(),this._createScatterCompute(),this._createWriteIndirectArgsCompute()}destroy(){this.compactedSplatIds?.destroy(),this.intervalsBuffer?.destroy(),this.countBuffer?.destroy(),this.prefixSumKernel?.destroy(),this.numSplatsBuffer?.destroy(),this.sortElementCountBuffer?.destroy(),this._destroyCullPass(),this._scatterCompute?.shader?.destroy(),this._scatterBindGroupFormat?.destroy(),this._writeIndirectArgsCompute?.shader?.destroy(),this._writeArgsBindGroupFormat?.destroy(),this.compactedSplatIds=null,this.intervalsBuffer=null,this.countBuffer=null,this.prefixSumKernel=null,this.numSplatsBuffer=null,this.sortElementCountBuffer=null,this._scatterCompute=null,this._scatterBindGroupFormat=null,this._writeIndirectArgsCompute=null,this._writeArgsBindGroupFormat=null,this._scatterUniformBufferFormat=null,this._writeArgsUniformBufferFormat=null}_destroyCullPass(){this._cullComputePerspective?.shader?.destroy(),this._cullBindGroupFormatPerspective?.destroy(),this._cullComputePerspective=null,this._cullBindGroupFormatPerspective=null,this._cullComputeFisheye?.shader?.destroy(),this._cullBindGroupFormatFisheye?.destroy(),this._cullComputeFisheye=null,this._cullBindGroupFormatFisheye=null}_createUniformBufferFormats(){let t=this.device;this._scatterUniformBufferFormat=new Xe(t,[new Y("numIntervals",pe),new Y("pad0",pe),new Y("pad1",pe),new Y("pad2",pe)]),this._writeArgsUniformBufferFormat=new Xe(t,[new Y("drawSlot",pe),new Y("indexCount",pe),new Y("dispatchSlotBase",pe),new Y("totalSplats",pe),new Y("sortIndirectInfo",Li)])}_createCullPass(t){let e=this.device,s=t?"Fisheye":"",i=new Ue(e,[new Qe("uniforms",X),new K("intervals",X,!0),new K("countBuffer",X,!1),new K("boundsBuffer",X,!0),new K("transformsBuffer",X,!0)]),r=new Map([["{WORKGROUP_SIZE}",VR.toString()]]);t&&r.set("GSPLAT_FISHEYE","");let a=t?new Xe(e,[new Y("cameraWorldPos",Kt),new Y("maxTheta",Te),new Y("cameraForward",Kt),new Y("numIntervals",pe)]):new Xe(e,[new Y("frustumPlanes",oi,6),new Y("numIntervals",pe)]),o=new Be(e,{name:`GSplatIntervalCull${s}`,shaderLanguage:se,cshader:hz,cdefines:r,computeBindGroupFormat:i,computeUniformBufferFormats:{uniforms:a}});return{compute:new Ye(e,o,`GSplatIntervalCull${s}`),bindGroupFormat:i}}_getCullCompute(t){if(t){if(!this._cullComputeFisheye){let{compute:e,bindGroupFormat:s}=this._createCullPass(!0);this._cullComputeFisheye=e,this._cullBindGroupFormatFisheye=s}return this._cullComputeFisheye}if(!this._cullComputePerspective){let{compute:e,bindGroupFormat:s}=this._createCullPass(!1);this._cullComputePerspective=e,this._cullBindGroupFormatPerspective=s}return this._cullComputePerspective}_createScatterCompute(){let t=this.device;this._scatterBindGroupFormat=new Ue(t,[new Qe("uniforms",X),new K("intervals",X,!0),new K("prefixSumBuffer",X,!0),new K("compactedOutput",X,!1)]);let e=new Map([["{WORKGROUP_SIZE}",VR.toString()]]),s=new Be(t,{name:"GSplatIntervalScatter",shaderLanguage:se,cshader:fz,cdefines:e,computeBindGroupFormat:this._scatterBindGroupFormat,computeUniformBufferFormats:{uniforms:this._scatterUniformBufferFormat}});this._scatterCompute=new Ye(t,s,"GSplatIntervalScatter")}_createWriteIndirectArgsCompute(){let t=this.device;this._writeArgsBindGroupFormat=new Ue(t,[new K("prefixSumBuffer",X,!0),new K("indirectDrawArgs",X,!1),new K("numSplatsBuf",X,!1),new K("indirectDispatchArgs",X,!1),new K("sortElementCountBuf",X,!1),new Qe("uniforms",X)]);let e=new Map([["{INSTANCE_SIZE}",rt.instanceSize],["{KEYGEN_THREADS_PER_WORKGROUP}",256],["{MAX_WORKGROUPS_PER_DIM}",t.limits.maxComputeWorkgroupsPerDimension||65535]]),s=new Be(t,{name:"GSplatIntervalWriteIndirectArgs",shaderLanguage:se,cshader:uz,cdefines:e,computeBindGroupFormat:this._writeArgsBindGroupFormat,computeUniformBufferFormats:{uniforms:this._writeArgsUniformBufferFormat}});this._writeIndirectArgsCompute=new Ye(t,s,"GSplatIntervalWriteIndirectArgs")}_ensureCapacity(t,e){e>this.allocatedCompactedCount&&(this.compactedSplatIds?.destroy(),this.allocatedCompactedCount=e,this.compactedSplatIds=new Ee(this.device,e*4,4));let s=t+1;s>this.allocatedCountBufferSize&&(this.countBuffer?.destroy(),this.allocatedCountBufferSize=s,this.countBuffer=new Ee(this.device,s*4),this.prefixSumKernel&&this.prefixSumKernel.destroyPasses())}uploadIntervals(t){if(t.version===this._uploadedVersion)return;this._uploadedVersion=t.version;let e=t.splats,s=t.totalIntervals;if(s===0)return;s>this.allocatedIntervalCount&&(this.intervalsBuffer?.destroy(),this.allocatedIntervalCount=s,this.intervalsBuffer=new Ee(this.device,s*HR*4,8));let i=new Uint32Array(s*HR),r=0;for(let a=0;a0){let l=o.intervalNodeIndices;for(let h=0;h0?l[h/2]:0),i[r++]=0}}else i[r++]=o.intervalOffsets[0],i[r++]=o.activeSplats,i[r++]=o.boundsBaseIndex,i[r++]=0}this.intervalsBuffer.write(0,i,0,s*HR)}dispatchCompact(t,e,s,i){if(e===0)return;this._ensureCapacity(e,s);let r=this._getCullCompute(i);r.setParameter("intervals",this.intervalsBuffer),r.setParameter("countBuffer",this.countBuffer),r.setParameter("boundsBuffer",t.boundsBuffer),r.setParameter("transformsBuffer",t.transformsBuffer),i?(r.setParameter("cameraWorldPos",t.fisheyeCameraPos),r.setParameter("maxTheta",t.fisheyeMaxTheta),r.setParameter("cameraForward",t.fisheyeCameraForward)):r.setParameter("frustumPlanes[0]",t.frustumPlanes),r.setParameter("numIntervals",e);let a=Math.ceil(e/VR);r.setupDispatch(a),this.device.computeDispatch([r],"GSplatIntervalCull");let o=e+1;this.prefixSumKernel.resize(this.countBuffer,o),this.prefixSumKernel.dispatch(this.device);let l=this._scatterCompute;l.setParameter("intervals",this.intervalsBuffer),l.setParameter("prefixSumBuffer",this.countBuffer),l.setParameter("compactedOutput",this.compactedSplatIds),l.setParameter("numIntervals",e),l.setParameter("pad0",0),l.setParameter("pad1",0),l.setParameter("pad2",0),l.setupDispatch(e),this.device.computeDispatch([l],"GSplatIntervalScatter")}writeIndirectArgs(t,e,s,i){let r=this._writeIndirectArgsCompute;r.setParameter("prefixSumBuffer",this.countBuffer),r.setParameter("indirectDrawArgs",this.device.indirectDrawBuffer),r.setParameter("numSplatsBuf",this.numSplatsBuffer),r.setParameter("indirectDispatchArgs",this.device.indirectDispatchBuffer),r.setParameter("sortElementCountBuf",this.sortElementCountBuffer),r.setParameter("drawSlot",t),r.setParameter("indexCount",UK),r.setParameter("dispatchSlotBase",e),r.setParameter("totalSplats",s),r.setParameter("sortIndirectInfo",i),r.setupDispatch(1),this.device.computeDispatch([r],"GSplatIntervalWriteIndirectArgs")}};var IE=class{constructor(){n(this,"_buckets",null)}_initBuckets(){if(!this._buckets){this._buckets=new Array(rn);for(let t=0;te,a=!1;for(;!a&&(r?i>e:i=0&&!a;l--){let h=this._buckets[l];for(let f=0,u=h.length;fd.inst.rangeMin){let p=d.lods,m=d.optimalLod,_=p[m-1].count-p[m].count;if(i+_<=e){if(d.optimalLod=m-1,i+=_,o=!0,i>=e){a=!0;break}}else{a=!0;break}}}}if(!o)break}}};var WR=class{constructor(){n(this,"_offset",0);n(this,"_size",0);n(this,"_free",!0);n(this,"_prev",null);n(this,"_next",null);n(this,"_prevFree",null);n(this,"_nextFree",null);n(this,"_bucket",-1)}get offset(){return this._offset}get size(){return this._size}},RE=class{constructor(t=0,e=1.1){n(this,"_headAll",null);n(this,"_tailAll",null);n(this,"_freeBucketHeads",[]);n(this,"_pool",[]);n(this,"_capacity",0);n(this,"_usedSize",0);n(this,"_freeSize",0);n(this,"_freeRegionCount",0);n(this,"_growMultiplier");if(this._growMultiplier=e,t>0){this._capacity=t,this._freeSize=t;let s=this._obtain(0,t,!0);this._headAll=s,this._tailAll=s,this._addToBucket(s)}}get capacity(){return this._capacity}get usedSize(){return this._usedSize}get freeSize(){return this._freeSize}get fragmentation(){return this._freeSize>0?1-1/this._freeRegionCount:0}_bucketFor(t){return 31-Math.clz32(t)}_addToBucket(t){let e=this._bucketFor(t._size);for(t._bucket=e;e>=this._freeBucketHeads.length;)this._freeBucketHeads.push(null);t._prevFree=null,t._nextFree=this._freeBucketHeads[e],this._freeBucketHeads[e]&&(this._freeBucketHeads[e]._prevFree=t),this._freeBucketHeads[e]=t,this._freeRegionCount++}_removeFromBucket(t){let e=t._bucket;t._prevFree?t._prevFree._nextFree=t._nextFree:this._freeBucketHeads[e]=t._nextFree,t._nextFree&&(t._nextFree._prevFree=t._prevFree),t._prevFree=null,t._nextFree=null,t._bucket=-1,this._freeRegionCount--}_rebucket(t){this._bucketFor(t._size)!==t._bucket&&(this._removeFromBucket(t),this._addToBucket(t))}_obtain(t,e,s){let i;return this._pool.length>0?i=this._pool.pop():i=new WR,i._offset=t,i._size=e,i._free=s,i._prev=null,i._next=null,i._prevFree=null,i._nextFree=null,i._bucket=-1,i}_release(t){t._prev=null,t._next=null,t._prevFree=null,t._nextFree=null,t._bucket=-1,this._pool.push(t)}_insertAfterInMainList(t,e){e===null?(t._prev=null,t._next=this._headAll,this._headAll&&(this._headAll._prev=t),this._headAll=t,this._tailAll||(this._tailAll=t)):(t._prev=e,t._next=e._next,e._next&&(e._next._prev=t),e._next=t,this._tailAll===e&&(this._tailAll=t))}_removeFromMainList(t){t._prev?t._prev._next=t._next:this._headAll=t._next,t._next?t._next._prev=t._prev:this._tailAll=t._prev,t._prev=null,t._next=null}_findFreeBlock(t){let e=this._bucketFor(t),s=this._freeBucketHeads.length;if(e=t&&(!i||r._size0){let r=this._obtain(e,i,!0);this._insertAfterInMainList(r,this._tailAll),this._addToBucket(r)}}_defragIncremental(t,e){let s=Math.ceil(t/2),i=t-s;for(let a=0;a=o._offset)break;this._moveBlock(o,l),e.add(o)}let r=this._headAll;for(let a=0;athis._capacity&&this.grow(l),this.defrag(0);for(let h=s;h0?Math.ceil(a*r):0,r),this.workBuffer=new AS(t,this.scene.gsplat.format),this.layer=s,this._createRenderer(this.scene.gsplat.currentRenderer),this._workBufferFormatVersion=this.workBuffer.format.extraStreamsVersion}destroy(){this._destroyed=!0;for(let[,t]of this.worldStates){for(let e of t.splats)e.resource.decRefCount();t.destroy()}this.worldStates.clear();for(let[,t]of this.octreeInstances)t.destroy();this.octreeInstances.clear();for(let t of this.octreeInstancesToDestroy)t.destroy();this.octreeInstancesToDestroy.length=0,this.destroyGpuSorting(),this.destroyCpuSorting(),this.workBuffer.destroy(),this.renderer.destroy()}destroyGpuSorting(){this.gpuSorter?.destroy(),this.gpuSorter=null,this.projector?.destroy(),this.projector=null;let t=!1;this.renderer.setCpuSortedRendering(),this.destroyIntervalCompaction(t)}destroyIntervalCompaction(t=!0){this.intervalCompaction&&(t&&this.renderer.setCpuSortedRendering(),this.intervalCompaction.destroy(),this.intervalCompaction=null)}destroyCpuSorting(){this.cpuSorter?.destroy(),this.cpuSorter=null}initHybridSorting(){this.gpuSorter||(this.gpuSorter=new tm(this.device,{indirect:!0})),this.projector||(this.projector=new TE(this.device))}initCpuSorting(){this.cpuSorter||(this.cpuSorter=this.createSorter());let t=this.worldStates.get(this.sortedVersion);t&&(t.sortParametersSet=!1,t.sortedBefore=!1,this.cpuSorter.updateCentersForSplats(t.splats)),this.renderer.setCpuSortedRendering()}get material(){return this.renderer.material}prepareForPicking(t,e,s){if(this.activeRenderer===Cc){let r=this.worldStates.get(this.sortedVersion);if(!r?.sortedBefore||!t.node)return null;let a=this.sortGpuHybridForCamera(r,t.node,e,s,Math.max(f_,this.scene.gsplat.alphaClip),!!this.workBuffer.format.getStream("pcId"));if(!a)return null;let o=this.projector,l=this.intervalCompaction;return this.renderer.prepareForPicking(this.indirectDrawSlot,a,o.projCache,l.numSplatsBuffer,this.scene.gsplat.alphaClip,this.scene.gsplat.alphaClipForward,t.node)}return this.activeRenderer!==Hf?null:this.renderer.dispatchPick(t,e,s)}createSorter(){let t=new nE(this.scene);return t.on("sorted",(e,s,i)=>{this.onSorted(e,s,i)}),t}setRenderMode(t){this.renderMode=t,this.renderer.setRenderMode(t)}get canCull(){return this.activeRenderer!==tl&&this.workBuffer.frustumCuller.totalBoundsEntries>0}_createRenderer(t){t===Hf?this.renderer=new vE(this.device,this.node,this.cameraNode,this.layer,this.workBuffer):t===Cc?(this.renderer=new hE(this.device,this.node,this.cameraNode,this.layer,this.workBuffer),this.initHybridSorting()):(this.renderer=new cE(this.device,this.node,this.cameraNode,this.layer,this.workBuffer),this.initCpuSorting()),this.activeRenderer=t}prepareRendererMode(){let t=this.scene.gsplat.currentRenderer;t!==this.activeRenderer&&(this._worldStateDirty=!0,this.destroyGpuSorting(),this.destroyCpuSorting(),this.renderer.destroy(),this._createRenderer(t),this.renderer.setRenderMode(this.renderMode),this._workBufferRebuildRequired=!0,this.sortNeeded=!0)}reconcile(t){__.clear();for(let e of t)e.resource instanceof d_?(this.octreeInstances.has(e)||(this.octreeInstances.set(e,new EE(this.device,e.resource.octree,e)),this.hasNewOctreeInstances=!0),XR.add(e)):__.add(e);for(let[e,s]of this.octreeInstances)XR.has(e)||(this.octreeInstances.delete(e),this.layerPlacementsDirty=!0,this._placementSetChanged=!0,this.octreeInstancesToDestroy.push(s));if(this.layerPlacementsDirty||(this.layerPlacementsDirty=this.layerPlacements.length!==__.size),!this.layerPlacementsDirty)for(let e=0;e{if(o.resource){let l=o.resource;if(this.cpuSorter&&!l.hasCenters)return;o.ensureInstanceStreams(this.device);let h=o.intervals.size>0?a.octree.nodes:null,f=h?a.nodeInfos:null,u=new ZS(this.device,o.resource,o,o.consumeRenderDirty.bind(o),h,f);i.push(u)}});if(this.cpuSorter)for(let a of i){let o=a.resource;this._centersVersions.get(o.id)!==o.centersVersion&&(this._centersVersions.set(o.id,o.centersVersion),this.cpuSorter.setCenters(o.id,null),this.cpuSorter.setCenters(o.id,o.centers))}this.cpuSorter?.updateCentersForSplats(i);let r=new PE(this.device,this.lastWorldStateVersion,i,this._allocator,this._allocationMap);for(let a of r.splats)a.resource.incRefCount();for(let[,a]of this.octreeInstances)if(a.removedCandidates&&a.removedCandidates.size){for(let o of a.removedCandidates)r.pendingReleases.push([a.octree,o]);a.removedCandidates.clear()}if(this.octreeInstancesToDestroy.length){for(let a of this.octreeInstancesToDestroy){if(a.removedCandidates&&a.removedCandidates.size){for(let l of a.removedCandidates)r.pendingReleases.push([a.octree,l]);a.removedCandidates.clear()}let o=a.getFileDecrements();for(let l of o)r.pendingReleases.push([a.octree,l]);a.destroy(!0)}this.octreeInstancesToDestroy.length=0}this._placementSetChanged&&(r.fullRebuild=!0),this.worldStates.set(this.lastWorldStateVersion,r),this.layerPlacementsDirty=!1,this._placementSetChanged=!1,this._worldStateDirty=!1,this.sortNeeded=!0}}onSorted(t,e,s){this.cleanupOldWorldStates(e),this.sortedVersion=e;let i=this.worldStates.get(e);i&&(i.sortedBefore||(i.sortedBefore=!0,this.rebuildWorkBuffer(i,t)),this.workBuffer.setOrderData(s),this.renderer.setOrderData())}rebuildWorkBuffer(t,e,s=!1){let i=t.textureSize;i!==this.workBuffer.textureSize&&this.workBuffer.resize(i),this.activeRenderer!==tl&&(this.workBuffer.frustumCuller.updateBoundsData(t.boundsGroups),this.workBuffer.frustumCuller.updateTransformsData(t.boundsGroups));let r=s||t.fullRebuild,a=r?t.splats:t.needsUpload,o=r?null:t.needsUploadIds;if(a.length>0){let l=this._allocationMap.size,h=r?l:t.needsUploadIds.size;this.bufferCopyUploaded+=h,this.bufferCopyTotal=l,this.workBuffer.render(a,this.cameraNode,this.getDebugColors(),o)}for(let l=0;l0,o=0;t.splats.forEach(l=>{if(l.update()){if(bE.push(l),o+=l.intervalAllocIds.length,l.nodeInfos)for(let h of l.intervalNodeIndices)l.nodeInfos[h].colorAccumulatedTranslation=0;else l.colorAccumulatedTranslation=0;this.sortNeeded=!0}else if(a&&l.hasSphericalHarmonics)if(YR.push(l),l.nodeInfos){let h=l.intervalNodeIndices;for(let f=0;f=d&&(tx.add(l.intervalAllocIds[f]),u.colorAccumulatedTranslation=0,o++)}}else{l.colorAccumulatedTranslation+=r,ex.copy(l.node.getWorldTransform()).invert(),ex.transformPoint(i,jR),l.aabb.closestPoint(jR,pz);let h=jR.distance(pz)*l.node.getWorldTransform().getScale().x,f=s*Math.max(1,h);l.colorAccumulatedTranslation>=f&&(tx.add(l.allocId),o+=l.intervalAllocIds.length,l.colorAccumulatedTranslation=0)}}),this.bufferCopyUploaded+=o,this.bufferCopyTotal=this._allocationMap.size,bE.length>0&&(this.workBuffer.render(bE,this.cameraNode,this.getDebugColors()),bE.length=0),tx.size>0&&(this.workBuffer.renderColor(YR,this.cameraNode,this.getDebugColors(),tx),tx.clear()),YR.length=0}testCameraMovedForLod(){let t=this.scene.gsplat.lodUpdateDistance,e=this.cameraNode.getPosition(),s=this.lastLodCameraPos.distance(e)>t;if(s)return!0;let i=!1,r=this.scene.gsplat.lodUpdateAngle;if(r>0)if(Number.isFinite(this.lastLodCameraFwd.x)){let l=this.cameraNode.forward,h=Math.min(1,Math.max(-1,this.lastLodCameraFwd.dot(l))),f=Math.acos(h),u=r*R.DEG_TO_RAD;i=f>u}else i=!0;let a=this.cameraNode.camera.fov,o=this.lastLodCameraFov<0||Math.abs(a-this.lastLodCameraFov)>this.lastLodCameraFov*.02;return s||i||o}testCameraMovedForSort(){if(this.scene.gsplat.radialSorting){let e=this.cameraNode.getPosition();return this.lastSortCameraPos.distance(e)>.001}if(Number.isFinite(this.lastSortCameraFwd.x)){let e=this.cameraNode.forward,s=Math.min(1,Math.max(-1,this.lastSortCameraFwd.dot(e)));return Math.acos(s)>.001}return!0}testFrustumChanged(){if(!this.lastCullingProjMat.equals(this.cameraNode.camera.projectionMatrix))return!0;let e=this.cameraNode.forward,s=Math.min(1,Math.max(-1,this.lastCullingCameraFwd.dot(e)));return Math.acos(s)>.001}updateColorCameraTracking(){this.lastColorUpdateCameraPos.copy(this.cameraNode.getPosition())}getDebugColors(){let t=this.scene.gsplat.debug;if(t===yp){xh??(xh=[]);let e=Math.random(),s=Math.random(),i=Math.random();for(let r=0;rt&&(t=a)}return Math.max(t,1)}_enforceBudget(t){let e=this.workBuffer.textureSize,s=0,i=0;for(let h of this.layerPlacements){let f=h.resource;if(f){let u=f.numSplats??0;s+=u,i+=(e-u%e)%e}}let r=Math.max(1,t-s),a=this.computeGlobalMaxDistance(),o=0;for(let[,h]of this.octreeInstances){o+=h.evaluateOptimalLods(this.cameraNode,this.scene.gsplat,this._budgetScale,a);for(let f of h.activePlacements){let d=f.resource?.numSplats??0;i+=(e-d%e)%e}}let l=Math.max(1,r-i);if(o>0){let h=o/l,f=.4,u=.3;if(h>1+f||h<1-f){let d=1/Math.sqrt(h);this._budgetScale*=1+(d-1)*u,this._budgetScale=Math.max(.01,Math.min(this._budgetScale,100))}}this._budgetBalancer.balance(this.octreeInstances,l);for(let[,h]of this.octreeInstances){let f=h.octree.lodLevels-1;h.applyLodChanges(f,this.scene.gsplat)}}handleFormatChange(){let t=this.scene.gsplat.format;this.workBuffer.format!==t&&(this.workBuffer.destroy(),this.workBuffer=new AS(this.device,t),this.renderer.setDataSource(this.workBuffer),this._workBufferFormatVersion=this.workBuffer.format.extraStreamsVersion,this._workBufferRebuildRequired=!0,this.sortNeeded=!0)}update(){this.bufferCopyUploaded=0,this.bufferCopyTotal=0,this.handleFormatChange();let t=this.workBuffer.format.extraStreamsVersion;this._workBufferFormatVersion!==t&&(this._workBufferFormatVersion=t,this.workBuffer.syncWithFormat(),this._workBufferRebuildRequired=!0,this.sortNeeded=!0),this.prepareRendererMode(),this.cpuSorter&&this.cpuSorter.applyPendingSorted();let e=this.activeRenderer!==tl||this.cpuSorter&&this.cpuSorter.jobsInFlight<3,s=!1;this.framesTillFullUpdate--,this.framesTillFullUpdate<=0&&(this.framesTillFullUpdate=10,e&&(s=!0));let i=this.hasNewOctreeInstances&&e;i&&(this.hasNewOctreeInstances=!1);let r=!1,a=!1,o=!1;if(s){for(let[,p]of this.octreeInstances){let m=p.update();this.layerPlacementsDirty||(this.layerPlacementsDirty=m),this._placementSetChanged||(this._placementSetChanged=p.consumePlacementSetChanged());let _=p.consumeNeedsLodUpdate();r||(r=_)}let d=this.scene.gsplat.lodUpdateDistance;for(let[,p]of this.octreeInstances){let m=p.testMoved(d);a||(a=m)}o=this.testCameraMovedForLod(),this._awaitingLodUpdate=!1}if(this.testCameraMovedForSort()&&(this.sortNeeded=!0),this.intervalCompaction&&!this.sortNeeded&&this.testFrustumChanged()&&(this.lastCullingCameraFwd.copy(this.cameraNode.forward),this.lastCullingProjMat.copy(this.cameraNode.camera.projectionMatrix),this.sortNeeded=!0),this.scene.gsplat.dirty&&(this.layerPlacementsDirty=!0,this.renderer.updateOverdrawMode(this.scene.gsplat),this._workBufferRebuildRequired=!0,this.sortNeeded=!0,this.octreeInstances.size>0&&(this._awaitingLodUpdate=!0)),o||a||this.scene.gsplat.dirty||r||i){for(let[,m]of this.octreeInstances)m.updateMoved();let d=this.cameraNode;this.lastLodCameraPos.copy(d.getPosition()),this.lastLodCameraFwd.copy(d.forward),this.lastLodCameraFov=d.camera.fov;let p=this.scene.gsplat.splatBudget;if(p>0)this._enforceBudget(p);else{this._budgetScale=1;for(let[,m]of this.octreeInstances)m.updateLod(this.cameraNode,this.scene.gsplat)}}this.updateWorldState();let l=this.worldStates.get(this.lastWorldStateVersion);if(l&&this.cpuSorter&&!l.sortParametersSet){l.sortParametersSet=!0;let d=this.prepareSortParameters(l);this.cpuSorter.setSortParameters(d)}let h=this.worldStates.get(this.sortedVersion);if(h?.sortedBefore)if(this._workBufferRebuildRequired){let d=h.totalActiveSplats;this.rebuildWorkBuffer(h,d,!0),this._workBufferRebuildRequired=!1,this.renderer.setOrderData(),this.intervalCompaction&&(this.intervalCompaction._uploadedVersion=-1)}else this.applyWorkBufferUpdates(h);let f=!1;if(this.sortNeeded&&l&&(this.activeRenderer===Hf?(this.compactGpu(l),f=!0):this.activeRenderer===Cc?(this.sortGpuHybrid(l),f=!0):this.sortCpu(l),this.sortNeeded=!1,this.lastSortCameraPos.copy(this.cameraNode.getPosition()),this.lastSortCameraFwd.copy(this.cameraNode.forward),this.lastCullingCameraFwd.copy(this.cameraNode.forward),this.lastCullingProjMat.copy(this.cameraNode.camera.projectionMatrix)),this.activeRenderer===Cc&&l&&!f&&(this.sortGpuHybrid(l),f=!0),h?.sortedBefore&&this.updateColorCameraTracking(),this.octreeInstances.size){let d=this.scene.gsplat.cooldownTicks;for(let[,p]of this.octreeInstances){let m=p.octree;qR.has(m)||(qR.add(m),m.updateCooldownTick(d))}qR.clear()}if(this.fireFrameReadyEvent(),this.scene.gsplat.dirty)for(let[,d]of this.octreeInstances)d.needsLodUpdate=!0;let u=this.scene.gsplat.useFog?this.cameraNode.camera.fogParams??this.scene.fog:null;return this.renderer.frameUpdate(this.scene.gsplat,this.scene.exposure,u),h?h.totalActiveSplats:0}sortGpuHybrid(t){let e=this.cameraNode.camera,s=e.camera,i=e.renderTarget,r=e.rect,a=s.xr?.session?s.xr.views.list[0]:null,o=Math.floor((a?a.viewport.z:i?i.width:this.device.width)*r.z),l=Math.floor((a?a.viewport.w:i?i.height:this.device.height)*r.w),h=this.sortGpuHybridForCamera(t,this.cameraNode,o,l,Math.max(f_,this.scene.gsplat.alphaClipForward),!1);h&&this.applyGpuSortResults(h)}sortGpuHybridForCamera(t,e,s,i,r,a){let o=this.gpuSorter,l=this.projector;if(!o||!l)return null;let h=t.totalActiveSplats;if(h===0)return null;if(this.intervalCompaction||(this.intervalCompaction=new QS(this.device)),t.sortedBefore||(t.sortedBefore=!0,this.cleanupOldWorldStates(t.version),this.sortedVersion=t.version,this.rebuildWorkBuffer(t,h)),this.intervalCompaction.uploadIntervals(t),this.canCull){let y=this.worldStates.get(this.sortedVersion);y&&this._runFrustumCulling(y,e)}let f=this.renderer.fisheyeProj,u=t.totalIntervals,d=t.totalActiveSplats;this.intervalCompaction.dispatchCompact(this.workBuffer.frustumCuller,u,d,f.enabled),this.allocateAndWriteIntervalIndirectArgs(u);let p=this.intervalCompaction,m=p.compactedSplatIds,_=this.scene.gsplat,S=Math.max(10,Math.min(20,Math.round(Math.log2(h/4)))),g=o.radixBits,T=Math.ceil(S/g)*g,{minDist:C,maxDist:v}=this.computeDistanceRange(t,e),E=o.prepareIndirect();return l.dispatch({workBuffer:this.workBuffer,cameraNode:e,compactedSplatIds:m,sortElementCountBuffer:p.sortElementCountBuffer,totalCapacity:h,radialSort:_.radialSorting,numBits:T,minDist:C,maxDist:v,alphaClip:r,minPixelSize:_.minPixelSize*.5,minContribution:_.minContribution,viewportWidth:s,viewportHeight:i,flipY:!!e.camera.renderTarget?.flipY,pickMode:a,fisheyeProj:f,antiAlias:_.antiAlias}),l.writeIndirectArgs(this.indirectDrawSlot,this.indirectDispatchSlot+1,p.numSplatsBuffer,p.sortElementCountBuffer,E),o.sortIndirect(l.sortKeys,h,T,this.indirectDispatchSlot+1,p.sortElementCountBuffer,void 0,!1,!0)}compactGpu(t){this.intervalCompaction||(this.intervalCompaction=new QS(this.device));let e=t.totalActiveSplats;if(e===0)return;if(t.sortedBefore||(t.sortedBefore=!0,this.cleanupOldWorldStates(t.version),this.sortedVersion=t.version,this.rebuildWorkBuffer(t,e)),this.intervalCompaction.uploadIntervals(t),this.canCull){let o=this.worldStates.get(this.sortedVersion);o&&this._runFrustumCulling(o)}let s=t.totalIntervals,i=t.totalActiveSplats;this.intervalCompaction.dispatchCompact(this.workBuffer.frustumCuller,s,i,this.renderer.fisheyeProj.enabled),this.allocateAndWriteIntervalIndirectArgs(s);let r=this.intervalCompaction;this.renderer.setCompactedData(r.compactedSplatIds,r.sortElementCountBuffer,t.textureSize,i)}allocateAndWriteIntervalIndirectArgs(t){let e=this.gpuSorter,s=e?e.prepareIndirect():kK,i=s[0];this.indirectDrawSlot=this.device.getIndirectDrawSlot(1),this.indirectDispatchSlot=this.device.getIndirectDispatchSlot(1+i),this.intervalCompaction.writeIndirectArgs(this.indirectDrawSlot,this.indirectDispatchSlot,t,s),this.lastCompactedNumIntervals=t}applyGpuSortResults(t){let e=this.projector,s=this.intervalCompaction;this.renderer.setHybridSortedRendering(this.indirectDrawSlot,t,e.projCache,s.numSplatsBuffer)}_runFrustumCulling(t,e=this.cameraNode){this.workBuffer.frustumCuller.updateTransformsData(t.boundsGroups);let s=e.camera;this.workBuffer.frustumCuller.computeFrustumPlanes(s.projectionMatrix,s.viewMatrix);let i=this.scene.gsplat,r=this.renderer.fisheyeProj;r.update(i.fisheye,s.fov,s.projectionMatrix),r.enabled&&this.workBuffer.frustumCuller.setFisheyeData(e.getPosition(),e.forward,r.maxTheta)}computeDistanceRange(t,e=this.cameraNode){let s=e.getWorldTransform();s.getTranslation(Sh),s.getZ(JS).normalize();let i=this.scene.gsplat.radialSorting,r=i?0:1/0,a=i?0:-1/0;for(let o of t.splats){let l=o.node.getWorldTransform(),h=o.aabb.getMin(),f=o.aabb.getMax();for(let u=0;u<8;u++)if(wl.x=u&1?f.x:h.x,wl.y=u&2?f.y:h.y,wl.z=u&4?f.z:h.z,l.transformPoint(wl,wl),i){let d=wl.distance(Sh);d>a&&(a=d)}else{let d=wl.sub(Sh).dot(JS);da&&(a=d)}}return a===0||a===-1/0?{minDist:0,maxDist:1}:{minDist:r,maxDist:a}}sortCpu(t){if(!this.cpuSorter)return;let s=this.cameraNode.getWorldTransform();s.getTranslation(Sh),s.getZ(JS).normalize();let i=[];t.splats.forEach(r=>{let a=r.node.getWorldTransform();ex.copy(a).invert();let o=a.getScale().x,l=ex.transformVector(JS).normalize(),h=ex.transformPoint(Sh);a.getTranslation(dz);let f=dz.sub(Sh).dot(JS),u=r.aabb.getMin(),d=r.aabb.getMax();i.push({transformedDirection:l,transformedPosition:h,offset:f,scale:o,modelMat:a.data.slice(),aabbMin:[u.x,u.y,u.z],aabbMax:[d.x,d.y,d.z]})}),this.cpuSorter.setSortParams(i,this.scene.gsplat.radialSorting)}prepareSortParameters(t){return{command:"intervals",textureSize:t.textureSize,totalActiveSplats:t.totalActiveSplats,version:t.version,ids:t.splats.map(e=>e.resource.id),pixelOffsets:t.splats.map(e=>e.intervalOffsets),intervals:t.splats.map(e=>e.intervals)}}};var LE=class{static equals(t,e){if(t.size!==e.size)return!1;for(let s of t)if(!e.has(s))return!1;return!0}};var ME=[],ZR=class{constructor(t,e,s,i){n(this,"gsplatManager",null);n(this,"gsplatManagerShadow",null);this.updateConfiguration(t,e,s,i)}createManager(t,e,s,i,r,a){let o=new DE(t,e,s,i);return o.setRenderMode(a),e.eventHandler&&e.eventHandler.fire("material:created",o.material,r,s),o}updateConfiguration(t,e,s,i){let r=i.node,a=s.gsplatPlacements.length>0,o=s.gsplatShadowCasters.length>0,h=LE.equals(s.gsplatPlacementsSet,s.gsplatShadowCastersSet)&&a,f=h?Fs|el:a?Fs:0,u=h?0:o?el:0;f?this.gsplatManager?this.gsplatManager.setRenderMode(f):this.gsplatManager=this.createManager(t,e,s,r,i,f):this.gsplatManager&&(this.gsplatManager.destroy(),this.gsplatManager=null),u?this.gsplatManagerShadow?this.gsplatManagerShadow.setRenderMode(u):this.gsplatManagerShadow=this.createManager(t,e,s,r,i,u):this.gsplatManagerShadow&&(this.gsplatManagerShadow.destroy(),this.gsplatManagerShadow=null)}destroy(){this.gsplatManager?.destroy(),this.gsplatManager=null,this.gsplatManagerShadow?.destroy(),this.gsplatManagerShadow=null}},QR=class{constructor(){n(this,"layersMap",new Map)}destroy(){this.layersMap.forEach(t=>t.destroy()),this.layersMap.clear()}removeLayerData(t){let e=this.layersMap.get(t);e&&(e.destroy(),this.layersMap.delete(t))}getLayerData(t,e,s,i){let r=this.layersMap.get(s);return r||(r=new ZR(t,e,s,i),this.layersMap.set(s,r)),r}},OE=class{constructor(t,e,s,i){n(this,"device");n(this,"camerasMap",new Map);n(this,"scene");n(this,"eventHandler");this.device=t,this.renderer=e,this.scene=s,this.eventHandler=i}destroy(){this.camerasMap.forEach(t=>t.destroy()),this.camerasMap.clear()}getCameraData(t){let e=this.camerasMap.get(t);return e||(e=new QR,this.camerasMap.set(t,e)),e}prepareForPicking(t,e,s,i){let r=this.camerasMap.get(t);if(!r)return null;let a=r.layersMap.get(i);return a?.gsplatManager?a.gsplatManager.prepareForPicking(t,e,s):null}update(t){am.process(this.device),this.camerasMap.forEach((a,o)=>{if(!t.camerasSet.has(o))a.destroy(),this.camerasMap.delete(o);else{a.layersMap.forEach((l,h)=>{(!o.layersSet.has(h.id)||!h.enabled)&&ME.push(h)});for(let l=0;l0,p=u.gsplatShadowCasters.length>0;if(!d&&!p)l&&l.removeLayerData(u);else{l??(l=this.getCameraData(o));let m=l.getLayerData(this.device,this,u,o);m.updateConfiguration(this.device,this,u,o),m.gsplatManager&&m.gsplatManager.reconcile(u.gsplatPlacements),m.gsplatManagerShadow&&m.gsplatManagerShadow.reconcile(u.gsplatShadowCasters)}}}if(l)for(let f of l.layersMap.values())f.gsplatManager&&(e+=f.gsplatManager.update(),s+=f.gsplatManager.bufferCopyUploaded,i+=f.gsplatManager.bufferCopyTotal),f.gsplatManagerShadow&&(e+=f.gsplatManagerShadow.update(),s+=f.gsplatManagerShadow.bufferCopyUploaded,i+=f.gsplatManagerShadow.bufferCopyTotal)}this.renderer._gsplatCount=e,this.renderer._gsplatBufferCopy=i>0?s/i*100:0,this.scene.gsplat.frameEnd();for(let a=0;a0&&(this.lodBaseDistance=e[0],this.lodMultiplier=3)}get lodDistances(){return[]}set splatBudget(e){}get splatBudget(){return 0}set unified(e){this._unified!==e&&(this._unified=e,this._onGSplatAssetAdded())}get unified(){return this._unified}get id(){return this._id}set workBufferUpdate(e){this._workBufferUpdate=e,this._placement&&(this._placement.workBufferUpdate=e)}get workBufferUpdate(){return this._workBufferUpdate}setWorkBufferModifier(e){if(e){let i=(this.system.app.graphicsDevice.isWebGPU?e.wgsl:e.glsl)??null;this._workBufferModifier=i?{code:i,hash:xt(i)}:null}else this._workBufferModifier=null;this._placement&&(this._placement.workBufferModifier=this._workBufferModifier)}set layers(e){this.removeFromLayers(),this._layers.length=0;for(let s=0;s 0 + const float SH_C1 = 0.4886025119029199f; + #if SH_BANDS > 1 + const float SH_C2_0 = 1.0925484305920792f; + const float SH_C2_1 = -1.0925484305920792f; + const float SH_C2_2 = 0.31539156525252005f; + const float SH_C2_3 = -1.0925484305920792f; + const float SH_C2_4 = 0.5462742152960396f; + #endif + #if SH_BANDS > 2 + const float SH_C3_0 = -0.5900435899266435f; + const float SH_C3_1 = 2.890611442640554f; + const float SH_C3_2 = -0.4570457994644658f; + const float SH_C3_3 = 0.3731763325901154f; + const float SH_C3_4 = -0.4570457994644658f; + const float SH_C3_5 = 1.445305721320277f; + const float SH_C3_6 = -0.5900435899266435f; + #endif + vec3 evalSH(in vec3 sh[SH_COEFFS], in vec3 dir) { + float x = dir.x; + float y = dir.y; + float z = dir.z; + vec3 result = SH_C1 * (-sh[0] * y + sh[1] * z - sh[2] * x); + #if SH_BANDS > 1 + float xx = x * x; + float yy = y * y; + float zz = z * z; + float xy = x * y; + float yz = y * z; + float xz = x * z; + result += + sh[3] * (SH_C2_0 * xy) + + sh[4] * (SH_C2_1 * yz) + + sh[5] * (SH_C2_2 * (2.0 * zz - xx - yy)) + + sh[6] * (SH_C2_3 * xz) + + sh[7] * (SH_C2_4 * (xx - yy)); + #endif + #if SH_BANDS > 2 + result += + sh[8] * (SH_C3_0 * y * (3.0 * xx - yy)) + + sh[9] * (SH_C3_1 * xy * z) + + sh[10] * (SH_C3_2 * y * (4.0 * zz - xx - yy)) + + sh[11] * (SH_C3_3 * z * (2.0 * zz - 3.0 * xx - 3.0 * yy)) + + sh[12] * (SH_C3_4 * x * (4.0 * zz - xx - yy)) + + sh[13] * (SH_C3_5 * z * (xx - yy)) + + sh[14] * (SH_C3_6 * x * (xx - 3.0 * yy)); + #endif + return result; + } + #endif +`;var vz=` +void gsplatMakeSpherical(inout vec3 scale, float size) { + scale = vec3(size); +} +float gsplatGetSizeFromScale(vec3 scale) { + return sqrt((scale.x * scale.x + scale.y * scale.y + scale.z * scale.z) / 3.0); +} +`;var Tz=` +void modifySplatCenter(inout vec3 center) { +} +void modifySplatRotationScale(vec3 originalCenter, vec3 modifiedCenter, inout vec4 rotation, inout vec3 scale) { +} +void modifySplatColor(vec3 center, inout vec4 color) { +} +`;var yz=` +mat3 quatToMat3(vec4 R) { + vec4 R2 = R + R; + float X = R2.x * R.w; + vec4 Y = R2.y * R; + vec4 Z = R2.z * R; + float W = R2.w * R.w; + return mat3( + 1.0 - Z.z - W, + Y.z + X, + Y.w - Z.x, + Y.z - X, + 1.0 - Y.y - W, + Z.w + Y.x, + Y.w + Z.x, + Z.w - Y.x, + 1.0 - Y.y - Z.z + ); +} +vec4 quatMul(vec4 a, vec4 b) { + return vec4( + a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, + a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, + a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, + a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z + ); +} +`;var Ez=` +#include "gsplatSplatVS" +struct SplatSource { + uint order; + vec2 cornerUV; +}; +struct SplatCenter { + vec3 view; + vec4 proj; + mat4 modelView; + float projMat00; + vec3 modelCenterOriginal; + vec3 modelCenterModified; + #ifdef GSPLAT_FISHEYE + float fisheyeSinTK; + float fisheyeCosTK; + float fisheyeRxy; + #endif +}; +struct SplatCorner { + vec3 offset; + vec2 uv; + #if GSPLAT_AA + float aaFactor; + #endif + vec2 v; + float dlen; +}; +`;var Az=` uniform vec4 viewport_size; uniform float minPixelSize; void computeCovariance(vec4 rotation, vec3 scale, out vec3 covA, out vec3 covB) { @@ -15437,164 +16152,7 @@ bool initCorner(SplatSource source, SplatCenter center, out SplatCorner corner) return initCornerCov(source, center, corner, covA, covB); #endif } -`,gsplatCommonVS:` -#include "gsplatHelpersVS" -#include "gsplatFormatVS" -#include "gsplatStructsVS" -#include "gsplatDeclarationsVS" -#include "gsplatModifyVS" -#include "gsplatEvalSHVS" -#include "gsplatQuatToMat3VS" -#include "gsplatReadVS" -#include "gsplatSourceVS" -#include "gsplatCenterVS" -#include "gsplatCornerVS" -#include "gsplatOutputVS" -void clipCorner(inout SplatCorner corner, float alpha) { - float clip = min(1.0, sqrt(log(255.0 * alpha)) * 0.5); - corner.offset *= clip; - corner.uv *= clip; -} -`,gsplatSplatVS:` -struct Splat { - uint index; - ivec2 uv; -}; -Splat splat; -void setSplat(uint idx) { - splat.index = idx; - splat.uv = ivec2(idx % splatTextureSize, idx / splatTextureSize); -} -`,gsplatEvalSHVS:` - #if SH_BANDS == 1 - #define SH_COEFFS 3 - #elif SH_BANDS == 2 - #define SH_COEFFS 8 - #elif SH_BANDS == 3 - #define SH_COEFFS 15 - #else - #define SH_COEFFS 0 - #endif - #if SH_BANDS > 0 - const float SH_C1 = 0.4886025119029199f; - #if SH_BANDS > 1 - const float SH_C2_0 = 1.0925484305920792f; - const float SH_C2_1 = -1.0925484305920792f; - const float SH_C2_2 = 0.31539156525252005f; - const float SH_C2_3 = -1.0925484305920792f; - const float SH_C2_4 = 0.5462742152960396f; - #endif - #if SH_BANDS > 2 - const float SH_C3_0 = -0.5900435899266435f; - const float SH_C3_1 = 2.890611442640554f; - const float SH_C3_2 = -0.4570457994644658f; - const float SH_C3_3 = 0.3731763325901154f; - const float SH_C3_4 = -0.4570457994644658f; - const float SH_C3_5 = 1.445305721320277f; - const float SH_C3_6 = -0.5900435899266435f; - #endif - vec3 evalSH(in vec3 sh[SH_COEFFS], in vec3 dir) { - float x = dir.x; - float y = dir.y; - float z = dir.z; - vec3 result = SH_C1 * (-sh[0] * y + sh[1] * z - sh[2] * x); - #if SH_BANDS > 1 - float xx = x * x; - float yy = y * y; - float zz = z * z; - float xy = x * y; - float yz = y * z; - float xz = x * z; - result += - sh[3] * (SH_C2_0 * xy) + - sh[4] * (SH_C2_1 * yz) + - sh[5] * (SH_C2_2 * (2.0 * zz - xx - yy)) + - sh[6] * (SH_C2_3 * xz) + - sh[7] * (SH_C2_4 * (xx - yy)); - #endif - #if SH_BANDS > 2 - result += - sh[8] * (SH_C3_0 * y * (3.0 * xx - yy)) + - sh[9] * (SH_C3_1 * xy * z) + - sh[10] * (SH_C3_2 * y * (4.0 * zz - xx - yy)) + - sh[11] * (SH_C3_3 * z * (2.0 * zz - 3.0 * xx - 3.0 * yy)) + - sh[12] * (SH_C3_4 * x * (4.0 * zz - xx - yy)) + - sh[13] * (SH_C3_5 * z * (xx - yy)) + - sh[14] * (SH_C3_6 * x * (xx - 3.0 * yy)); - #endif - return result; - } - #endif -`,gsplatHelpersVS:` -void gsplatMakeSpherical(inout vec3 scale, float size) { - scale = vec3(size); -} -float gsplatGetSizeFromScale(vec3 scale) { - return sqrt((scale.x * scale.x + scale.y * scale.y + scale.z * scale.z) / 3.0); -} -`,gsplatModifyVS:` -void modifySplatCenter(inout vec3 center) { -} -void modifySplatRotationScale(vec3 originalCenter, vec3 modifiedCenter, inout vec4 rotation, inout vec3 scale) { -} -void modifySplatColor(vec3 center, inout vec4 color) { -} -`,gsplatQuatToMat3VS:` -mat3 quatToMat3(vec4 R) { - vec4 R2 = R + R; - float X = R2.x * R.w; - vec4 Y = R2.y * R; - vec4 Z = R2.z * R; - float W = R2.w * R.w; - return mat3( - 1.0 - Z.z - W, - Y.z + X, - Y.w - Z.x, - Y.z - X, - 1.0 - Y.y - W, - Z.w + Y.x, - Y.w + Z.x, - Z.w - Y.x, - 1.0 - Y.y - Z.z - ); -} -vec4 quatMul(vec4 a, vec4 b) { - return vec4( - a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, - a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, - a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, - a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z - ); -} -`,gsplatStructsVS:` -#include "gsplatSplatVS" -struct SplatSource { - uint order; - vec2 cornerUV; -}; -struct SplatCenter { - vec3 view; - vec4 proj; - mat4 modelView; - float projMat00; - vec3 modelCenterOriginal; - vec3 modelCenterModified; - #ifdef GSPLAT_FISHEYE - float fisheyeSinTK; - float fisheyeCosTK; - float fisheyeRxy; - #endif -}; -struct SplatCorner { - vec3 offset; - vec2 uv; - #if GSPLAT_AA - float aaFactor; - #endif - vec2 v; - float dlen; -}; -`,gsplatOutputVS:` +`;var Cz=` #include "tonemappingPS" #include "decodePS" #include "gammaPS" @@ -15618,7 +16176,7 @@ vec3 prepareOutputFromGamma(vec3 gammaColor, float depth) { #endif return color; } -`,gsplatPS:` +`;var Pz=` #ifndef DITHER_NONE #include "bayerPS" #include "opacityDitherPS" @@ -15631,6 +16189,9 @@ vec3 prepareOutputFromGamma(vec3 gammaColor, float depth) { varying float vLinearDepth; #include "floatAsUintPS" #endif +#if !defined(SHADOW_PASS) && !defined(PICK_PASS) && !defined(PREPASS_PASS) + uniform float alphaClipForward; +#endif varying mediump vec2 gaussianUV; varying mediump vec4 gaussianColor; #if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) @@ -15669,7 +16230,7 @@ void main(void) { #elif PREPASS_PASS gl_FragColor = float2vec4(vLinearDepth); #else - if (alpha < 1.0 / 255.0) { + if (alpha < alphaClipForward) { discard; } #ifndef DITHER_NONE @@ -15678,7 +16239,7 @@ void main(void) { gl_FragColor = vec4(gaussianColor.xyz * alpha, alpha); #endif } -`,gsplatSourceVS:` +`;var wz=` attribute vec3 vertex_position; uniform uint numSplats; uniform highp usampler2D splatOrder; @@ -15693,7 +16254,7 @@ bool initSource(out SplatSource source) { source.cornerUV = vertex_position.xy; return true; } -`,gsplatVS:` +`;var Iz=` #include "gsplatCommonVS" varying mediump vec2 gaussianUV; varying mediump vec4 gaussianColor; @@ -15749,7 +16310,12 @@ void main(void) { clr.xyz += evalSH(sh, dir) * scale; #endif modifySplatColor(modelCenter, clr); - if (255.0 * clr.w <= 1.0) { + #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) + float alphaClipValue = alphaClip; + #else + float alphaClipValue = alphaClipForward; + #endif + if (clr.w <= alphaClipValue) { gl_Position = discardVec; return; } @@ -15779,7 +16345,7 @@ void main(void) { vPickId = loadPcId().r; #endif } -`,gsplatPackingPS:` +`;var Rz=` uint pack8888(vec4 v) { uvec4 t = uvec4(v * 255.0) << uvec4(24u, 16u, 8u, 0u); return t.x | t.y | t.z | t.w; @@ -15810,13 +16376,13 @@ vec3 resolveCodebook(vec3 s, vec4 codebook[64]) { ); return (v - codebook[0].x) / (codebook[63].w - codebook[0].x); } -`,gsplatFormatVS:` +`;var bz=` uniform uint splatTextureSize; -`,gsplatUncompressedVS:` +`;var Dz=` uint tAw; vec4 tBcached; -vec4 unpackRotation(vec3 packed) { - return vec4(packed.xyz, sqrt(max(0.0, 1.0 - dot(packed, packed)))); +vec4 unpackRotation(vec3 data) { + return vec4(data.xyz, sqrt(max(0.0, 1.0 - dot(data, data)))); } vec3 getCenter() { uvec4 tA = loadTransformA(); @@ -15834,7 +16400,7 @@ vec3 getScale() { return tBcached.xyz; } #include "gsplatUncompressedSHVS" -`,gsplatUncompressedSHVS:` +`;var Lz=` #if SH_BANDS > 0 vec3 unpack111011s(uint bits) { return vec3((uvec3(bits) >> uvec3(21u, 11u, 0u)) & uvec3(0x7ffu, 0x3ffu, 0x7ffu)) / vec3(2047.0, 1023.0, 2047.0) * 2.0 - 1.0; @@ -15873,7 +16439,7 @@ void fetch(in uint t, out vec3 a) { } #endif #endif -`,gsplatCompressedVS:` +`;var Mz=` #include "gsplatPackingPS" uniform highp sampler2D chunkTexture; vec4 chunkDataA; @@ -15924,7 +16490,7 @@ vec3 getScale() { return exp(mix(vec3(chunkDataB.zw, chunkDataC.x), chunkDataC.yzw, unpack111011(packedData.z))); } #include "gsplatCompressedSHVS" -`,gsplatCompressedSHVS:` +`;var Oz=` #if SH_BANDS > 0 vec4 unpack8888s(in uint bits) { return vec4((uvec4(bits) >> uvec4(0u, 8u, 16u, 24u)) & 0xffu) * (8.0 / 255.0) - 4.0; @@ -15963,68 +16529,92 @@ void readSHData(out vec3 sh[15], out float scale) { scale = 1.0; } #endif -`,gsplatSogVS:` -#include "gsplatPackingPS" +`;var Fz=` uniform vec3 means_mins; uniform vec3 means_maxs; -uniform float scales_mins; -uniform float scales_maxs; -uniform float sh0_mins; -uniform float sh0_maxs; -uniform highp sampler2D packedSh0; +#ifndef SOG_V2 + uniform vec3 scales_mins; + uniform vec3 scales_maxs; + uniform vec4 sh0_mins; + uniform vec4 sh0_maxs; +#endif const float SH_C0 = 0.28209479177387814; -uvec4 packedSample; const float norm = sqrt(2.0); +#ifdef SOG_V2 + float lutScales(int b) { return texelFetch(sogCodebook, ivec2(b, 0), 0).r; } + float lutSh0(int b) { return texelFetch(sogCodebook, ivec2(b, 0), 0).g; } + float lutShN(int b) { return texelFetch(sogCodebook, ivec2(b, 0), 0).b; } +#endif vec3 getCenter() { - packedSample = loadPackedTexture(); - vec3 l = unpack8888(packedSample.x).xyz; - vec3 u = unpack8888(packedSample.y).xyz; + vec3 l = texelFetch(means_l, splat.uv, 0).xyz; + vec3 u = texelFetch(means_u, splat.uv, 0).xyz; vec3 n = (l + u * 256.0) / 257.0; vec3 v = mix(means_mins, means_maxs, n); return sign(v) * (exp(abs(v)) - 1.0); } -vec4 getColor() { - vec3 clr = mix(vec3(sh0_mins), vec3(sh0_maxs), unpack111110(pack8888(texelFetch(packedSh0, splat.uv, 0)))); - float alpha = float(packedSample.z & 0xffu) / 255.0; - return vec4(vec3(0.5) + clr * SH_C0, alpha); -} vec4 getRotation() { - vec3 qdata = unpack8888(packedSample.z).xyz; - uint qmode = packedSample.w & 0x3u; - vec3 abc = (qdata - 0.5) * norm; + vec4 q = texelFetch(quats, splat.uv, 0); + uint qmode = uint(q.w * 255.0 + 0.5) - 252u; + vec3 abc = (q.xyz - 0.5) * norm; float d = sqrt(max(0.0, 1.0 - dot(abc, abc))); return (qmode == 0u) ? vec4(d, abc) : ((qmode == 1u) ? vec4(abc.x, d, abc.yz) : ((qmode == 2u) ? vec4(abc.xy, d, abc.z) : vec4(abc, d))); } vec3 getScale() { - vec3 sdata = unpack101010(packedSample.w >> 2u); - return exp(mix(vec3(scales_mins), vec3(scales_maxs), sdata)); + vec3 s = texelFetch(scales, splat.uv, 0).xyz; + #ifdef SOG_V2 + ivec3 i = ivec3(s * 255.0 + 0.5); + vec3 logS = vec3(lutScales(i.x), lutScales(i.y), lutScales(i.z)); + #else + vec3 logS = mix(scales_mins, scales_maxs, s); + #endif + return exp(logS); +} +vec4 getColor() { + vec4 c = texelFetch(sh0, splat.uv, 0); + #ifdef SOG_V2 + ivec3 i = ivec3(c.xyz * 255.0 + 0.5); + vec3 rgb = vec3(lutSh0(i.x), lutSh0(i.y), lutSh0(i.z)); + float alpha = c.w; + #else + vec3 rgb = mix(sh0_mins.xyz, sh0_maxs.xyz, c.xyz); + float logitAlpha = mix(sh0_mins.w, sh0_maxs.w, c.w); + float alpha = 1.0 / (1.0 + exp(-logitAlpha)); + #endif + return vec4(vec3(0.5) + rgb * SH_C0, alpha); } #include "gsplatSogSHVS" -`,gsplatSogSHVS:` +`;var Nz=` #if SH_BANDS > 0 -uniform highp sampler2D packedShN; -uniform float shN_mins; -uniform float shN_maxs; -void readSHData(out vec3 sh[SH_COEFFS], out float scale) { - ivec2 t = ivec2(packedSample.xy & 255u); - int n = t.x + t.y * 256; - int u = (n % 64) * SH_COEFFS; - int v = n / 64; - for (int i = 0; i < SH_COEFFS; i++) { - sh[i] = mix(vec3(shN_mins), vec3(shN_maxs), unpack111110(pack8888(texelFetch(packedShN, ivec2(u + i, v), 0)))); + #ifndef SOG_V2 + uniform float shN_mins; + uniform float shN_maxs; + #endif + void readSHData(out vec3 sh[SH_COEFFS], out float scale) { + vec4 labels = texelFetch(sh_labels, splat.uv, 0); + int n = int(labels.x * 255.0 + 0.5) + int(labels.y * 255.0 + 0.5) * 256; + int u = (n % 64) * SH_COEFFS; + int v = n / 64; + for (int i = 0; i < SH_COEFFS; i++) { + vec4 t = texelFetch(sh_centroids, ivec2(u + i, v), 0); + #ifdef SOG_V2 + ivec3 idx = ivec3(t.xyz * 255.0 + 0.5); + sh[i] = vec3(lutShN(idx.x), lutShN(idx.y), lutShN(idx.z)); + #else + sh[i] = mix(vec3(shN_mins), vec3(shN_maxs), t.xyz); + #endif + } + scale = 1.0; } - scale = 1.0; -} #endif -`,gsplatContainerDeclVS:` +`;var Bz=` #include "gsplatContainerDeclarationsVS" vec3 splatCenter; vec4 splatColor; vec3 splatScale; vec4 splatRotation; -`,gsplatContainerReadVS:` +`;var Uz=` vec3 getCenter() { #include "gsplatContainerUserReadVS" return splatCenter; @@ -16038,7 +16628,7 @@ vec3 getScale() { vec4 getColor() { return splatColor; } -`,gsplatContainerFloatReadVS:cP},yf={gsplatCenterVS:` +`;var kz={gsplatCenterVS:_z,gsplatCornerVS:Az,gsplatCommonVS:gz,gsplatSplatVS:Sz,gsplatEvalSHVS:xz,gsplatHelpersVS:vz,gsplatModifyVS:Tz,gsplatQuatToMat3VS:yz,gsplatStructsVS:Ez,gsplatOutputVS:Cz,gsplatPS:Pz,gsplatSourceVS:wz,gsplatVS:Iz,gsplatPackingPS:Rz,gsplatFormatVS:bz,gsplatUncompressedVS:Dz,gsplatUncompressedSHVS:Lz,gsplatCompressedVS:Mz,gsplatCompressedSHVS:Oz,gsplatSogVS:Fz,gsplatSogSHVS:Nz,gsplatContainerDeclVS:Bz,gsplatContainerReadVS:Uz,gsplatContainerFloatReadVS:Sy};var zz=` uniform matrix_model: mat4x4f; uniform matrix_view: mat4x4f; #ifndef GSPLAT_CENTER_NOPROJ @@ -16093,7 +16683,166 @@ fn initCenter(modelCenter: vec3f, center: ptr) -> bool { center.modelView = modelView; return true; } -`,gsplatCornerVS:` +`;var Gz=` +#include "gsplatHelpersVS" +#include "gsplatFormatVS" +#include "gsplatStructsVS" +#include "gsplatDeclarationsVS" +#include "gsplatModifyVS" +#include "gsplatEvalSHVS" +#include "gsplatQuatToMat3VS" +#include "gsplatReadVS" +#include "gsplatSourceVS" +#include "gsplatCenterVS" +#include "gsplatCornerVS" +#include "gsplatOutputVS" +#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) +uniform alphaClip: f32; +#else +uniform alphaClipForward: f32; +#endif +fn clipCorner(corner: ptr, alpha: half) { + #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) + let alphaClipValue = half(uniform.alphaClip); + #else + let alphaClipValue = half(uniform.alphaClipForward); + #endif + let clip = min(half(1.0), sqrt(max(half(0.0), log(alpha / alphaClipValue))) * half(0.5)); + corner.offset = corner.offset * f32(clip); + corner.uv = corner.uv * clip; +} +`;var Vz=` +struct Splat { + index: u32, + uv: vec2i +} +var splat: Splat; +fn setSplat(idx: u32) { + splat.index = idx; + splat.uv = vec2i(i32(idx % uniform.splatTextureSize), i32(idx / uniform.splatTextureSize)); +} +`;var Hz=` + #if SH_BANDS == 1 + const SH_COEFFS: i32 = 3; + #elif SH_BANDS == 2 + const SH_COEFFS: i32 = 8; + #elif SH_BANDS == 3 + const SH_COEFFS: i32 = 15; + #else + const SH_COEFFS: i32 = 0; + #endif + #if SH_BANDS > 0 + const SH_C1: half = half(0.4886025119029199); + #if SH_BANDS > 1 + const SH_C2_0: half = half(1.0925484305920792); + const SH_C2_1: half = half(-1.0925484305920792); + const SH_C2_2: half = half(0.31539156525252005); + const SH_C2_3: half = half(-1.0925484305920792); + const SH_C2_4: half = half(0.5462742152960396); + #endif + #if SH_BANDS > 2 + const SH_C3_0: half = half(-0.5900435899266435); + const SH_C3_1: half = half(2.890611442640554); + const SH_C3_2: half = half(-0.4570457994644658); + const SH_C3_3: half = half(0.3731763325901154); + const SH_C3_4: half = half(-0.4570457994644658); + const SH_C3_5: half = half(1.445305721320277); + const SH_C3_6: half = half(-0.5900435899266435); + #endif + fn evalSH(sh: ptr>, dir: vec3f) -> half3 { + let d: half3 = half3(dir); + var result: half3 = SH_C1 * (-sh[0] * d.y + sh[1] * d.z - sh[2] * d.x); + #if SH_BANDS > 1 + let xx: half = d.x * d.x; + let yy: half = d.y * d.y; + let zz: half = d.z * d.z; + let xy: half = d.x * d.y; + let yz: half = d.y * d.z; + let xz: half = d.x * d.z; + result = result + ( + sh[3] * (SH_C2_0 * xy) + + sh[4] * (SH_C2_1 * yz) + + sh[5] * (SH_C2_2 * (half(2.0) * zz - xx - yy)) + + sh[6] * (SH_C2_3 * xz) + + sh[7] * (SH_C2_4 * (xx - yy)) + ); + #endif + #if SH_BANDS > 2 + result = result + ( + sh[8] * (SH_C3_0 * d.y * (half(3.0) * xx - yy)) + + sh[9] * (SH_C3_1 * xy * d.z) + + sh[10] * (SH_C3_2 * d.y * (half(4.0) * zz - xx - yy)) + + sh[11] * (SH_C3_3 * d.z * (half(2.0) * zz - half(3.0) * xx - half(3.0) * yy)) + + sh[12] * (SH_C3_4 * d.x * (half(4.0) * zz - xx - yy)) + + sh[13] * (SH_C3_5 * d.z * (xx - yy)) + + sh[14] * (SH_C3_6 * d.x * (xx - half(3.0) * yy)) + ); + #endif + return result; + } + #endif +`;var Wz=` +fn gsplatMakeSpherical(scale: ptr, size: f32) { + *scale = vec3f(size); +} +fn gsplatGetSizeFromScale(scale: vec3f) -> f32 { + return sqrt((scale.x * scale.x + scale.y * scale.y + scale.z * scale.z) / 3.0); +} +`;var Xz=` +fn modifySplatCenter(center: ptr) { +} +fn modifySplatRotationScale(originalCenter: vec3f, modifiedCenter: vec3f, rotation: ptr, scale: ptr) { +} +fn modifySplatColor(center: vec3f, color: ptr) { +} +`;var Yz=` +fn quatToMat3(r: half4) -> half3x3 { + let r2: half4 = r + r; + let x: half = r2.x * r.w; + let y: half4 = r2.y * r; + let z: half4 = r2.z * r; + let w: half = r2.w * r.w; + return half3x3( + half(1.0) - z.z - w, y.z + x, y.w - z.x, + y.z - x, half(1.0) - y.y - w, z.w + y.x, + y.w + z.x, z.w - y.x, half(1.0) - y.y - z.z + ); +} +fn quatMul(a: half4, b: half4) -> half4 { + return half4( + a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, + a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, + a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, + a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z + ); +} +`;var Kz=` +#include "gsplatSplatVS" +struct SplatSource { + order: u32, + cornerUV: half2 +} +struct SplatCenter { + view: vec3f, + proj: vec4f, + modelView: mat4x4f, + projMat00: f32, + modelCenterOriginal: vec3f, + modelCenterModified: vec3f, + #ifdef GSPLAT_FISHEYE + fisheyeSinTK: f32, + fisheyeCosTK: f32, + fisheyeRxy: f32, + #endif +} +struct SplatCorner { + offset: vec3f, + uv: half2, + #if GSPLAT_AA + aaFactor: half, + #endif +} +`;var jz=` uniform viewport_size: vec4f; uniform minPixelSize: f32; fn computeCovariance(rotation: half4, scale: half3, covA_ptr: ptr, covB_ptr: ptr) { @@ -16193,7 +16942,7 @@ fn initCorner(source: ptr, center: ptr rasterizeTileList: array; uniform numTilesX: u32; @@ -16225,156 +16974,7 @@ fn vertexMain(input: VertexInput) -> VertexOutput { pixelY / uniform.screenHeight); return output; } -`,gsplatCommonVS:` -#include "gsplatHelpersVS" -#include "gsplatFormatVS" -#include "gsplatStructsVS" -#include "gsplatDeclarationsVS" -#include "gsplatModifyVS" -#include "gsplatEvalSHVS" -#include "gsplatQuatToMat3VS" -#include "gsplatReadVS" -#include "gsplatSourceVS" -#include "gsplatCenterVS" -#include "gsplatCornerVS" -#include "gsplatOutputVS" -fn clipCorner(corner: ptr, alpha: half) { - let clip = min(half(1.0), sqrt(log(half(255.0) * alpha)) * half(0.5)); - corner.offset = corner.offset * f32(clip); - corner.uv = corner.uv * clip; -} -`,gsplatSplatVS:` -struct Splat { - index: u32, - uv: vec2i -} -var splat: Splat; -fn setSplat(idx: u32) { - splat.index = idx; - splat.uv = vec2i(i32(idx % uniform.splatTextureSize), i32(idx / uniform.splatTextureSize)); -} -`,gsplatEvalSHVS:` - #if SH_BANDS == 1 - const SH_COEFFS: i32 = 3; - #elif SH_BANDS == 2 - const SH_COEFFS: i32 = 8; - #elif SH_BANDS == 3 - const SH_COEFFS: i32 = 15; - #else - const SH_COEFFS: i32 = 0; - #endif - #if SH_BANDS > 0 - const SH_C1: half = half(0.4886025119029199); - #if SH_BANDS > 1 - const SH_C2_0: half = half(1.0925484305920792); - const SH_C2_1: half = half(-1.0925484305920792); - const SH_C2_2: half = half(0.31539156525252005); - const SH_C2_3: half = half(-1.0925484305920792); - const SH_C2_4: half = half(0.5462742152960396); - #endif - #if SH_BANDS > 2 - const SH_C3_0: half = half(-0.5900435899266435); - const SH_C3_1: half = half(2.890611442640554); - const SH_C3_2: half = half(-0.4570457994644658); - const SH_C3_3: half = half(0.3731763325901154); - const SH_C3_4: half = half(-0.4570457994644658); - const SH_C3_5: half = half(1.445305721320277); - const SH_C3_6: half = half(-0.5900435899266435); - #endif - fn evalSH(sh: ptr>, dir: vec3f) -> half3 { - let d: half3 = half3(dir); - var result: half3 = SH_C1 * (-sh[0] * d.y + sh[1] * d.z - sh[2] * d.x); - #if SH_BANDS > 1 - let xx: half = d.x * d.x; - let yy: half = d.y * d.y; - let zz: half = d.z * d.z; - let xy: half = d.x * d.y; - let yz: half = d.y * d.z; - let xz: half = d.x * d.z; - result = result + ( - sh[3] * (SH_C2_0 * xy) + - sh[4] * (SH_C2_1 * yz) + - sh[5] * (SH_C2_2 * (half(2.0) * zz - xx - yy)) + - sh[6] * (SH_C2_3 * xz) + - sh[7] * (SH_C2_4 * (xx - yy)) - ); - #endif - #if SH_BANDS > 2 - result = result + ( - sh[8] * (SH_C3_0 * d.y * (half(3.0) * xx - yy)) + - sh[9] * (SH_C3_1 * xy * d.z) + - sh[10] * (SH_C3_2 * d.y * (half(4.0) * zz - xx - yy)) + - sh[11] * (SH_C3_3 * d.z * (half(2.0) * zz - half(3.0) * xx - half(3.0) * yy)) + - sh[12] * (SH_C3_4 * d.x * (half(4.0) * zz - xx - yy)) + - sh[13] * (SH_C3_5 * d.z * (xx - yy)) + - sh[14] * (SH_C3_6 * d.x * (xx - half(3.0) * yy)) - ); - #endif - return result; - } - #endif -`,gsplatHelpersVS:` -fn gsplatMakeSpherical(scale: ptr, size: f32) { - *scale = vec3f(size); -} -fn gsplatGetSizeFromScale(scale: vec3f) -> f32 { - return sqrt((scale.x * scale.x + scale.y * scale.y + scale.z * scale.z) / 3.0); -} -`,gsplatModifyVS:` -fn modifySplatCenter(center: ptr) { -} -fn modifySplatRotationScale(originalCenter: vec3f, modifiedCenter: vec3f, rotation: ptr, scale: ptr) { -} -fn modifySplatColor(center: vec3f, color: ptr) { -} -`,gsplatStructsVS:` -#include "gsplatSplatVS" -struct SplatSource { - order: u32, - cornerUV: half2 -} -struct SplatCenter { - view: vec3f, - proj: vec4f, - modelView: mat4x4f, - projMat00: f32, - modelCenterOriginal: vec3f, - modelCenterModified: vec3f, - #ifdef GSPLAT_FISHEYE - fisheyeSinTK: f32, - fisheyeCosTK: f32, - fisheyeRxy: f32, - #endif -} -struct SplatCorner { - offset: vec3f, - uv: half2, - #if GSPLAT_AA - aaFactor: half, - #endif -} -`,gsplatQuatToMat3VS:` -fn quatToMat3(r: half4) -> half3x3 { - let r2: half4 = r + r; - let x: half = r2.x * r.w; - let y: half4 = r2.y * r; - let z: half4 = r2.z * r; - let w: half = r2.w * r.w; - return half3x3( - half(1.0) - z.z - w, y.z + x, y.w - z.x, - y.z - x, half(1.0) - y.y - w, z.w + y.x, - y.w + z.x, z.w - y.x, half(1.0) - y.y - z.z - ); -} -fn quatMul(a: half4, b: half4) -> half4 { - return half4( - a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, - a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, - a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, - a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z - ); -} -`,gsplatOutputVS:vQ,gsplatPS:` +`;var $z=` #ifndef DITHER_NONE #include "bayerPS" #include "opacityDitherPS" @@ -16387,6 +16987,9 @@ fn quatMul(a: half4, b: half4) -> half4 { varying vLinearDepth: f32; #include "floatAsUintPS" #endif +#if !defined(SHADOW_PASS) && !defined(PICK_PASS) && !defined(PREPASS_PASS) + uniform alphaClipForward: f32; +#endif const EXP4: half = exp(half(-4.0)); const INV_EXP4: half = half(1.0) / (half(1.0) - EXP4); fn normExp(x: half) -> half { @@ -16429,7 +17032,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { #elif PREPASS_PASS output.color = float2vec4(vLinearDepth); #else - if (alpha < half(1.0 / 255.0)) { + if (alpha < half(uniform.alphaClipForward)) { discard; return output; } @@ -16439,7 +17042,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { output.color = vec4f(vec3f(gaussianColor.xyz * alpha), f32(alpha)); #endif return output; -}`,gsplatTileCompositePS:` +}`;var Zz=` #ifdef PICK_MODE #include "pickPS" #include "floatAsUintPS" @@ -16473,7 +17076,7 @@ varying vUv0: vec2f; #endif return output; } -`,gsplatSourceVS:` +`;var Qz=` attribute vertex_position: vec3f; #ifdef GSPLAT_INDIRECT_DRAW var numSplatsStorage: array; @@ -16502,7 +17105,7 @@ fn initSource(source: ptr) -> bool { source.cornerUV = half2(vertex_position.xy); return true; } -`,gsplatVS:` +`;var Jz=` #include "gsplatCommonVS" varying gaussianUV: half2; varying gaussianColor: half4; @@ -16564,7 +17167,12 @@ fn vertexMain(input: VertexInput) -> VertexOutput { var clrF32 = vec4f(clr); modifySplatColor(modelCenter, &clrF32); clr = half4(clrF32); - if (half(255.0) * clr.w <= half(1.0)) { + #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) + let alphaClipValue = half(uniform.alphaClip); + #else + let alphaClipValue = half(uniform.alphaClipForward); + #endif + if (clr.w <= alphaClipValue) { output.position = discardVec; return output; } @@ -16595,7 +17203,104 @@ fn vertexMain(input: VertexInput) -> VertexOutput { #endif return output; } -`,gsplatPackingPS:` +`;var eG=` +#include "gsplatHelpersVS" +#include "gsplatOutputVS" +attribute vertex_position: vec3f; +uniform viewport_size: vec4f; +uniform clipToViewZ: vec4f; +#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) + uniform alphaClip: f32; +#else + uniform alphaClipForward: f32; +#endif +var sortedIndices: array; +var projCache: array; +var numSplatsStorage: array; +varying gaussianUV: half2; +varying gaussianColor: half4; +#ifndef DITHER_NONE + varying id: f32; +#endif +#ifdef PREPASS_PASS + varying vLinearDepth: f32; +#endif +#if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) + varying @interpolate(flat) vPickId: u32; +#endif +#ifdef GSPLAT_OVERDRAW + uniform colorRampIntensity: f32; + var colorRamp: texture_2d; + var colorRampSampler: sampler; +#endif +const discardVec: vec4f = vec4f(0.0, 0.0, 2.0, 1.0); +@vertex +fn vertexMain(input: VertexInput) -> VertexOutput { + var output: VertexOutput; + let order = pcInstanceIndex * {GSPLAT_INSTANCE_SIZE}u + u32(vertex_position.z); + let numSplats = numSplatsStorage[0]; + if (order >= numSplats) { + output.position = discardVec; + return output; + } + let cacheIdx = sortedIndices[order]; + let base = cacheIdx * {CACHE_STRIDE}u; + let proj = vec4f( + bitcast(projCache[base + 0u]), + bitcast(projCache[base + 1u]), + bitcast(projCache[base + 2u]), + bitcast(projCache[base + 3u]) + ); + let v1 = unpack2x16float(projCache[base + 4u]); + let v2 = unpack2x16float(projCache[base + 5u]); + let ba = unpack2x16float(projCache[base + 7u]); + let alpha = half(ba.y); + #if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) + let pickId = projCache[base + 6u]; + #endif + #ifdef PICK_PASS + var clr: half4 = half4(half(0.0), half(0.0), half(0.0), alpha); + #else + let rg = unpack2x16float(projCache[base + 6u]); + var clr: half4 = half4(half(rg.x), half(rg.y), half(ba.x), alpha); + #endif + let cornerUV = vec2f(vertex_position.xy); + #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) + let alphaClipValue = half(uniform.alphaClip); + #else + let alphaClipValue = half(uniform.alphaClipForward); + #endif + let clip = min(half(1.0), sqrt(max(half(0.0), log(alpha / alphaClipValue))) * half(0.5)); + let cornerClipped = cornerUV * f32(clip); + let c = vec2f(proj.w) * uniform.viewport_size.zw; + let pixelOffset = cornerClipped.x * v1 + cornerClipped.y * v2; + let clipOffset = pixelOffset * c; + output.position = proj + vec4f(clipOffset, 0.0, 0.0); + output.gaussianUV = half2(cornerClipped); + let viewDepth = dot(uniform.clipToViewZ, proj); + #ifdef GSPLAT_OVERDRAW + let t: f32 = clamp(viewDepth / 20.0, 0.0, 1.0); + let rampColor: vec3f = textureSampleLevel(colorRamp, colorRampSampler, vec2f(t, 0.5), 0.0).rgb; + let outAlpha = alpha * half(1.0 / 32.0) * half(uniform.colorRampIntensity); + output.gaussianColor = half4(half3(rampColor), outAlpha); + #else + output.gaussianColor = half4( + half3(prepareOutputFromGamma(max(vec3f(clr.xyz), vec3f(0.0)), viewDepth)), + alpha + ); + #endif + #ifndef DITHER_NONE + output.id = f32(cacheIdx); + #endif + #ifdef PREPASS_PASS + output.vLinearDepth = viewDepth; + #endif + #if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) + output.vPickId = pickId; + #endif + return output; +} +`;var tG=` fn pack8888(v: vec4f) -> u32 { let t = vec4u(v * 255.0) << vec4u(24u, 16u, 8u, 0u); return t.x | t.y | t.z | t.w; @@ -16616,13 +17321,13 @@ fn unpack101010(v: u32) -> vec3f { } fn unpack111110(v: u32) -> vec3f { return vec3f((vec3u(v) >> vec3u(21u, 10u, 0u)) & vec3u(0x7ffu, 0x7ffu, 0x3ffu)) / vec3f(2047.0, 2047.0, 1023.0); -}`,gsplatFormatVS:` +}`;var sG=` uniform splatTextureSize: u32; -`,gsplatUncompressedVS:` +`;var iG=` var tAw: u32; var tBcached: vec4f; -fn unpackRotation(packed: vec3f) -> vec4f { - return vec4f(packed.xyz, sqrt(max(0.0, 1.0 - dot(packed, packed)))); +fn unpackRotation(data: vec3f) -> vec4f { + return vec4f(data.xyz, sqrt(max(0.0, 1.0 - dot(data, data)))); } fn getCenter() -> vec3f { let tA: vec4 = loadTransformA(); @@ -16640,7 +17345,7 @@ fn getScale() -> vec3f { return tBcached.xyz; } #include "gsplatUncompressedSHVS" -`,gsplatUncompressedSHVS:` +`;var rG=` #if SH_BANDS > 0 fn unpack111011s(bits: u32) -> vec3f { return (vec3f((vec3(bits) >> vec3(21u, 11u, 0u)) & vec3(0x7ffu, 0x3ffu, 0x7ffu)) / vec3f(2047.0, 1023.0, 2047.0)) * 2.0 - 1.0; @@ -16723,7 +17428,7 @@ fn fetch1(t_in: u32) -> vec3f { } #endif #endif -`,gsplatCompressedVS:` +`;var aG=` #include "gsplatPackingPS" var chunkTexture: texture_2d; var chunkDataA: vec4f; @@ -16771,7 +17476,7 @@ fn getScale() -> vec3f { return exp(mix(vec3f(chunkDataB.zw, chunkDataC.x), chunkDataC.yzw, unpack111011(packedData.z))); } #include "gsplatCompressedSHVS" -`,gsplatCompressedSHVS:` +`;var oG=` #if SH_BANDS > 0 fn unpack8888s(bits: u32) -> half4 { let unpacked_u = (vec4(bits) >> vec4(0u, 8u, 16u, 24u)) & vec4(0xffu); @@ -16811,35 +17516,33 @@ fn readSHData(sh: ptr>, scale: ptr) { *scale = 1.0; } #endif -`,gsplatSogVS:` -#include "gsplatPackingPS" +`;var nG=` uniform means_mins: vec3f; uniform means_maxs: vec3f; -uniform scales_mins: f32; -uniform scales_maxs: f32; -uniform sh0_mins: f32; -uniform sh0_maxs: f32; -var packedSh0: texture_2d; +#ifndef SOG_V2 + uniform scales_mins: vec3f; + uniform scales_maxs: vec3f; + uniform sh0_mins: vec4f; + uniform sh0_maxs: vec4f; +#endif const SH_C0: f32 = 0.28209479177387814; -var packedSample: vec4; const norm: f32 = sqrt(2.0); +#ifdef SOG_V2 + fn lutScales(b: i32) -> f32 { return textureLoad(sogCodebook, vec2i(b, 0), 0).r; } + fn lutSh0(b: i32) -> f32 { return textureLoad(sogCodebook, vec2i(b, 0), 0).g; } + fn lutShN(b: i32) -> f32 { return textureLoad(sogCodebook, vec2i(b, 0), 0).b; } +#endif fn getCenter() -> vec3f { - packedSample = loadPackedTexture(); - let l = unpack8888(packedSample.x).xyz; - let u = unpack8888(packedSample.y).xyz; + let l = textureLoad(means_l, splat.uv, 0).xyz; + let u = textureLoad(means_u, splat.uv, 0).xyz; let n = (l + u * 256.0) / 257.0; let v = mix(uniform.means_mins, uniform.means_maxs, n); return sign(v) * (exp(abs(v)) - 1.0); } -fn getColor() -> vec4f { - let clr = mix(half3(half(uniform.sh0_mins)), half3(half(uniform.sh0_maxs)), half3(unpack111110(pack8888(textureLoad(packedSh0, splat.uv, 0))))); - let alpha = half(f32(packedSample.z & 0xffu) / 255.0); - return vec4f(half4(half3(0.5) + clr * half(SH_C0), alpha)); -} fn getRotation() -> vec4f { - let qdata = unpack8888(packedSample.z).xyz; - let qmode = packedSample.w & 0x3u; - let abc = (qdata - 0.5) * norm; + let q = textureLoad(quats, splat.uv, 0); + let qmode = u32(q.w * 255.0 + 0.5) - 252u; + let abc = (q.xyz - 0.5) * norm; let d = sqrt(max(0.0, 1.0 - dot(abc, abc))); var quat: vec4f; if (qmode == 0u) { @@ -16854,52 +17557,81 @@ fn getRotation() -> vec4f { return quat; } fn getScale() -> vec3f { - let sdata = unpack101010(packedSample.w >> 2u); - return exp(mix(vec3f(uniform.scales_mins), vec3f(uniform.scales_maxs), sdata)); + let s = textureLoad(scales, splat.uv, 0).xyz; + var logS: vec3f; + #ifdef SOG_V2 + let i = vec3i(s * 255.0 + 0.5); + logS = vec3f(lutScales(i.x), lutScales(i.y), lutScales(i.z)); + #else + logS = mix(uniform.scales_mins, uniform.scales_maxs, s); + #endif + return exp(logS); +} +fn getColor() -> vec4f { + let c = textureLoad(sh0, splat.uv, 0); + var rgb: vec3f; + var alpha: f32; + #ifdef SOG_V2 + let i = vec3i(c.xyz * 255.0 + 0.5); + rgb = vec3f(lutSh0(i.x), lutSh0(i.y), lutSh0(i.z)); + alpha = c.w; + #else + rgb = mix(uniform.sh0_mins.xyz, uniform.sh0_maxs.xyz, c.xyz); + let logitAlpha = mix(uniform.sh0_mins.w, uniform.sh0_maxs.w, c.w); + alpha = 1.0 / (1.0 + exp(-logitAlpha)); + #endif + return vec4f(vec3f(0.5) + rgb * SH_C0, alpha); } #include "gsplatSogSHVS" -`,gsplatSogSHVS:` +`;var lG=` #if SH_BANDS > 0 -var packedShN: texture_2d; -uniform shN_mins: f32; -uniform shN_maxs: f32; -fn readSHTexel(u: i32, v: i32) -> half3 { - return mix(half3(half(uniform.shN_mins)), half3(half(uniform.shN_maxs)), half3(unpack111110(pack8888(textureLoad(packedShN, vec2i(u, v), 0))))); -} -fn readSHData(sh: ptr>, scale: ptr) { - let t = vec2i(packedSample.xy & vec2u(255u)); - let n = t.x + t.y * 256; - let u = (n % 64) * SH_COEFFS; - let v = n / 64; - sh[0] = readSHTexel(u, v); - sh[1] = readSHTexel(u + 1, v); - sh[2] = readSHTexel(u + 2, v); - #if SH_BANDS > 1 - sh[3] = readSHTexel(u + 3, v); - sh[4] = readSHTexel(u + 4, v); - sh[5] = readSHTexel(u + 5, v); - sh[6] = readSHTexel(u + 6, v); - sh[7] = readSHTexel(u + 7, v); + #ifndef SOG_V2 + uniform shN_mins: f32; + uniform shN_maxs: f32; #endif - #if SH_BANDS > 2 - sh[8] = readSHTexel(u + 8, v); - sh[9] = readSHTexel(u + 9, v); - sh[10] = readSHTexel(u + 10, v); - sh[11] = readSHTexel(u + 11, v); - sh[12] = readSHTexel(u + 12, v); - sh[13] = readSHTexel(u + 13, v); - sh[14] = readSHTexel(u + 14, v); - #endif - *scale = 1.0; -} + fn readSHTexel(u: i32, v: i32) -> half3 { + let t = textureLoad(sh_centroids, vec2i(u, v), 0); + #ifdef SOG_V2 + let idx = vec3i(t.xyz * 255.0 + 0.5); + return half3(vec3f(lutShN(idx.x), lutShN(idx.y), lutShN(idx.z))); + #else + return mix(half3(half(uniform.shN_mins)), half3(half(uniform.shN_maxs)), half3(t.xyz)); + #endif + } + fn readSHData(sh: ptr>, scale: ptr) { + let labels = textureLoad(sh_labels, splat.uv, 0); + let n = i32(labels.x * 255.0 + 0.5) + i32(labels.y * 255.0 + 0.5) * 256; + let u = (n % 64) * SH_COEFFS; + let v = n / 64; + sh[0] = readSHTexel(u, v); + sh[1] = readSHTexel(u + 1, v); + sh[2] = readSHTexel(u + 2, v); + #if SH_BANDS > 1 + sh[3] = readSHTexel(u + 3, v); + sh[4] = readSHTexel(u + 4, v); + sh[5] = readSHTexel(u + 5, v); + sh[6] = readSHTexel(u + 6, v); + sh[7] = readSHTexel(u + 7, v); + #endif + #if SH_BANDS > 2 + sh[8] = readSHTexel(u + 8, v); + sh[9] = readSHTexel(u + 9, v); + sh[10] = readSHTexel(u + 10, v); + sh[11] = readSHTexel(u + 11, v); + sh[12] = readSHTexel(u + 12, v); + sh[13] = readSHTexel(u + 13, v); + sh[14] = readSHTexel(u + 14, v); + #endif + *scale = 1.0; + } #endif -`,gsplatContainerDeclVS:` +`;var cG=` #include "gsplatContainerDeclarationsVS" var splatCenter: vec3f; var splatColor: vec4f; var splatScale: vec3f; var splatRotation: vec4f; -`,gsplatContainerReadVS:` +`;var hG=` fn getCenter() -> vec3f { #include "gsplatContainerUserReadVS" return splatCenter; @@ -16913,14 +17645,17 @@ fn getScale() -> vec3f { fn getColor() -> vec4f { return splatColor; } -`,gsplatContainerFloatReadVS:cI},yp=["enabled"],ym=["unified","lodBaseDistance","lodMultiplier","castShadows","material","highQualitySH","asset","resource","layers"];class y_ extends pT{initializeComponentData(e,t,i){t.layers&&t.layers.length&&(t.layers=t.layers.slice(0));for(let i=0;i{if("material"===e){if(!i.unified){let t=i[e];t&&(s[e]=t.clone());}}else s[e]=i[e];}),s.enabled=i.enabled;let r=this.addComponent(t,s);return r.customAabb=i.customAabb?.clone()??null,r}onRemove(e,t){t.onRemove();}getMaterial(e,t){let i=this.app.renderer.gsplatDirector;if(!i)return null;let s=i.camerasMap.get(e);if(!s)return null;let r=s.layersMap.get(t);return r?.gsplatManager?.material??null}getGSplatMaterial(e,t){return this.getMaterial(e,t)}constructor(e){super(e),this.id="gsplat",this.ComponentType=yc,this.DataType=yd,this.schema=yp,e.renderer.gsplatDirector=new yh(e.graphicsDevice,e.renderer,e.scene,this),n$.get(e.graphicsDevice,tz).add(yu),n$.get(e.graphicsDevice,tV).add(yf),this.on("beforeremove",this.onRemove,this);}}y_.EVENT_MATERIALCREATED="material:created",y_.EVENT_FRAMEREADY="frame:ready",px._buildAccessors(yc.prototype,yp);class yg extends X{set meshes(e){this.decRefMeshes(),this._meshes=e,this.incRefMeshes(),this.fire("set:meshes",e);}get meshes(){return this._meshes}destroy(){this.meshes=null;}decRefMeshes(){this._meshes?.forEach((e,t)=>{e&&(e.decRefCount(),e.refCount<1&&(e.destroy(),this._meshes[t]=null));});}incRefMeshes(){this._meshes?.forEach(e=>{e?.incRefCount();});}constructor(...e){super(...e),this._meshes=null;}}function yv(e){if(!this.resource)return;let t=e.resource,i=t.renders&&t.renders[this.data.renderIndex];i&&(this.resource.meshes=i.resource.meshes);}function yS(e){this.registry.off(`load:${e.id}`,yv,this),this.registry.on(`load:${e.id}`,yv,this),this.registry.off(`remove:${e.id}`,yy,this),this.registry.once(`remove:${e.id}`,yy,this),e.resource?yv.call(this,e):this.registry.load(e);}function yy(e){this.registry.off(`load:${e.id}`,yv,this),this.resource&&this.resource.destroy();}yg.EVENT_SETMESHES="set:meshes";class yx extends fQ{open(e,t){return new yg}patch(e,t){if(!e.data.containerAsset)return;let i=t.get(e.data.containerAsset);i?yS.call(e,i):t.once(`add:${e.data.containerAsset}`,yS,e);}constructor(e){super(e,"render"),this._registry=e.assets;}}class yT{get paths(){return this._paths}get input(){return this._input}get output(){return this._output}get interpolation(){return this._interpolation}constructor(e,t,i,s){this._paths=e,this._input=t,this._output=i,this._interpolation=s;}}class yE{get components(){return this._components}get data(){return this._data}constructor(e,t){this._components=e,this._data=t;}}function yw(e,t){let i,s=(e,t)=>{switch(t){case i.DT_INT8:return new Int8Array(e.buffer,e.byteOffset,e.byteLength);case i.DT_INT16:return new Int16Array(e.buffer,e.byteOffset,e.byteLength/2);case i.DT_INT32:return new Int32Array(e.buffer,e.byteOffset,e.byteLength/4);case i.DT_UINT8:return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);case i.DT_UINT16:return new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2);case i.DT_UINT32:return new Uint32Array(e.buffer,e.byteOffset,e.byteLength/4);case i.DT_FLOAT32:return new Float32Array(e.buffer,e.byteOffset,e.byteLength/4)}return null},r=e=>e.num_components()*(e=>{switch(e){case i.DT_INT8:break;case i.DT_INT16:return 2;case i.DT_INT32:return 4;case i.DT_UINT8:break;case i.DT_UINT16:return 2;case i.DT_UINT32:case i.DT_FLOAT32:return 4}return 1})(e.data_type()),a={0:0,1:1,5:2,2:3,7:4,8:5,4:6,3:7},n=(e,t)=>{let i=(e,t,i)=>{e[0]=t[0]-i[0],e[1]=t[1]-i[1],e[2]=t[2]-i[2];},s=(e,t,i)=>{e[0]=t[1]*i[2]-i[1]*t[2],e[1]=t[2]*i[0]-i[2]*t[0],e[2]=t[0]*i[1]-i[0]*t[1];},r=(e,t)=>{let i=e[t+0],s=e[t+1],r=e[t+2],a=1/Math.sqrt(i*i+s*s+r*r);e[t+0]*=a,e[t+1]*=a,e[t+2]*=a;},a=(e,t,i)=>{for(let s=0;s<3;++s)e[s]=t[i+s];},n=t.length/3,o=e.length/3,l=new Float32Array(e.length),h=[0,0,0],c=[0,0,0],d=[0,0,0],u=[0,0,0],f=[0,0,0],p=[0,0,0];for(let o=0;o{let t=(e=>{let t={},o=new i.DecoderBuffer;o.Init(e,e.length);let l=new i.Decoder;if(l.GetEncodedGeometryType(o)!==i.TRIANGULAR_MESH)return t.error="Failed to decode draco mesh: not a mesh",t;let h=new i.Mesh,c=l.DecodeBufferToMesh(o,h);if(!c||!c.ok()||0===i.getPointer(h))return t.error="Failed to decode draco asset",t;let d=3*h.num_faces(),u=65535>=h.num_points(),f=d*(u?2:4),p=i._malloc(f);u?(l.GetTrianglesUInt16Array(h,f,p),t.indices=new Uint16Array(i.HEAPU16.buffer,p,d).slice().buffer):(l.GetTrianglesUInt32Array(h,f,p),t.indices=new Uint32Array(i.HEAPU32.buffer,p,d).slice().buffer),i._free(p);let m=[];for(let e=0;e(a[e.attribute_type()]??a.length)-(a[t.attribute_type()]??a.length));let _=0,g=m.map(e=>{let t=_;return _+=4*Math.ceil(r(e)/4),t}),v=m.some(e=>1===e.attribute_type()),S=g[1]??0;if(!v){S=g[0]+4*Math.ceil(r(m[0])/4);for(let e=1;e({id:e.unique_id(),dataType:(e=>{switch(e){case i.DT_INT8:return 0;case i.DT_UINT8:return 1;case i.DT_INT16:return 2;case i.DT_UINT16:return 3;case i.DT_INT32:return 4;case i.DT_UINT32:return 5;case i.DT_FLOAT32:default:return 6}})(e.data_type()),numComponents:e.num_components(),offset:g[t]})),v||t.attributes.splice(1,0,{id:-1,dataType:6,numComponents:3,offset:S}),t.stride=_,t.vertices=new ArrayBuffer(h.num_points()*_);let y=new Uint8Array(t.vertices);for(let e=0;enull!=e));},l=[];self.onmessage=e=>{let t=e.data;switch(t.type){case "init":self.DracoDecoderModule({instantiateWasm:(e,i)=>(WebAssembly.instantiate(t.module,e).then(e=>i(e)).catch(e=>void 0),{})}).then(e=>{i=e,l.forEach(e=>o(e));});break;case "decodeMesh":i?o(t):l.push(t);}};}class yb{init(e){for(e.forEach(e=>{e.addEventListener("message",t=>{let i=t.data,s=this.jobCallbacks.get(i.jobId);if(s&&s(i.error,{indices:i.indices,vertices:i.vertices,attributes:i.attributes,stride:i.stride}),this.jobCallbacks.delete(i.jobId),this.jobQueue.length>0){let t=this.jobQueue.shift();this.run(e,t);}else {let t=this.workers[2].indexOf(e);if(-1!==t)this.workers[2].splice(t,1),this.workers[1].push(e);else {let t=this.workers[1].indexOf(e);-1!==t&&(this.workers[1].splice(t,1),this.workers[0].push(e));}}});}),this.workers[0]=e;this.jobQueue.length&&(this.workers[0].length||this.workers[1].length);){let e=this.jobQueue.shift();if(this.workers[0].length>0){let t=this.workers[0].shift();this.workers[1].push(t),this.run(t,e);}else {let t=this.workers[1].shift();this.workers[2].push(t),this.run(t,e);}}}enqueueJob(e,t){let i={jobId:this.jobId++,buffer:e};if(this.jobCallbacks.set(i.jobId,t),this.workers[0].length>0){let e=this.workers[0].shift();this.workers[1].push(e),this.run(e,i);}else if(this.workers[1].length>0){let e=this.workers[1].shift();this.workers[2].push(e),this.run(e,i);}else this.jobQueue.push(i);}constructor(){this.workers=[[],[],[]],this.jobId=0,this.jobQueue=[],this.jobCallbacks=new Map,this.run=(e,t)=>{e.postMessage({type:"decodeMesh",jobId:t.jobId,buffer:t.buffer},[t.buffer]);};}}let yC=e=>{var t;let i,s;if(m)return true;if(!e)if(_)e=_;else {let t=j.getConfig("DracoDecoderModule");e=t?{jsUrl:t.glueUrl,wasmUrl:t.wasmUrl,numWorkers:t.numWorkers}:{jsUrl:"draco.wasm.js",wasmUrl:"draco.wasm.wasm",numWorkers:1};}return !!e.jsUrl&&!!e.wasmUrl&&(m=new yb,Promise.all([(i=e.jsUrl,new Promise((e,t)=>{a0.get(i,{cache:true,responseType:"text",retry:true,maxRetries:3},(i,s)=>{i?t(i):e(s);});})),(t=e.wasmUrl,s=()=>fetch(t).then(e=>e.arrayBuffer()).then(e=>WebAssembly.compile(e)),WebAssembly.compileStreaming?WebAssembly.compileStreaming(fetch(t)).catch(e=>s()):s())]).then(([t,i])=>{let s=new Blob([["/* draco */",t,"/* worker */",`( -${yw.toString()} +`;var fG={gsplatCenterVS:zz,gsplatCornerVS:jz,gsplatTileCompositeVS:qz,gsplatCommonVS:Gz,gsplatSplatVS:Vz,gsplatEvalSHVS:Hz,gsplatHelpersVS:Wz,gsplatModifyVS:Xz,gsplatStructsVS:Kz,gsplatQuatToMat3VS:Yz,gsplatOutputVS:lE,gsplatPS:$z,gsplatTileCompositePS:Zz,gsplatSourceVS:Qz,gsplatVS:Jz,gsplatHybridVS:eG,gsplatPackingPS:tG,gsplatFormatVS:sG,gsplatUncompressedVS:iG,gsplatUncompressedSHVS:rG,gsplatCompressedVS:aG,gsplatCompressedSHVS:oG,gsplatSogVS:nG,gsplatSogSHVS:lG,gsplatContainerDeclVS:cG,gsplatContainerReadVS:hG,gsplatContainerFloatReadVS:xy};var JR=["enabled"],sx=["unified","lodBaseDistance","lodMultiplier","castShadows","material","highQualitySH","asset","resource","layers"],vh=class extends Fe{constructor(t){super(t),this.id="gsplat",this.ComponentType=Du,this.DataType=FE,this.schema=JR,t.renderer.gsplatDirector=new OE(t.graphicsDevice,t.renderer,t.scene,this),ne.get(t.graphicsDevice,fe).add(kz),ne.get(t.graphicsDevice,se).add(fG),this.on("beforeremove",this.onRemove,this)}initializeComponentData(t,e,s){e.layers&&e.layers.length&&(e.layers=e.layers.slice(0));for(let i=0;i{if(a==="material"){if(!s.unified){let o=s[a];o&&(i[a]=o.clone())}}else i[a]=s[a]}),i.enabled=s.enabled;let r=this.addComponent(e,i);return r.customAabb=s.customAabb?.clone()??null,r}onRemove(t,e){e.onRemove()}getMaterial(t,e){let s=this.app.renderer.gsplatDirector;if(!s)return null;let i=s.camerasMap.get(t);return i?i.layersMap.get(e)?.gsplatManager?.material??null:null}getGSplatMaterial(t,e){return this.getMaterial(t,e)}};n(vh,"EVENT_MATERIALCREATED","material:created"),n(vh,"EVENT_FRAMEREADY","frame:ready");le._buildAccessors(Du.prototype,JR);var Lu=class extends J{constructor(){super(...arguments);n(this,"_meshes",null)}set meshes(e){this.decRefMeshes(),this._meshes=e,this.incRefMeshes(),this.fire("set:meshes",e)}get meshes(){return this._meshes}destroy(){this.meshes=null}decRefMeshes(){this._meshes?.forEach((e,s)=>{e&&(e.decRefCount(),e.refCount<1&&(e.destroy(),this._meshes[s]=null))})}incRefMeshes(){this._meshes?.forEach(e=>{e?.incRefCount()})}};n(Lu,"EVENT_SETMESHES","set:meshes");function NE(c){let t=this;if(!t.resource)return;let e=c.resource,s=e.renders&&e.renders[t.data.renderIndex];s&&(t.resource.meshes=s.resource.meshes)}function uG(c){let t=this;t.registry.off(`load:${c.id}`,NE,t),t.registry.on(`load:${c.id}`,NE,t),t.registry.off(`remove:${c.id}`,dG,t),t.registry.once(`remove:${c.id}`,dG,t),c.resource?NE.call(t,c):t.registry.load(c)}function dG(c){let t=this;t.registry.off(`load:${c.id}`,NE,t),t.resource&&t.resource.destroy()}var g_=class extends Re{constructor(t){super(t,"render"),this._registry=t.assets}open(t,e){return new Lu}patch(t,e){if(!t.data.containerAsset)return;let s=e.get(t.data.containerAsset);if(!s){e.once(`add:${t.data.containerAsset}`,uG,t);return}uG.call(t,s)}};var Th=class{constructor(t,e,s,i){this._paths=t,this._input=e,this._output=s,this._interpolation=i}get paths(){return this._paths}get input(){return this._input}get output(){return this._output}get interpolation(){return this._interpolation}};var an=class{constructor(t,e){this._components=t,this._data=e}get components(){return this._components}get data(){return this._data}};function pG(c,t){let e,r=(m,_)=>{switch(_){case e.DT_INT8:return new Int8Array(m.buffer,m.byteOffset,m.byteLength);case e.DT_INT16:return new Int16Array(m.buffer,m.byteOffset,m.byteLength/2);case e.DT_INT32:return new Int32Array(m.buffer,m.byteOffset,m.byteLength/4);case e.DT_UINT8:return new Uint8Array(m.buffer,m.byteOffset,m.byteLength);case e.DT_UINT16:return new Uint16Array(m.buffer,m.byteOffset,m.byteLength/2);case e.DT_UINT32:return new Uint32Array(m.buffer,m.byteOffset,m.byteLength/4);case e.DT_FLOAT32:return new Float32Array(m.buffer,m.byteOffset,m.byteLength/4)}return null},a=m=>{switch(m){case e.DT_INT8:return 1;case e.DT_INT16:return 2;case e.DT_INT32:return 4;case e.DT_UINT8:return 1;case e.DT_UINT16:return 2;case e.DT_UINT32:return 4;case e.DT_FLOAT32:return 4}return 1},o=m=>{switch(m){case e.DT_INT8:return 0;case e.DT_UINT8:return 1;case e.DT_INT16:return 2;case e.DT_UINT16:return 3;case e.DT_INT32:return 4;case e.DT_UINT32:return 5;case e.DT_FLOAT32:return 6;default:return 6}},l=m=>m.num_components()*a(m.data_type()),h={0:0,1:1,5:2,2:3,7:4,8:5,4:6,3:7},f=(m,_)=>{let S=(G,M,H)=>{G[0]=M[0]-H[0],G[1]=M[1]-H[1],G[2]=M[2]-H[2]},g=(G,M,H)=>{G[0]=M[1]*H[2]-H[1]*M[2],G[1]=M[2]*H[0]-H[2]*M[0],G[2]=M[0]*H[1]-H[0]*M[1]},T=(G,M)=>{let H=G[M+0],U=G[M+1],L=G[M+2],b=1/Math.sqrt(H*H+U*U+L*L);G[M+0]*=b,G[M+1]*=b,G[M+2]*=b},C=(G,M,H)=>{for(let U=0;U<3;++U)G[U]=M[H+U]},v=_.length/3,E=m.length/3,y=new Float32Array(m.length),P=[0,0,0],A=[0,0,0],w=[0,0,0],I=[0,0,0],D=[0,0,0],O=[0,0,0];for(let G=0;G{let _={},S=new e.DecoderBuffer;S.Init(m,m.length);let g=new e.Decoder;if(g.GetEncodedGeometryType(S)!==e.TRIANGULAR_MESH)return _.error="Failed to decode draco mesh: not a mesh",_;let T=new e.Mesh,C=g.DecodeBufferToMesh(S,T);if(!C||!C.ok()||e.getPointer(T)===0)return _.error="Failed to decode draco asset",_;let v=T.num_faces()*3,E=T.num_points()<=65535,y=v*(E?2:4),P=e._malloc(y);E?(g.GetTrianglesUInt16Array(T,y,P),_.indices=new Uint16Array(e.HEAPU16.buffer,P,v).slice().buffer):(g.GetTrianglesUInt32Array(T,y,P),_.indices=new Uint32Array(e.HEAPU32.buffer,P,v).slice().buffer),e._free(P);let A=[];for(let M=0;M(h[M.attribute_type()]??h.length)-(h[H.attribute_type()]??h.length));let w=0,I=A.map(M=>{let H=w;return w+=Math.ceil(l(M)/4)*4,H}),D=A.some(M=>M.attribute_type()===1),O=I[1]??0;if(!D){O=I[0]+Math.ceil(l(A[0])/4)*4;for(let M=1;M({id:M.unique_id(),dataType:o(M.data_type()),numComponents:M.num_components(),offset:I[H]})),D||_.attributes.splice(1,0,{id:-1,dataType:6,numComponents:3,offset:O}),_.stride=w,_.vertices=new ArrayBuffer(T.num_points()*w);let G=new Uint8Array(_.vertices);for(let M=0;M{let _=u(new Uint8Array(m.buffer));self.postMessage({jobId:m.jobId,error:_.error,indices:_.indices,vertices:_.vertices,attributes:_.attributes,stride:_.stride},[_.indices,_.vertices].filter(S=>S!=null))},p=[];self.onmessage=m=>{let _=m.data;switch(_.type){case"init":self.DracoDecoderModule({instantiateWasm:(S,g)=>(WebAssembly.instantiate(_.module,S).then(T=>g(T)).catch(T=>{}),{})}).then(S=>{e=S,p.forEach(g=>d(g))});break;case"decodeMesh":e?d(_):p.push(_);break}}}var mG=3,eb=class{constructor(){this.workers=[[],[],[]],this.jobId=0,this.jobQueue=[],this.jobCallbacks=new Map,this.run=(t,e)=>{t.postMessage({type:"decodeMesh",jobId:e.jobId,buffer:e.buffer},[e.buffer])}}init(t){for(t.forEach(e=>{e.addEventListener("message",s=>{let i=s.data,r=this.jobCallbacks.get(i.jobId);if(r&&r(i.error,{indices:i.indices,vertices:i.vertices,attributes:i.attributes,stride:i.stride}),this.jobCallbacks.delete(i.jobId),this.jobQueue.length>0){let a=this.jobQueue.shift();this.run(e,a)}else{let a=this.workers[2].indexOf(e);if(a!==-1)this.workers[2].splice(a,1),this.workers[1].push(e);else{let o=this.workers[1].indexOf(e);o!==-1&&(this.workers[1].splice(o,1),this.workers[0].push(e))}}})}),this.workers[0]=t;this.jobQueue.length&&(this.workers[0].length||this.workers[1].length);){let e=this.jobQueue.shift();if(this.workers[0].length>0){let s=this.workers[0].shift();this.workers[1].push(s),this.run(s,e)}else{let s=this.workers[1].shift();this.workers[2].push(s),this.run(s,e)}}}enqueueJob(t,e){let s={jobId:this.jobId++,buffer:t};if(this.jobCallbacks.set(s.jobId,e),this.workers[0].length>0){let i=this.workers[0].shift();this.workers[1].push(i),this.run(i,s)}else if(this.workers[1].length>0){let i=this.workers[1].shift();this.workers[2].push(i),this.run(i,s)}else this.jobQueue.push(s)}},zK=c=>new Promise((t,e)=>{let s={cache:!0,responseType:"text",retry:mG>0,maxRetries:mG};Le.get(c,s,(i,r)=>{i?e(i):t(r)})}),GK=c=>{let t=()=>fetch(c).then(s=>s.arrayBuffer()).then(s=>WebAssembly.compile(s)),e=()=>WebAssembly.compileStreaming(fetch(c)).catch(s=>t());return WebAssembly.compileStreaming?e():t()},_G=1,BE,tb,gG=c=>{if(BE)return!0;if(!c)if(tb)c=tb;else{let t=Yl.getConfig("DracoDecoderModule");t?c={jsUrl:t.glueUrl,wasmUrl:t.wasmUrl,numWorkers:t.numWorkers}:c={jsUrl:"draco.wasm.js",wasmUrl:"draco.wasm.wasm",numWorkers:_G}}return!c.jsUrl||!c.wasmUrl?!1:(BE=new eb,Promise.all([zK(c.jsUrl),GK(c.wasmUrl)]).then(([t,e])=>{let s=["/* draco */",t,"/* worker */",`( +${pG.toString()} )() -`].join("\n")],{type:"application/javascript"}),r=URL.createObjectURL(s),a=Math.max(1,Math.min(16,e.numWorkers||1)),n=[];for(let e=0;e!!yC()&&(m.enqueueJob(e,t),true);class yP{destroy(){this.renders&&this.renders.forEach(e=>{e.meshes=null;});}}let yI=e=>{switch(e){case "SCALAR":return 1;case "VEC2":return 2;case "VEC3":default:return 3;case "VEC4":case "MAT2":return 4;case "MAT3":return 9;case "MAT4":return 16}},yD=e=>{switch(e){case 5120:default:return 0;case 5121:return 1;case 5122:return 2;case 5123:return 3;case 5124:return 4;case 5125:return 5;case 5126:return 6}},yR=e=>{switch(e){case 5120:case 5121:return 1;case 5122:case 5123:return 2;case 5124:case 5125:case 5126:return 4;default:return 0}},yL={POSITION:e8,NORMAL:e9,TANGENT:e7,COLOR_0:ti,JOINTS_0:tt,WEIGHTS_0:te,TEXCOORD_0:tr,TEXCOORD_1:ta,TEXCOORD_2:tn,TEXCOORD_3:to,TEXCOORD_4:tl,TEXCOORD_5:th,TEXCOORD_6:tc,TEXCOORD_7:td},yM={[e8]:0,[e9]:1,[e7]:2,[ti]:3,[tt]:4,[te]:5,[tr]:6,[ta]:7,[tn]:8,[to]:9,[tl]:10,[th]:11,[tc]:12,[td]:13},yO=(e,t,i)=>{let s=(e=>{switch(e){case 0:return e=>Math.max(e/127,-1);case 1:return e=>e/255;case 2:return e=>Math.max(e/32767,-1);case 3:return e=>e/65535;default:return e=>e}})(i),r=t.length;for(let i=0;i{let s,r=yI(e.type),a=(e=>{switch(e){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:return null}})(e.componentType);if(!a)return null;if(e.sparse){let i=e.sparse,n=yF(Object.assign({count:i.count,type:"SCALAR"},i.indices),t,true),o=yF(Object.assign({count:i.count,type:e.type,componentType:e.componentType},i.values),t,true);s=e.hasOwnProperty("bufferView")?yF({bufferView:e.bufferView,byteOffset:e.byteOffset,componentType:e.componentType,count:e.count,type:e.type},t,true).slice():new a(e.count*r);for(let e=0;e{let i=yF(e,t,true);if(i instanceof Float32Array||!e.normalized)return i;let s=new Float32Array(i.length);return yO(s,i,yD(e.componentType)),s},yB=e=>{let t=e.min,i=e.max;if(!t||!i)return null;if(e.normalized){let s=yD(e.componentType);t=yO([],t,s),i=yO([],i,s);}return new eA(new ed((i[0]+t[0])*.5,(i[1]+t[1])*.5,(i[2]+t[2])*.5),new ed((i[0]-t[0])*.5,(i[1]-t[1])*.5,(i[2]-t[2])*.5))},yk=e=>{if(!e.hasOwnProperty("mode"))return 4;switch(e.mode){case 0:return 0;case 1:return 1;case 2:return 2;case 3:return 3;case 4:default:return 4;case 5:return 5;case 6:return 6}},yU=(e,t,i)=>{let s,r=e.texCoord;if(r)for(s=0;s{let s;if(e.hasOwnProperty("diffuseFactor")){let[i,s,r,a]=e.diffuseFactor;t.diffuse.set(i,s,r).gamma(),t.opacity=a;}else t.diffuse.set(1,1,1),t.opacity=1;if(e.hasOwnProperty("diffuseTexture")){let r=e.diffuseTexture;t.diffuseMap=s=i[r.index],t.diffuseMapChannel="rgb",t.opacityMap=s,t.opacityMapChannel="a",yU(r,t,["diffuse","opacity"]);}if(t.useMetalness=false,e.hasOwnProperty("specularFactor")){let[i,s,r]=e.specularFactor;t.specular.set(i,s,r).gamma();}else t.specular.set(1,1,1);if(e.hasOwnProperty("glossinessFactor")?t.gloss=e.glossinessFactor:t.gloss=1,e.hasOwnProperty("specularGlossinessTexture")){let s=e.specularGlossinessTexture;t.specularMap=t.glossMap=i[s.index],t.specularMapChannel="rgb",t.glossMapChannel="a",yU(s,t,["gloss","metalness"]);}},yV=(e,t,i)=>{if(e.hasOwnProperty("clearcoatFactor")?t.clearCoat=.25*e.clearcoatFactor:t.clearCoat=0,e.hasOwnProperty("clearcoatTexture")){let s=e.clearcoatTexture;t.clearCoatMap=i[s.index],t.clearCoatMapChannel="r",yU(s,t,["clearCoat"]);}if(e.hasOwnProperty("clearcoatRoughnessFactor")?t.clearCoatGloss=e.clearcoatRoughnessFactor:t.clearCoatGloss=0,e.hasOwnProperty("clearcoatRoughnessTexture")){let s=e.clearcoatRoughnessTexture;t.clearCoatGlossMap=i[s.index],t.clearCoatGlossMapChannel="g",yU(s,t,["clearCoatGloss"]);}if(e.hasOwnProperty("clearcoatNormalTexture")){let s=e.clearcoatNormalTexture;t.clearCoatNormalMap=i[s.index],yU(s,t,["clearCoatNormal"]),s.hasOwnProperty("scale")?t.clearCoatBumpiness=s.scale:t.clearCoatBumpiness=1;}t.clearCoatGlossInvert=true;},yG=(e,t,i)=>{t.useLighting=false,t.emissive.copy(t.diffuse),t.emissiveMap=t.diffuseMap,t.emissiveMapUv=t.diffuseMapUv,t.emissiveMapTiling.copy(t.diffuseMapTiling),t.emissiveMapOffset.copy(t.diffuseMapOffset),t.emissiveMapRotation=t.diffuseMapRotation,t.emissiveMapChannel=t.diffuseMapChannel,t.emissiveVertexColor=t.diffuseVertexColor,t.emissiveVertexColorChannel=t.diffuseVertexColorChannel,t.useLighting=false,t.useSkybox=false,t.diffuse.set(1,1,1),t.diffuseMap=null,t.diffuseVertexColor=false;},yH=(e,t,i)=>{if(t.useMetalnessSpecularColor=true,e.hasOwnProperty("specularColorTexture")&&(t.specularMap=i[e.specularColorTexture.index],t.specularMapChannel="rgb",yU(e.specularColorTexture,t,["specular"])),e.hasOwnProperty("specularColorFactor")){let[i,s,r]=e.specularColorFactor;t.specular.set(i,s,r).gamma();}else t.specular.set(1,1,1);e.hasOwnProperty("specularFactor")?t.specularityFactor=e.specularFactor:t.specularityFactor=1,e.hasOwnProperty("specularTexture")&&(t.specularityFactorMapChannel="a",t.specularityFactorMap=i[e.specularTexture.index],yU(e.specularTexture,t,["specularityFactor"]));},yW=(e,t,i)=>{e.hasOwnProperty("ior")&&(t.refractionIndex=1/e.ior);},yX=(e,t,i)=>{e.hasOwnProperty("dispersion")&&(t.dispersion=e.dispersion);},yY=(e,t,i)=>{t.blendType=2,t.useDynamicRefraction=true,e.hasOwnProperty("transmissionFactor")&&(t.refraction=e.transmissionFactor),e.hasOwnProperty("transmissionTexture")&&(t.refractionMapChannel="r",t.refractionMap=i[e.transmissionTexture.index],yU(e.transmissionTexture,t,["refraction"]));},yq=(e,t,i)=>{if(t.useSheen=true,e.hasOwnProperty("sheenColorFactor")){let[i,s,r]=e.sheenColorFactor;t.sheen.set(i,s,r).gamma();}else t.sheen.set(1,1,1);e.hasOwnProperty("sheenColorTexture")&&(t.sheenMap=i[e.sheenColorTexture.index],yU(e.sheenColorTexture,t,["sheen"])),t.sheenGloss=e.hasOwnProperty("sheenRoughnessFactor")?e.sheenRoughnessFactor:0,e.hasOwnProperty("sheenRoughnessTexture")&&(t.sheenGlossMap=i[e.sheenRoughnessTexture.index],t.sheenGlossMapChannel="a",yU(e.sheenRoughnessTexture,t,["sheenGloss"])),t.sheenGlossInvert=true;},yj=(e,t,i)=>{if(t.blendType=2,t.useDynamicRefraction=true,e.hasOwnProperty("thicknessFactor")&&(t.thickness=e.thicknessFactor),e.hasOwnProperty("thicknessTexture")&&(t.thicknessMap=i[e.thicknessTexture.index],t.thicknessMapChannel="g",yU(e.thicknessTexture,t,["thickness"])),e.hasOwnProperty("attenuationDistance")&&(t.attenuationDistance=e.attenuationDistance),e.hasOwnProperty("attenuationColor")){let[i,s,r]=e.attenuationColor;t.attenuation.set(i,s,r).gamma();}},yK=(e,t,i)=>{e.hasOwnProperty("emissiveStrength")&&(t.emissiveIntensity=e.emissiveStrength);},y$=(e,t,i)=>{t.useIridescence=true,e.hasOwnProperty("iridescenceFactor")&&(t.iridescence=e.iridescenceFactor),e.hasOwnProperty("iridescenceTexture")&&(t.iridescenceMapChannel="r",t.iridescenceMap=i[e.iridescenceTexture.index],yU(e.iridescenceTexture,t,["iridescence"])),e.hasOwnProperty("iridescenceIor")&&(t.iridescenceRefractionIndex=e.iridescenceIor),e.hasOwnProperty("iridescenceThicknessMinimum")&&(t.iridescenceThicknessMin=e.iridescenceThicknessMinimum),e.hasOwnProperty("iridescenceThicknessMaximum")&&(t.iridescenceThicknessMax=e.iridescenceThicknessMaximum),e.hasOwnProperty("iridescenceThicknessTexture")&&(t.iridescenceThicknessMapChannel="g",t.iridescenceThicknessMap=i[e.iridescenceThicknessTexture.index],yU(e.iridescenceThicknessTexture,t,["iridescenceThickness"]));},yZ=(e,t,i)=>{if(t.enableGGXSpecular=true,e.hasOwnProperty("anisotropyStrength")?t.anisotropyIntensity=e.anisotropyStrength:t.anisotropyIntensity=0,e.hasOwnProperty("anisotropyTexture")){let s=e.anisotropyTexture;t.anisotropyMap=i[s.index],yU(s,t,["anisotropy"]);}e.hasOwnProperty("anisotropyRotation")?t.anisotropyRotation=e.anisotropyRotation*ei.RAD_TO_DEG:t.anisotropyRotation=0;},yQ=(e,t)=>{let i,s=new ud;if(e.hasOwnProperty("name")&&(s.name=e.name),s.occludeSpecular=1,s.diffuseVertexColor=true,s.specularTint=true,s.specularVertexColor=true,s.specular.set(1,1,1),s.gloss=1,s.glossInvert=true,s.useMetalness=true,e.hasOwnProperty("pbrMetallicRoughness")){let r=e.pbrMetallicRoughness;if(r.hasOwnProperty("baseColorFactor")){let[e,t,i,a]=r.baseColorFactor;s.diffuse.set(e,t,i).gamma(),s.opacity=a;}if(r.hasOwnProperty("baseColorTexture")){let e=r.baseColorTexture;s.diffuseMap=i=t[e.index],s.diffuseMapChannel="rgb",s.opacityMap=i,s.opacityMapChannel="a",yU(e,s,["diffuse","opacity"]);}if(r.hasOwnProperty("metallicFactor")&&(s.metalness=r.metallicFactor),r.hasOwnProperty("roughnessFactor")&&(s.gloss=r.roughnessFactor),r.hasOwnProperty("metallicRoughnessTexture")){let e=r.metallicRoughnessTexture;s.metalnessMap=s.glossMap=t[e.index],s.metalnessMapChannel="b",s.glossMapChannel="g",yU(e,s,["gloss","metalness"]);}}if(e.hasOwnProperty("normalTexture")){let i=e.normalTexture;s.normalMap=t[i.index],yU(i,s,["normal"]),i.hasOwnProperty("scale")&&(s.bumpiness=i.scale);}if(e.hasOwnProperty("occlusionTexture")){let i=e.occlusionTexture;s.aoMap=t[i.index],s.aoMapChannel="r",yU(i,s,["ao"]);}if(e.hasOwnProperty("emissiveFactor")){let[t,i,r]=e.emissiveFactor;s.emissive.set(t,i,r).gamma();}if(e.hasOwnProperty("emissiveTexture")){let i=e.emissiveTexture;s.emissiveMap=t[i.index],yU(i,s,["emissive"]);}if(e.hasOwnProperty("alphaMode"))switch(e.alphaMode){case "MASK":s.blendType=3,e.hasOwnProperty("alphaCutoff")?s.alphaTest=e.alphaCutoff:s.alphaTest=.5;break;case "BLEND":s.blendType=2,s.depthWrite=false;break;default:s.blendType=3;}else s.blendType=3;e.hasOwnProperty("doubleSided")?(s.twoSidedLighting=e.doubleSided,s.cull=+!e.doubleSided):(s.twoSidedLighting=false,s.cull=1);let r={KHR_materials_clearcoat:yV,KHR_materials_emissive_strength:yK,KHR_materials_ior:yW,KHR_materials_dispersion:yX,KHR_materials_iridescence:y$,KHR_materials_pbrSpecularGlossiness:yz,KHR_materials_sheen:yq,KHR_materials_specular:yH,KHR_materials_transmission:yY,KHR_materials_unlit:yG,KHR_materials_volume:yj,KHR_materials_anisotropy:yZ};if(e.hasOwnProperty("extensions"))for(let i in e.extensions){let a=r[i];void 0!==a&&a(e.extensions[i],s,t);}return s.update(),s},yJ=new ey,y0=new ed,y1=new ex,y2=(e,t,i)=>{let s=new oJ;if(e.hasOwnProperty("name")&&e.name.length>0?s.name=e.name:s.name=`node_${t}`,e.hasOwnProperty("matrix")&&(yJ.data.set(e.matrix),yJ.getTranslation(y0),s.setLocalPosition(y0),y1.setFromMat4(yJ),s.setLocalRotation(y1),yJ.getScale(y0),y0.x*=yJ.scaleSign,s.setLocalScale(y0)),e.hasOwnProperty("rotation")){let t=e.rotation;s.setLocalRotation(t[0],t[1],t[2],t[3]);}if(e.hasOwnProperty("translation")){let t=e.translation;s.setLocalPosition(t[0],t[1],t[2]);}if(e.hasOwnProperty("scale")){let t=e.scale;s.setLocalScale(t[0],t[1],t[2]);}return e.hasOwnProperty("extensions")&&e.extensions.EXT_mesh_gpu_instancing&&i.set(e,{ext:e.extensions.EXT_mesh_gpu_instancing}),s},y3=(e,t)=>{let i="orthographic"===e.type,s=i?e.orthographic:e.perspective,r={enabled:false,projection:+!!i,nearClip:s.znear,aspectRatioMode:0};s.zfar&&(r.farClip=s.zfar),i?(r.orthoHeight=s.ymag,s.xmag&&s.ymag&&(r.aspectRatioMode=1,r.aspectRatio=s.xmag/s.ymag)):(r.fov=s.yfov*ei.RAD_TO_DEG,s.aspectRatio&&(r.aspectRatioMode=1,r.aspectRatio=s.aspectRatio));let a=new f9(e.name);return a.addComponent("camera",r),a},y4=(e,t)=>{let i={enabled:false,type:"point"===e.type?"omni":e.type,color:e.hasOwnProperty("color")?new es(e.color):es.WHITE,range:e.hasOwnProperty("range")?e.range:9999,falloffMode:1,intensity:e.hasOwnProperty("intensity")?ei.clamp(e.intensity,0,2):1};if(e.hasOwnProperty("spot")&&(i.innerConeAngle=e.spot.hasOwnProperty("innerConeAngle")?e.spot.innerConeAngle*ei.RAD_TO_DEG:0,i.outerConeAngle=e.spot.hasOwnProperty("outerConeAngle")?e.spot.outerConeAngle*ei.RAD_TO_DEG:45),e.hasOwnProperty("intensity")){let t=e.spot?.outerConeAngle??Math.PI/4,s=e.spot?.innerConeAngle??0;i.luminance=e.intensity*hL.getLightUnitConversion(hA[i.type],t,s);}let s=new f9(t.name);return s.rotateLocal(90,0,0),s.addComponent("light",i),s},y5=async(e,t,i,s,r)=>{let a,n,o,l,h,c=r?.global?.preprocess,d=r?.global?.postprocess;c&&c(t),t.asset&&t.asset.generator;let u=new Map,f=((e,t,i)=>{if(!e.hasOwnProperty("nodes")||0===e.nodes.length)return [];let s=t?.node?.preprocess,r=t?.node?.process??y2,a=t?.node?.postprocess,n=e.nodes.map((e,t)=>{s&&s(e);let n=r(e,t,i);return a&&a(e,n),n});for(let t=0;t{let i=[],s=e.scenes.length;if(1===s&&e.scenes[0].nodes?.length===1){let s=e.scenes[0].nodes[0];i.push(t[s]);}else for(let r=0;r{let s=null;if(e.hasOwnProperty("nodes")&&e.hasOwnProperty("extensions")&&e.extensions.hasOwnProperty("KHR_lights_punctual")&&e.extensions.KHR_lights_punctual.hasOwnProperty("lights")){let r=e.extensions.KHR_lights_punctual.lights;if(r.length){let a=i?.light?.preprocess,n=i?.light?.process??y4,o=i?.light?.postprocess;e.nodes.forEach((e,i)=>{if(e.hasOwnProperty("extensions")&&e.extensions.hasOwnProperty("KHR_lights_punctual")&&e.extensions.KHR_lights_punctual.hasOwnProperty("light")){let l=r[e.extensions.KHR_lights_punctual.light];if(l){a&&a(l);let r=n(l,t[i]);o&&o(l,r),r&&(s||(s=new Map),s.set(e,r));}}});}}return s})(t,f,r),_=((e,t,i)=>{let s=null;if(e.hasOwnProperty("nodes")&&e.hasOwnProperty("cameras")&&e.cameras.length>0){let r=i?.camera?.preprocess,a=i?.camera?.process??y3,n=i?.camera?.postprocess;e.nodes.forEach((i,o)=>{if(i.hasOwnProperty("camera")){let l=e.cameras[i.camera];if(l){r&&r(l);let e=a(l,t[o]);n&&n(l,e),e&&(s||(s=new Map),s.set(i,e));}}});}return s})(t,f,r),g=(e=>{if(!e.hasOwnProperty("extensions")||!e.extensions.hasOwnProperty("KHR_materials_variants"))return null;let t=e.extensions.KHR_materials_variants.variants,i={};for(let e=0;e{var s;let h;return s=t.accessors,h=[],i.primitives.forEach(t=>{if(t.extensions?.KHR_draco_mesh_compression)h.push(((e,t,i,s,r,a,n)=>{let o=new on(e);if(o.aabb=yB(i[t.attributes.POSITION]),n.push(new Promise((r,a)=>{let n=t.extensions.KHR_draco_mesh_compression;yA(s[n.bufferView].slice().buffer,(s,l)=>{if(s)a(s);else {let s={};for(let[e,t]of Object.entries(n.attributes))s[t]=yL[e];s[-1]=e9;let a=[];for(let e of l.attributes){let r=s[e.id];if(void 0!==r){let s=false;if(-1!==e.id){for(let[a,o]of Object.entries(n.attributes))if(o===e.id&&void 0!==t.attributes[a]){s=i[t.attributes[a]].normalized??(r===ti&&(1===e.dataType||3===e.dataType));break}}a.push({semantic:r,components:e.numComponents,type:e.dataType,normalize:s,offset:e.offset,stride:l.stride});}}let h=new iB(e,a),c=l.vertices.byteLength/l.stride,d=l.indices.byteLength/(c<=65535?2:4),u=new iR(e,h,c,{data:l.vertices}),f=new iw(e,c<=65535?1:2,d,0,l.indices);o.vertexBuffer=u,o.indexBuffer[0]=f,o.primitive[0].type=yk(t),o.primitive[0].base=0,o.primitive[0].count=f?d:c,o.primitive[0].indexed=!!f,r();}});})),t?.extensions?.KHR_materials_variants){let e=t.extensions.KHR_materials_variants,i={};e.mappings.forEach(e=>{e.variants.forEach(t=>{i[t]=e.material;});}),r[o.id]=i;}return a[o.id]=t.material,o})(e,t,s,v,n,o,l));else {let l=t.hasOwnProperty("indices")?yF(s[t.indices],v,true):null,c=((e,t,i,s,r,a)=>{let n={},o=[];for(let e in t)t.hasOwnProperty(e)&&yL.hasOwnProperty(e)&&(n[e]=t[e],o.push(`${e}:${t[e]}`));o.sort();let l=o.join(),h=a[l];if(!h){let o={};for(let e in n){let i=s[t[e]],a=yF(i,r),n=r[i.bufferView],l=yL[e],h=yI(i.type)*yR(i.componentType),c=n&&n.hasOwnProperty("byteStride")?n.byteStride:h;o[l]={buffer:a.buffer,size:h,offset:a.byteOffset,stride:c,count:i.count,components:yI(i.type),type:yD(i.componentType),normalize:i.normalized};}o.hasOwnProperty(e9)||((e,t)=>{let i,s=e[e8];if(!s||3!==s.components)return;if(s.size!==s.stride){let e=s.stride/t1[s.type],t=new t0[s.type](s.buffer,s.offset,s.count*e);i=new t0[s.type](3*s.count);for(let r=0;r{let t=new Uint16Array(e);for(let i=0;i{let i,s,r,a,n,o,l,h=t[e8];if(!h)return null;let c=h.count,d=[];for(let i in t)if(t.hasOwnProperty(i)){let s={semantic:i,components:t[i].components,type:t[i].type,normalize:!!t[i].normalize};!iB.isElementValid(e,s)&&s.components++,d.push(s);}d.sort((e,t)=>yM[e.semantic]-yM[t.semantic]);let u=new iB(e,d),f=true;for(i=0;i{e.variants.forEach(t=>{i[t]=e.material;});}),n[u.id]=i;}o[u.id]=t.material;let f=s[t.attributes.POSITION];if(u.aabb=yB(f),t.hasOwnProperty("targets")){let a=[];t.targets.forEach((e,t)=>{let n={};e.hasOwnProperty("POSITION")&&(n.deltaPositions=yN(f=s[e.POSITION],v),n.aabb=yB(f)),e.hasOwnProperty("NORMAL")&&(n.deltaNormals=yN(f=s[e.NORMAL],v)),i.hasOwnProperty("extras")&&i.extras.hasOwnProperty("targetNames")?n.name=i.extras.targetNames[t]:n.name=t.toString(10),i.hasOwnProperty("weights")&&(n.defaultWeight=i.weights[t]),n.preserveData=r.morphPreserveData,a.push(new hB(n));}),u.morph=new hN(a,e,{preferHighPrecision:r.morphPreferHighPrecision});}h.push(u);}}),h}):[],meshVariants:n,meshDefaultMaterials:o,promises:l}),E=((e,t,i,s)=>{if(!e.hasOwnProperty("animations")||0===e.animations.length)return [];let r=s?.animation?.preprocess,a=s?.animation?.postprocess;return e.animations.map((s,n)=>{r&&r(s);let o=((e,t,i,s,r,a,n)=>{let o,l,h=e=>new yE(yI(e.type),yN(e,s)),c={STEP:0,LINEAR:1,CUBICSPLINE:2},d={},u={},f={},p=1;for(o=0;o{let t=[];for(;e;)t.unshift(e.name),e=e.parent;return t},v=(e,t,i)=>{let s,r=u[e.output];if(!r)return;if(a&&a[t.mesh]){let e=a[t.mesh];e.hasOwnProperty("extras")&&e.extras.hasOwnProperty("targetNames")&&(s=e.extras.targetNames);}let n=r.data,l=n.length/d[e.input].data.length,h=n.length/l,c=4*h,m=new ArrayBuffer(c*l);for(let t=0;t0&&"localRotation"===t.paths[0].propertyPath[0]&&2!==t.interpolation&&m.push(x[x.length-1].output));}m.sort();let T=null;for(o=0;o{let i,s,r,a=e.ext.attributes;a.hasOwnProperty("TRANSLATION")&&(i=yN(h[a.TRANSLATION],v)),a.hasOwnProperty("ROTATION")&&(s=yN(h[a.ROTATION],v)),a.hasOwnProperty("SCALE")&&(r=yN(h[a.SCALE],v));let n=(i?i.length/3:0)||(s?s.length/4:0)||(r?r.length/3:0);if(n){let t=new Float32Array(16*n),a=new ed,o=new ex,l=new ed(1,1,1),h=new ey,c=0;for(let e=0;e{if(!e.hasOwnProperty("materials")||0===e.materials.length)return [];let s=i?.material?.preprocess,r=i?.material?.process??yQ,a=i?.material?.postprocess;return e.materials.map(e=>{s&&s(e);let i=r(e,t);return a&&a(e,i),i})})(t,w.map(e=>e.resource),r),C=((e,t,i,s)=>{if(!t.hasOwnProperty("skins")||0===t.skins.length)return [];let r=new Map;return t.skins.map(a=>((e,t,i,s,r,a)=>{let n,o,l,h=t.joints,c=h.length,d=[];if(t.hasOwnProperty("inverseBindMatrices")){let e=yF(i[t.inverseBindMatrices],s,true),r=[];for(n=0;n{e.hasOwnProperty("mesh")&&e.hasOwnProperty("skin")&&A[e.mesh].meshes.forEach(t=>{t.skin=C[e.skin];});});let P=new yP;return P.gltf=t,P.nodes=f,P.scenes=p,P.animations=E,P.textures=w,P.materials=b,P.variants=g,P.meshVariants=y,P.meshDefaultMaterials=x,P.renders=A,P.skins=C,P.lights=m,P.cameras=_,P.nodeInstancingMap=u,d&&d(t,P),await Promise.all(T),P},y6=0,y8=e=>e.extensions?.KHR_texture_basisu?.source??e.extensions?.EXT_texture_webp?.source??e.source;class y9{static parse(e,t,i,s,r,a,n){let o;var l=(e,i)=>{var o,l;let h;e?n(e):(o=i.gltfChunk,l=(e,o)=>{if(e)return void n(e);let l=((e,t,i,s)=>{if(!e.buffers||0===e.buffers.length)return [];let r=s?.buffer?.preprocess,a=s?.buffer?.processAsync,n=s?.buffer?.postprocess;return e.buffers.map((s,o)=>{let l;return r&&r(s),l=(l=new Promise(a?(e,t)=>{a(s,(i,s)=>{i?t(i):e(s);});}:e=>{e(null);})).then(e=>{if(e)return e;if(s.hasOwnProperty("uri")){let e;if(e=s.uri,/^data:[^\n\r,\u2028\u2029]*,.*$/i.test(e)){let e=atob(s.uri.split(",")[1]),t=new Uint8Array(e.length);for(let i=0;i{a0.get(fz.test(s.uri)?s.uri:P.join(i,s.uri),{cache:true,responseType:"arraybuffer",retry:false},(i,s)=>{i?t(i):e(new Uint8Array(s));});})}return t}),n&&(l=l.then(t=>(n(e.buffers[o],t),t))),l})})(o,i.binaryChunk,t,a),h=((e,t,i)=>{let s=[],r=i?.bufferView?.preprocess,a=i?.bufferView?.processAsync,n=i?.bufferView?.postprocess;if(!e.bufferViews?.length)return s;for(let i=0;i{a(l,t,(t,s)=>{t?i(t):e(s);});}:e=>{e(null);})).then(e=>e||t[l.buffer].then(e=>new Uint8Array(e.buffer,e.byteOffset+(l.byteOffset||0),l.byteLength))),l.hasOwnProperty("byteStride")&&(o=o.then(e=>(e.byteStride=l.byteStride,e))),n&&(o=o.then(e=>(n(l,e),e))),s.push(o);}return s})(o,l,a),c=((e,t,i,s,r)=>{let a;if(!e.images||0===e.images.length)return [];let n=r?.image?.preprocess,o=r?.image?.processAsync,l=r?.image?.postprocess,h={"image/png":"png","image/jpeg":"jpg","image/basis":"basis","image/ktx":"ktx","image/ktx2":"ktx2","image/vnd-ms.dds":"dds"},c=(e,t,i,r,a,n)=>new Promise((o,l)=>{let c=i=>{let c=`${e.name||"gltf-texture"}-${y6++}`,d={url:t||c};if(i&&(d.contents=i.slice(0).buffer),r){let e=h[r];e&&(d.filename=`${d.url}.${e}`);}let u=new fX(c,"texture",d,{srgb:n},a);u.on("load",e=>o(e)),u.on("error",e=>l(e)),s.add(u),s.load(u);};i?i.then(e=>c(e)):c(null);}),d=(a=new Set,e.hasOwnProperty("materials")&&e.materials.forEach(t=>{if(t.hasOwnProperty("pbrMetallicRoughness")){let i=t.pbrMetallicRoughness;if(i.hasOwnProperty("baseColorTexture")){let t=e.textures[i.baseColorTexture.index];a.add(y8(t));}}if(t.hasOwnProperty("emissiveTexture")){let i=e.textures[t.emissiveTexture.index];a.add(y8(i));}if(t.hasOwnProperty("extensions")){let i=t.extensions.KHR_materials_sheen;if(i&&i.hasOwnProperty("sheenColorTexture")){let t=e.textures[i.sheenColorTexture.index];a.add(y8(t));}let s=t.extensions.KHR_materials_pbrSpecularGlossiness;if(s&&s.hasOwnProperty("specularGlossinessTexture")){let t=e.textures[s.specularGlossinessTexture.index];a.add(y8(t));}let r=t.extensions.KHR_materials_specular;if(r&&r.hasOwnProperty("specularColorTexture")){let t=e.textures[r.specularColorTexture.index];a.add(y8(t));}}}),a);return e.images.map((e,s)=>{let r;return n&&n(e),r=(r=new Promise(o?(t,i)=>{o(e,(e,s)=>{e?i(e):t(s);});}:e=>{e(null);})).then(r=>{let a=d.has(s);if(r)return r;if(e.hasOwnProperty("uri")){let t;if(t=e.uri,/^data:[^\n\r,\u2028\u2029]*,.*$/i.test(t)){let t;return c(e,e.uri,null,(t=e.uri).substring(t.indexOf(":")+1,t.indexOf(";")),null,a)}return c(e,fz.test(e.uri)?e.uri:P.join(i,e.uri),null,null,{crossOrigin:"anonymous"},a)}return e.hasOwnProperty("bufferView")&&e.hasOwnProperty("mimeType")?c(e,null,t[e.bufferView],e.mimeType,null,a):Promise.reject(Error(`Invalid image found in gltf (neither uri or bufferView found). index=${s}`))}),l&&(r=r.then(t=>(l(e,t),t))),r})})(o,h,t,r,a),d=((e,t,i)=>{if(!e?.images?.length||!e?.textures?.length)return [];let s=i?.texture?.preprocess,r=i?.texture?.processAsync,a=i?.texture?.postprocess,n=new Set;return e.textures.map(i=>{let o;return s&&s(i),o=(o=new Promise(r?(t,s)=>{r(i,e.images,(e,i)=>{e?s(e):t(i);});}:e=>{e(null);})).then(s=>{s=s??y8(i);let r=n.has(s);return n.add(s),t[s].then(t=>{var s,a,n;let o,l,h,c,d=r?((o=new fX(`${t.name}_clone`,t.type,t.file,t.data,t.options)).loaded=true,(l=new ic((s=t.resource).device,s))._levels=(e=>{let t=[];for(let i=0;i{switch(e){case 9728:return 0;case 9729:return 1;case 9984:return 2;case 9985:return 4;case 9986:return 3;case 9987:return 5;default:return t}},c=(e,t)=>{switch(e){case 33071:return 1;case 33648:return 2;case 10497:return 0;default:return t}},a&&(a.minFilter=h((n=n??{}).minFilter,5),a.magFilter=h(n.magFilter,1),a.addressU=c(n.wrapS,0),a.addressV=c(n.wrapT,0)),d})}),a&&(o=o.then(e=>(a(i,e),e))),o})})(o,c,a);y5(s,o,h,d,a).then(e=>n(null,e)).catch(e=>n(e));},(h=JSON.parse((e=>{if("u">typeof TextDecoder)return new TextDecoder().decode(e);let t="";for(let i=0;iparseFloat(h.asset.version)?l(`Invalid gltf version. Expected version 2.0 or above but found version '${h.asset.version}'.`):l(null,h));};e&&e.toLowerCase().endsWith(".glb")||103===(o=new Uint8Array(i))[0]&&108===o[1]&&84===o[2]&&70===o[3]?((e,t)=>{let i=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),s=i.getUint32(0,true),r=i.getUint32(4,true),a=i.getUint32(8,true);if(0x46546c67!==s)return t(`Invalid magic number found in glb header. Expected 0x46546C67, found 0x${s.toString(16)}`);if(2!==r)return t(`Invalid version number found in glb header. Expected 2, found ${r}`);if(a<=0||a>i.byteLength)return t(`Invalid length found in glb header. Found ${a}`);let n=[],o=12;for(;oi.byteLength&&t(`Invalid chunk length found in glb. Found ${e}`);let s=i.getUint32(o+4,true),r=new Uint8Array(i.buffer,i.byteOffset+o+8,e);n.push({length:e,type:s,data:r}),o+=e+8;}1!==n.length&&2!==n.length?t("Invalid number of chunks found in glb file."):0x4e4f534a!==n[0].type?t(`Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x${n[0].type.toString(16)}`):n.length>1&&5130562!==n[1].type?t(`Invalid chunk type found in glb file. Expected 0x004E4942, found 0x${n[1].type.toString(16)}`):t(null,{gltfChunk:n[0].data,binaryChunk:2===n.length?n[1].data:null});})(i,l):l(null,{gltfChunk:i,binaryChunk:null});}static createDefaultMaterial(){return yQ({name:"defaultGlbMaterial"},[])}}class y7 extends fQ{load(e,t,i){"string"==typeof e&&(e={load:e,original:e});let s={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(".glb"===P.getExtension(e.original).toLowerCase()?s.responseType=aJ.ResponseType.ARRAY_BUFFER:s.responseType=aJ.ResponseType.JSON),a0.get(e.load,s,(s,r)=>{s?t(`Error loading animation resource: ${e.original} [${s}]`):".glb"===P.getExtension(e.original).toLowerCase()?y9.parse("filename.glb","",r,this.device,this.assets,i?.options??{},(e,s)=>{if(e)t(e);else {let e=s.animations;if(i?.data?.events)for(let t=0;t0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=aJ.ResponseType.JSON),a0.get(e.load,i,(i,s)=>{i?t(`Error loading animation clip resource: ${e.original} [${i}]`):t(null,s);});}open(e,t){return new pQ(t.name,t.duration,t.inputs.map(e=>new yE(1,e)),t.outputs.map(e=>new yE(e.components,e.data)),t.curves.map(e=>new yT([e.path],e.inputIndex,e.outputIndex,e.interpolation)))}constructor(e){super(e,"animclip");}}class xt extends fQ{load(e,t){"string"==typeof e&&(e={load:e,original:e});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=aJ.ResponseType.JSON),a0.get(e.load,i,(i,s)=>{i?t(`Error loading animation state graph resource: ${e.original} [${i}]`):t(null,s);});}open(e,t){return new mu(t)}constructor(e){super(e,"animstategraph");}}let xi=function(){if("u"0)return parseInt(e.substring(t+5,e.indexOf(".",t)),10);if(e.indexOf("Trident/")>0){let t=e.indexOf("rv:");return parseInt(e.substring(t+3,e.indexOf(".",t)),10)}return false}(),xs=[".ogg",".mp3",".wav",".mp4a",".m4a",".mp4",".aac",".opus"];class xr extends fQ{_isSupported(e){let t=P.getExtension(e);return xs.indexOf(t)>-1}load(e,t){"string"==typeof e&&(e={load:e,original:e});let i=function(i){let s=`Error loading audio url: ${e.original}`;i&&(s+=`: ${i.message||i}`),t(s);};if(this._createSound){if(!this._isSupported(e.original))return void i(`Audio format for ${e.original} not supported`);this._createSound(e.load,function(e){t(null,new a9(e));},i);}else i(null);}_createSound(e,t,i){if(a7()){let s=this.manager;if(!s.context)return void i("Audio manager has no audio context");let r={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.startsWith("blob:")||e.startsWith("data:"))&&(r.responseType=aJ.ResponseType.ARRAY_BUFFER),a0.get(e,r,(e,r)=>{e?i(e):s.context.decodeAudioData(r,t,i);});}else {let s=null;try{s=new Audio;}catch(e){i("No support for Audio element");return}xi&&document.body.appendChild(s);let r=function(){s.removeEventListener("canplaythrough",r),xi&&document.body.removeChild(s),t(s);};s.onerror=function(){s.onerror=null,xi&&document.body.removeChild(s),i();},s.addEventListener("canplaythrough",r),s.src=e;}}constructor(e){super(e,"audio"),this.manager=e.soundManager;}}class xa extends fQ{load(e,t){"string"==typeof e&&(e={load:e,original:e}),a0.get(e.load,{responseType:aJ.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,s)=>{i?t(`Error loading binary resource: ${e.original} [${i}]`):t(null,s);});}openBinary(e){return e.buffer}constructor(e){super(e,"binary");}}class xn{get model(){if(!this._model){let e=xn.createModel(this.data,this._defaultMaterial),t=xn.createAsset(this._assetName,"model",e,0);this._assets.add(t),this._model=t;}return this._model}static createAsset(e,t,i,s){let r=new fX(`${e}/${t}/${s}`,t,{url:""});return r.resource=i,r.loaded=true,r}instantiateModelEntity(e){let t=new f9(void 0,this._assets._loader._app);return t.addComponent("model",Object.assign({type:"asset",asset:this.model},e)),t}instantiateRenderEntity(e){let t=this._defaultMaterial,i=[],s=function(e,s,r,a,n,o,l,h){let c=n[r.id],d=new oS(r,void 0===c?t:a[c]);r.morph&&(d.morphInstance=new hO(r.morph)),l.hasOwnProperty("skin")&&i.push({meshInstance:d,rootBone:e,entity:s});let u=h.get(l);if(u){let e=u.matrices,t=iB.getDefaultInstancingFormat(r.device),i=new iR(r.device,t,e.length/16,{data:e});d.setInstancing(i),d.instancingData._destroyVertexBuffer=true;}return d},r=(t,i,a)=>{let n=new f9(void 0,this._assets._loader._app);i._cloneInternal(n),t||(t=n);let o=null,l=null;for(let e=0;e{e.meshInstance.skinInstance=gg.createCachedSkinInstance(e.meshInstance.mesh.skin,e.rootBone,e.entity),e.meshInstance.node.render.rootBone=e.rootBone;}),xn.createSceneHierarchy(a,f9)}getMaterialVariants(){return this.data.variants?Object.keys(this.data.variants):[]}applyMaterialVariant(e,t){let i=t?this.data.variants[t]:null;if(void 0===i)return;let s=e.findComponents("render");for(let e=0;e{if(null===e)t.material=this._defaultMaterial;else {let i=this.data.meshVariants[t.mesh.id];i&&(t.material=this.data.materials[i[e]]);}});}static createSceneHierarchy(e,t){let i=null;if(1===e.length)i=e[0];else for(let s of(i=new t("SceneGroup"),e))i.addChild(s);return i}static createModel(e,t){let i=new hF,s=[];for(let t of e.skins){let e=new ot(t);e.bones=t.bones,s.push(e);}i.graph=xn.createSceneHierarchy(e.scenes,oJ);for(let r=0;r{t(e);});};this.animations&&(i(this.animations),this.animations=null),this.textures&&(i(this.textures),this.textures=null),this.materials&&(i(this.materials),this.materials=null),this.renders&&(i(this.renders),this.renders=null),this._model&&(t(this._model),this._model=null),this.data=null,this.assets=null;}constructor(e,t,i,s){let r=function(e,s,r){let a=xn.createAsset(t.name,e,s,r);return i.add(a),a},a=[];for(let t=0;t=0?e.split("?")[0]:e}load(e,t,i){fX.fetchArrayBuffer(e.load,(s,r)=>{s?t(s):y9.parse(this._getUrlWithoutParams(e.original),P.extractPath(e.load),r,this._device,i.registry,i.options,(e,s)=>{e?t(e):t(null,new xn(s,i,this._assets,this._defaultMaterial));});},i,this.maxRetries);}open(e,t,i){return t}patch(e,t){}constructor(e,t,i){this._device=e,this._assets=t,this._defaultMaterial=y9.createDefaultMaterial(),this.maxRetries=i;}}class xl extends fQ{set maxRetries(e){for(let t in this.glbContainerParser.maxRetries=e,this.parsers)this.parsers.hasOwnProperty(t)&&(this.parsers[t].maxRetries=e);}get maxRetries(){return this.glbContainerParser.maxRetries}_getUrlWithoutParams(e){return e.indexOf("?")>=0?e.split("?")[0]:e}_getParser(e){let t=e?P.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".",""):null;return this.parsers[t]||this.glbContainerParser}load(e,t,i){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,i);}open(e,t,i){return this._getParser(e).open(e,t,i)}constructor(e){super(e,"container"),this.glbContainerParser=new xo(e.graphicsDevice,e.assets,0),this.parsers={};}}class xh extends fQ{load(e,t){"string"==typeof e&&(e={load:e,original:e}),a0.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,s)=>{i?t(`Error loading css resource: ${e.original} [${i}]`):t(null,s);});}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}constructor(e){super(e,"css"),this.decoder=null;}}class xc extends fQ{load(e,t,i){this.loadAssets(i,t);}open(e,t,i){return i?i.resource:null}patch(e,t){this.loadAssets(e,(i,s)=>{i&&(t.fire("error",e),t.fire(`error:${e.id}`,i,e),e.fire("error",e));});}getAssetIds(e){let t=[];if(t[0]=e.file,(e.loadFaces||!e.file)&&e.data&&e.data.textures)for(let i=0;i<6;++i)t[i+1]=e.data.textures[i];else t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=null;return t}compareAssetIds(e,t){return e&&t?parseInt(e,10)===e||"string"==typeof e?e===t:e.url===t.url:null!==e==(null!==t)}update(e,t,i){let s,r,a,n=e.data||{},o=e._handlerState.assets,l=e._resources,h=[null,null,null,null,null,null,null],c=function(){return n.hasOwnProperty("type")?n.type:n.hasOwnProperty("rgbm")?n.rgbm?tI:tP:null};if(e.loaded&&i[0]===o[0])h[1]=l[1]||null,h[2]=l[2]||null,h[3]=l[3]||null,h[4]=l[4]||null,h[5]=l[5]||null,h[6]=l[6]||null;else if(i[0])if((s=i[0].resource).cubemap)for(a=0;a<6;++a)h[a+1]=new ic(this._device,{name:`${e.name}_prelitCubemap${s.width>>a}`,cubemap:true,type:c()||s.type,width:s.width>>a,height:s.height>>a,format:s.format,levels:[s._levels[a]],addressU:1,addressV:1,mipmaps:0===a});else h[1]=s;let d=i.slice(1);if(e.loaded&&this.cmpArrays(d,o.slice(1)))h[0]=l[0]||null;else if(-1===d.indexOf(null)){let t=d.map(e=>e.resource),i=[];for(r=0;re._levels[r]));let s=t[0].format,a=new ic(this._device,{name:`${e.name}_faces`,cubemap:true,type:c()||t[0].type,width:t[0].width,height:t[0].height,format:6===s?7:s,mipmaps:n.mipmaps??true,levels:i,minFilter:n.hasOwnProperty("minFilter")?n.minFilter:t[0].minFilter,magFilter:n.hasOwnProperty("magFilter")?n.magFilter:t[0].magFilter,anisotropy:n.hasOwnProperty("anisotropy")?n.anisotropy:1,addressU:1,addressV:1});h[0]=a;}if(!this.cmpArrays(h,l))for(a=0,e.resources=h,e._handlerState.assetIds=t,e._handlerState.assets=i;a{let i=l.get(t);i?u(e,i):d(e,`failed to find dependent cubemap asset=${t}`);}).bind(null,t,a));else {let s="string"==typeof a?{url:a,filename:a}:a,r=-1===s.url.search(".dds")?{type:"rgbp",addressu:"clamp",addressv:"clamp",mipmaps:false}:null;i=new fX(`${e.name}_part_${t}`,"texture",s,r),l.add(i),u(t,i);}else c(t,null);}}constructor(e){super(e,"cubemap"),this._device=e.graphicsDevice,this._registry=e.assets,this._loader=e.loader;}}class xd extends fQ{load(e,t){t(null,null);}constructor(e){super(e,"folder");}}class xu{set data(e){if(this._data=e,e&&(void 0!==this._data.intensity&&(this.intensity=this._data.intensity),this._data.info||(this._data.info={}),!this._data.version||this._data.version<2)&&(this._data.info.maps=[{width:this._data.info.width,height:this._data.info.height}],this._data.chars))for(let e in this._data.chars)this._data.chars[e].map=0;}get data(){return this._data}constructor(e,t){this.type=t&&t.type||_s,this.em=1,this.textures=e,this.intensity=0,this._data=null,this.data=t;}}function xf(e){return e.version<3&&(e.version<2&&(e.info.maps=e.info.maps||[{width:e.info.width,height:e.info.height}]),e.chars=Object.keys(e.chars||{}).reduce((t,i)=>{let s=e.chars[i],r=void 0!==s.letter?s.letter:H.fromCodePoint(i);return e.version<2&&(s.map=s.map||0),t[r]=s,t},{}),e.version=3),e}class xp extends fQ{load(e,t,i){"string"==typeof e&&(e={load:e,original:e});let s=this;".json"===P.getExtension(e.original)?a0.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,r)=>{if(i)t(`Error loading font resource: ${e.original} [${i}]`);else {let i=xf(r);s._loadTextures(e.load.replace(".json",".png"),i,(e,s)=>{e?t(e):t(null,{data:i,textures:s});});}}):(i&&i.data&&(i.data=xf(i.data)),this._loadTextures(e.load,i&&i.data,t));}_loadTextures(e,t,i){let s=t.info.maps.length,r=0,a=null,n=Array(s),o=this._loader,l=function(t){let l=function(e,o){if(!a){if(e){a=e,i(e);return}o.upload(),n[t]=o,++r===s&&i(null,n);}};0===t?o.load(e,"texture",l):o.load(e.replace(".png",`${t}.png`),"texture",l);};for(let e=0;e{let i=(1<{e.x=n(t>>>21,11),e.y=n(t>>>11,10),e.z=n(t,11);},l=(e,t,i)=>e*(1-i)+t*i,{chunkData:h,chunkSize:c,vertexData:d,shData0:u,shData1:f,shData2:p,shBands:m}=e,_=[3,8,15][m-1];this.read=e=>{let g=Math.floor(e/256)*c;if(t&&(o(t,d[4*e+0]),t.x=l(h[g+0],h[g+3],t.x),t.y=l(h[g+1],h[g+4],t.y),t.z=l(h[g+2],h[g+5],t.z)),i&&((e,t)=>{let i=Math.SQRT2,s=(n(t>>>20,10)-.5)*i,r=(n(t>>>10,10)-.5)*i,a=(n(t,10)-.5)*i,o=Math.sqrt(1-(s*s+r*r+a*a));switch(t>>>30){case 0:e.set(s,r,a,o);break;case 1:e.set(o,r,a,s);break;case 2:e.set(r,o,a,s);break;case 3:e.set(r,a,o,s);}})(i,d[4*e+1]),s&&(o(s,d[4*e+2]),s.x=l(h[g+6],h[g+9],s.x),s.y=l(h[g+7],h[g+10],s.y),s.z=l(h[g+8],h[g+11],s.z)),r){var v;r.x=n((v=d[4*e+3])>>>24,8),r.y=n(v>>>16,8),r.z=n(v>>>8,8),r.w=n(v,8),c>12&&(r.x=l(h[g+12],h[g+15],r.x),r.y=l(h[g+13],h[g+16],r.y),r.z=l(h[g+14],h[g+17],r.z));}if(a&&m>0){let t=[u,f,p];for(let i=0;i<3;++i)for(let s=0;s<15;++s)a[15*i+s]=s<_?t[i][16*e+s]*(8/255)-4:0;}};}}class x_{createIter(e,t,i,s,r){return new xm(this,e,t,i,s,r)}calcAabb(e){let{chunkData:t,numChunks:i,chunkSize:s}=this,r=Math.exp(Math.max(t[9],t[10],t[11])),a=t[0]-r,n=t[1]-r,o=t[2]-r,l=t[3]+r,h=t[4]+r,c=t[5]+r;for(let e=1;e>>21)/2047,d=(l>>>11&1023)/1023,u=(2047&l)/2047;c[3*o+0]=(1-h)*e+h*s,c[3*o+1]=(1-d)*t+d*r,c[3*o+2]=(1-u)*i+u*a;}}return c}getChunks(e){let t,i,s,r,a,n,{chunkData:o,numChunks:l,chunkSize:h}=this;for(let c=0;c0){let t=[];for(let e=0;e<45;++e)t.push(`f_rest_${e}`);let i=Math.max(...["f_dc_0","f_dc_1","f_dc_2"].map(t=>e.indexOf(t)));e.splice(i+1,0,...t);}let i={};e.forEach(e=>{i[e]=new Float32Array(this.numSplats);});let s=new ed,r=new ex,a=new ed,n=new ep,o=t>0?new Float32Array(45):null,l=this.createIter(s,r,a,n,o);for(let e=0;e=1?40:-Math.log(1/n.w-1),o)for(let t=0;t<45;++t)i[`f_rest_${t}`][e]=o[t];return new u2([{name:"vertex",count:this.numSplats,properties:e.map(e=>({name:e,type:"float",byteSize:4,storage:i[e]}))}],this.comments)}}class xg extends uj{destroy(){super.destroy();}configureMaterialDefines(e){e.set("SH_BANDS",3*!!this.streams.textures.has("shTexture0"));}evalChunkTextureSize(e){let t=Math.ceil(Math.sqrt(e)),i=Math.ceil(e/t);return new ef(5*t,i)}constructor(e,t){super(e,t);let{chunkData:i,chunkSize:s,numChunks:r,numSplats:a,vertexData:n,shBands:o}=t;this.chunks=new Float32Array(6*r),t.getChunks(this.chunks);let l=[{name:"packedTexture",format:49}];o>0&&(l.push({name:"shTexture0",format:49}),l.push({name:"shTexture1",format:49}),l.push({name:"shTexture2",format:49})),this._format=new cG(e,l,{readGLSL:'#include "gsplatCompressedVS"',readWGSL:'#include "gsplatCompressedVS"'}),this.streams.init(this.format,a);let h=this.streams.getTexture("packedTexture");if(h.lock().set(n),h.unlock(),o>0){let e=this.streams.getTexture("shTexture0"),i=this.streams.getTexture("shTexture1"),s=this.streams.getTexture("shTexture2");e.lock().set(new Uint32Array(t.shData0.buffer)),e.unlock(),i.lock().set(new Uint32Array(t.shData1.buffer)),i.unlock(),s.lock().set(new Uint32Array(t.shData2.buffer)),s.unlock();}let c=this.evalChunkTextureSize(r),d=this.streams.createTexture("chunkTexture",14,c);this.streams.textures.set("chunkTexture",d);let u=d.lock();for(let e=0;e=i)this.head>0?(this.data.copyWithin(0,this.head,this.tail),this.data.set(e,t),this.head=0,this.tail=i):(this.data.set(e,this.tail),this.tail+=e.length);else {let s=new Uint8Array(i);this.head>0||this.tail0&&(this.data.copyWithin(0,this.head,this.tail),this.tail-=this.head,this.head=0);}get remaining(){return this.tail-this.head}getInt8(){let e=this.view.getInt8(this.head);return this.head++,e}getUint8(){let e=this.view.getUint8(this.head);return this.head++,e}getInt16(){let e=this.view.getInt16(this.head,true);return this.head+=2,e}getUint16(){let e=this.view.getUint16(this.head,true);return this.head+=2,e}getInt32(){let e=this.view.getInt32(this.head,true);return this.head+=4,e}getUint32(){let e=this.view.getUint32(this.head,true);return this.head+=4,e}getFloat32(){let e=this.view.getFloat32(this.head,true);return this.head+=4,e}getFloat64(){let e=this.view.getFloat64(this.head,true);return this.head+=8,e}constructor(e,t){this.head=0,this.tail=0,this.reader=e,this.progressFunc=t;}}let xT=async(e,t,i)=>{let s,r,a=new x_;a.comments=i;let n=t[0].count,o=t[0].properties.length,l=t[1].count,h=(s=Math.ceil(Math.sqrt(l)),r=Math.ceil(l/s),s*r);a.numSplats=l,a.chunkData=new Float32Array(n*o),a.vertexData=new Uint32Array(4*h);let c=async(t,i)=>{let s=new Uint8Array(t),r=0;for(;r{let s,r=t[0],a=r.properties,n=a.length,o=a.map(e=>e.storage),l=a.reduce((e,t)=>e+t.byteSize,0),h=0,c=()=>{let t=e.data.buffer;s?.buffer!==t&&(s=new Float32Array(t,0,t.byteLength/4));};for(c();h{for(let i=0;ie+t.byteSize,0),a=s.properties.map(e=>{if(!e.storage)return t=>{t.head+=e.byteSize;};switch(e.type){case "char":return (t,i)=>{e.storage[i]=t.getInt8();};case "uchar":return (t,i)=>{e.storage[i]=t.getUint8();};case "short":return (t,i)=>{e.storage[i]=t.getInt16();};case "ushort":return (t,i)=>{e.storage[i]=t.getUint16();};case "int":return (t,i)=>{e.storage[i]=t.getInt32();};case "uint":return (t,i)=>{e.storage[i]=t.getUint32();};case "float":return (t,i)=>{e.storage[i]=t.getFloat32();};case "double":return (t,i)=>{e.storage[i]=t.getFloat64();};default:throw Error(`Unsupported property data type '${e.type}' in ply header`)}}),n=0;for(;n{let s,r=(e,t)=>{let i,s,r=e.length-t.length;for(i=0;i<=r;++i){for(s=0;s{if(e.length=xv.length&&!a(n.data,xv))throw Error("Invalid ply header");if(-1!==(s=r(n.data,xS)))break}let{elements:o,format:l,comments:h}=(e=>{let t,i=[],s=[];for(let r=1;r{let e,i,s,r;return (e=["min_x","min_y","min_z","max_x","max_y","max_z","min_scale_x","min_scale_y","min_scale_z","max_scale_x","max_scale_y","max_scale_z","min_r","min_g","min_b","max_r","max_g","max_b"],i=["packed_position","packed_rotation","packed_scale","packed_color"],s=Array(45).fill("").map((e,t)=>`f_rest_${t}`),r=()=>"chunk"===o[0].name&&o[0].properties.every((t,i)=>t.name===e[i]&&"float"===t.type)&&"vertex"===o[1].name&&o[1].properties.every((e,t)=>e.name===i[t]&&"uint"===e.type),2===o.length&&r()||3===o.length&&r()&&"sh"===o[2].name&&-1!==[9,24,45].indexOf(o[2].properties.length)&&o[2].properties.every((e,t)=>e.name===s[t]&&"uchar"===e.type))?await xT(n,o,h):(o.forEach(e=>{e.properties.forEach(i=>{let s=xy.get(i.type);if(s){let r=!t||t(i.name)?new s(e.count):null;i.storage=r;}});}),1===o.length&&"vertex"===o[0].name&&o[0].properties.every(e=>"float"===e.type)?await xE(n,o,h):await xw(n,o,h))};return await c()},xC=e=>true;class xA{async load(e,t,i){try{let s=await (i.file?.contents??fetch(e.load));if(s&&s.body){let e=parseInt(s.headers.get("content-length")??"0",10),r=0,a=await xb(s.body.getReader(),i.data.elementFilter??xC,t=>{r+=t,i&&i.fire("progress",r,e);});i.fire("load:data",a),!a.isCompressed&&(i.data.reorder??!0)&&a.reorderData();let n=a.isCompressed&&!i.data.decompress?new xg(this.app.graphicsDevice,a):new fx(this.app.graphicsDevice,a.isCompressed?a.decompress():a);t(null,n);}else t("Error loading resource",null);}catch(e){t(e,null);}}open(e,t){return t}constructor(e,t){this.app=e,this.maxRetries=t;}}class xP{_shouldAbort(e,t){return !(!t&&this.app.assets.get(e.id)&&this.app?.graphicsDevice&&!this.app.graphicsDevice._destroyed)}async loadTextures(e,t,i,s){var r;let a,n,o;2!==s.version&&(a={version:1,count:(r=s).means.shape[0],means:{mins:r.means.mins,maxs:r.means.maxs,files:r.means.files},scales:{mins:r.scales.mins,maxs:r.scales.maxs,files:r.scales.files},quats:{files:r.quats.files},sh0:{mins:r.sh0.mins,maxs:r.sh0.maxs,files:r.sh0.files}},r.shN&&(a.shN={mins:r.shN.mins,maxs:r.shN.maxs,files:r.shN.files}),s=a);let{assets:l}=this.app,h=["means","quats","scales","sh0","shN"],c={},d=[];h.forEach(t=>{let r=s[t]?.files??[];c[t]=r.map(t=>{let s=new fX(t,"texture",{url:i.options?.mapUrl?.(t)??new URL(t,new URL(e.load,window.location.href).toString()).toString(),filename:t},{mipmaps:false},{crossOrigin:"anonymous"}),r=new Promise((e,t)=>{s.on("load",()=>e(null)),s.on("error",e=>t(e));});return l.add(s),d.push(r),s});});let u=h.map(e=>c[e]).flat(),f=false;if(i.once("unload",()=>{f=true,u.forEach(e=>{l.remove(e),e.unload();});}),n=new Map,o=u.length,u.forEach(e=>{let t=(t,s)=>{let r,a,l;n.set(e,{loaded:t,total:s}),r=0,a=0,n.forEach(e=>{r+=e.loaded,a+=e.total;}),(l=n.size)>0&&l{e.off("progress",t),e.off("load",s),e.off("error",s);};e.on("progress",t),e.on("load",s),e.on("error",s);}),u.forEach(e=>l.load(e)),await Promise.allSettled(d),this._shouldAbort(i,f)){u.forEach(e=>{l.remove(e),e.unload();}),t(null,null);return}let p=new fp;p.url=e.original,p.meta=s,p.numSplats=s.count,p.means_l=c.means[0].resource,p.means_u=c.means[1].resource,p.quats=c.quats[0].resource,p.scales=c.scales[0].resource,p.sh0=c.sh0[0].resource,p.sh_centroids=c.shN?.[0]?.resource,p.sh_labels=c.shN?.[1]?.resource,p.shBands=fp.calcBands(p.sh_centroids?.width);let m=i.data?.decompress;if(p.minimalMemory=i.options?.minimalMemory??false,!m){if(this._shouldAbort(i,f)){p.destroy(),t(null,null);return}await p.prepareGpuData();}if(this._shouldAbort(i,f)){p.destroy(),t(null,null);return}let _=m?new fx(this.app.graphicsDevice,await p.decompress()):new fT(this.app.graphicsDevice,p);if(this._shouldAbort(i,f)){_.destroy(),t(null,null);return}t(null,_);}load(e,t,i){if(i.data?.means)this.loadTextures(e,t,i,i.data);else {"string"==typeof e&&(e={load:e,original:e});let s={retry:this.maxRetries>0,maxRetries:this.maxRetries,responseType:aJ.ResponseType.JSON};a0.get(e.load,s,(s,r)=>{this._shouldAbort(i,false)?t(null,null):s?t(`Error loading gsplat meta: ${e.original} [${s}]`):this.loadTextures(e,t,i,r);});}}constructor(e,t){this.app=e,this.maxRetries=t;}}let xI=async e=>{let t=new DecompressionStream("deflate-raw"),i=new Blob([e]).stream().pipeThrough(t);return new Uint8Array(await new Response(i).arrayBuffer())},xD=async(e,t)=>{let i=await (t.file?.contents??fetch(e.load));if(!i)throw Error("Error loading resource");if(i instanceof Response){if(!i.ok)throw Error(`Error loading resource: ${i.status} ${i.statusText}`);let e=parseInt(i.headers.get("content-length")??"0",10);if(!i.body||!i.body.getReader){let s=await i.arrayBuffer();return t.fire("progress",s.byteLength,e),s}let s=i.body.getReader(),r=[],a=0;try{for(;;){let{done:i,value:n}=await s.read();if(i)break;r.push(n),a+=n.byteLength,t.fire("progress",a,e);}}finally{s.releaseLock();}return new Blob(r).arrayBuffer()}return i};class xR{async load(e,t,i){try{let s,r=await xD(e,i),a=(e=>{var t;let i,s,r,a,n=new DataView(e),o=t=>{let i,s,r,a,o,l,h,c=(i=t+28,n.getUint16(i,!0)),d=(s=t+30,n.getUint16(s,!0)),u=(r=t+32,n.getUint16(r,!0));return {magic:n.getUint32(t,!0),compressionMethod:(a=t+10,n.getUint16(a,!0)),compressedSizeBytes:(o=t+20,n.getUint32(o,!0)),uncompressedSizeBytes:(l=t+24,n.getUint32(l,!0)),lfhOffsetBytes:(h=t+42,n.getUint32(h,!0)),filename:new TextDecoder().decode(new Uint8Array(e,t+46,c)),recordSizeBytes:46+c+d+u}},l=e=>{let t,i,s=(t=e+26,n.getUint16(t,!0)),r=(i=e+28,n.getUint16(i,!0));return {magic:n.getUint32(e,!0),offsetBytes:e+30+s+r}},h={magic:(i=t=n.byteLength-22,n.getUint32(i,!0)),numFiles:(s=t+8,n.getUint16(s,!0)),cdSizeBytes:(r=t+12,n.getUint32(r,!0)),cdOffsetBytes:(a=t+16,n.getUint32(a,!0))};if(0x6054b50!==h.magic)throw Error("Invalid zip file: EOCDR not found");if(0xffffffff===h.cdOffsetBytes||0xffffffff===h.cdSizeBytes)throw Error("Invalid zip file: Zip64 not supported");let c=[],d=h.cdOffsetBytes;for(let t=0;t"meta.json"===e.filename);if(!n)return void t("Error: meta.json not found");try{s=JSON.parse(new TextDecoder().decode(n.data));}catch(e){t(`Error parsing meta.json: ${e}`);return}let o=["means","scales","quats","sh0","shN"].map(e=>s[e]?.files??[]).flat(),l={},h=[];for(let t of o){let i,s=a.find(e=>e.filename===t);if(s)i=new fX(t,"texture",{url:`${e.load}/${t}`,filename:t,contents:s.data},{mipmaps:!1},{crossOrigin:"anonymous"});else {let e=new URL(t,new URL(t,window.location.href).toString()).toString();i=new fX(t,"texture",{url:e,filename:t},{mipmaps:!1},{crossOrigin:"anonymous"});}let r=new Promise((e,t)=>{i.on("load",()=>e(null)),i.on("error",e=>t(e));});this.app.assets.add(i),l[t]=i,h.push(r);}Object.values(l).forEach(e=>this.app.assets.load(e)),await Promise.allSettled(h);let{assets:c}=this.app;i.once("unload",()=>{Object.values(l).forEach(e=>{c.remove(e),e.unload();});});let d=i.data?.decompress,u=i.options?.minimalMemory??!1,f=new fp;f.url=e.original,f.minimalMemory=u,f.meta=s,f.numSplats=s.count,f.means_l=l[s.means.files[0]].resource,f.means_u=l[s.means.files[1]].resource,f.quats=l[s.quats.files[0]].resource,f.scales=l[s.scales.files[0]].resource,f.sh0=l[s.sh0.files[0]].resource,f.sh_centroids=l[s.shN?.files[0]]?.resource,f.sh_labels=l[s.shN?.files[1]]?.resource,f.shBands=fp.calcBands(f.sh_centroids?.width),d||await f.prepareGpuData();let p=d?new fx(this.app.graphicsDevice,await f.decompress()):new fT(this.app.graphicsDevice,f);t(null,p);}catch(e){t(e);}}constructor(e,t=3){this.app=e,this.maxRetries=t;}}class xL{load(e){}unload(e){}getResource(e){}destroy(){}}class xM extends xL{destroy(){for(let e of(this._destroyed=true,this._urlToAsset.values()))e.fire("unload",e),e.off("load"),e.off("error"),this._registry.remove(e),e.unload();this._urlToAsset.clear(),this._loadQueue.length=0,this._currentlyLoading.clear(),this._retryCount.clear();}_canLoad(){return !!this._registry.loader?.getHandler("gsplat")}load(e){let t=this._urlToAsset.get(e);t?.loaded||this._currentlyLoading.has(e)||this._loadQueue.includes(e)||(this._currentlyLoading.sizethis._onAssetLoadSuccess(e,t)),t.once("error",i=>this._onAssetLoadError(e,t,i)),t.loaded||t.loading||this._registry.load(t);}_onAssetLoadSuccess(e,t){!this._destroyed&&this._urlToAsset.has(e)&&(this._currentlyLoading.delete(e),this._retryCount.delete(e),this._processQueue());}_onAssetLoadError(e,t,i){if(this._destroyed||!this._canLoad()||!this._urlToAsset.has(e))return;let s=this._retryCount.get(e)||0;s0;){let e=this._loadQueue.shift();e&&this._startLoading(e);}}unload(e){this._currentlyLoading.delete(e);let t=this._loadQueue.indexOf(e);-1!==t&&this._loadQueue.splice(t,1),this._retryCount.delete(e);let i=this._urlToAsset.get(e);i&&(i.fire("unload",i),i.off("load"),i.off("error"),this._registry.remove(i),i.unload(),this._urlToAsset.delete(e)),this._processQueue();}getResource(e){let t=this._urlToAsset.get(e);return t?.resource}constructor(e){super(),this._urlToAsset=new Map,this.maxConcurrentLoads=2,this.maxRetries=2,this._currentlyLoading=new Set,this._loadQueue=[],this._retryCount=new Map,this._destroyed=false,this._registry=e;}}class xO{load(e,t,i){"string"==typeof e&&(e={load:e,original:e});let s={retry:this.maxRetries>0,maxRetries:this.maxRetries,responseType:aJ.ResponseType.JSON};a0.get(e.load,s,(s,r)=>{if(s)t(`Error loading gsplat octree: ${e.original} [${s}]`);else {let e=new xM(this.app.assets);t(null,new SL(i.file.url,r,e));}});}constructor(e,t){this.app=e,this.maxRetries=t;}}class xF extends fQ{_getUrlWithoutParams(e){return e.indexOf("?")>=0?e.split("?")[0]:e}_getParser(e){let t=P.getBasename(this._getUrlWithoutParams(e)).toLowerCase();if("lod-meta.json"===t)return this.parsers.octree;let i=P.getExtension(t).replace(".","");return this.parsers[i]||this.parsers.ply}load(e,t,i){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,i);}open(e,t,i){return t}constructor(e){super(e,"gsplat"),this.parsers={ply:new xA(e,3),sog:new xR(e),json:new xP(e,3),octree:new xO(e,3)};}}class xN{static setCompressedPRS(e,t,i){let s,r,a=i.singleVecs,n=t.___1;n||(s=i.tripleVecs,r=t.___2);let o=n?n[0]:s[r];e.setLocalPosition(a[o],a[o+1],a[o+2]),o=n?n[1]:s[r+1],e.setLocalEulerAngles(a[o],a[o+1],a[o+2]),o=n?n[2]:s[r+2],e.setLocalScale(a[o],a[o+1],a[o+2]);}static oneCharToKey(e,t){let i=e.charCodeAt(0)-t.fieldFirstCode;return t.fieldArray[i]}static multCharToKey(e,t){let i=0;for(let s=0;s0,maxRetries:t},(t,s)=>{if(t){let s=`Error while loading scene JSON ${e.original}`;t.message?(s+=`: ${t.message}`,t.stack&&(s+=` -${t.stack}`)):s+=`: ${t}`,i(s);}else i(t,s);});}}class xz extends fQ{load(e,t){xU.load(e,this.maxRetries,t);}open(e,t){this._app.systems.script.preloading=true;let i=new xk(this._app,false).parse(t);return this._app.systems.script.preloading=false,i}constructor(e){super(e,"hierarchy");}}class xV extends fQ{load(e,t){"string"==typeof e&&(e={load:e,original:e}),a0.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,s)=>{i?t(`Error loading html resource: ${e.original} [${i}]`):t(null,s);});}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}constructor(e){super(e,"html"),this.decoder=null;}}class xG extends fQ{load(e,t){"string"==typeof e&&(e={load:e,original:e});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=aJ.ResponseType.JSON),a0.get(e.load,i,(i,s)=>{i?t(`Error loading JSON resource: ${e.original} [${i}]`):t(null,s);});}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),JSON.parse(this.decoder.decode(e))}constructor(e){super(e,"json"),this.decoder=null;}}class xH{setInvalid(e,t){this.valid=false,this.removeInvalid&&delete t[e];}validate(e){let t="path"===e.mappingFormat;for(let i in e){let s=us[i];if(!s){un[i]?delete e[i]:this.valid=false;continue}if(s.startsWith("enum")){let t=s.split(":")[1];this.enumValidators[t]&&!this.enumValidators[t](e[i])&&this.setInvalid(i,e);}else if("number"===s)"number"!=typeof e[i]&&this.setInvalid(i,e);else if("boolean"===s)"boolean"!=typeof e[i]&&this.setInvalid(i,e);else if("string"===s)"string"!=typeof e[i]&&this.setInvalid(i,e);else if("vec2"===s)e[i]instanceof Array&&2===e[i].length||this.setInvalid(i,e);else if("rgb"===s)e[i]instanceof Array&&3===e[i].length||this.setInvalid(i,e);else if("texture"===s)t?"string"==typeof e[i]||null===e[i]||e[i]instanceof ic||this.setInvalid(i,e):"number"==typeof e[i]||null===e[i]||e[i]instanceof ic||this.setInvalid(i,e);else if("boundingbox"===s)e[i].center&&e[i].center instanceof Array&&3===e[i].center.length||this.setInvalid(i,e),e[i].halfExtents&&e[i].halfExtents instanceof Array&&3===e[i].halfExtents.length||this.setInvalid(i,e);else if("cubemap"===s)"number"==typeof e[i]||null===e[i]||void 0===e[i]||e[i]instanceof ic&&e[i].cubemap||this.setInvalid(i,e);else if("chunks"===s){let t=Object.keys(e[i]);for(let s=0;s=0}}constructor(){this.removeInvalid=true,this.valid=true,this.enumValidators={occludeSpecular:this._createEnumValidator([0,1,2]),cull:this._createEnumValidator([0,1,2,3]),blendType:this._createEnumValidator([0,1,2,3,4,5,6,7,8,9,10]),depthFunc:this._createEnumValidator([0,1,2,3,4,5,6,7])};}}class xW{parse(e){let t=this.migrate(e),i=this._validate(t),s=new ud;return this.initialize(s,i),s}initialize(e,t){if(t.validated||(t=this._validate(t)),t.chunks&&t.chunks&&Object.keys(t.chunks).length>0){let i=e.shaderChunks.glsl;Object.entries(t.chunks).forEach(([e,t])=>i.set(e,t));}for(let i in t){let s=us[i],r=t[i];if("vec2"===s)e[i]=new ef(r[0],r[1]);else if("rgb"===s)e[i]=new es(r[0],r[1],r[2]);else if("texture"===s)r instanceof ic?e[i]=r:e[i]instanceof ic&&"number"==typeof r&&r>0||(e[i]=null);else if("cubemap"===s)r instanceof ic?e[i]=r:e[i]instanceof ic&&"number"==typeof r&&r>0||(e[i]=null),"cubeMap"!==i||r||(e.prefilteredCubemaps=null);else if("boundingbox"===s){let t=new ed(r.center[0],r.center[1],r.center[2]),s=new ed(r.halfExtents[0],r.halfExtents[1],r.halfExtents[2]);e[i]=new eA(t,s);}else e[i]=t[i];}e.update();}migrate(e){let t;e.shader&&delete e.shader,e.mapping_format&&(e.mappingFormat=e.mapping_format,delete e.mapping_format);let i=[["bumpMapFactor","bumpiness"],["aoUvSet","aoMapUv"],["aoMapVertexColor","aoVertexColor"],["diffuseMapVertexColor","diffuseVertexColor"],["emissiveMapVertexColor","emissiveVertexColor"],["specularMapVertexColor","specularVertexColor"],["metalnessMapVertexColor","metalnessVertexColor"],["opacityMapVertexColor","opacityVertexColor"],["glossMapVertexColor","glossVertexColor"],["lightMapVertexColor","lightVertexColor"],["specularMapTint","specularTint"],["metalnessMapTint","metalnessTint"],["clearCoatGlossiness","clearCoatGloss"]];for(t=0;t0,maxRetries:this.maxRetries},(i,s)=>{i?t&&t(`Error loading material: ${e.original} [${i}]`):t&&(s._engine=true,t(null,s));});}open(e,t){let i=this._parser.parse(t);return t._engine&&(i._data=t,delete t._engine),i}patch(e,t){e.resource._data&&(e._data=e.resource._data,delete e.resource._data),e.data.name=e.name,e.resource.name=e.name,this._bindAndAssignAssets(e,t),e.off("unload",this._onAssetUnload,this),e.on("unload",this._onAssetUnload,this);}_onAssetUnload(e){delete e.data.parameters,delete e.data.chunks,delete e.data.name;}_assignTexture(e,t,i){t.resource[e]=i;}_getPlaceholderTexture(e){let t=xX[e];return im(this._device,t)}_assignPlaceholderTexture(e,t){t.resource[e]=this._getPlaceholderTexture(e);}_onTextureLoad(e,t,i){this._assignTexture(e,t,i.resource),t.resource.update();}_onTextureAdd(e,t,i){this._assets.load(i);}_onTextureRemoveOrUnload(e,t,i){let s=t.resource;s&&t.resource[e]===i.resource&&(this._assignPlaceholderTexture(e,t),s.update());}_assignCubemap(e,t,i){if(t.resource[e]=i[0],"cubeMap"===e){let e=i.slice(1);e.every(e=>e)?t.resource.prefilteredCubemaps=e:e[0]&&(t.resource.envAtlas=e[0]);}}_onCubemapLoad(e,t,i){this._assignCubemap(e,t,i.resources),this._parser.initialize(t.resource,t.data);}_onCubemapAdd(e,t,i){this._assets.load(i);}_onCubemapRemoveOrUnload(e,t,i){let s=t.resource;t.data.prefilteredCubeMap128===i.resources[1]&&(this._assignCubemap(e,t,[null,null,null,null,null,null,null]),s.update());}_bindAndAssignAssets(e,t){let i,s,r,a=this._parser.migrate(e.data),n=e.resource,o="path"===a.mappingFormat;for(i=0;i{if(e)t(e);else {let e=xn.createModel(i,this._defaultMaterial);i.destroy(),t(null,e);}});}constructor(e){this._device=e.device,this._defaultMaterial=e.defaultMaterial,this._assets=e.assets;}}let xj={points:0,lines:1,lineloop:2,linestrip:3,triangles:4,trianglestrip:5,trianglefan:6},xK={int8:0,uint8:1,int16:2,uint16:3,int32:4,uint32:5,float32:6};class x${parse(e,t){let i=e.model;if(!i)return void t(null,null);if(i.version<=1)return void t("JsonModelParser#parse: Trying to parse unsupported model format.");let s=this._parseNodes(e),r=this._parseSkins(e,s),a=this._parseVertexBuffers(e),n=this._parseIndexBuffers(e,a),o=this._parseMorphs(e,s,a),l=this._parseMeshes(e,r.skins,o.morphs,a,n.buffer,n.data),h=this._parseMeshInstances(e,s,l,r.skins,r.instances,o.morphs,o.instances),c=new hF;c.graph=s[0],c.meshInstances=h,c.skinInstances=r.instances,c.morphInstances=o.instances,c.getGraph().syncHierarchy(),t(null,c);}_parseNodes(e){let t,i=e.model,s=[];for(t=0;t0&&(a=o>65535?new Uint32Array((r=new iw(this._device,2,n)).lock()):new Uint16Array((r=new iw(this._device,1,n)).lock())),{buffer:r,data:a}}_parseMeshes(e,t,i,s,r,a){let n=e.model,o=[],l=0;for(let e=0;e0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(".glb"===P.getExtension(e.original).toLowerCase()?s.responseType=aJ.ResponseType.ARRAY_BUFFER:s.responseType=aJ.ResponseType.JSON),a0.get(e.load,s,(s,r)=>{if(t)if(s)t(`Error loading model: ${e.original} [${s}]`);else {for(let s=0;s{e?t(e):t(null,i);},i)}t("No parsers found");}});}open(e,t){return t}patch(e,t){if(!e.resource)return;let i=e.data,s=this;e.resource.meshInstances.forEach((r,a)=>{if(i.mapping){let n,o=function(e){e.resource?r.material=e.resource:(e.once("load",o),t.load(e)),e.once("remove",e=>{r.material===e.resource&&(r.material=s.defaultMaterial);});};if(!i.mapping[a]){r.material=s.defaultMaterial;return}let l=i.mapping[a].material,h=i.mapping[a].path;if(void 0!==l)l?(n=t.get(l))?o(n):t.once(`add:${l}`,o):r.material=s.defaultMaterial;else if(h){let s=e.getAbsoluteUrl(i.mapping[a].path);(n=t.getByUrl(s))?o(n):t.once(`add:url:${s}`,o);}}});}addParser(e,t){this._parsers.push({parser:e,decider:t});}constructor(e){super(e,"model"),this._parsers=[],this.device=e.graphicsDevice,this.assets=e.assets,this.defaultMaterial=ol(this.device),this.addParser(new x$(this),(e,t)=>".json"===P.getExtension(e)),this.addParser(new xq(this),(e,t)=>".glb"===P.getExtension(e));}}class xQ extends fQ{load(e,t){xU.load(e,this.maxRetries,t);}open(e,t){this._app.systems.script.preloading=true;let i=new xk(this._app,false).parse(t),s=this._app.scene;return s.root=i,this._app.applySceneSettings(t.settings),this._app.systems.script.preloading=false,s}constructor(e){super(e,"scene");}}class xJ{static push(e){xJ._types.push(e);}}xJ._types=[];let x0=new Set(["system","entity","create","destroy","swap","move","data","scripts","_scripts","_scriptsIndex","_scriptsData","enabled","_oldState","onEnable","onDisable","onPostStateChange","_onSetEnabled","_checkState","_onBeforeRemove","_onInitializeAttributes","_onInitialize","_onPostInitialize","_onUpdate","_onPostUpdate","_callbacks","_callbackActive","has","get","on","off","fire","once","hasEvent","worker"]);function x1(e,t){if(x0.has(e))throw Error(`Script name '${e}' is reserved, please rename the script`);let i=function(e){X.prototype.initEventHandler.call(this),vU.prototype.initScriptType.call(this,e);};return i.prototype=Object.create(vU.prototype),i.prototype.constructor=i,i.extend=vU.extend,i.attributes=new vM(i),x3(i,e,t),i}let x2={};function x3(e,t,i){if("function"!=typeof e)throw Error(`script class: '${e}' must be a constructor function (i.e. class).`);if(!(e.prototype instanceof vN))throw Error(`script class: '${vU.__getScriptName(e)}' does not extend pc.Script.`);if(t=t||e.__name||vU.__getScriptName(e),x0.has(t))throw Error(`script name: '${t}' is reserved, please change script name`);e.__name=t,(i?i.scripts:pa.getApplication().scripts).add(e),xJ.push(e);}vM.reservedNames.forEach((e,t,i)=>{x2[e]=1;}),x1.reservedAttributes=x2;let x4=e=>e[0].toLowerCase()+e.substring(1);class x5 extends fQ{clearCache(){for(let e in this._cache){let t=this._cache[e],i=t.parentNode;i&&i.removeChild(t);}this._cache={};}load(e,t){"string"==typeof e&&(e={load:e,original:e});let i=this;fP.app=this._app;let s=(e.load,(e,s,r)=>{if(e)t(e);else {let e={};for(let t=0;t{t(`Script: ${e.target.src} failed to load`);},false);let r=false;s.onload=s.onreadystatechange=function(){r||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState||(r=true,t(null,e,s));},s.src=e,i.appendChild(s);}_loadModule(e,t){let i=k.browser&&"null"!==window.location.origin?window.location.origin+window.location.pathname:"u"{let r=s.pathname.split("/").pop(),a=this._app.assets.find(r,"script")?.data?.scripts;for(let e in i){let t=i[e];if(t.prototype instanceof vN){let e=x4(t.name);t.scriptName;let i=t.scriptName??e;x3(t,i),a&&this._app.scripts.addSchema(i,a[i]);}}t(null,e,null);}).catch(e=>{t(e);});}constructor(e){super(e,"script"),this._scripts={},this._cache={};}}class x6 extends fQ{load(e,t){"string"==typeof e&&(e={load:e,original:e}),a0.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,s)=>{i?t(`Error loading shader resource: ${e.original} [${i}]`):t(null,s);});}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}constructor(e){super(e,"shader"),this.decoder=null;}}function x8(e){this.resource&&(this.resource.atlas=e.resource);}function x9(e){this.registry.load(e);}class x7 extends fQ{load(e,t){"string"==typeof e&&(e={load:e,original:e}),".json"===P.getExtension(e.original)&&a0.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(e,i)=>{e?t(e):t(null,i);});}open(e,t){let i=new dP(this._device);return e&&(i.__data=t),i}patch(e,t){let i=e.resource;if(i.__data&&(e.data.pixelsPerUnit=i.__data.pixelsPerUnit,e.data.renderMode=i.__data.renderMode,e.data.frameKeys=i.__data.frameKeys,i.__data.textureAtlasAsset)){let s=t.getByUrl(i.__data.textureAtlasAsset);s&&(e.data.textureAtlasAsset=s.id);}i.startUpdate(),i.renderMode=e.data.renderMode,i.pixelsPerUnit=e.data.pixelsPerUnit,i.frameKeys=e.data.frameKeys,this._updateAtlas(e),i.endUpdate(),e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this);}_updateAtlas(e){let t=e.resource;if(!e.data.textureAtlasAsset){t.atlas=null;return}this._assets.off(`load:${e.data.textureAtlasAsset}`,x8,e),this._assets.on(`load:${e.data.textureAtlasAsset}`,x8,e);let i=this._assets.get(e.data.textureAtlasAsset);i&&i.resource?t.atlas=i.resource:i?this._assets.load(i):(this._assets.off(`add:${e.data.textureAtlasAsset}`,x9,e),this._assets.on(`add:${e.data.textureAtlasAsset}`,x9,e));}_onAssetChange(e,t,i,s){"data"===t&&i&&i.textureAtlasAsset&&s&&i.textureAtlasAsset!==s.textureAtlasAsset&&(this._assets.off(`load:${s.textureAtlasAsset}`,x8,e),this._assets.off(`add:${s.textureAtlasAsset}`,x9,e));}constructor(e){super(e,"sprite"),this._assets=e.assets,this._device=e.graphicsDevice;}}class Te{instantiate(){return this._templateRoot||this._parseTemplate(),this._templateRoot.clone()}_parseTemplate(){let e=new xk(this._app,true);this._templateRoot=e.parse(this._data);}set data(e){this._data=e,this._templateRoot=null;}get data(){return this._data}constructor(e,t){this._templateRoot=null,this._app=e,this._data=t;}}class Tt extends fQ{load(e,t){"string"==typeof e&&(e={load:e,original:e});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};a0.get(e.load,i,(i,s)=>{i?t(`Error requesting template: ${e.original}`):t(i,s);});}open(e,t){return new Te(this._app,t)}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),new Te(this._app,JSON.parse(this.decoder.decode(e)))}patch(e,t){e&&e.resource&&e.data&&e.data.entities&&(e.resource.data=e.data);}constructor(e){super(e,"template"),this.decoder=null;}}class Ti extends fQ{load(e,t){"string"==typeof e&&(e={load:e,original:e}),a0.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,s)=>{i?t(`Error loading text resource: ${e.original} [${i}]`):t(null,s);});}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}constructor(e){super(e,"text"),this.decoder=null;}}let Ts={repeat:0,clamp:1,mirror:2},Tr={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},Ta=/^data\.frames\.(\d+)$/;class Tn extends fQ{load(e,t){"string"==typeof e&&(e={load:e,original:e});let i=this,s=this._loader.getHandler("texture");".json"===P.getExtension(e.original)?a0.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(s,r)=>{if(s)t(s);else {let s=e.original.replace(".json",".png");i._loader.load(s,"texture",(e,i)=>{e?t(e):t(null,{data:r,texture:i});});}}):s.load(e,t);}open(e,t,i){let s=new dI;if(t.texture&&t.data)s.texture=t.texture,s.__data=t.data;else {let r=this._loader.getHandler("texture").open(e,t,i);if(!r)return null;s.texture=r;}return s}patch(e,t){if(!e.resource)return;e.resource.__data&&(void 0!==e.resource.__data.minfilter&&(e.data.minfilter=e.resource.__data.minfilter),void 0!==e.resource.__data.magfilter&&(e.data.magfilter=e.resource.__data.magfilter),void 0!==e.resource.__data.addressu&&(e.data.addressu=e.resource.__data.addressu),void 0!==e.resource.__data.addressv&&(e.data.addressv=e.resource.__data.addressv),void 0!==e.resource.__data.mipmaps&&(e.data.mipmaps=e.resource.__data.mipmaps),void 0!==e.resource.__data.anisotropy&&(e.data.anisotropy=e.resource.__data.anisotropy),void 0!==e.resource.__data.rgbm&&(e.data.rgbm=!!e.resource.__data.rgbm),e.data.frames=e.resource.__data.frames,delete e.resource.__data);let i=e.resource.texture;if(i&&(i.name=e.name,e.data.hasOwnProperty("minfilter")&&i.minFilter!==Tr[e.data.minfilter]&&(i.minFilter=Tr[e.data.minfilter]),e.data.hasOwnProperty("magfilter")&&i.magFilter!==Tr[e.data.magfilter]&&(i.magFilter=Tr[e.data.magfilter]),e.data.hasOwnProperty("addressu")&&i.addressU!==Ts[e.data.addressu]&&(i.addressU=Ts[e.data.addressu]),e.data.hasOwnProperty("addressv")&&i.addressV!==Ts[e.data.addressv]&&(i.addressV=Ts[e.data.addressv]),e.data.hasOwnProperty("mipmaps")&&i.mipmaps!==e.data.mipmaps&&(i.mipmaps=e.data.mipmaps),e.data.hasOwnProperty("anisotropy")&&i.anisotropy!==e.data.anisotropy&&(i.anisotropy=e.data.anisotropy),e.data.hasOwnProperty("rgbm"))){let t=e.data.rgbm?tI:tP;i.type!==t&&(i.type=t);}e.resource.texture=i;let s={};for(let t in e.data.frames){let i=e.data.frames[t];s[t]={rect:new ep(i.rect),pivot:new ef(i.pivot),border:new ep(i.border)};}e.resource.frames=s,e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this);}_onAssetChange(e,t,i){let s;if("data"===t||"data.frames"===t){let t={};for(let e in i.frames)s=i.frames[e],t[e]={rect:new ep(s.rect),pivot:new ef(s.pivot),border:new ep(s.border)};e.resource.frames=t;}else {let r=t.match(Ta);if(r){let t=r[1];i?(e.resource.frames[t]?((s=e.resource.frames[t]).rect.set(i.rect[0],i.rect[1],i.rect[2],i.rect[3]),s.pivot.set(i.pivot[0],i.pivot[1]),s.border.set(i.border[0],i.border[1],i.border[2],i.border[3])):e.resource.frames[t]={rect:new ep(i.rect),pivot:new ef(i.pivot),border:new ep(i.border)},e.resource.fire("set:frame",t,e.resource.frames[t])):e.resource.frames[t]&&(delete e.resource.frames[t],e.resource.fire("remove:frame",t));}}}constructor(e){super(e,"textureatlas"),this._loader=e.loader;}}function To(){let e,t,i,s={astc:10,dxt:2,etc1:0,etc2:0,pvr:8,atc:11,none:14},r={astc:10,dxt:3,etc1:16,etc2:1,pvr:9,atc:12,none:16},a=(e,t)=>{switch(e){case 0:return t.formats.etc2?22:21;case 1:return 23;case 2:return 8;case 3:return 10;case 8:return 26;case 9:return 27;case 10:return 28;case 11:return 29;case 12:return 30;case 13:return 7;case 14:return 3;case 16:return 5}},n=e=>{for(let t=0;t{let t=new Uint16Array(e.length/4);for(let i=0;i>3;}return t},l=()=>"u">typeof performance?performance.now():0,h=(e,s,r)=>{if(r){if(e.formats.astc)return "astc"}else if(s){if(e.formats.etc2)return "etc2"}else {if(e.formats.etc2)return "etc2";if(e.formats.etc1)return "etc1"}var a=s?i:t;for(let t=0;t{switch(i){case 0:case 1:case 10:case 11:case 12:return true;case 2:case 3:return (3&e)==0&&(3&t)==0;case 8:case 9:return (e&e-1)==0&&(t&t-1)==0}return false},d=(t,i,d)=>{try{let u=d.isKTX2?((t,i,d)=>{let u,f;if(!e.KTX2File)throw Error("Basis transcoder module does not include support for KTX2.");let p=l(),m=new e.KTX2File(new Uint8Array(i)),_=m.getWidth(),g=m.getHeight(),v=m.getLevels(),S=!!m.getHasAlpha(),y=m.isUASTC&&m.isUASTC();if(!_||!g||!v)throw m.close(),m.delete(),Error(`Invalid image dimensions url=${t} width=${_} height=${g} levels=${v}`);let x=h(d.deviceDetails,S,y),T=!!d.isGGGR&&"pvr"===x;if(T?u=13:c(_,g,u=S?r[x]:s[x])||(u=S?13:14),!m.startTranscoding())throw m.close(),m.delete(),Error(`Failed to start transcoding url=${t}`);let E=[];for(let e=0;e{let u,f,p=l(),m=new e.BasisFile(new Uint8Array(i)),_=m.getImageWidth(0,0),g=m.getImageHeight(0,0),v=m.getNumImages(),S=m.getNumLevels(0),y=!!m.getHasAlpha(),x=m.isUASTC&&m.isUASTC();if(!_||!g||!v||!S)throw m.close(),m.delete(),Error(`Invalid image dimensions url=${t} width=${_} height=${g} images=${v} levels=${S}`);let T=h(d.deviceDetails,y,x),E=!!d.isGGGR&&"pvr"===T;if(E?u=13:c(_,g,u=y?r[T]:s[T])||(u=y?13:14),!m.startTranscoding())throw m.close(),m.delete(),Error(`Failed to start transcoding url=${t}`);let w=[];for(let e=0;ee.buffer),self.postMessage({url:t,data:u},u.levels);}catch(e){self.postMessage({url:t,err:e},null);}},u=[];self.onmessage=s=>{let r=s.data;switch(r.type){case "init":var a;a=r.config,self.BASIS(a.module?{instantiateWasm:(e,t)=>(WebAssembly.instantiate(a.module,e).then(e=>{t(e);}).catch(e=>{}),{})}:null).then(s=>{s.initializeBasis(),e=s,t=a.rgbPriority,i=a.rgbaPriority,(()=>{for(let e=0;e{let t=e.data;this.queue.handleResponse(t.url,t.err,t.data),this.eager||this.queue.enqueueClient(this);}),this.worker.postMessage({type:"init",config:t}),this.eager=i;}}let Th=["etc2","etc1","astc","dxt","pvr","atc"],Tc=["astc","dxt","etc2","pvr","atc"],Td=new class{enqueueJob(e,t,i,s){if(this.callbacks.hasOwnProperty(e))this.callbacks[e].push(i);else {this.callbacks[e]=[i];let r={url:e,data:t,options:s};this.clients.length>0?this.clients.shift().run(r):this.queue.push(r);}}enqueueClient(e){this.queue.length>0?e.run(this.queue.shift()):this.clients.push(e);}handleResponse(e,t,i){let s=this.callbacks[e];if(t)for(let e=0;enew Uint16Array(e)):i.levels=i.levels.map(e=>new Uint8Array(e));for(let e=0;e{let i=(i,s)=>{t(null,{workerUrl:URL.createObjectURL(new Blob([["/* basis */",i,"",`(${To.toString()})() +`].join(` +`),i=new Blob([s],{type:"application/javascript"}),r=URL.createObjectURL(i),a=Math.max(1,Math.min(16,c.numWorkers||_G)),o=[];for(let l=0;l{c?.lazyInit?tb=c:gG(c)},UE=(c,t)=>gG()?(BE.enqueueJob(c,t),!0):!1;var sb=class{constructor(){n(this,"gltf");n(this,"nodes");n(this,"scenes");n(this,"animations");n(this,"textures");n(this,"materials");n(this,"variants");n(this,"meshVariants");n(this,"meshDefaultMaterials");n(this,"renders");n(this,"skins");n(this,"lights");n(this,"cameras");n(this,"nodeInstancingMap")}destroy(){this.renders&&this.renders.forEach(t=>{t.meshes=null})}},TG=c=>/^data:[^\n\r,\u2028\u2029]*,.*$/i.test(c),VK=c=>c.substring(c.indexOf(":")+1,c.indexOf(";")),kE=c=>{switch(c){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;default:return 3}},ob=c=>{switch(c){case 5120:return js;case 5121:return ai;case 5122:return qs;case 5123:return Ri;case 5124:return He;case 5125:return kt;case 5126:return ye;default:return 0}},HK=c=>{switch(c){case 5120:return 1;case 5121:return 1;case 5122:return 2;case 5123:return 2;case 5124:return 4;case 5125:return 4;case 5126:return 4;default:return 0}},WK=c=>{switch(c){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:return null}},ib={POSITION:ee,NORMAL:Ot,TANGENT:vs,COLOR_0:Ct,JOINTS_0:$t,WEIGHTS_0:bs,TEXCOORD_0:_t,TEXCOORD_1:ri,TEXCOORD_2:Ca,TEXCOORD_3:Pa,TEXCOORD_4:wa,TEXCOORD_5:Ia,TEXCOORD_6:Ra,TEXCOORD_7:ba},xG={[ee]:0,[Ot]:1,[vs]:2,[Ct]:3,[$t]:4,[bs]:5,[_t]:6,[ri]:7,[Ca]:8,[Pa]:9,[wa]:10,[Ia]:11,[Ra]:12,[ba]:13},XK=c=>{switch(c){case js:return t=>Math.max(t/127,-1);case ai:return t=>t/255;case qs:return t=>Math.max(t/32767,-1);case Ri:return t=>t/65535;default:return t=>t}},rb=(c,t,e)=>{let s=XK(e),i=t.length;for(let r=0;r{let s=kE(c.type),i=WK(c.componentType);if(!i)return null;let r;if(c.sparse){let a=c.sparse,o={count:a.count,type:"SCALAR"},l=Mu(Object.assign(o,a.indices),t,!0),h={count:a.count,type:c.type,componentType:c.componentType},f=Mu(Object.assign(h,a.values),t,!0);if(c.hasOwnProperty("bufferView")){let u={bufferView:c.bufferView,byteOffset:c.byteOffset,componentType:c.componentType,count:c.count,type:c.type};r=Mu(u,t,!0).slice()}else r=new i(c.count*s);for(let u=0;u{let e=Mu(c,t,!0);if(e instanceof Float32Array||!c.normalized)return e;let s=new Float32Array(e.length);return rb(s,e,ob(c.componentType)),s},ab=c=>{let t=c.min,e=c.max;if(!t||!e)return null;if(c.normalized){let s=ob(c.componentType);t=rb([],t,s),e=rb([],e,s)}return new ge(new x((e[0]+t[0])*.5,(e[1]+t[1])*.5,(e[2]+t[2])*.5),new x((e[0]-t[0])*.5,(e[1]-t[1])*.5,(e[2]-t[2])*.5))},yG=c=>{if(!c.hasOwnProperty("mode"))return Yt;switch(c.mode){case 0:return Aa;case 1:return Pn;case 2:return Eg;case 3:return mf;case 4:return Yt;case 5:return Ks;case 6:return dr;default:return Yt}},YK=c=>{let t=new Uint16Array(c);for(let e=0;e{let e=c[ee];if(!e||e.components!==3)return;let s;if(e.size!==e.stride){let o=e.stride/Wn[e.type],l=new Ro[e.type](e.buffer,e.offset,e.count*o);s=new Ro[e.type](e.count*3);for(let h=0;h{let t=s=>{let i=[];for(let r=0;r{let t=new ae(`${c.name}_clone`,c.type,c.file,c.data,c.options);return t.loaded=!0,t.resource=jK(c.resource),c.registry.add(t),t},$K=(c,t)=>{let e=t[ee];if(!e)return null;let s=e.count,i=[];for(let g in t)if(t.hasOwnProperty(g)){let T={semantic:g,components:t[g].components,type:t[g].type,normalize:!!t[g].normalize};Ft.isElementValid(c,T)||T.components++,i.push(T)}i.sort((g,T)=>xG[g.semantic]-xG[T.semantic]);let r,a,o,l,h,f,u=new Ft(c,i),d=!0;for(r=0;r{let a={},o=[];for(let f in t)t.hasOwnProperty(f)&&ib.hasOwnProperty(f)&&(a[f]=t[f],o.push(`${f}:${t[f]}`));o.sort();let l=o.join(),h=r[l];if(!h){let f={};for(let u in a){let d=s[t[u]],p=Mu(d,i),m=i[d.bufferView],_=ib[u],S=kE(d.type)*HK(d.componentType),g=m&&m.hasOwnProperty("byteStride")?m.byteStride:S;f[_]={buffer:p.buffer,size:S,offset:p.byteOffset,stride:g,count:d.count,components:kE(d.type),type:ob(d.componentType),normalize:d.normalized}}f.hasOwnProperty(Ot)||KK(f,e),h=$K(c,f),r[l]=h}return h},QK=(c,t,e,s,i,r)=>{let a,o,l,h=t.joints,f=h.length,u=[];if(t.hasOwnProperty("inverseBindMatrices")){let _=t.inverseBindMatrices,S=Mu(e[_],s,!0),g=[];for(a=0;a{let o=new _e(c);if(o.aabb=ab(e[t.attributes.POSITION]),a.push(new Promise((l,h)=>{let f=t.extensions.KHR_draco_mesh_compression;UE(s[f.bufferView].slice().buffer,(u,d)=>{if(u)h(u);else{let p={};for(let[E,y]of Object.entries(f.attributes))p[y]=ib[E];p[-1]=Ot;let m=[];for(let E of d.attributes){let y=p[E.id];if(y!==void 0){let P=!1;if(E.id!==-1){for(let[A,w]of Object.entries(f.attributes))if(w===E.id&&t.attributes[A]!==void 0){P=e[t.attributes[A]].normalized??(y===Ct&&(E.dataType===ai||E.dataType===Ri));break}}m.push({semantic:y,components:E.numComponents,type:E.dataType,normalize:P,offset:E.offset,stride:d.stride})}}let _=new Ft(c,m),S=d.vertices.byteLength/d.stride,g=S<=65535?1:2,T=d.indices.byteLength/(S<=65535?2:4),C=new ft(c,_,S,{data:d.vertices}),v=new os(c,g,T,0,d.indices);o.vertexBuffer=C,o.indexBuffer[0]=v,o.primitive[0].type=yG(t),o.primitive[0].base=0,o.primitive[0].count=v?T:S,o.primitive[0].indexed=!!v,l()}})})),t?.extensions?.KHR_materials_variants){let l=t.extensions.KHR_materials_variants,h={};l.mappings.forEach(f=>{f.variants.forEach(u=>{h[u]=f.material})}),i[o.id]=h}return r[o.id]=t.material,o},ej=(c,t,e,s,i,r,a,o,l)=>{let h=[];return t.primitives.forEach(f=>{if(f.extensions?.KHR_draco_mesh_compression)h.push(JK(c,f,e,s,r,a,l));else{let u=f.hasOwnProperty("indices")?Mu(e[f.indices],s,!0):null,d=ZK(c,f.attributes,u,e,s,i),p=yG(f),m=new _e(c);if(m.vertexBuffer=d,m.primitive[0].type=p,m.primitive[0].base=0,m.primitive[0].indexed=u!==null,u!==null){let S;u instanceof Uint8Array?S=0:u instanceof Uint16Array?S=1:S=2,S===0&&c.isWebGPU&&(S=1,u=new Uint16Array(u));let g=new os(c,S,u.length,0,u);m.indexBuffer[0]=g,m.primitive[0].count=u.length}else m.primitive[0].count=d.numVertices;if(f.hasOwnProperty("extensions")&&f.extensions.hasOwnProperty("KHR_materials_variants")){let S=f.extensions.KHR_materials_variants,g={};S.mappings.forEach(T=>{T.variants.forEach(C=>{g[C]=T.material})}),r[m.id]=g}a[m.id]=f.material;let _=e[f.attributes.POSITION];if(m.aabb=ab(_),f.hasOwnProperty("targets")){let S=[];f.targets.forEach((g,T)=>{let C={};g.hasOwnProperty("POSITION")&&(_=e[g.POSITION],C.deltaPositions=x_(_,s),C.aabb=ab(_)),g.hasOwnProperty("NORMAL")&&(_=e[g.NORMAL],C.deltaNormals=x_(_,s)),t.hasOwnProperty("extras")&&t.extras.hasOwnProperty("targetNames")?C.name=t.extras.targetNames[T]:C.name=T.toString(10),t.hasOwnProperty("weights")&&(C.defaultWeight=t.weights[T]),C.preserveData=o.morphPreserveData,S.push(new Gc(C))}),m.morph=new Ko(S,c,{preferHighPrecision:o.morphPreferHighPrecision})}h.push(m)}}),h},Gs=(c,t,e)=>{let s,i=c.texCoord;if(i)for(s=0;s{let s;if(c.hasOwnProperty("diffuseFactor")){let[i,r,a,o]=c.diffuseFactor;t.diffuse.set(i,r,a).gamma(),t.opacity=o}else t.diffuse.set(1,1,1),t.opacity=1;if(c.hasOwnProperty("diffuseTexture")){let i=c.diffuseTexture;s=e[i.index],t.diffuseMap=s,t.diffuseMapChannel="rgb",t.opacityMap=s,t.opacityMapChannel="a",Gs(i,t,["diffuse","opacity"])}if(t.useMetalness=!1,c.hasOwnProperty("specularFactor")){let[i,r,a]=c.specularFactor;t.specular.set(i,r,a).gamma()}else t.specular.set(1,1,1);if(c.hasOwnProperty("glossinessFactor")?t.gloss=c.glossinessFactor:t.gloss=1,c.hasOwnProperty("specularGlossinessTexture")){let i=c.specularGlossinessTexture;t.specularMap=t.glossMap=e[i.index],t.specularMapChannel="rgb",t.glossMapChannel="a",Gs(i,t,["gloss","metalness"])}},sj=(c,t,e)=>{if(c.hasOwnProperty("clearcoatFactor")?t.clearCoat=c.clearcoatFactor*.25:t.clearCoat=0,c.hasOwnProperty("clearcoatTexture")){let s=c.clearcoatTexture;t.clearCoatMap=e[s.index],t.clearCoatMapChannel="r",Gs(s,t,["clearCoat"])}if(c.hasOwnProperty("clearcoatRoughnessFactor")?t.clearCoatGloss=c.clearcoatRoughnessFactor:t.clearCoatGloss=0,c.hasOwnProperty("clearcoatRoughnessTexture")){let s=c.clearcoatRoughnessTexture;t.clearCoatGlossMap=e[s.index],t.clearCoatGlossMapChannel="g",Gs(s,t,["clearCoatGloss"])}if(c.hasOwnProperty("clearcoatNormalTexture")){let s=c.clearcoatNormalTexture;t.clearCoatNormalMap=e[s.index],Gs(s,t,["clearCoatNormal"]),s.hasOwnProperty("scale")?t.clearCoatBumpiness=s.scale:t.clearCoatBumpiness=1}t.clearCoatGlossInvert=!0},ij=(c,t,e)=>{t.useLighting=!1,t.emissive.copy(t.diffuse),t.emissiveMap=t.diffuseMap,t.emissiveMapUv=t.diffuseMapUv,t.emissiveMapTiling.copy(t.diffuseMapTiling),t.emissiveMapOffset.copy(t.diffuseMapOffset),t.emissiveMapRotation=t.diffuseMapRotation,t.emissiveMapChannel=t.diffuseMapChannel,t.emissiveVertexColor=t.diffuseVertexColor,t.emissiveVertexColorChannel=t.diffuseVertexColorChannel,t.useLighting=!1,t.useSkybox=!1,t.diffuse.set(1,1,1),t.diffuseMap=null,t.diffuseVertexColor=!1},rj=(c,t,e)=>{if(t.useMetalnessSpecularColor=!0,c.hasOwnProperty("specularColorTexture")&&(t.specularMap=e[c.specularColorTexture.index],t.specularMapChannel="rgb",Gs(c.specularColorTexture,t,["specular"])),c.hasOwnProperty("specularColorFactor")){let[s,i,r]=c.specularColorFactor;t.specular.set(s,i,r).gamma()}else t.specular.set(1,1,1);c.hasOwnProperty("specularFactor")?t.specularityFactor=c.specularFactor:t.specularityFactor=1,c.hasOwnProperty("specularTexture")&&(t.specularityFactorMapChannel="a",t.specularityFactorMap=e[c.specularTexture.index],Gs(c.specularTexture,t,["specularityFactor"]))},aj=(c,t,e)=>{c.hasOwnProperty("ior")&&(t.refractionIndex=1/c.ior)},oj=(c,t,e)=>{c.hasOwnProperty("dispersion")&&(t.dispersion=c.dispersion)},nj=(c,t,e)=>{t.blendType=ls,t.useDynamicRefraction=!0,c.hasOwnProperty("transmissionFactor")&&(t.refraction=c.transmissionFactor),c.hasOwnProperty("transmissionTexture")&&(t.refractionMapChannel="r",t.refractionMap=e[c.transmissionTexture.index],Gs(c.transmissionTexture,t,["refraction"]))},lj=(c,t,e)=>{if(t.useSheen=!0,c.hasOwnProperty("sheenColorFactor")){let[s,i,r]=c.sheenColorFactor;t.sheen.set(s,i,r).gamma()}else t.sheen.set(1,1,1);c.hasOwnProperty("sheenColorTexture")&&(t.sheenMap=e[c.sheenColorTexture.index],Gs(c.sheenColorTexture,t,["sheen"])),t.sheenGloss=c.hasOwnProperty("sheenRoughnessFactor")?c.sheenRoughnessFactor:0,c.hasOwnProperty("sheenRoughnessTexture")&&(t.sheenGlossMap=e[c.sheenRoughnessTexture.index],t.sheenGlossMapChannel="a",Gs(c.sheenRoughnessTexture,t,["sheenGloss"])),t.sheenGlossInvert=!0},cj=(c,t,e)=>{if(t.blendType=ls,t.useDynamicRefraction=!0,c.hasOwnProperty("thicknessFactor")&&(t.thickness=c.thicknessFactor),c.hasOwnProperty("thicknessTexture")&&(t.thicknessMap=e[c.thicknessTexture.index],t.thicknessMapChannel="g",Gs(c.thicknessTexture,t,["thickness"])),c.hasOwnProperty("attenuationDistance")&&(t.attenuationDistance=c.attenuationDistance),c.hasOwnProperty("attenuationColor")){let[s,i,r]=c.attenuationColor;t.attenuation.set(s,i,r).gamma()}},hj=(c,t,e)=>{c.hasOwnProperty("emissiveStrength")&&(t.emissiveIntensity=c.emissiveStrength)},fj=(c,t,e)=>{t.useIridescence=!0,c.hasOwnProperty("iridescenceFactor")&&(t.iridescence=c.iridescenceFactor),c.hasOwnProperty("iridescenceTexture")&&(t.iridescenceMapChannel="r",t.iridescenceMap=e[c.iridescenceTexture.index],Gs(c.iridescenceTexture,t,["iridescence"])),c.hasOwnProperty("iridescenceIor")&&(t.iridescenceRefractionIndex=c.iridescenceIor),c.hasOwnProperty("iridescenceThicknessMinimum")&&(t.iridescenceThicknessMin=c.iridescenceThicknessMinimum),c.hasOwnProperty("iridescenceThicknessMaximum")&&(t.iridescenceThicknessMax=c.iridescenceThicknessMaximum),c.hasOwnProperty("iridescenceThicknessTexture")&&(t.iridescenceThicknessMapChannel="g",t.iridescenceThicknessMap=e[c.iridescenceThicknessTexture.index],Gs(c.iridescenceThicknessTexture,t,["iridescenceThickness"]))},uj=(c,t,e)=>{if(t.enableGGXSpecular=!0,c.hasOwnProperty("anisotropyStrength")?t.anisotropyIntensity=c.anisotropyStrength:t.anisotropyIntensity=0,c.hasOwnProperty("anisotropyTexture")){let s=c.anisotropyTexture;t.anisotropyMap=e[s.index],Gs(s,t,["anisotropy"])}c.hasOwnProperty("anisotropyRotation")?t.anisotropyRotation=c.anisotropyRotation*R.RAD_TO_DEG:t.anisotropyRotation=0},EG=(c,t)=>{let e=new it;c.hasOwnProperty("name")&&(e.name=c.name),e.occludeSpecular=Bo,e.diffuseVertexColor=!0,e.specularTint=!0,e.specularVertexColor=!0,e.specular.set(1,1,1),e.gloss=1,e.glossInvert=!0,e.useMetalness=!0;let s;if(c.hasOwnProperty("pbrMetallicRoughness")){let r=c.pbrMetallicRoughness;if(r.hasOwnProperty("baseColorFactor")){let[a,o,l,h]=r.baseColorFactor;e.diffuse.set(a,o,l).gamma(),e.opacity=h}if(r.hasOwnProperty("baseColorTexture")){let a=r.baseColorTexture;s=t[a.index],e.diffuseMap=s,e.diffuseMapChannel="rgb",e.opacityMap=s,e.opacityMapChannel="a",Gs(a,e,["diffuse","opacity"])}if(r.hasOwnProperty("metallicFactor")&&(e.metalness=r.metallicFactor),r.hasOwnProperty("roughnessFactor")&&(e.gloss=r.roughnessFactor),r.hasOwnProperty("metallicRoughnessTexture")){let a=r.metallicRoughnessTexture;e.metalnessMap=e.glossMap=t[a.index],e.metalnessMapChannel="b",e.glossMapChannel="g",Gs(a,e,["gloss","metalness"])}}if(c.hasOwnProperty("normalTexture")){let r=c.normalTexture;e.normalMap=t[r.index],Gs(r,e,["normal"]),r.hasOwnProperty("scale")&&(e.bumpiness=r.scale)}if(c.hasOwnProperty("occlusionTexture")){let r=c.occlusionTexture;e.aoMap=t[r.index],e.aoMapChannel="r",Gs(r,e,["ao"])}if(c.hasOwnProperty("emissiveFactor")){let[r,a,o]=c.emissiveFactor;e.emissive.set(r,a,o).gamma()}if(c.hasOwnProperty("emissiveTexture")){let r=c.emissiveTexture;e.emissiveMap=t[r.index],Gs(r,e,["emissive"])}if(c.hasOwnProperty("alphaMode"))switch(c.alphaMode){case"MASK":e.blendType=wt,c.hasOwnProperty("alphaCutoff")?e.alphaTest=c.alphaCutoff:e.alphaTest=.5;break;case"BLEND":e.blendType=ls,e.depthWrite=!1;break;default:case"OPAQUE":e.blendType=wt;break}else e.blendType=wt;c.hasOwnProperty("doubleSided")?(e.twoSidedLighting=c.doubleSided,e.cull=c.doubleSided?0:1):(e.twoSidedLighting=!1,e.cull=1);let i={KHR_materials_clearcoat:sj,KHR_materials_emissive_strength:hj,KHR_materials_ior:aj,KHR_materials_dispersion:oj,KHR_materials_iridescence:fj,KHR_materials_pbrSpecularGlossiness:tj,KHR_materials_sheen:lj,KHR_materials_specular:rj,KHR_materials_transmission:nj,KHR_materials_unlit:ij,KHR_materials_volume:cj,KHR_materials_anisotropy:uj};if(c.hasOwnProperty("extensions"))for(let r in c.extensions){let a=i[r];a!==void 0&&a(c.extensions[r],e,t)}return e.update(),e},dj=(c,t,e,s,i,r,a)=>{let o=A=>new an(kE(A.type),x_(A,s)),l={STEP:0,LINEAR:1,CUBICSPLINE:2},h={},f={},u={},d=1,p;for(p=0;p{let w=[];for(;A;)w.unshift(A.name),A=A.parent;return w},g=(A,w,I)=>{let D=f[A.output];if(!D)return;let O;if(r&&r[w.mesh]){let b=r[w.mesh];b.hasOwnProperty("extras")&&b.extras.hasOwnProperty("targetNames")&&(O=b.extras.targetNames)}let G=D.data,M=G.length/h[A.input].data.length,H=G.length/M,U=H*4,L=new ArrayBuffer(U*M);for(let b=0;b0&&w.paths[0].propertyPath[0]==="localRotation"&&w.interpolation!==2&&m.push(v[v.length-1].output))}m.sort();let E=null,y;for(p=0;p{let s=new Pe;if(c.hasOwnProperty("name")&&c.name.length>0?s.name=c.name:s.name=`node_${t}`,c.hasOwnProperty("matrix")&&(ix.data.set(c.matrix),ix.getTranslation(rx),s.setLocalPosition(rx),vG.setFromMat4(ix),s.setLocalRotation(vG),ix.getScale(rx),rx.x*=ix.scaleSign,s.setLocalScale(rx)),c.hasOwnProperty("rotation")){let i=c.rotation;s.setLocalRotation(i[0],i[1],i[2],i[3])}if(c.hasOwnProperty("translation")){let i=c.translation;s.setLocalPosition(i[0],i[1],i[2])}if(c.hasOwnProperty("scale")){let i=c.scale;s.setLocalScale(i[0],i[1],i[2])}return c.hasOwnProperty("extensions")&&c.extensions.EXT_mesh_gpu_instancing&&e.set(c,{ext:c.extensions.EXT_mesh_gpu_instancing}),s},mj=(c,t)=>{let e=c.type==="orthographic",s=e?c.orthographic:c.perspective,i={enabled:!1,projection:e?ni:ts,nearClip:s.znear,aspectRatioMode:Ac};s.zfar&&(i.farClip=s.zfar),e?(i.orthoHeight=s.ymag,s.xmag&&s.ymag&&(i.aspectRatioMode=vp,i.aspectRatio=s.xmag/s.ymag)):(i.fov=s.yfov*R.RAD_TO_DEG,s.aspectRatio&&(i.aspectRatioMode=vp,i.aspectRatio=s.aspectRatio));let r=new Ne(c.name);return r.addComponent("camera",i),r},_j=(c,t)=>{let e={enabled:!1,type:c.type==="point"?"omni":c.type,color:c.hasOwnProperty("color")?new F(c.color):F.WHITE,range:c.hasOwnProperty("range")?c.range:9999,falloffMode:dT,intensity:c.hasOwnProperty("intensity")?R.clamp(c.intensity,0,2):1};if(c.hasOwnProperty("spot")&&(e.innerConeAngle=c.spot.hasOwnProperty("innerConeAngle")?c.spot.innerConeAngle*R.RAD_TO_DEG:0,e.outerConeAngle=c.spot.hasOwnProperty("outerConeAngle")?c.spot.outerConeAngle*R.RAD_TO_DEG:45),c.hasOwnProperty("intensity")){let i=c.spot?.outerConeAngle??Math.PI/4,r=c.spot?.innerConeAngle??0;e.luminance=c.intensity*kc.getLightUnitConversion(ly[e.type],i,r)}let s=new Ne(t.name);return s.rotateLocal(90,0,0),s.addComponent("light",e),s},gj=(c,t,e,s)=>{if(!t.hasOwnProperty("skins")||t.skins.length===0)return[];let i=new Map;return t.skins.map(r=>QK(c,r,t.accessors,s,e,i))},Sj=(c,t,e,s)=>{let i={},r={},a={},o=[];return{meshes:!s.skipMeshes&&t?.meshes?.length&&t?.accessors?.length&&t?.bufferViews?.length?t.meshes.map(f=>ej(c,f,t.accessors,e,i,r,a,s,o)):[],meshVariants:r,meshDefaultMaterials:a,promises:o}},xj=(c,t,e)=>{if(!c.hasOwnProperty("materials")||c.materials.length===0)return[];let s=e?.material?.preprocess,i=e?.material?.process??EG,r=e?.material?.postprocess;return c.materials.map(a=>{s&&s(a);let o=i(a,t);return r&&r(a,o),o})},vj=c=>{if(!c.hasOwnProperty("extensions")||!c.extensions.hasOwnProperty("KHR_materials_variants"))return null;let t=c.extensions.KHR_materials_variants.variants,e={};for(let s=0;s{if(!c.hasOwnProperty("animations")||c.animations.length===0)return[];let i=s?.animation?.preprocess,r=s?.animation?.postprocess;return c.animations.map((a,o)=>{i&&i(a);let l=dj(a,o,c.accessors,e,t,c.meshes,c.nodes);return r&&r(a,l),l})},yj=(c,t,e,s)=>{let i=t.accessors;e.forEach((r,a)=>{let o=r.ext.attributes,l;if(o.hasOwnProperty("TRANSLATION")){let d=i[o.TRANSLATION];l=x_(d,s)}let h;if(o.hasOwnProperty("ROTATION")){let d=i[o.ROTATION];h=x_(d,s)}let f;if(o.hasOwnProperty("SCALE")){let d=i[o.SCALE];f=x_(d,s)}let u=(l?l.length/3:0)||(h?h.length/4:0)||(f?f.length/3:0);if(u){let d=new Float32Array(u*16),p=new x,m=new $,_=new x(1,1,1),S=new W,g=0;for(let T=0;T{if(!c.hasOwnProperty("nodes")||c.nodes.length===0)return[];let s=t?.node?.preprocess,i=t?.node?.process??pj,r=t?.node?.postprocess,a=c.nodes.map((o,l)=>{s&&s(o);let h=i(o,l,e);return r&&r(o,h),h});for(let o=0;o{let e=[],s=c.scenes.length;if(s===1&&c.scenes[0].nodes?.length===1){let i=c.scenes[0].nodes[0];e.push(t[i])}else for(let i=0;i{let s=null;if(c.hasOwnProperty("nodes")&&c.hasOwnProperty("cameras")&&c.cameras.length>0){let i=e?.camera?.preprocess,r=e?.camera?.process??mj,a=e?.camera?.postprocess;c.nodes.forEach((o,l)=>{if(o.hasOwnProperty("camera")){let h=c.cameras[o.camera];if(h){i&&i(h);let f=r(h,t[l]);a&&a(h,f),f&&(s||(s=new Map),s.set(o,f))}}})}return s},Pj=(c,t,e)=>{let s=null;if(c.hasOwnProperty("nodes")&&c.hasOwnProperty("extensions")&&c.extensions.hasOwnProperty("KHR_lights_punctual")&&c.extensions.KHR_lights_punctual.hasOwnProperty("lights")){let i=c.extensions.KHR_lights_punctual.lights;if(i.length){let r=e?.light?.preprocess,a=e?.light?.process??_j,o=e?.light?.postprocess;c.nodes.forEach((l,h)=>{if(l.hasOwnProperty("extensions")&&l.extensions.hasOwnProperty("KHR_lights_punctual")&&l.extensions.KHR_lights_punctual.hasOwnProperty("light")){let f=l.extensions.KHR_lights_punctual.light,u=i[f];if(u){r&&r(u);let d=a(u,t[h]);o&&o(u,d),d&&(s||(s=new Map),s.set(l,d))}}})}}return s},wj=(c,t,e)=>{c.nodes.forEach(s=>{s.hasOwnProperty("mesh")&&s.hasOwnProperty("skin")&&t[s.mesh].meshes.forEach(r=>{r.skin=e[s.skin]})})},Ij=async(c,t,e,s,i)=>{let r=i?.global?.preprocess,a=i?.global?.postprocess;r&&r(t),t.asset&&t.asset.generator;let o=new Map,l=Ej(t,i,o),h=Aj(t,l),f=Pj(t,l,i),u=Cj(t,l,i),d=vj(t),p=await Promise.all(e),{meshes:m,meshVariants:_,meshDefaultMaterials:S,promises:g}=Sj(c,t,p,i),T=Tj(t,l,p,i);yj(c,t,o,p);let C=await Promise.all(s),v=C.map(w=>w.resource),E=xj(t,v,i),y=gj(c,t,l,p),P=[];for(let w=0;w{let e=(i,r)=>{switch(i){case 9728:return 0;case 9729:return 1;case 9984:return 2;case 9985:return 4;case 9986:return 3;case 9987:return 5;default:return r}},s=(i,r)=>{switch(i){case 33071:return 1;case 33648:return 2;case 10497:return 0;default:return r}};c&&(t=t??{},c.minFilter=e(t.minFilter,5),c.magFilter=e(t.magFilter,1),c.addressU=s(t.wrapS,0),c.addressV=s(t.wrapT,0))},bj=0,S_=c=>c.extensions?.KHR_texture_basisu?.source??c.extensions?.EXT_texture_webp?.source??c.source,Dj=(c,t,e,s,i)=>{if(!c.images||c.images.length===0)return[];let r=i?.image?.preprocess,a=i?.image?.processAsync,o=i?.image?.postprocess,l={"image/png":"png","image/jpeg":"jpg","image/basis":"basis","image/ktx":"ktx","image/ktx2":"ktx2","image/vnd-ms.dds":"dds"},h=d=>{let p=new Set;return d.hasOwnProperty("materials")&&d.materials.forEach(m=>{if(m.hasOwnProperty("pbrMetallicRoughness")){let _=m.pbrMetallicRoughness;if(_.hasOwnProperty("baseColorTexture")){let S=d.textures[_.baseColorTexture.index];p.add(S_(S))}}if(m.hasOwnProperty("emissiveTexture")){let _=d.textures[m.emissiveTexture.index];p.add(S_(_))}if(m.hasOwnProperty("extensions")){let _=m.extensions.KHR_materials_sheen;if(_&&_.hasOwnProperty("sheenColorTexture")){let T=d.textures[_.sheenColorTexture.index];p.add(S_(T))}let S=m.extensions.KHR_materials_pbrSpecularGlossiness;if(S&&S.hasOwnProperty("specularGlossinessTexture")){let T=d.textures[S.specularGlossinessTexture.index];p.add(S_(T))}let g=m.extensions.KHR_materials_specular;if(g&&g.hasOwnProperty("specularColorTexture")){let T=d.textures[g.specularColorTexture.index];p.add(S_(T))}}}),p},f=(d,p,m,_,S,g)=>new Promise((T,C)=>{let v=E=>{let y=`${d.name||"gltf-texture"}-${bj++}`,P={url:p||y};if(E&&(P.contents=E.slice(0).buffer),_){let I=l[_];I&&(P.filename=`${P.url}.${I}`)}let A={srgb:g},w=new ae(y,"texture",P,A,S);w.on("load",I=>T(I)),w.on("error",I=>C(I)),s.add(w),s.load(w)};m?m.then(E=>v(E)):v(null)}),u=h(c);return c.images.map((d,p)=>{r&&r(d);let m;return a?m=new Promise((_,S)=>{a(d,(g,T)=>{g?S(g):_(T)})}):m=new Promise(_=>{_(null)}),m=m.then(_=>{let S=u.has(p);return _||(d.hasOwnProperty("uri")?TG(d.uri)?f(d,d.uri,null,VK(d.uri),null,S):f(d,Ja.test(d.uri)?d.uri:xe.join(e,d.uri),null,null,{crossOrigin:"anonymous"},S):d.hasOwnProperty("bufferView")&&d.hasOwnProperty("mimeType")?f(d,null,t[d.bufferView],d.mimeType,null,S):Promise.reject(new Error(`Invalid image found in gltf (neither uri or bufferView found). index=${p}`)))}),o&&(m=m.then(_=>(o(d,_),_))),m})},Lj=(c,t,e)=>{if(!c?.images?.length||!c?.textures?.length)return[];let s=e?.texture?.preprocess,i=e?.texture?.processAsync,r=e?.texture?.postprocess,a=new Set;return c.textures.map(o=>{s&&s(o);let l;return i?l=new Promise((h,f)=>{i(o,c.images,(u,d)=>{u?f(u):h(d)})}):l=new Promise(h=>{h(null)}),l=l.then(h=>{h=h??S_(o);let f=a.has(h);return a.add(h),t[h].then(u=>{let d=f?qK(u):u;return Rj(d.resource,(c.samplers??[])[o.sampler]),d})}),r&&(l=l.then(h=>(r(o,h),h))),l})},Mj=(c,t,e,s)=>{if(!c.buffers||c.buffers.length===0)return[];let i=s?.buffer?.preprocess,r=s?.buffer?.processAsync,a=s?.buffer?.postprocess;return c.buffers.map((o,l)=>{i&&i(o);let h;return r?h=new Promise((f,u)=>{r(o,(d,p)=>{d?u(d):f(p)})}):h=new Promise(f=>{f(null)}),h=h.then(f=>{if(f)return f;if(o.hasOwnProperty("uri")){if(TG(o.uri)){let u=atob(o.uri.split(",")[1]),d=new Uint8Array(u.length);for(let p=0;p{Le.get(Ja.test(o.uri)?o.uri:xe.join(e,o.uri),{cache:!0,responseType:"arraybuffer",retry:!1},(p,m)=>{p?d(p):u(new Uint8Array(m))})})}return t}),a&&(h=h.then(f=>(a(c.buffers[l],f),f))),h})},Oj=(c,t)=>{let s=JSON.parse((i=>{if(typeof TextDecoder<"u")return new TextDecoder().decode(i);let r="";for(let a=0;a{let e=c instanceof ArrayBuffer?new DataView(c):new DataView(c.buffer,c.byteOffset,c.byteLength),s=e.getUint32(0,!0),i=e.getUint32(4,!0),r=e.getUint32(8,!0);if(s!==1179937895){t(`Invalid magic number found in glb header. Expected 0x46546C67, found 0x${s.toString(16)}`);return}if(i!==2){t(`Invalid version number found in glb header. Expected 2, found ${i}`);return}if(r<=0||r>e.byteLength){t(`Invalid length found in glb header. Found ${r}`);return}let a=[],o=12;for(;oe.byteLength&&t(`Invalid chunk length found in glb. Found ${l}`);let h=e.getUint32(o+4,!0),f=new Uint8Array(e.buffer,e.byteOffset+o+8,l);a.push({length:l,type:h,data:f}),o+=l+8}if(a.length!==1&&a.length!==2){t("Invalid number of chunks found in glb file.");return}if(a[0].type!==1313821514){t(`Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x${a[0].type.toString(16)}`);return}if(a.length>1&&a[1].type!==5130562){t(`Invalid chunk type found in glb file. Expected 0x004E4942, found 0x${a[1].type.toString(16)}`);return}t(null,{gltfChunk:a[0].data,binaryChunk:a.length===2?a[1].data:null})},Nj=(c,t,e)=>{let s=()=>{let i=new Uint8Array(t);return i[0]===103&&i[1]===108&&i[2]===84&&i[3]===70};c&&c.toLowerCase().endsWith(".glb")||s()?Fj(t,e):e(null,{gltfChunk:t,binaryChunk:null})},Bj=(c,t,e)=>{let s=[],i=e?.bufferView?.preprocess,r=e?.bufferView?.processAsync,a=e?.bufferView?.postprocess;if(!c.bufferViews?.length)return s;for(let o=0;o{r(l,t,(d,p)=>{d?u(d):f(p)})}):h=new Promise(f=>{f(null)}),h=h.then(f=>f||t[l.buffer].then(u=>new Uint8Array(u.buffer,u.byteOffset+(l.byteOffset||0),l.byteLength))),l.hasOwnProperty("byteStride")&&(h=h.then(f=>(f.byteStride=l.byteStride,f))),a&&(h=h.then(f=>(a(l,f),f))),s.push(h)}return s},Il=class{static parse(t,e,s,i,r,a,o){Nj(t,s,(l,h)=>{if(l){o(l);return}Oj(h.gltfChunk,(f,u)=>{if(f){o(f);return}let d=Mj(u,h.binaryChunk,e,a),p=Bj(u,d,a),m=Dj(u,p,e,r,a),_=Lj(u,m,a);Ij(i,u,p,_,a).then(S=>o(null,S)).catch(S=>o(S))})})}static createDefaultMaterial(){return EG({name:"defaultGlbMaterial"},[])}};var v_=class extends Re{constructor(t){super(t,"animation"),this.device=t.graphicsDevice,this.assets=t.assets}load(t,e,s){typeof t=="string"&&(t={load:t,original:t});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};(t.load.startsWith("blob:")||t.load.startsWith("data:"))&&(xe.getExtension(t.original).toLowerCase()===".glb"?i.responseType=Vt.ResponseType.ARRAY_BUFFER:i.responseType=Vt.ResponseType.JSON),Le.get(t.load,i,(r,a)=>{r?e(`Error loading animation resource: ${t.original} [${r}]`):xe.getExtension(t.original).toLowerCase()===".glb"?Il.parse("filename.glb","",a,this.device,this.assets,s?.options??{},(o,l)=>{if(o)e(o);else{let h=l.animations;if(s?.data?.events)for(let f=0;f0,maxRetries:this.maxRetries};t.load.startsWith("blob:")&&(s.responseType=Vt.ResponseType.JSON),Le.get(t.load,s,(i,r)=>{i?e(`Error loading animation clip resource: ${t.original} [${i}]`):e(null,r)})}open(t,e){let s=e.name,i=e.duration,r=e.inputs.map(l=>new an(1,l)),a=e.outputs.map(l=>new an(l.components,l.data)),o=e.curves.map(l=>new Th([l.path],l.inputIndex,l.outputIndex,l.interpolation));return new Qs(s,i,r,a,o)}};var y_=class extends Re{constructor(t){super(t,"animstategraph")}load(t,e){typeof t=="string"&&(t={load:t,original:t});let s={retry:this.maxRetries>0,maxRetries:this.maxRetries};t.load.startsWith("blob:")&&(s.responseType=Vt.ResponseType.JSON),Le.get(t.load,s,(i,r)=>{i?e(`Error loading animation state graph resource: ${t.original} [${i}]`):e(null,r)})}open(t,e){return new en(e)}};var Uj=[".ogg",".mp3",".wav",".mp4a",".m4a",".mp4",".aac",".opus"],E_=class extends Re{constructor(t){super(t,"audio"),this.manager=t.soundManager}_isSupported(t){let e=xe.getExtension(t);return Uj.indexOf(e)>-1}load(t,e){typeof t=="string"&&(t={load:t,original:t});let s=function(r){e(null,new sp(r))},i=function(r){let a=`Error loading audio url: ${t.original}`;r&&(a+=`: ${r.message||r}`),e(a)};if(this._createSound){if(!this._isSupported(t.original)){i(`Audio format for ${t.original} not supported`);return}this._createSound(t.load,s,i)}else i(null)}_createSound(t,e,s){let i=this.manager;if(!i.context){s("Audio manager has no audio context");return}let r={retry:this.maxRetries>0,maxRetries:this.maxRetries};(t.startsWith("blob:")||t.startsWith("data:"))&&(r.responseType=Vt.ResponseType.ARRAY_BUFFER),Le.get(t,r,(a,o)=>{if(a){s(a);return}i.context.decodeAudioData(o,e,s)})}};var A_=class extends Re{constructor(t){super(t,"binary")}load(t,e){typeof t=="string"&&(t={load:t,original:t}),Le.get(t.load,{responseType:Vt.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(s,i)=>{s?e(`Error loading binary resource: ${t.original} [${s}]`):e(null,i)})}openBinary(t){return t.buffer}};var C_=class c{constructor(t,e,s,i){let r=function(h,f,u){let d=c.createAsset(e.name,h,f,u);return s.add(d),d},a=[];for(let h=0;h{let f=new Ne(void 0,this._assets._loader._app);l._cloneInternal(f),o||(o=f);let u=null,d=null;for(let m=0;m{o.meshInstance.skinInstance=Eu.createCachedSkinInstance(o.meshInstance.mesh.skin,o.rootBone,o.entity),o.meshInstance.node.render.rootBone=o.rootBone}),c.createSceneHierarchy(a,Ne)}getMaterialVariants(){return this.data.variants?Object.keys(this.data.variants):[]}applyMaterialVariant(t,e){let s=e?this.data.variants[e]:null;if(s===void 0)return;let i=t.findComponents("render");for(let r=0;r{if(t===null)s.material=this._defaultMaterial;else{let i=this.data.meshVariants[s.mesh.id];i&&(s.material=this.data.materials[i[t]])}})}static createSceneHierarchy(t,e){let s=null;if(t.length===1)s=t[0];else{s=new e("SceneGroup");for(let i of t)s.addChild(i)}return s}static createModel(t,e){let s=function(a,o,l,h,f,u,d){let p=t.meshDefaultMaterials[o.id],m=p===void 0?e:f[p],_=new we(o,m,u);if(o.morph){let S=new Ar(o.morph);_.morphInstance=S,a.morphInstances.push(S)}if(d.hasOwnProperty("skin")){let S=d.skin,g=l[S];o.skin=g;let T=h[S];_.skinInstance=T,a.skinInstances.push(T)}a.meshInstances.push(_)},i=new Ei,r=[];for(let a of t.skins){let o=new er(a);o.bones=a.bones,r.push(o)}i.graph=c.createSceneHierarchy(t.scenes,Pe);for(let a=0;a{e(r)})};this.animations&&(s(this.animations),this.animations=null),this.textures&&(s(this.textures),this.textures=null),this.materials&&(s(this.materials),this.materials=null),this.renders&&(s(this.renders),this.renders=null),this._model&&(e(this._model),this._model=null),this.data=null,this.assets=null}};var zE=class{constructor(t,e,s){this._device=t,this._assets=e,this._defaultMaterial=Il.createDefaultMaterial(),this.maxRetries=s}_getUrlWithoutParams(t){return t.indexOf("?")>=0?t.split("?")[0]:t}load(t,e,s){ae.fetchArrayBuffer(t.load,(i,r)=>{i?e(i):Il.parse(this._getUrlWithoutParams(t.original),xe.extractPath(t.load),r,this._device,s.registry,s.options,(a,o)=>{a?e(a):e(null,new C_(o,s,this._assets,this._defaultMaterial))})},s,this.maxRetries)}open(t,e,s){return e}patch(t,e){}};var GE=class{instantiateModelEntity(t){return null}instantiateRenderEntity(t){return null}getMaterialVariants(){return null}applyMaterialVariant(t,e){}applyMaterialVariantInstances(t,e){}},P_=class extends Re{constructor(t){super(t,"container"),this.glbContainerParser=new zE(t.graphicsDevice,t.assets,0),this.parsers={}}set maxRetries(t){this.glbContainerParser.maxRetries=t;for(let e in this.parsers)this.parsers.hasOwnProperty(e)&&(this.parsers[e].maxRetries=t)}get maxRetries(){return this.glbContainerParser.maxRetries}_getUrlWithoutParams(t){return t.indexOf("?")>=0?t.split("?")[0]:t}_getParser(t){let e=t?xe.getExtension(this._getUrlWithoutParams(t)).toLowerCase().replace(".",""):null;return this.parsers[e]||this.glbContainerParser}load(t,e,s){typeof t=="string"&&(t={load:t,original:t}),this._getParser(t.original).load(t,e,s)}open(t,e,s){return this._getParser(t).open(t,e,s)}};var w_=class extends Re{constructor(e){super(e,"css");n(this,"decoder",null)}load(e,s){typeof e=="string"&&(e={load:e,original:e}),Le.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,r)=>{i?s(`Error loading css resource: ${e.original} [${i}]`):s(null,r)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}};var I_=class extends Re{constructor(t){super(t,"cubemap"),this._device=t.graphicsDevice,this._registry=t.assets,this._loader=t.loader}load(t,e,s){this.loadAssets(s,e)}open(t,e,s){return s?s.resource:null}patch(t,e){this.loadAssets(t,(s,i)=>{s&&(e.fire("error",t),e.fire(`error:${t.id}`,s,t),t.fire("error",t))})}getAssetIds(t){let e=[];if(e[0]=t.file,(t.loadFaces||!t.file)&&t.data&&t.data.textures)for(let s=0;s<6;++s)e[s+1]=t.data.textures[s];else e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=null;return e}compareAssetIds(t,e){return t&&e?parseInt(t,10)===t||typeof t=="string"?t===e:t.url===e.url:t!==null==(e!==null)}update(t,e,s){let i=t.data||{},r=t._handlerState.assets,a=t._resources,o,l,h,f=[null,null,null,null,null,null,null],u=function(){return i.hasOwnProperty("type")?i.type:i.hasOwnProperty("rgbm")?i.rgbm?_i:Gt:null};if(!t.loaded||s[0]!==r[0]){if(s[0])if(o=s[0].resource,o.cubemap)for(h=0;h<6;++h)f[h+1]=new Z(this._device,{name:`${t.name}_prelitCubemap${o.width>>h}`,cubemap:!0,type:u()||o.type,width:o.width>>h,height:o.height>>h,format:o.format,levels:[o._levels[h]],addressU:1,addressV:1,mipmaps:h===0});else f[1]=o}else f[1]=a[1]||null,f[2]=a[2]||null,f[3]=a[3]||null,f[4]=a[4]||null,f[5]=a[5]||null,f[6]=a[6]||null;let d=s.slice(1);if(!t.loaded||!this.cmpArrays(d,r.slice(1))){if(d.indexOf(null)===-1){let p=d.map(g=>g.resource),m=[];for(l=0;lg._levels[l]));let _=p[0].format,S=new Z(this._device,{name:`${t.name}_faces`,cubemap:!0,type:u()||p[0].type,width:p[0].width,height:p[0].height,format:_===Ss?ce:_,mipmaps:i.mipmaps??!0,levels:m,minFilter:i.hasOwnProperty("minFilter")?i.minFilter:p[0].minFilter,magFilter:i.hasOwnProperty("magFilter")?i.magFilter:p[0].magFilter,anisotropy:i.hasOwnProperty("anisotropy")?i.anisotropy:1,addressU:1,addressV:1});f[0]=S}}else f[0]=a[0]||null;if(!this.cmpArrays(f,a))for(t.resources=f,t._handlerState.assetIds=e,t._handlerState.assets=s,h=0;h{let T=l.get(g);T?d(S,T):u(S,`failed to find dependent cubemap asset=${g}`)}).bind(null,m,_));else{let S=typeof _=="string"?{url:_,filename:_}:_,g=S.url.search(".dds")===-1?{type:"rgbp",addressu:"clamp",addressv:"clamp",mipmaps:!1}:null;p=new ae(`${t.name}_part_${m}`,"texture",S,g),l.add(p),d(m,p)}}}};var R_=class extends Re{constructor(t){super(t,"folder")}load(t,e){e(null,null)}};var Ou=class{constructor(t,e){this.type=e?e.type||vu:vu,this.em=1,this.textures=t,this.intensity=0,this._data=null,this.data=e}set data(t){if(this._data=t,!!t&&(this._data.intensity!==void 0&&(this.intensity=this._data.intensity),this._data.info||(this._data.info={}),(!this._data.version||this._data.version<2)&&(this._data.info.maps=[{width:this._data.info.width,height:this._data.info.height}],this._data.chars)))for(let e in this._data.chars)this._data.chars[e].map=0}get data(){return this._data}};function nb(c){return c.version<3&&(c.version<2&&(c.info.maps=c.info.maps||[{width:c.info.width,height:c.info.height}]),c.chars=Object.keys(c.chars||{}).reduce((t,e)=>{let s=c.chars[e],i=s.letter!==void 0?s.letter:Nr.fromCodePoint(e);return c.version<2&&(s.map=s.map||0),t[i]=s,t},{}),c.version=3),c}var b_=class extends Re{constructor(t){super(t,"font"),this._loader=t.loader,this.maxRetries=0}load(t,e,s){typeof t=="string"&&(t={load:t,original:t});let i=this;xe.getExtension(t.original)===".json"?Le.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(r,a)=>{if(r)e(`Error loading font resource: ${t.original} [${r}]`);else{let o=nb(a);i._loadTextures(t.load.replace(".json",".png"),o,(l,h)=>{l?e(l):e(null,{data:o,textures:h})})}}):(s&&s.data&&(s.data=nb(s.data)),this._loadTextures(t.load,s&&s.data,e))}_loadTextures(t,e,s){let i=e.info.maps.length,r=0,a=null,o=new Array(i),l=this._loader,h=function(f){let u=function(d,p){if(!a){if(d){a=d,s(d);return}p.upload(),o[f]=p,r++,r===i&&s(null,o)}};f===0?l.load(t,"texture",u):l.load(t.replace(".png",`${f}.png`),"texture",u)};for(let f=0;f{let y=(1<{v.x=o(E>>>21,11),v.y=o(E>>>11,10),v.z=o(E,11)},h=(v,E)=>{v.x=o(E>>>24,8),v.y=o(E>>>16,8),v.z=o(E>>>8,8),v.w=o(E,8)},f=(v,E)=>{let y=Math.SQRT2,P=(o(E>>>20,10)-.5)*y,A=(o(E>>>10,10)-.5)*y,w=(o(E,10)-.5)*y,I=Math.sqrt(1-(P*P+A*A+w*w));switch(E>>>30){case 0:v.set(P,A,w,I);break;case 1:v.set(I,A,w,P);break;case 2:v.set(A,I,w,P);break;case 3:v.set(A,w,I,P);break}},u=(v,E,y)=>v*(1-y)+E*y,{chunkData:d,chunkSize:p,vertexData:m,shData0:_,shData1:S,shData2:g,shBands:T}=t,C=[3,8,15][T-1];this.read=v=>{let E=Math.floor(v/256)*p;if(e&&(l(e,m[v*4+0]),e.x=u(d[E+0],d[E+3],e.x),e.y=u(d[E+1],d[E+4],e.y),e.z=u(d[E+2],d[E+5],e.z)),s&&f(s,m[v*4+1]),i&&(l(i,m[v*4+2]),i.x=u(d[E+6],d[E+9],i.x),i.y=u(d[E+7],d[E+10],i.y),i.z=u(d[E+8],d[E+11],i.z)),r&&(h(r,m[v*4+3]),p>12&&(r.x=u(d[E+12],d[E+15],r.x),r.y=u(d[E+13],d[E+16],r.y),r.z=u(d[E+14],d[E+17],r.z))),a&&T>0){let y=[_,S,g];for(let P=0;P<3;++P)for(let A=0;A<15;++A)a[P*15+A]=A>>21)/2047,T=(S>>>11&1023)/1023,C=(S&2047)/2047;r[_*3+0]=(1-g)*a+g*h,r[_*3+1]=(1-T)*o+T*f,r[_*3+2]=(1-C)*l+C*u}}return r}getChunks(t){let{chunkData:e,numChunks:s,chunkSize:i}=this,r,a,o,l,h,f;for(let u=0;u0){let f=[];for(let d=0;d<45;++d)f.push(`f_rest_${d}`);let u=Math.max(...["f_dc_0","f_dc_1","f_dc_2"].map(d=>t.indexOf(d)));t.splice(u+1,0,...f)}let s={};t.forEach(f=>{s[f]=new Float32Array(this.numSplats)});let i=new x,r=new $,a=new x,o=new Q,l=e>0?new Float32Array(45):null,h=this.createIter(i,r,a,o,l);for(let f=0;f=1?40:-Math.log(1/o.w-1),l)for(let u=0;u<45;++u)s[`f_rest_${u}`][f]=l[u];return new Qa([{name:"vertex",count:this.numSplats,properties:t.map(f=>({name:f,type:"float",byteSize:4,storage:s[f]}))}],this.comments)}};var kj=(c,t,e,s,i)=>{for(let r=0;r0&&(f.push({name:"shTexture0",format:At}),f.push({name:"shTexture1",format:At}),f.push({name:"shTexture2",format:At})),this._format=new Pr(t,f,{readGLSL:'#include "gsplatCompressedVS"',readWGSL:'#include "gsplatCompressedVS"'}),this.streams.init(this.format,o);let u=this.streams.getTexture("packedTexture");if(u.lock().set(l),u.unlock(),h>0){let S=this.streams.getTexture("shTexture0"),g=this.streams.getTexture("shTexture1"),T=this.streams.getTexture("shTexture2");S.lock().set(new Uint32Array(e.shData0.buffer)),S.unlock(),g.lock().set(new Uint32Array(e.shData1.buffer)),g.unlock(),T.lock().set(new Uint32Array(e.shData2.buffer)),T.unlock()}let p=this.evalChunkTextureSize(a),m=this.streams.createTexture("chunkTexture",ke,p);this.streams.textures.set("chunkTexture",m);let _=m.lock();if(kj(_,20,i,r,a),r===12)for(let S=0;S=s)this.head>0?(this.data.copyWithin(0,this.head,this.tail),this.data.set(t,e),this.head=0,this.tail=s):(this.data.set(t,this.tail),this.tail+=t.length);else{let i=new Uint8Array(s);this.head>0||this.tail0&&(this.data.copyWithin(0,this.head,this.tail),this.tail-=this.head,this.head=0)}get remaining(){return this.tail-this.head}getInt8(){let t=this.view.getInt8(this.head);return this.head++,t}getUint8(){let t=this.view.getUint8(this.head);return this.head++,t}getInt16(){let t=this.view.getInt16(this.head,!0);return this.head+=2,t}getUint16(){let t=this.view.getUint16(this.head,!0);return this.head+=2,t}getInt32(){let t=this.view.getInt32(this.head,!0);return this.head+=4,t}getUint32(){let t=this.view.getUint32(this.head,!0);return this.head+=4,t}getFloat32(){let t=this.view.getFloat32(this.head,!0);return this.head+=4,t}getFloat64(){let t=this.view.getFloat64(this.head,!0);return this.head+=8,t}},zj=c=>{let t=[],e=[],s;for(let i=1;i{let t=["min_x","min_y","min_z","max_x","max_y","max_z","min_scale_x","min_scale_y","min_scale_z","max_scale_x","max_scale_y","max_scale_z","min_r","min_g","min_b","max_r","max_g","max_b"],e=["packed_position","packed_rotation","packed_scale","packed_color"],s=new Array(45).fill("").map((a,o)=>`f_rest_${o}`),i=()=>c[0].name==="chunk"&&c[0].properties.every((a,o)=>a.name===t[o]&&a.type==="float")&&c[1].name==="vertex"&&c[1].properties.every((a,o)=>a.name===e[o]&&a.type==="uint"),r=()=>c[2].name==="sh"&&[9,24,45].indexOf(c[2].properties.length)!==-1&&c[2].properties.every((a,o)=>a.name===s[o]&&a.type==="uchar");return c.length===2&&i()||c.length===3&&i()&&r()},Vj=c=>c.length===1&&c[0].name==="vertex"&&c[0].properties.every(t=>t.type==="float"),Hj=async(c,t,e)=>{let s=new VE;s.comments=e;let i=t[0].count,r=t[0].properties.length,a=t[1].count,l=(f=>{let u=Math.ceil(Math.sqrt(f)),d=Math.ceil(f/u);return u*d})(a);s.numSplats=a,s.chunkData=new Float32Array(i*r),s.vertexData=new Uint32Array(l*4);let h=async(f,u)=>{let d=new Uint8Array(f),p=0;for(;p{let s=t[0],i=s.properties,r=i.length,a=i.map(u=>u.storage),o=i.reduce((u,d)=>u+d.byteSize,0),l=0,h,f=()=>{let u=c.data.buffer;h?.buffer!==u&&(h=new Float32Array(u,0,u.byteLength/4))};for(f();l{for(let s=0;sl+h.byteSize,0),a=i.properties.map(l=>{if(l.storage)switch(l.type){case"char":return(h,f)=>{l.storage[f]=h.getInt8()};case"uchar":return(h,f)=>{l.storage[f]=h.getUint8()};case"short":return(h,f)=>{l.storage[f]=h.getInt16()};case"ushort":return(h,f)=>{l.storage[f]=h.getUint16()};case"int":return(h,f)=>{l.storage[f]=h.getInt32()};case"uint":return(h,f)=>{l.storage[f]=h.getUint32()};case"float":return(h,f)=>{l.storage[f]=h.getFloat32()};case"double":return(h,f)=>{l.storage[f]=h.getFloat64()};default:throw new Error(`Unsupported property data type '${l.type}' in ply header`)}else return h=>{h.head+=l.byteSize}}),o=0;for(;o{let s=(d,p)=>{let m=d.length-p.length,_,S;for(_=0;_<=m;++_){for(S=0;S{if(d.length=AG.length&&!i(r.data,AG))throw new Error("Invalid ply header");if(a=s(r.data,CG),a!==-1)break}let o=new TextDecoder("ascii").decode(r.data.subarray(0,a)).split(` +`),{elements:l,format:h,comments:f}=zj(o);if(h!=="binary_little_endian")throw new Error("Unsupported ply format");return r.head=a+CG.length,r.compact(),await(async()=>Gj(l)?await Hj(r,l,f):(l.forEach(d=>{d.properties.forEach(p=>{let m=hb.get(p.type);if(m){let _=!t||t(p.name)?new m(d.count):null;p.storage=_}})}),Vj(l)?await Wj(r,l,f):await Xj(r,l,f)))()},Kj=c=>!0,WE=class{constructor(t,e){n(this,"app");n(this,"maxRetries");this.app=t,this.maxRetries=e}async load(t,e,s){let i=this.app.scene?.gsplatCentersEnabled!==!1;try{let r=await(s.file?.contents??fetch(t.load));if(!r||!r.body)e("Error loading resource",null);else{let a=parseInt(r.headers.get("content-length")??"0",10),o=0,l=await Yj(r.body.getReader(),s.data.elementFilter??Kj,u=>{o+=u,s&&s.fire("progress",o,a)});s.fire("load:data",l),l.isCompressed||(s.data.reorder??!0)&&l.reorderData();let h=i,f=l.isCompressed&&!s.data.decompress?new HE(this.app.graphicsDevice,l,{prepareCenters:h}):new $o(this.app.graphicsDevice,l.isCompressed?l.decompress():l,{prepareCenters:h});e(null,f)}}catch(r){e(r,null)}}open(t,e){return e}};var jj=(c,t)=>{let e=new Map,s=t.length,i=()=>{let r=0,a=0;e.forEach(l=>{r+=l.loaded,a+=l.total});let o=e.size;o>0&&o{let a=(l,h)=>{e.set(r,{loaded:l,total:h}),i()},o=()=>{r.off("progress",a),r.off("load",o),r.off("error",o)};r.on("progress",a),r.on("load",o),r.on("error",o)})},qj=c=>{let t={version:1,count:c.means.shape[0],means:{mins:c.means.mins,maxs:c.means.maxs,files:c.means.files},scales:{mins:c.scales.mins,maxs:c.scales.maxs,files:c.scales.files},quats:{files:c.quats.files},sh0:{mins:c.sh0.mins,maxs:c.sh0.maxs,files:c.sh0.files}};return c.shN&&(t.shN={mins:c.shN.mins,maxs:c.shN.maxs,files:c.shN.files}),t},XE=class{constructor(t,e){n(this,"app");n(this,"maxRetries");this.app=t,this.maxRetries=e}_shouldAbort(t,e){return!!(e||!this.app.assets.get(t.id)||!this.app?.graphicsDevice||this.app.graphicsDevice._destroyed)}async loadTextures(t,e,s,i){let r=this.app.scene?.gsplatCentersEnabled!==!1;i.version!==2&&(i=qj(i));let{assets:a}=this.app,o=["means","quats","scales","sh0","shN"],l={},h=[],f=window.document?.baseURI??window.location.href;o.forEach(g=>{let T=i[g]?.files??[];l[g]=T.map(C=>{let v=new ae(C,"texture",{url:s.options?.mapUrl?.(C)??new URL(C,new URL(t.load,f).toString()).toString(),filename:C},{mipmaps:!1},{crossOrigin:"anonymous"}),E=new Promise((y,P)=>{v.on("load",()=>y(null)),v.on("error",A=>P(A))});return a.add(v),h.push(E),v})});let u=o.map(g=>l[g]).flat(),d=!1;if(s.once("unload",()=>{d=!0,u.forEach(g=>{a.remove(g),g.unload()})}),jj(s,u),u.forEach(g=>a.load(g)),await Promise.allSettled(h),this._shouldAbort(s,d)){u.forEach(g=>{a.remove(g),g.unload()}),e(null,null);return}let p=new ca;p.url=t.original,p.meta=i,p.numSplats=i.count,p.means_l=l.means[0].resource,p.means_u=l.means[1].resource,p.quats=l.quats[0].resource,p.scales=l.scales[0].resource,p.sh0=l.sh0[0].resource,p.sh_centroids=l.shN?.[0]?.resource,p.sh_labels=l.shN?.[1]?.resource,p.shBands=ca.calcBands(p.sh_centroids?.width);let m=s.data?.decompress;if(!m){if(this._shouldAbort(s,d)){p.destroy(),e(null,null);return}p.prepareCodebook(),r&&await p.prepareGpuData()}if(this._shouldAbort(s,d)){p.destroy(),e(null,null);return}let _=r,S=m?new $o(this.app.graphicsDevice,await p.decompress(),{prepareCenters:_}):new jc(this.app.graphicsDevice,p,{prepareCenters:_});if(this._shouldAbort(s,d)){S.destroy(),e(null,null);return}e(null,S)}load(t,e,s){if(s.data?.means)this.loadTextures(t,e,s,s.data);else{typeof t=="string"&&(t={load:t,original:t});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries,responseType:Vt.ResponseType.JSON};Le.get(t.load,i,(r,a)=>{if(this._shouldAbort(s,!1)){e(null,null);return}r?e(`Error loading gsplat meta: ${t.original} [${r}]`):this.loadTextures(t,e,s,a)})}}};var $j=c=>{let t=new DataView(c),e=f=>t.getUint16(f,!0),s=f=>t.getUint32(f,!0),i=f=>({magic:s(f),numFiles:e(f+8),cdSizeBytes:s(f+12),cdOffsetBytes:s(f+16)}),r=f=>{let u=e(f+28),d=e(f+30),p=e(f+32);return{magic:s(f),compressionMethod:e(f+10),compressedSizeBytes:s(f+20),uncompressedSizeBytes:s(f+24),lfhOffsetBytes:s(f+42),filename:new TextDecoder().decode(new Uint8Array(c,f+46,u)),recordSizeBytes:46+u+d+p}},a=f=>{let u=e(f+26),d=e(f+28);return{magic:s(f),offsetBytes:f+30+u+d}},o=i(t.byteLength-22);if(o.magic!==101010256)throw new Error("Invalid zip file: EOCDR not found");if(o.cdOffsetBytes===4294967295||o.cdSizeBytes===4294967295)throw new Error("Invalid zip file: Zip64 not supported");let l=[],h=o.cdOffsetBytes;for(let f=0;f{let t=new DecompressionStream("deflate-raw"),e=new Blob([c]).stream().pipeThrough(t),s=await new Response(e).arrayBuffer();return new Uint8Array(s)},Qj=async(c,t)=>{let e=await(t.file?.contents??fetch(c.load));if(!e)throw new Error("Error loading resource");if(e instanceof Response){if(!e.ok)throw new Error(`Error loading resource: ${e.status} ${e.statusText}`);let s=parseInt(e.headers.get("content-length")??"0",10);if(!e.body||!e.body.getReader){let o=await e.arrayBuffer();return t.fire("progress",o.byteLength,s),o}let i=e.body.getReader(),r=[],a=0;try{for(;;){let{done:o,value:l}=await i.read();if(o)break;r.push(l),a+=l.byteLength,t.fire("progress",a,s)}}finally{i.releaseLock()}return new Blob(r).arrayBuffer()}return e},YE=class{constructor(t,e=3){n(this,"app");n(this,"maxRetries");this.app=t,this.maxRetries=e}async load(t,e,s){let i=this.app.scene?.gsplatCentersEnabled!==!1;try{let r=await Qj(t,s),a=$j(r);for(let g of a)g.compression==="deflate"&&(g.data=await Zj(g.data));let o=a.find(g=>g.filename==="meta.json");if(!o){e("Error: meta.json not found");return}let l;try{l=JSON.parse(new TextDecoder().decode(o.data))}catch(g){e(`Error parsing meta.json: ${g}`);return}let h=["means","scales","quats","sh0","shN"].map(g=>l[g]?.files??[]).flat(),f={},u=[];for(let g of h){let T=a.find(E=>E.filename===g),C;if(T)C=new ae(g,"texture",{url:`${t.load}/${g}`,filename:g,contents:T.data},{mipmaps:!1},{crossOrigin:"anonymous"});else{let E=new URL(g,new URL(g,window.location.href).toString()).toString();C=new ae(g,"texture",{url:E,filename:g},{mipmaps:!1},{crossOrigin:"anonymous"})}let v=new Promise((E,y)=>{C.on("load",()=>E(null)),C.on("error",P=>y(P))});this.app.assets.add(C),f[g]=C,u.push(v)}Object.values(f).forEach(g=>this.app.assets.load(g)),await Promise.allSettled(u);let{assets:d}=this.app;s.once("unload",()=>{Object.values(f).forEach(g=>{d.remove(g),g.unload()})});let p=s.data?.decompress,m=new ca;m.url=t.original,m.meta=l,m.numSplats=l.count,m.means_l=f[l.means.files[0]].resource,m.means_u=f[l.means.files[1]].resource,m.quats=f[l.quats.files[0]].resource,m.scales=f[l.scales.files[0]].resource,m.sh0=f[l.sh0.files[0]].resource,m.sh_centroids=f[l.shN?.files[0]]?.resource,m.sh_labels=f[l.shN?.files[1]]?.resource,m.shBands=ca.calcBands(m.sh_centroids?.width),p||(m.prepareCodebook(),i&&await m.prepareGpuData());let _=i,S=p?new $o(this.app.graphicsDevice,await m.decompress(),{prepareCenters:_}):new jc(this.app.graphicsDevice,m,{prepareCenters:_});e(null,S)}catch(r){e(r)}}};var KE=class{load(t){}unload(t){}getResource(t){}destroy(){}};var jE=class extends KE{constructor(e){super();n(this,"_urlToAsset",new Map);n(this,"_registry");n(this,"maxConcurrentLoads",2);n(this,"maxRetries",2);n(this,"_currentlyLoading",new Set);n(this,"_loadQueue",[]);n(this,"_retryCount",new Map);n(this,"_destroyed",!1);this._registry=e}destroy(){this._destroyed=!0;for(let e of this._urlToAsset.values())e.fire("unload",e),e.off("load"),e.off("error"),this._registry.remove(e),e.unload();this._urlToAsset.clear(),this._loadQueue.length=0,this._currentlyLoading.clear(),this._retryCount.clear()}_canLoad(){return!!this._registry.loader?.getHandler("gsplat")}load(e){this._urlToAsset.get(e)?.loaded||this._currentlyLoading.has(e)||this._loadQueue.includes(e)||(this._currentlyLoading.sizethis._onAssetLoadSuccess(e,s)),s.once("error",i=>this._onAssetLoadError(e,s,i)),!s.loaded&&!s.loading&&this._registry.load(s)}_onAssetLoadSuccess(e,s){this._destroyed||!this._urlToAsset.has(e)||(this._currentlyLoading.delete(e),this._retryCount.delete(e),this._processQueue())}_onAssetLoadError(e,s,i){if(this._destroyed||!this._canLoad()||!this._urlToAsset.has(e))return;let r=this._retryCount.get(e)||0;r0;){let e=this._loadQueue.shift();e&&this._startLoading(e)}}unload(e){this._currentlyLoading.delete(e);let s=this._loadQueue.indexOf(e);s!==-1&&this._loadQueue.splice(s,1),this._retryCount.delete(e);let i=this._urlToAsset.get(e);i&&(i.fire("unload",i),i.off("load"),i.off("error"),this._registry.remove(i),i.unload(),this._urlToAsset.delete(e)),this._processQueue()}getResource(e){return this._urlToAsset.get(e)?.resource}};var qE=class{constructor(t,e){n(this,"app");n(this,"maxRetries");this.app=t,this.maxRetries=e}load(t,e,s){typeof t=="string"&&(t={load:t,original:t});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries,responseType:Vt.ResponseType.JSON};Le.get(t.load,i,(r,a)=>{if(r)e(`Error loading gsplat octree: ${t.original} [${r}]`);else{let o=new jE(this.app.assets),l=new d_(s.file.url,a,o);e(null,l)}})}};var D_=class extends Re{constructor(t){super(t,"gsplat"),this.parsers={ply:new WE(t,3),sog:new YE(t),json:new XE(t,3),octree:new qE(t,3)}}_getUrlWithoutParams(t){return t.indexOf("?")>=0?t.split("?")[0]:t}_getParser(t){let e=xe.getBasename(this._getUrlWithoutParams(t)).toLowerCase();if(e==="lod-meta.json")return this.parsers.octree;let s=xe.getExtension(e).replace(".","");return this.parsers[s]||this.parsers.ply}load(t,e,s){typeof t=="string"&&(t={load:t,original:t}),this._getParser(t.original).load(t,e,s)}open(t,e,s){return e}};var Fu=class{static setCompressedPRS(t,e,s){let i=s.singleVecs,r,a,o=e.___1;o||(r=s.tripleVecs,a=e.___2);let l=o?o[0]:r[a];t.setLocalPosition(i[l],i[l+1],i[l+2]),l=o?o[1]:r[a+1],t.setLocalEulerAngles(i[l],i[l+1],i[l+2]),l=o?o[2]:r[a+2],t.setLocalScale(i[l],i[l+1],i[l+2])}static oneCharToKey(t,e){let s=t.charCodeAt(0)-e.fieldFirstCode;return e.fieldArray[s]}static multCharToKey(t,e){let s=0;for(let i=0;i0,maxRetries:e},(i,r)=>{if(!i)s(i,r);else{let a=`Error while loading scene JSON ${t.original}`;i.message?(a+=`: ${i.message}`,i.stack&&(a+=` +${i.stack}`)):a+=`: ${i}`,s(a)}})}};var L_=class extends Re{constructor(t){super(t,"hierarchy")}load(t,e){Eh.load(t,this.maxRetries,e)}open(t,e){this._app.systems.script.preloading=!0;let i=new yh(this._app,!1).parse(e);return this._app.systems.script.preloading=!1,i}};var M_=class extends Re{constructor(e){super(e,"html");n(this,"decoder",null)}load(e,s){typeof e=="string"&&(e={load:e,original:e}),Le.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,r)=>{i?s(`Error loading html resource: ${e.original} [${i}]`):s(null,r)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}};var O_=class extends Re{constructor(e){super(e,"json");n(this,"decoder",null)}load(e,s){typeof e=="string"&&(e={load:e,original:e});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=Vt.ResponseType.JSON),Le.get(e.load,i,(r,a)=>{r?s(`Error loading JSON resource: ${e.original} [${r}]`):s(null,a)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),JSON.parse(this.decoder.decode(e))}};var ZE=class{constructor(){this.removeInvalid=!0,this.valid=!0,this.enumValidators={occludeSpecular:this._createEnumValidator([xT,Bo,vT]),cull:this._createEnumValidator([0,1,2,3]),blendType:this._createEnumValidator([rp,ea,ls,wt,Ms,ap,op,np,lp,cp,hp]),depthFunc:this._createEnumValidator([0,1,2,3,4,5,6,7])}}setInvalid(t,e){this.valid=!1,this.removeInvalid&&delete e[t]}validate(t){let e=Mc,s=WL,i=t.mappingFormat==="path";for(let r in t){let a=e[r];if(!a){s[r]?delete t[r]:this.valid=!1;continue}if(a.startsWith("enum")){let o=a.split(":")[1];this.enumValidators[o]&&(this.enumValidators[o](t[r])||this.setInvalid(r,t))}else if(a==="number")typeof t[r]!="number"&&this.setInvalid(r,t);else if(a==="boolean")typeof t[r]!="boolean"&&this.setInvalid(r,t);else if(a==="string")typeof t[r]!="string"&&this.setInvalid(r,t);else if(a==="vec2")t[r]instanceof Array&&t[r].length===2||this.setInvalid(r,t);else if(a==="rgb")t[r]instanceof Array&&t[r].length===3||this.setInvalid(r,t);else if(a==="texture")i?typeof t[r]=="string"||t[r]===null||t[r]instanceof Z||this.setInvalid(r,t):typeof t[r]=="number"||t[r]===null||t[r]instanceof Z||this.setInvalid(r,t);else if(a==="boundingbox")t[r].center&&t[r].center instanceof Array&&t[r].center.length===3||this.setInvalid(r,t),t[r].halfExtents&&t[r].halfExtents instanceof Array&&t[r].halfExtents.length===3||this.setInvalid(r,t);else if(a==="cubemap")typeof t[r]=="number"||t[r]===null||t[r]===void 0||t[r]instanceof Z&&t[r].cubemap||this.setInvalid(r,t);else if(a==="chunks"){let o=Object.keys(t[r]);for(let l=0;l=0}}};var F_=class{constructor(){this._validator=null}parse(t){let e=this.migrate(t),s=this._validate(e),i=new it;return this.initialize(i,s),i}initialize(t,e){if(e.validated||(e=this._validate(e)),e.chunks&&e.chunks&&Object.keys(e.chunks).length>0){let s=t.shaderChunks.glsl;Object.entries(e.chunks).forEach(([i,r])=>s.set(i,r))}for(let s in e){let i=Mc[s],r=e[s];if(i==="vec2")t[s]=new B(r[0],r[1]);else if(i==="rgb")t[s]=new F(r[0],r[1],r[2]);else if(i==="texture")r instanceof Z?t[s]=r:t[s]instanceof Z&&typeof r=="number"&&r>0||(t[s]=null);else if(i==="cubemap")r instanceof Z?t[s]=r:t[s]instanceof Z&&typeof r=="number"&&r>0||(t[s]=null),s==="cubeMap"&&!r&&(t.prefilteredCubemaps=null);else if(i==="boundingbox"){let a=new x(r.center[0],r.center[1],r.center[2]),o=new x(r.halfExtents[0],r.halfExtents[1],r.halfExtents[2]);t[s]=new ge(a,o)}else t[s]=e[s]}t.update()}migrate(t){t.shader&&delete t.shader,t.mapping_format&&(t.mappingFormat=t.mapping_format,delete t.mapping_format);let e,s=[["bumpMapFactor","bumpiness"],["aoUvSet","aoMapUv"],["aoMapVertexColor","aoVertexColor"],["diffuseMapVertexColor","diffuseVertexColor"],["emissiveMapVertexColor","emissiveVertexColor"],["specularMapVertexColor","specularVertexColor"],["metalnessMapVertexColor","metalnessVertexColor"],["opacityMapVertexColor","opacityVertexColor"],["glossMapVertexColor","glossVertexColor"],["lightMapVertexColor","lightVertexColor"],["specularMapTint","specularTint"],["metalnessMapTint","metalnessTint"],["clearCoatGlossiness","clearCoatGloss"]];for(e=0;e0,maxRetries:this.maxRetries},(s,i)=>{s?e&&e(`Error loading material: ${t.original} [${s}]`):e&&(i._engine=!0,e(null,i))})}open(t,e){let s=this._parser.parse(e);return e._engine&&(s._data=e,delete e._engine),s}patch(t,e){t.resource._data&&(t._data=t.resource._data,delete t.resource._data),t.data.name=t.name,t.resource.name=t.name,this._bindAndAssignAssets(t,e),t.off("unload",this._onAssetUnload,this),t.on("unload",this._onAssetUnload,this)}_onAssetUnload(t){delete t.data.parameters,delete t.data.chunks,delete t.data.name}_assignTexture(t,e,s){e.resource[t]=s}_getPlaceholderTexture(t){let e=Jj[t];return bo(this._device,e)}_assignPlaceholderTexture(t,e){e.resource[t]=this._getPlaceholderTexture(t)}_onTextureLoad(t,e,s){this._assignTexture(t,e,s.resource),e.resource.update()}_onTextureAdd(t,e,s){this._assets.load(s)}_onTextureRemoveOrUnload(t,e,s){let i=e.resource;i&&e.resource[t]===s.resource&&(this._assignPlaceholderTexture(t,e),i.update())}_assignCubemap(t,e,s){if(e.resource[t]=s[0],t==="cubeMap"){let i=s.slice(1);i.every(r=>r)?e.resource.prefilteredCubemaps=i:i[0]&&(e.resource.envAtlas=i[0])}}_onCubemapLoad(t,e,s){this._assignCubemap(t,e,s.resources),this._parser.initialize(e.resource,e.data)}_onCubemapAdd(t,e,s){this._assets.load(s)}_onCubemapRemoveOrUnload(t,e,s){let i=e.resource;e.data.prefilteredCubeMap128===s.resources[1]&&(this._assignCubemap(t,e,[null,null,null,null,null,null,null]),i.update())}_bindAndAssignAssets(t,e){let s=this._parser.migrate(t.data),i=t.resource,r=s.mappingFormat==="path",a=qf,o,l,h;for(o=0;o{if(i)e(i);else{let a=C_.createModel(r,this._defaultMaterial);r.destroy(),e(null,a)}})}};var eq={points:Aa,lines:Pn,lineloop:Eg,linestrip:mf,triangles:Yt,trianglestrip:Ks,trianglefan:dr},tq={int8:js,uint8:ai,int16:qs,uint16:Ri,int32:He,uint32:kt,float32:ye},JE=class{constructor(t){this._device=t.device,this._defaultMaterial=t.defaultMaterial}parse(t,e){let s=t.model;if(!s){e(null,null);return}if(s.version<=1){e("JsonModelParser#parse: Trying to parse unsupported model format.");return}let i=this._parseNodes(t),r=this._parseSkins(t,i),a=this._parseVertexBuffers(t),o=this._parseIndexBuffers(t,a),l=this._parseMorphs(t,i,a),h=this._parseMeshes(t,r.skins,l.morphs,a,o.buffer,o.data),f=this._parseMeshInstances(t,i,h,r.skins,r.instances,l.morphs,l.instances),u=new Ei;u.graph=i[0],u.meshInstances=f,u.skinInstances=r.instances,u.morphInstances=l.instances,u.getGraph().syncHierarchy(),e(null,u)}_parseNodes(t){let e=t.model,s=[],i;for(i=0;i0&&(l>65535?(i=new os(this._device,2,o),r=new Uint32Array(i.lock())):(i=new os(this._device,1,o),r=new Uint16Array(i.lock()))),{buffer:i,data:r}}_parseMeshes(t,e,s,i,r,a){let o=t.model,l=[],h=0;for(let f=0;fxe.getExtension(e)===".json"),this.addParser(new QE(this),(e,s)=>xe.getExtension(e)===".glb")}load(t,e,s){typeof t=="string"&&(t={load:t,original:t});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};(t.load.startsWith("blob:")||t.load.startsWith("data:"))&&(xe.getExtension(t.original).toLowerCase()===".glb"?i.responseType=Vt.ResponseType.ARRAY_BUFFER:i.responseType=Vt.ResponseType.JSON),Le.get(t.load,i,(r,a)=>{if(e)if(r)e(`Error loading model: ${t.original} [${r}]`);else{for(let o=0;o{h?e(h):e(null,f)},s);return}}e("No parsers found")}})}open(t,e){return e}patch(t,e){if(!t.resource)return;let s=t.data,i=this;t.resource.meshInstances.forEach((r,a)=>{if(s.mapping){let o=function(u){u.resource?r.material=u.resource:(u.once("load",o),e.load(u)),u.once("remove",d=>{r.material===d.resource&&(r.material=i.defaultMaterial)})};if(!s.mapping[a]){r.material=i.defaultMaterial;return}let l=s.mapping[a].material,h=s.mapping[a].path,f;if(l!==void 0)l?(f=e.get(l),f?o(f):e.once(`add:${l}`,o)):r.material=i.defaultMaterial;else if(h){let u=t.getAbsoluteUrl(s.mapping[a].path);f=e.getByUrl(u),f?o(f):e.once(`add:url:${u}`,o)}}})}addParser(t,e){this._parsers.push({parser:t,decider:e})}};var U_=class extends Re{constructor(t){super(t,"scene")}load(t,e){Eh.load(t,this.maxRetries,e)}open(t,e){this._app.systems.script.preloading=!0;let i=new yh(this._app,!1).parse(e),r=this._app.scene;return r.root=i,this._app.applySceneSettings(e.settings),this._app.systems.script.preloading=!1,r}};var eA=class eA{static push(t){eA._types.push(t)}};n(eA,"_types",[]);var Rl=eA;function PG(){return gm}function ub(c,t){if(gm.has(c))throw new Error(`Script name '${c}' is reserved, please rename the script`);let e=function(s){J.prototype.initEventHandler.call(this),Mr.prototype.initScriptType.call(this,s)};return e.prototype=Object.create(Mr.prototype),e.prototype.constructor=e,e.extend=Mr.extend,e.attributes=new ao(e),ax(e,c,t),e}var wG={};ao.reservedNames.forEach((c,t,e)=>{wG[c]=1});ub.reservedAttributes=wG;function ax(c,t,e){if(typeof c!="function")throw new Error(`script class: '${c}' must be a constructor function (i.e. class).`);if(!(c.prototype instanceof ks))throw new Error(`script class: '${Mr.__getScriptName(c)}' does not extend pc.Script.`);if(t=t||Qc(c),!t)return;if(gm.has(t))throw new Error(`script name: '${t}' is reserved, please change script name`);c.__name=t,(e?e.scripts:Pi.getApplication().scripts).add(c),Rl.push(c)}var k_=class extends Re{constructor(t){super(t,"script"),this._scripts={},this._cache={}}clearCache(){for(let t in this._cache){let e=this._cache[t],s=e.parentNode;s&&s.removeChild(e)}this._cache={}}load(t,e){typeof t=="string"&&(t={load:t,original:t});let s=this;fm.app=this._app;let i=(t.load,(o,l,h)=>{if(o)e(o);else{let f={};for(let d=0;d{e(`Script: ${a.target.src} failed to load`)},!1);let r=!1;i.onload=i.onreadystatechange=function(){!r&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")&&(r=!0,e(null,t,i))},i.src=t,s.appendChild(i)}_loadModule(t,e){let i=ue.browser&&window.location.origin!=="null"?window.location.origin+window.location.pathname:typeof document>"u"&&typeof location>"u"?EC("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("playcanvas.min.js",document.baseURI).href,r=new URL(t,i);new Function("modulePath","return import(modulePath)")(r.toString()).then(a=>{let o=r.pathname.split("/").pop(),l=this._app.assets.find(o,"script")?.data?.scripts;for(let h in a){let f=a[h];if(f.prototype instanceof ks){let d=Object.prototype.hasOwnProperty.call(f,"scriptName")&&f.scriptName,p=Qc(f);if(!p)continue;ax(f,p),l&&this._app.scripts.addSchema(p,l[p])}}e(null,t,null)}).catch(a=>{e(a)})}};var z_=class extends Re{constructor(e){super(e,"shader");n(this,"decoder",null)}load(e,s){typeof e=="string"&&(e={load:e,original:e}),Le.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,r)=>{i?s(`Error loading shader resource: ${e.original} [${i}]`):s(null,r)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}};function db(c){let t=this;t.resource&&(t.resource.atlas=c.resource)}function pb(c){this.registry.load(c)}var G_=class extends Re{constructor(t){super(t,"sprite"),this._assets=t.assets,this._device=t.graphicsDevice}load(t,e){typeof t=="string"&&(t={load:t,original:t}),xe.getExtension(t.original)===".json"&&Le.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(s,i)=>{s?e(s):e(null,i)})}open(t,e){let s=new Qp(this._device);return t&&(s.__data=e),s}patch(t,e){let s=t.resource;if(s.__data&&(t.data.pixelsPerUnit=s.__data.pixelsPerUnit,t.data.renderMode=s.__data.renderMode,t.data.frameKeys=s.__data.frameKeys,s.__data.textureAtlasAsset)){let i=e.getByUrl(s.__data.textureAtlasAsset);i&&(t.data.textureAtlasAsset=i.id)}s.startUpdate(),s.renderMode=t.data.renderMode,s.pixelsPerUnit=t.data.pixelsPerUnit,s.frameKeys=t.data.frameKeys,this._updateAtlas(t),s.endUpdate(),t.off("change",this._onAssetChange,this),t.on("change",this._onAssetChange,this)}_updateAtlas(t){let e=t.resource;if(!t.data.textureAtlasAsset){e.atlas=null;return}this._assets.off(`load:${t.data.textureAtlasAsset}`,db,t),this._assets.on(`load:${t.data.textureAtlasAsset}`,db,t);let s=this._assets.get(t.data.textureAtlasAsset);s&&s.resource?e.atlas=s.resource:s?this._assets.load(s):(this._assets.off(`add:${t.data.textureAtlasAsset}`,pb,t),this._assets.on(`add:${t.data.textureAtlasAsset}`,pb,t))}_onAssetChange(t,e,s,i){e==="data"&&s&&s.textureAtlasAsset&&i&&s.textureAtlasAsset!==i.textureAtlasAsset&&(this._assets.off(`load:${i.textureAtlasAsset}`,db,t),this._assets.off(`add:${i.textureAtlasAsset}`,pb,t))}};var Nu=class{constructor(t,e){n(this,"_app");n(this,"_data");n(this,"_templateRoot",null);this._app=t,this._data=e}instantiate(){return this._templateRoot||this._parseTemplate(),this._templateRoot.clone()}_parseTemplate(){let t=new yh(this._app,!0);this._templateRoot=t.parse(this._data)}set data(t){this._data=t,this._templateRoot=null}get data(){return this._data}};var V_=class extends Re{constructor(e){super(e,"template");n(this,"decoder",null)}load(e,s){typeof e=="string"&&(e={load:e,original:e});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};Le.get(e.load,i,(r,a)=>{r?s(`Error requesting template: ${e.original}`):s(r,a)})}open(e,s){return new Nu(this._app,s)}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),new Nu(this._app,JSON.parse(this.decoder.decode(e)))}patch(e,s){if(!e||!e.resource||!e.data||!e.data.entities)return;let i=e.resource;i.data=e.data}};var H_=class extends Re{constructor(e){super(e,"text");n(this,"decoder",null)}load(e,s){typeof e=="string"&&(e={load:e,original:e}),Le.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,r)=>{i?s(`Error loading text resource: ${e.original} [${i}]`):s(null,r)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}};var tA={repeat:0,clamp:1,mirror:2},sA={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},sq=/^data\.frames\.(\d+)$/,W_=class extends Re{constructor(t){super(t,"textureatlas"),this._loader=t.loader}load(t,e){typeof t=="string"&&(t={load:t,original:t});let s=this,i=this._loader.getHandler("texture");xe.getExtension(t.original)===".json"?Le.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(r,a)=>{if(r)e(r);else{let o=t.original.replace(".json",".png");s._loader.load(o,"texture",(l,h)=>{l?e(l):e(null,{data:a,texture:h})})}}):i.load(t,e)}open(t,e,s){let i=new Jp;if(e.texture&&e.data)i.texture=e.texture,i.__data=e.data;else{let a=this._loader.getHandler("texture").open(t,e,s);if(!a)return null;i.texture=a}return i}patch(t,e){if(!t.resource)return;t.resource.__data&&(t.resource.__data.minfilter!==void 0&&(t.data.minfilter=t.resource.__data.minfilter),t.resource.__data.magfilter!==void 0&&(t.data.magfilter=t.resource.__data.magfilter),t.resource.__data.addressu!==void 0&&(t.data.addressu=t.resource.__data.addressu),t.resource.__data.addressv!==void 0&&(t.data.addressv=t.resource.__data.addressv),t.resource.__data.mipmaps!==void 0&&(t.data.mipmaps=t.resource.__data.mipmaps),t.resource.__data.anisotropy!==void 0&&(t.data.anisotropy=t.resource.__data.anisotropy),t.resource.__data.rgbm!==void 0&&(t.data.rgbm=!!t.resource.__data.rgbm),t.data.frames=t.resource.__data.frames,delete t.resource.__data);let s=t.resource.texture;if(s&&(s.name=t.name,t.data.hasOwnProperty("minfilter")&&s.minFilter!==sA[t.data.minfilter]&&(s.minFilter=sA[t.data.minfilter]),t.data.hasOwnProperty("magfilter")&&s.magFilter!==sA[t.data.magfilter]&&(s.magFilter=sA[t.data.magfilter]),t.data.hasOwnProperty("addressu")&&s.addressU!==tA[t.data.addressu]&&(s.addressU=tA[t.data.addressu]),t.data.hasOwnProperty("addressv")&&s.addressV!==tA[t.data.addressv]&&(s.addressV=tA[t.data.addressv]),t.data.hasOwnProperty("mipmaps")&&s.mipmaps!==t.data.mipmaps&&(s.mipmaps=t.data.mipmaps),t.data.hasOwnProperty("anisotropy")&&s.anisotropy!==t.data.anisotropy&&(s.anisotropy=t.data.anisotropy),t.data.hasOwnProperty("rgbm"))){let r=t.data.rgbm?_i:Gt;s.type!==r&&(s.type=r)}t.resource.texture=s;let i={};for(let r in t.data.frames){let a=t.data.frames[r];i[r]={rect:new Q(a.rect),pivot:new B(a.pivot),border:new Q(a.border)}}t.resource.frames=i,t.off("change",this._onAssetChange,this),t.on("change",this._onAssetChange,this)}_onAssetChange(t,e,s){let i;if(e==="data"||e==="data.frames"){let r={};for(let a in s.frames)i=s.frames[a],r[a]={rect:new Q(i.rect),pivot:new B(i.pivot),border:new Q(i.border)};t.resource.frames=r}else{let r=e.match(sq);if(r){let a=r[1];s?(t.resource.frames[a]?(i=t.resource.frames[a],i.rect.set(s.rect[0],s.rect[1],s.rect[2],s.rect[3]),i.pivot.set(s.pivot[0],s.pivot[1]),i.border.set(s.border[0],s.border[1],s.border[2],s.border[3])):t.resource.frames[a]={rect:new Q(s.rect),pivot:new B(s.pivot),border:new Q(s.border)},t.resource.fire("set:frame",a,t.resource.frames[a])):t.resource.frames[a]&&(delete t.resource.frames[a],t.resource.fire("remove:frame",a))}}}};function IG(){let c={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFATC_RGB:11,cTFATC_RGBA_INTERPOLATED_ALPHA:12,cTFRGBA32:13,cTFRGB565:14,cTFRGBA4444:16},t={astc:c.cTFASTC_4x4,dxt:c.cTFBC1,etc1:c.cTFETC1,etc2:c.cTFETC1,pvr:c.cTFPVRTC1_4_RGB,atc:c.cTFATC_RGB,none:c.cTFRGB565},e={astc:c.cTFASTC_4x4,dxt:c.cTFBC3,etc1:c.cTFRGBA4444,etc2:c.cTFETC2,pvr:c.cTFPVRTC1_4_RGBA,atc:c.cTFATC_RGBA_INTERPOLATED_ALPHA,none:c.cTFRGBA4444},s={ETC1:21,ETC2_RGB:22,ETC2_RGBA:23,DXT1:8,DXT5:10,PVRTC_4BPP_RGB_1:26,PVRTC_4BPP_RGBA_1:27,ASTC_4x4:28,ATC_RGB:29,ATC_RGBA:30,R8_G8_B8_A8:7,R5_G6_B5:3,R4_G4_B4_A4:5},i=(v,E)=>{switch(v){case c.cTFETC1:return E.formats.etc2?s.ETC2_RGB:s.ETC1;case c.cTFETC2:return s.ETC2_RGBA;case c.cTFBC1:return s.DXT1;case c.cTFBC3:return s.DXT5;case c.cTFPVRTC1_4_RGB:return s.PVRTC_4BPP_RGB_1;case c.cTFPVRTC1_4_RGBA:return s.PVRTC_4BPP_RGBA_1;case c.cTFASTC_4x4:return s.ASTC_4x4;case c.cTFATC_RGB:return s.ATC_RGB;case c.cTFATC_RGBA_INTERPOLATED_ALPHA:return s.ATC_RGBA;case c.cTFRGBA32:return s.R8_G8_B8_A8;case c.cTFRGB565:return s.R5_G6_B5;case c.cTFRGBA4444:return s.R4_G4_B4_A4}},r=v=>{let E=function(y,P){let A=y*.00784313725490196-1,w=P*(2/255)-1,I=Math.sqrt(1-Math.min(1,A*A+w*w));return Math.max(0,Math.min(255,Math.floor((I+1)*.5*255)))};for(let y=0;y{let E=new Uint16Array(v.length/4);for(let y=0;y>3}return E},o=(v,E)=>(v&v-1)===0&&(E&E-1)===0,l=()=>typeof performance<"u"?performance.now():0,h,f,u,d=(v,E,y)=>{if(y){if(v.formats.astc)return"astc"}else if(E){if(v.formats.etc2)return"etc2"}else{if(v.formats.etc2)return"etc2";if(v.formats.etc1)return"etc1"}return(A=>{for(let w=0;w{switch(y){case c.cTFETC1:case c.cTFETC2:return!0;case c.cTFBC1:case c.cTFBC3:return(v&3)===0&&(E&3)===0;case c.cTFPVRTC1_4_RGB:case c.cTFPVRTC1_4_RGBA:return o(v,E);case c.cTFASTC_4x4:return!0;case c.cTFATC_RGB:case c.cTFATC_RGBA_INTERPOLATED_ALPHA:return!0}return!1},m=(v,E,y)=>{if(!h.KTX2File)throw new Error("Basis transcoder module does not include support for KTX2.");let P=l(),A=new h.KTX2File(new Uint8Array(E)),w=A.getWidth(),I=A.getHeight(),D=A.getLevels(),O=!!A.getHasAlpha(),G=A.isUASTC&&A.isUASTC();if(!w||!I||!D)throw A.close(),A.delete(),new Error(`Invalid image dimensions url=${v} width=${w} height=${I} levels=${D}`);let M=d(y.deviceDetails,O,G),H=!!y.isGGGR&&M==="pvr",U;if(H?U=c.cTFRGBA32:(U=O?e[M]:t[M],p(w,I,U)||(U=O?c.cTFRGBA32:c.cTFRGB565)),!A.startTranscoding())throw A.close(),A.delete(),new Error(`Failed to start transcoding url=${v}`);let L,b=[];for(let N=0;N{let P=l(),A=new h.BasisFile(new Uint8Array(E)),w=A.getImageWidth(0,0),I=A.getImageHeight(0,0),D=A.getNumImages(),O=A.getNumLevels(0),G=!!A.getHasAlpha(),M=A.isUASTC&&A.isUASTC();if(!w||!I||!D||!O)throw A.close(),A.delete(),new Error(`Invalid image dimensions url=${v} width=${w} height=${I} images=${D} levels=${O}`);let H=d(y.deviceDetails,G,M),U=!!y.isGGGR&&H==="pvr",L;if(U?L=c.cTFRGBA32:(L=G?e[H]:t[H],p(w,I,L)||(L=G?c.cTFRGBA32:c.cTFRGB565)),!A.startTranscoding())throw A.close(),A.delete(),new Error(`Failed to start transcoding url=${v}`);let b,N=[];for(let k=0;ky.isKTX2?m(v,E,y):_(v,E,y),g=(v,E,y)=>{try{let P=S(v,E,y);P.levels=P.levels.map(A=>A.buffer),self.postMessage({url:v,data:P},P.levels)}catch(P){self.postMessage({url:v,err:P},null)}},T=(v,E)=>{let y=(P,A)=>(WebAssembly.instantiate(v.module,P).then(w=>{A(w)}).catch(w=>{}),{});self.BASIS(v.module?{instantiateWasm:y}:null).then(P=>{P.initializeBasis(),h=P,f=v.rgbPriority,u=v.rgbaPriority,E(null)})},C=[];self.onmessage=v=>{let E=v.data;switch(E.type){case"init":T(E.config,()=>{for(let y=0;y({astc:!!c.extCompressedTextureASTC,atc:!!c.extCompressedTextureATC,dxt:!!c.extCompressedTextureS3TC,etc1:!!c.extCompressedTextureETC1,etc2:!!c.extCompressedTextureETC,pvr:!!c.extCompressedTexturePVRTC}),rq=(c,t)=>{let e=a=>{let o=["/* basis */",a,"",`(${IG.toString()})() -`].join("\n")],{type:"application/javascript"})),module:s,rgbPriority:e.rgbPriority,rgbaPriority:e.rgbaPriority});},s={cache:true,responseType:"text",retry:e.maxRetries>0,maxRetries:e.maxRetries};if(e.glueUrl&&e.wasmUrl&&(()=>{try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){let e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}return false})()){let r=null,a=null;a0.get(e.glueUrl,s,(e,s)=>{e?t(e):a?i(s,a):r=s;});let n=fetch(e.wasmUrl),o=()=>{n.then(e=>e.arrayBuffer()).then(e=>WebAssembly.compile(e)).then(e=>{r?i(r,e):a=e;}).catch(e=>{t(e,null);});};WebAssembly.compileStreaming?WebAssembly.compileStreaming(n).then(e=>{r?i(r,e):a=e;}).catch(e=>{o();}):o();}else a0.get(e.fallbackUrl,s,(e,s)=>{e?t(e,null):i(s,null);});})(e,(e,s)=>{if(e);else for(let e=0;e{if(r)t(r);else T_(s,e.load,a,t,{isGGGR:(i?.file?.variants?.basis?.opt&8)!=0})||t(`Basis module not found. Asset [${i.name}](${i.getFileUrl()}) basis texture variant will not be loaded.`);},i,this.maxRetries);}open(e,t,i,s={}){let r=s.srgb?e3(t.format):t.format,a=new ic(i,{name:e,addressU:+!!t.cubemap,addressV:+!!t.cubemap,width:t.width,height:t.height,format:r,cubemap:t.cubemap,levels:t.levels,...s});return a.upload(),a}constructor(e,t){super(),this.device=t,this.maxRetries=0;}}class TS extends Tg{load(e,t,i){let s,r=!!i?.file?.contents;if(r){if(this.device.supportsImageBitmap)return void this._loadImageBitmapFromBlob(new Blob([i.file.contents]),t);e={load:URL.createObjectURL(new Blob([i.file.contents])),original:e.original};}let a=(i,s)=>{r&&URL.revokeObjectURL(e.load),t(i,s);};i&&i.options&&i.options.hasOwnProperty("crossOrigin")?s=i.options.crossOrigin:fz.test(e.load)&&(s=this.crossOrigin),this.device.supportsImageBitmap?this._loadImageBitmap(e.load,e.original,s,a,i):this._loadImage(e.load,e.original,s,a,i);}open(e,t,i,s={}){let r=new ic(i,{name:e,width:t.width,height:t.height,format:s.srgb?20:7,...s});return r.setSource(t),r}_loadImage(e,t,i,s,r){let a,n=new Image;i&&(n.crossOrigin=i);let o=0,l=this.maxRetries;r?.fire("progress",0,1048576),n.onload=function(){r?.fire("progress",1048576,1048576),s(null,n);},n.onerror=function(){if(!a)if(l>0&&++o<=l){let t=100*Math.pow(2,o),i=e.indexOf("?")>=0?"&":"?";a=setTimeout(()=>{n.src=`${e+i}retry=${Date.now()}`,a=null;},t);}else s(`Error loading Texture from: '${t}'`);},n.src=e;}_loadImageBitmap(e,t,i,s,r){let a={cache:true,responseType:"blob",retry:this.maxRetries>0,maxRetries:this.maxRetries,progress:r};a0.get(e,a,(e,t)=>{e?s(e):this._loadImageBitmapFromBlob(t,s);});}_loadImageBitmapFromBlob(e,t){createImageBitmap(e,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(e=>t(null,e)).catch(e=>t(e));}constructor(e,t){super(),this.crossOrigin=e.prefix?"anonymous":null,this.maxRetries=0,this.device=t;}}let Ty={33776:8,33778:9,33779:10,36196:21,37492:22,37496:23,35840:26,35841:24,35842:27,35843:25,32849:6,32856:7,35905:19,35907:20,35898:18,34843:11,34842:12};class Tx extends Tg{load(e,t,i){fX.fetchArrayBuffer(e.load,t,i,this.maxRetries);}open(e,t,i,s={}){let r=this.parse(t);if(!r)return null;let a=s.srgb?e3(r.format):r.format,n=new ic(i,{name:e,addressU:+!!r.cubemap,addressV:+!!r.cubemap,width:r.width,height:r.height,format:a,cubemap:r.cubemap,levels:r.levels,...s});return n.upload(),n}parse(e){let t=new Uint32Array(e);if(0x58544bab!==t[0]||0xbb313120!==t[1]||0xa1a0a0d!==t[2])return null;let i={endianness:t[3],glType:t[4],glTypeSize:t[5],glFormat:t[6],glInternalFormat:t[7],glBaseInternalFormat:t[8],pixelWidth:t[9],pixelHeight:t[10],pixelDepth:t[11],numberOfArrayElements:t[12],numberOfFaces:t[13],numberOfMipmapLevels:t[14],bytesOfKeyValueData:t[15]};if(i.pixelDepth>1||0!==i.numberOfArrayElements)return null;let s=Ty[i.glInternalFormat];if(void 0===s)return null;let r=16+i.bytesOfKeyValueData/4,a=i.numberOfFaces>1,n=[];for(let l=0;l<(i.numberOfMipmapLevels||1);l++){let i=t[r++];a&&n.push([]);let h=a?n[l]:n;for(let t=0;t<(a?6:1);++t){var o;h.push((o=4*r,18===s?new Uint32Array(e,o,i/4):new Uint8Array(e,o,i))),r+=i+3>>2;}}return {format:s,width:i.pixelWidth,height:i.pixelHeight,levels:n,cubemap:a}}constructor(e){super(),this.maxRetries=0;}}class TT extends Tg{load(e,t,i){fX.fetchArrayBuffer(e.load,(s,r)=>{s?t(s,r):this.parse(r,e,t,i);},i,this.maxRetries);}open(e,t,i,s={}){let r=s.srgb?e3(t.format):t.format,a=new ic(i,{name:e,addressU:+!!t.cubemap,addressV:+!!t.cubemap,width:t.width,height:t.height,format:r,cubemap:t.cubemap,levels:t.levels,...s});return a.upload(),a}parse(e,t,i,s){let r=new K(e),a=[r.readU32be(),r.readU32be(),r.readU32be()];if(0xab4b5458!==a[0]||0x203230bb!==a[1]||0xd0a1a0a!==a[2])return null;let n={vkFormat:r.readU32(),typeSize:r.readU32(),pixelWidth:r.readU32(),pixelHeight:r.readU32(),pixelDepth:r.readU32(),layerCount:r.readU32(),faceCount:r.readU32(),levelCount:r.readU32(),supercompressionScheme:r.readU32()},o={dfdByteOffset:r.readU32(),dfdByteLength:r.readU32(),kvdByteOffset:r.readU32(),kvdByteLength:r.readU32(),sgdByteOffset:r.readU64(),sgdByteLength:r.readU64()},l=[];for(let e=0;e1,...s});let y=128,x=f?6:1,T=0x31545844===d?8:16;for(let e=0;e32767)return this._readPixelsFlat(e,t,i);let c=[0,0,0,0];if(e.readArray(c),2!==c[0]||2!==c[1]||(128&c[2])!=0)return e.skip(-4),this._readPixelsFlat(e,t,i);let d=new Uint8Array(new ArrayBuffer(t*i*4)),u=s?0:4*t*(i-1);for(a=0;a128){if(r+(l-=128)>t)return null;for(n=0,h=e.readU8();nt)return null;for(n=0;n>1),r=Math.max(1,t>>1),a=new i.constructor(s*r*4),n=Math.floor(e/s),o=Math.floor(t/r),l=n*o;for(let t=0;t>t-1),r=Math.max(1,e._height>>t-1);if(e._cubemap){let a=[];for(let n=0;n<6;++n)a.push(s(i,r,e._levels[t-1][n]));e._levels.push(a);}else e._levels.push(s(i,r,e._levels[t-1]));}e._levelsUpdated=e._cubemap?[[true,true,true,true,true,true]]:[true];};class TI extends fQ{set crossOrigin(e){this.imgParser.crossOrigin=e;}get crossOrigin(){return this.imgParser.crossOrigin}set maxRetries(e){for(let t in this.imgParser.maxRetries=e,this.parsers)this.parsers.hasOwnProperty(t)&&(this.parsers[t].maxRetries=e);}get maxRetries(){return this.imgParser.maxRetries}_getUrlWithoutParams(e){return e.indexOf("?")>=0?e.split("?")[0]:e}_getParser(e){let t=P.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".","");return this.parsers[t]||this.imgParser}_getTextureOptions(e){let t={};if(e){e.name?.length>0&&(t.name=e.name);let i=e.data;i.hasOwnProperty("minfilter")&&(t.minFilter=TC[i.minfilter]),i.hasOwnProperty("magfilter")&&(t.magFilter=TC[i.magfilter]),i.hasOwnProperty("addressu")&&(t.addressU=Tb[i.addressu]),i.hasOwnProperty("addressv")&&(t.addressV=Tb[i.addressv]),i.hasOwnProperty("mipmaps")&&(t.mipmaps=i.mipmaps),i.hasOwnProperty("anisotropy")&&(t.anisotropy=i.anisotropy),i.hasOwnProperty("flipY")&&(t.flipY=!!i.flipY),i.hasOwnProperty("srgb")&&(t.srgb=!!i.srgb),t.type=tP,i.hasOwnProperty("type")?t.type=TA[i.type]:i.hasOwnProperty("rgbm")&&i.rgbm?t.type=tI:e.file&&(8&e.file.opt)!=0&&(t.type=tL);}return t}load(e,t,i){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,i);}open(e,t,i){if(!e)return;let s=this._getTextureOptions(i),r=this._getParser(e).open(e,t,this._device,s);return null===r?r=new ic(this._device,{width:4,height:4,format:6}):(TP(r),t.unswizzledGGGR&&(i.file.variants.basis.opt&=-9)),r}patch(e,t){let i=e.resource;if(!i)return;let s=this._getTextureOptions(e);for(let e of Object.keys(s))i[e]=s[e];}constructor(e){super(e,"texture");let t=e.assets,i=e.graphicsDevice;this._device=i,this._assets=t,this.imgParser=new TS(t,i),this.parsers={dds:new TE(t),ktx:new Tx(t),ktx2:new TT(t,i),basis:new Tv(t,i),hdr:new Tw(t)};}}let TD="inline",TR="immersive-vr",TL="immersive-ar",TM="viewer",TO="left",TF="cpu-optimized",TN="gpu-optimized",TB="luminance-alpha",Tk="unsigned-short",TU="float32";class Tz{get supported(){return this._supported}get available(){return this._supported&&this._manager.active&&null!==this._manager._session.domOverlayState}get state(){return this._supported&&this._manager.active&&this._manager._session.domOverlayState?this._manager._session.domOverlayState.type:null}set root(e){this._supported&&!this._manager.active&&(this._root=e);}get root(){return this._root}constructor(e){this._supported=k.browser&&!!window.XRDOMOverlayState,this._root=null,this._manager=e;}}let TV=[],TG=[];class TH extends X{remove(){if(!this._xrHitTestSource)return;let e=this.manager.hitTest.sources,t=e.indexOf(this);-1!==t&&e.splice(t,1),this.onStop();}onStop(){this._xrHitTestSource.cancel(),this._xrHitTestSource=null,this.fire("remove"),this.manager.hitTest.fire("remove",this);}update(e){if(this._transient){let t=e.getHitTestResultsForTransientInput(this._xrHitTestSource);for(let e=0;e=s||(s=l,r=e[t],a.copy(o.transform.position),n.copy(o.transform.orientation));}this.fire("result",a,n,t||this._inputSource,r),this.manager.hitTest.fire("result",this,a,n,t||this._inputSource,r),TV.push(i),TV.push(a),TG.push(n);}constructor(e,t,i,s=null){super(),this.manager=e,this._xrHitTestSource=t,this._transient=i,this._inputSource=s;}}TH.EVENT_REMOVE="remove",TH.EVENT_RESULT="result";class TW extends X{_onSessionStart(){if(this.manager.session.enabledFeatures){let e=-1!==this.manager.session.enabledFeatures.indexOf("hit-test");e&&(this._available=e,this.fire("available"));}else this._checkingAvailability||(this._checkingAvailability=true,this.manager.session.requestReferenceSpace(TM).then(e=>{this.manager.session.requestHitTestSource({space:e}).then(e=>{e.cancel(),this.manager.active&&(this._available=true,this.fire("available"));}).catch(()=>{});}).catch(()=>{}));}_onSessionEnd(){if(this._available){this._available=false;for(let e=0;e{if(!this.manager.session){let e=Error("XR Session is not started (2)");s&&s(e),this.fire("error",e);return}this.manager.session.requestHitTestSource({space:i,entityTypes:e.entityTypes||void 0,offsetRay:t}).then(t=>{this._onHitTestSource(t,false,e.inputSource,s);}).catch(e=>{s&&s(e),this.fire("error",e);});}).catch(e=>{s&&s(e),this.fire("error",e);}):this.manager.session.requestHitTestSourceForTransientInput({profile:e.profile,entityTypes:e.entityTypes||void 0,offsetRay:t}).then(t=>{this._onHitTestSource(t,true,e.inputSource,s);}).catch(e=>{s&&s(e),this.fire("error",e);});}_onHitTestSource(e,t,i,s){if(!this.manager.session){e.cancel();let t=Error("XR Session is not started (3)");s&&s(t),this.fire("error",t);return}let r=new TH(this.manager,e,t,i??null);this.sources.push(r),s&&s(null,r),this.fire("add",r);}update(e){if(this._available)for(let t=0;t(this._bitmap=e,{image:this._bitmap,widthInMeters:this._width}))}destroy(){this._image=null,this._pose=null,this._bitmap&&(this._bitmap.close(),this._bitmap=null);}getPosition(){return this._pose&&this._position.copy(this._pose.transform.position),this._position}getRotation(){return this._pose&&this._rotation.copy(this._pose.transform.orientation),this._rotation}constructor(e,t){super(),this._bitmap=null,this._measuredWidth=0,this._trackable=false,this._tracking=false,this._emulated=false,this._pose=null,this._position=new ed,this._rotation=new ex,this._image=e,this._width=t;}}TX.EVENT_TRACKED="tracked",TX.EVENT_UNTRACKED="untracked";class TY extends X{add(e,t){if(!this._supported||this._manager.active)return null;let i=new TX(e,t);return this._images.push(i),i}remove(e){if(this._manager.active)return;let t=this._images.indexOf(e);-1!==t&&(e.destroy(),this._images.splice(t,1));}_onSessionStart(){this._manager.session.getTrackedImageScores().then(e=>{this._available=true;for(let t=0;t{this._available=false,this.fire("error",e);});}_onSessionEnd(){this._available=false;for(let e=0;ee.prepare())).then(t=>{e(null,t);}).catch(t=>{e(t,null);}):e(null,null);}update(e){if(!this._available)return;let t=e.getImageTrackingResults(),i={};for(let s=0;sTQ.dot(TJ)}getJointById(e){return this._jointsById[e]||null}get fingers(){return this._fingers}get joints(){return this._joints}get tips(){return this._tips}get wrist(){return this._wrist}get tracking(){return this._tracking}constructor(e){super(),this._tracking=false,this._fingers=[],this._joints=[],this._jointsById={},this._tips=[],this._wrist=null;let t=e._xrInputSource.hand;if(this._manager=e._manager,this._inputSource=e,t.get("wrist")){let e=new T$(0,"wrist",this,null);this._wrist=e,this._joints.push(e),this._jointsById.wrist=e;}for(let e=0;e0&&(T2.sub2(this._localPosition,this._localPositionLast).divScalar(t),this._linearVelocity.lerp(this._linearVelocity,T2,.15));}else this._velocitiesAvailable=false;}let i=e.getPose(this._xrInputSource.targetRaySpace,this._manager._referenceSpace);i&&(this._dirtyRay=true,this._rayLocal.origin.copy(i.transform.position),this._rayLocal.direction.set(0,0,-1),T3.copy(i.transform.orientation),T3.transformVector(this._rayLocal.direction,this._rayLocal.direction));}}_updateTransforms(){this._dirtyLocal&&(this._dirtyLocal=false,this._localTransform.setTRS(this._localPosition,this._localRotation,ed.ONE));let e=this._manager.camera.parent;e?this._worldTransform.mul2(e.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform);}_updateRayTransforms(){let e=this._dirtyRay;this._dirtyRay=false;let t=this._manager.camera.parent;if(t){let e=t.getWorldTransform();e.getTranslation(this._position),this._rotation.setFromMat4(e),this._rotation.transformVector(this._rayLocal.origin,this._ray.origin),this._ray.origin.add(this._position),this._rotation.transformVector(this._rayLocal.direction,this._ray.direction);}else e&&(this._ray.origin.copy(this._rayLocal.origin),this._ray.direction.copy(this._rayLocal.direction));}getPosition(){return this._grip?(this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position):null}getLocalPosition(){return this._localPosition}getRotation(){return this._grip?(this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation):null}getLocalRotation(){return this._localRotation}getLinearVelocity(){return this._velocitiesAvailable?this._linearVelocity:null}getOrigin(){return this._updateRayTransforms(),this._ray.origin}getDirection(){return this._updateRayTransforms(),this._ray.direction}hitTestStart(e={}){e.inputSource=this,e.profile=this._xrInputSource.profiles[0];let t=e.callback;e.callback=(e,i)=>{i&&this.onHitTestSourceAdd(i),t&&t(e,i);},this._manager.hitTest.start(e);}onHitTestSourceAdd(e){this._hitTestSources.push(e),this.fire("hittest:add",e),e.on("result",(t,i,s,r)=>{s===this&&this.fire("hittest:result",e,t,i,r);}),e.once("remove",()=>{this.onHitTestSourceRemove(e),this.fire("hittest:remove",e);});}onHitTestSourceRemove(e){let t=this._hitTestSources.indexOf(e);-1!==t&&this._hitTestSources.splice(t,1);}constructor(e,t){super(),this._ray=new eM,this._rayLocal=new eM,this._grip=false,this._hand=null,this._velocitiesAvailable=false,this._velocitiesTimestamp=Q(),this._localTransform=null,this._worldTransform=null,this._position=new ed,this._rotation=new ex,this._localPosition=null,this._localPositionLast=null,this._localRotation=null,this._linearVelocity=null,this._dirtyLocal=true,this._dirtyRay=false,this._selecting=false,this._squeezing=false,this._elementInput=true,this._elementEntity=null,this._hitTestSources=[],this._id=++T4,this._manager=e,this._xrInputSource=t,t.hand&&(this._hand=new T1(this));}}T5.EVENT_REMOVE="remove",T5.EVENT_SELECT="select",T5.EVENT_SELECTSTART="selectstart",T5.EVENT_SELECTEND="selectend",T5.EVENT_SQUEEZE="squeeze",T5.EVENT_SQUEEZESTART="squeezestart",T5.EVENT_SQUEEZEEND="squeezeend",T5.EVENT_HITTESTADD="hittest:add",T5.EVENT_HITTESTREMOVE="hittest:remove",T5.EVENT_HITTESTRESULT="hittest:result";class T6 extends X{_onSessionStart(){let e=this.manager.session;e.addEventListener("inputsourceschange",this._onInputSourcesChangeEvt),e.addEventListener("select",e=>{let t=this._getByInputSource(e.inputSource);t.update(e.frame),t.fire("select",e),this.fire("select",t,e);}),e.addEventListener("selectstart",e=>{let t=this._getByInputSource(e.inputSource);t.update(e.frame),t._selecting=true,t.fire("selectstart",e),this.fire("selectstart",t,e);}),e.addEventListener("selectend",e=>{let t=this._getByInputSource(e.inputSource);t.update(e.frame),t._selecting=false,t.fire("selectend",e),this.fire("selectend",t,e);}),e.addEventListener("squeeze",e=>{let t=this._getByInputSource(e.inputSource);t.update(e.frame),t.fire("squeeze",e),this.fire("squeeze",t,e);}),e.addEventListener("squeezestart",e=>{let t=this._getByInputSource(e.inputSource);t.update(e.frame),t._squeezing=true,t.fire("squeezestart",e),this.fire("squeezestart",t,e);}),e.addEventListener("squeezeend",e=>{let t=this._getByInputSource(e.inputSource);t.update(e.frame),t._squeezing=false,t.fire("squeezeend",e),this.fire("squeezeend",t,e);});let t=e.inputSources;for(let e=0;e{this._onInputSourcesChange(e);},this.manager.on("start",this._onSessionStart,this),this.manager.on("end",this._onSessionEnd,this);}}T6.EVENT_ADD="add",T6.EVENT_REMOVE="remove",T6.EVENT_SELECT="select",T6.EVENT_SELECTSTART="selectstart",T6.EVENT_SELECTEND="selectend",T6.EVENT_SQUEEZE="squeeze",T6.EVENT_SQUEEZESTART="squeezestart",T6.EVENT_SQUEEZEEND="squeezeend";let T8=new ed,T9=new ed,T7=new ey,Ee=new ey;class Et extends X{_onSessionStart(){this._manager.session.requestLightProbe&&(this._supported=true);}_onSessionEnd(){this._supported=false,this._available=false,this._lightProbeRequested=false,this._lightProbe=null;}start(){let e;(this._manager.session||(e=Error("XR session is not running")),e||this._manager.type===TL||(e=Error("XR session type is not AR")),e||this._supported||(e=Error("light-estimation is not supported")),(!e&&this._lightProbe||this._lightProbeRequested)&&(e=Error("light estimation is already requested")),e)?this.fire("error",e):(this._lightProbeRequested=true,this._manager.session.requestLightProbe().then(e=>{let t=this._lightProbeRequested;this._lightProbeRequested=false,this._manager.active?t&&(this._lightProbe=e):this.fire("error",Error("XR session is not active"));}).catch(e=>{this._lightProbeRequested=false,this.fire("error",e);}));}end(){this._lightProbeRequested=false,this._lightProbe=null,this._available=false;}update(e){if(!this._lightProbe)return;let t=e.getLightEstimate(this._lightProbe);if(!t)return;this._available||(this._available=true,this.fire("available"));let i=t.primaryLightIntensity;this._intensity=Math.max(1,Math.max(i.x,Math.max(i.y,i.z))),T8.copy(i).mulScalar(1/this._intensity),this._color.set(T8.x,T8.y,T8.z),T8.set(0,0,0),T9.copy(t.primaryLightDirection),T7.setLookAt(T9,T8,ed.UP),Ee.setFromAxisAngle(ed.RIGHT,90),T7.mul(Ee),this._rotation.setFromMat4(T7),this._sphericalHarmonics.set(t.sphericalHarmonicsCoefficients);}get supported(){return this._supported}get available(){return this._available}get intensity(){return this._available?this._intensity:null}get color(){return this._available?this._color:null}get rotation(){return this._available?this._rotation:null}get sphericalHarmonics(){return this._available?this._sphericalHarmonics:null}constructor(e){super(),this._supported=false,this._available=false,this._lightProbeRequested=false,this._lightProbe=null,this._intensity=0,this._rotation=new ex,this._color=new es,this._sphericalHarmonics=new Float32Array(27),this._manager=e,this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this);}}Et.EVENT_AVAILABLE="available",Et.EVENT_ERROR="error";let Ei=0;class Es extends X{destroy(){this._xrPlane&&(this._xrPlane=null,this.fire("remove"));}update(e){let t=this._planeDetection._manager,i=e.getPose(this._xrPlane.planeSpace,t._referenceSpace);i&&(this._position.copy(i.transform.position),this._rotation.copy(i.transform.orientation)),this._lastChangedTime!==this._xrPlane.lastChangedTime&&(this._lastChangedTime=this._xrPlane.lastChangedTime,this.fire("change"));}getPosition(){return this._position}getRotation(){return this._rotation}get id(){return this._id}get orientation(){return this._orientation}get points(){return this._xrPlane.polygon}get label(){return this._xrPlane.semanticLabel||""}constructor(e,t){super(),this._position=new ed,this._rotation=new ex,this._id=++Ei,this._planeDetection=e,this._xrPlane=t,this._lastChangedTime=t.lastChangedTime,this._orientation=t.orientation;}}Es.EVENT_REMOVE="remove",Es.EVENT_CHANGE="change";class Er extends X{_onSessionStart(){this._manager.session.enabledFeatures&&-1!==this._manager.session.enabledFeatures.indexOf("plane-detection")&&(this._available=true,this.fire("available"));}_onSessionEnd(){for(let e=0;e{for(let i of(this._uuid=t,this._anchors._indexByUuid.set(this._uuid,this),e?.(null,t),this._uuidRequests))i(null,t);this._uuidRequests=null,this.fire("persist",t);}).catch(t=>{for(let i of(e?.(t,null),this._uuidRequests))i(t,null);this._uuidRequests=null;});}forget(e){this._uuid?this._anchors.forget(this._uuid,t=>{this._uuid=null,e?.(t),this.fire("forget");}):e?.(Error("Anchor is not persistent"));}get uuid(){return this._uuid}get persistent(){return !!this._uuid}constructor(e,t,i=null){super(),this._position=new ed,this._rotation=new ex,this._uuid=null,this._uuidRequests=null,this._anchors=e,this._xrAnchor=t,this._uuid=i;}}Ea.EVENT_DESTROY="destroy",Ea.EVENT_CHANGE="change",Ea.EVENT_PERSIST="persist",Ea.EVENT_FORGET="forget";class En extends X{_onSessionStart(){let e=this.manager.session.enabledFeatures?.indexOf("anchors")>=0;e&&(this._available=e,this.fire("available"));}_onSessionEnd(){if(!this._available)return;this._available=false;for(let e=0;e{let t=this._createAnchor(e);i?.(null,t),this.fire("add",t);}).catch(e=>{i?.(e,null),this.fire("error",e);});}else this._creationQueue.push({transform:new XRRigidTransform(e,t),callback:i});}restore(e,t){this._available?this._persistence?this.manager.active?this.manager.session.restorePersistentAnchor(e).then(i=>{let s=this._createAnchor(i,e);t?.(null,s),this.fire("add",s);}).catch(e=>{t?.(e,null),this.fire("error",e);}):t?.(Error("WebXR session is not active"),null):t?.(Error("Anchor Persistence is not supported"),null):t?.(Error("Anchors API is not available"),null);}forget(e,t){this._available?this._persistence?this.manager.active?this.manager.session.deletePersistentAnchor(e).then(()=>{t?.(null);}).catch(e=>{t?.(e),this.fire("error",e);}):t?.(Error("WebXR session is not active")):t?.(Error("Anchor Persistence is not supported")):t?.(Error("Anchors API is not available"));}update(e){if(!this._available){this.manager.session.enabledFeatures||this._checkingAvailability||(this._checkingAvailability=true,e.createAnchor(new XRRigidTransform,this.manager._referenceSpace).then(e=>{e.delete(),this.manager.active&&(this._available=true,this.fire("available"));}).catch(()=>{}));return}if(this._creationQueue.length){for(let t=0;t{i.callback&&this._callbacksAnchors.set(e,i.callback);}).catch(e=>{i.callback&&i.callback(e,null),this.fire("error",e);});}this._creationQueue.length=0;}for(let[t,i]of this._index)e.trackedAnchors.has(t)||(this._index.delete(t),i.destroy());for(let t=0;t{if(e){r&&r(e),this.fire("error",e);return}null!==s&&(a.trackedImages=s),this._onStartOptionsReady(t,i,a,r);}):this._onStartOptionsReady(t,i,a,r);}_onStartOptionsReady(e,t,i,s){navigator.xr.requestSession(e,i).then(e=>{this._onSessionStart(e,t,s);}).catch(e=>{this._camera.camera.xr=null,this._camera=null,this._type=null,this._spaceType=null,s&&s(e),this.fire("error",e);});}end(e){if(!this._session){e&&e(Error("XR Session is not initialized"));return}this.webglBinding=null,e&&this.once("end",e),this._session.end();}isAvailable(e){return this._available[e]}_deviceAvailabilityCheck(){for(let e in this._available)this._sessionSupportCheck(e);}initiateRoomCapture(e){this._session?this._session.initiateRoomCapture?this._session.initiateRoomCapture().then(()=>{e&&e(null);}).catch(t=>{e&&e(t);}):e(Error("Session does not support manual room capture")):e(Error("Session is not active"));}updateTargetFrameRate(e,t){this._session?.updateTargetFrameRate?this._session.updateTargetFrameRate(e).then(()=>{t?.();}).catch(e=>{t?.(e);}):t?.(Error("unable to update frameRate"));}_sessionSupportCheck(e){navigator.xr.isSessionSupported(e).then(t=>{this._available[e]!==t&&(this._available[e]=t,this.fire("available",e,t),this.fire(`available:${e}`,t));}).catch(e=>{this.fire("error",e);});}_onSessionStart(e,t,i){let s=false;this._session=e;let r=()=>{this.fire("visibility:change",e.visibilityState);},a=()=>{this._setClipPlanes(this._camera.nearClip,this._camera.farClip);},n=()=>{this.fire("frameratechange",this._session?.frameRate);},o=()=>{this._camera&&(this._camera.off("set_nearClip",a),this._camera.off("set_farClip",a),this._camera.camera.xr=null,this._camera=null),e.removeEventListener("end",o),e.removeEventListener("visibilitychange",r),e.removeEventListener("frameratechange",n),s||this.fire("end"),this._session=null,this._referenceSpace=null,this._width=0,this._height=0,this._type=null,this._spaceType=null,this.app.systems&&this.app.requestAnimationFrame();};e.addEventListener("end",o),e.addEventListener("visibilitychange",r),this._camera.on("set_nearClip",a),this._camera.on("set_farClip",a),this._createBaseLayer(),this.session.supportedFrameRates?this._supportedFrameRates=Array.from(this.session.supportedFrameRates):this._supportedFrameRates=null,this._session.addEventListener("frameratechange",n),e.requestReferenceSpace(t).then(e=>{this._referenceSpace=e,this.app.requestAnimationFrame(),i&&i(null),this.fire("start");}).catch(t=>{s=true,e.end(),i&&i(t),this.fire("error",t);});}_setClipPlanes(e,t){this._depthNear===e&&this._depthFar===t||(this._depthNear=e,this._depthFar=t,this._session&&this._session.updateRenderState({depthNear:this._depthNear,depthFar:this._depthFar}));}_createBaseLayer(){let e=this.app.graphicsDevice,t=e.maxPixelRatio/window.devicePixelRatio*this._framebufferScaleFactor;if(this._baseLayer=new XRWebGLLayer(this._session,e.gl,{alpha:true,depth:true,stencil:true,framebufferScaleFactor:t,antialias:false}),e?.isWebGL2&&window.XRWebGLBinding)try{this.webglBinding=new XRWebGLBinding(this._session,e.gl);}catch(e){this.fire("error",e);}this._session.updateRenderState({baseLayer:this._baseLayer,depthNear:this._depthNear,depthFar:this._depthFar});}_onDeviceLost(){this._session&&(this.webglBinding&&(this.webglBinding=null),this._baseLayer=null,this._session.updateRenderState({baseLayer:this._baseLayer,depthNear:this._depthNear,depthFar:this._depthFar}));}_onDeviceRestored(){this._session&&setTimeout(()=>{this.app.graphicsDevice.gl.makeXRCompatible().then(()=>{this._createBaseLayer();}).catch(e=>{this.fire("error",e);});},0);}update(e){if(!this._session)return false;let t=e.session.renderState.baseLayer.framebufferWidth,i=e.session.renderState.baseLayer.framebufferHeight;(this._width!==t||this._height!==i)&&(this._width=t,this._height=i,this.app.graphicsDevice.setResolution(t,i));let s=e.getViewerPose(this._referenceSpace);if(!s)return false;let r=this.views.list.length;this.views.update(e,s.views);let a=s.transform.position,n=s.transform.orientation;if(this._localPosition.set(a.x,a.y,a.z),this._localRotation.set(n.x,n.y,n.z,n.w),0===r&&this.views.list.length>0){let e=new ey,t=this.views.list[0];e.copy(t.projMat);let i=e.data,s=2*Math.atan(1/i[5])*180/Math.PI,r=i[5]/i[0],a=i[14]/(i[10]+1),n=i[14]/(i[10]-1);this._camera.camera.setXrProperties({aspectRatio:r,farClip:a,fov:s,horizontalFov:false,nearClip:n});}return this._camera.camera._node.setLocalPosition(this._localPosition),this._camera.camera._node.setLocalRotation(this._localRotation),this.input.update(e),this._type===TL&&(this.hitTest.supported&&this.hitTest.update(e),this.lightEstimation.supported&&this.lightEstimation.update(e),this.imageTracking.supported&&this.imageTracking.update(e),this.anchors.supported&&this.anchors.update(e),this.planeDetection.supported&&this.planeDetection.update(e),this.meshDetection.supported&&this.meshDetection.update(e)),this.fire("update",e),true}get supported(){return this._supported}get active(){return !!this._session}get type(){return this._type}get spaceType(){return this._spaceType}get session(){return this._session}get frameRate(){return this._session?.frameRate??null}get supportedFrameRates(){return this._supportedFrameRates}get framebufferScaleFactor(){return this._framebufferScaleFactor}set fixedFoveation(e){(this._baseLayer?.fixedFoveation??null)!==null&&(this.app.graphicsDevice.samples,this._baseLayer.fixedFoveation=e);}get fixedFoveation(){return this._baseLayer?.fixedFoveation??null}get camera(){return this._camera?this._camera.entity:null}get visibilityState(){return this._session?this._session.visibilityState:null}constructor(e){super(),this._supported=k.browser&&!!navigator.xr,this._available={},this._type=null,this._spaceType=null,this._session=null,this._baseLayer=null,this.webglBinding=null,this._referenceSpace=null,this._camera=null,this._localPosition=new ed,this._localRotation=new ex,this._depthNear=.1,this._depthFar=1e3,this._supportedFrameRates=null,this._width=0,this._height=0,this._framebufferScaleFactor=1,this.app=e,this._available[TD]=false,this._available[TR]=false,this._available[TL]=false,this.domOverlay=new Tz(this),this.hitTest=new TW(this),this.imageTracking=new TY(this),this.planeDetection=new Er(this),this.meshDetection=new El(this),this.input=new T6(this),this.lightEstimation=new Et(this),this.anchors=new En(this),this.views=new Ec(this),this._supported&&(navigator.xr.addEventListener("devicechange",()=>{this._deviceAvailabilityCheck();}),this._deviceAvailabilityCheck(),this.app.graphicsDevice.on("devicelost",this._onDeviceLost,this),this.app.graphicsDevice.on("devicerestored",this._onDeviceRestored,this));}}Ed.EVENT_AVAILABLE="available",Ed.EVENT_START="start",Ed.EVENT_END="end",Ed.EVENT_UPDATE="update",Ed.EVENT_ERROR="error";class Eu{destroy(){this.texture.destroy();}clear(e){let{width:t,height:i}=this.canvas;this.ctx.clearRect(0,0,t,i),this.ctx.fillStyle=e,this.ctx.fillRect(0,0,t,i);}constructor(e,t,i,s){this.canvas=document.createElement("canvas"),this.canvas.width=t,this.canvas.height=i,this.texture=new ic(e,{name:s,format:20,width:t,height:i,mipmaps:true,minFilter:5,magFilter:1,addressU:1,addressV:1,levels:[this.canvas]}),this.ctx=this.canvas.getContext("2d",{alpha:true});}}let Ef=[],Ep=[[],[],[]],Em=new Float32Array(2);class E_ extends ah{destroy(){this.viewBindGroups.forEach(e=>{e.defaultUniformBuffer.destroy(),e.destroy();}),this.viewBindGroups.length=0;}update(e,t,i,s,r){this.camera=e,this.scene=t,this.layers=i,this.mapping=s,this.depth=r,t.clusteredLightingEnabled&&(this.emptyWorldClusters=this.renderer.worldClustersAllocator.empty);}before(){this._qualifiedLayerIndices.length=0,this._pickMeshInstances.clear();let{camera:e,scene:t,layers:i}=this,s=t.layers.layerList,r=t.layers.subLayerEnabled,a=this.renderer.gsplatDirector,n=this.renderTarget?.width??1,o=this.renderTarget?.height??1;for(let t=0;ti.indexOf(l))&&l.enabled&&r[t]&&l.camerasSet.has(e.camera)&&(this._qualifiedLayerIndices.push(t),a)){let i=a.prepareForPicking(e.camera,n,o,l);i&&this._pickMeshInstances.set(t,i);}}}execute(){let e=this.device,{renderer:t,camera:i,scene:s,mapping:r,renderTarget:a}=this,n=s.layers.layerList,o=s.layers.subLayerList;for(let l of this._qualifiedLayerIndices){let h=n[l],c=o[l];h._clearDepthBuffer&&t.clear(i.camera,false,true,false);let d=h.meshInstances;for(let e=0;e0){let r=s.clusteredLightingEnabled;r&&this.emptyWorldClusters.activate(),t.setCameraUniforms(i.camera,a),t.dispatchGlobalLights(s),e.scope.resolve("shadowAtlasParams").setValue(Em),e.supportsUniformBuffers&&(t.initViewBindGroupFormat(r),t.setupViewUniformBuffers(this.viewBindGroups,t.viewUniformFormat,t.viewBindGroupFormat,null));let n=this.depth?4:3;t.renderForward(i.camera,a,Ef,Ep,n,t=>{e.setBlendState(this.blendState);}),Ef.length=0;}}}constructor(e,t){super(e),this.viewBindGroups=[],this.blendState=iy.NOBLEND,this._qualifiedLayerIndices=[],this._pickMeshInstances=new Map,this.renderer=t;}}let Eg=new Set,Ev=new ep,ES=new Float32Array(1),Ey=new Int32Array(ES.buffer),Ex=new ed,ET=new ed,EE=new eM,Ew=new eM,Eb=new eM;EE.end=new ed,Ew.end=new ed,Eb.end=new ed;let EC=new ed,EA=new ed,EP=new ed,EI=new ed,ED=new ed,ER=new ed,EL=new ed,EM=new ed,EO=new ed,EF=new ed,EN=new ed,EB=new ed,Ek=new ed,EU=new ed,Ez=new ed,EV=new ed,EG=new ed,EH=new ed,EW=new ed,EX=new ed,EY=new ep;function Eq(e,t,i){return EN.cross(e,t).dot(i)}class Ej{stopPropagation(){this._stopPropagation=true,this.event&&(this.event.stopImmediatePropagation(),this.event.stopPropagation());}constructor(e,t,i){this.event=e,this.element=t,this.camera=i,this._stopPropagation=false;}}class EK extends Ej{constructor(e,t,i,s,r,a,n){super(e,t,i),this.x=s,this.y=r,this.ctrlKey=e.ctrlKey||false,this.altKey=e.altKey||false,this.shiftKey=e.shiftKey||false,this.metaKey=e.metaKey||false,this.button=e.button,aF.isPointerLocked()?(this.dx=e.movementX||e.webkitMovementX||e.mozMovementX||0,this.dy=e.movementY||e.webkitMovementY||e.mozMovementY||0):(this.dx=s-a,this.dy=r-n),this.wheelDelta=0,"wheel"===e.type&&(e.deltaY>0?this.wheelDelta=1:e.deltaY<0&&(this.wheelDelta=-1));}}class E$ extends Ej{constructor(e,t,i,s,r,a){super(e,t,i),this.touches=e.touches,this.changedTouches=e.changedTouches,this.x=s,this.y=r,this.touch=a;}}class EZ extends Ej{constructor(e,t,i,s){super(e,t,i),this.inputSource=s;}}class EQ{set enabled(e){this._enabled=e;}get enabled(){return this._enabled}set app(e){this._app=e;}get app(){return this._app||r}attach(e){this._attached&&(this._attached=false,this.detach()),this._target=e,this._attached=true;let t=!!k.passiveEvents&&{passive:true};this._useMouse&&(window.addEventListener("mouseup",this._upHandler,t),window.addEventListener("mousedown",this._downHandler,t),window.addEventListener("mousemove",this._moveHandler,t),window.addEventListener("wheel",this._wheelHandler,t)),this._useTouch&&k.touch&&(this._target.addEventListener("touchstart",this._touchstartHandler,t),this._target.addEventListener("touchend",this._touchendHandler,false),this._target.addEventListener("touchmove",this._touchmoveHandler,false),this._target.addEventListener("touchcancel",this._touchcancelHandler,false)),this.attachSelectEvents();}attachSelectEvents(){!this._selectEventsAttached&&this._useXr&&this.app&&this.app.xr&&this.app.xr.supported&&(this._clickedEntities||(this._clickedEntities={}),this._selectEventsAttached=true,this.app.xr.on("start",this._onXrStart,this));}detach(){if(!this._attached)return;this._attached=false;let e=!!k.passiveEvents&&{passive:true};this._useMouse&&(window.removeEventListener("mouseup",this._upHandler,e),window.removeEventListener("mousedown",this._downHandler,e),window.removeEventListener("mousemove",this._moveHandler,e),window.removeEventListener("wheel",this._wheelHandler,e)),this._useTouch&&(this._target.removeEventListener("touchstart",this._touchstartHandler,e),this._target.removeEventListener("touchend",this._touchendHandler,false),this._target.removeEventListener("touchmove",this._touchmoveHandler,false),this._target.removeEventListener("touchcancel",this._touchcancelHandler,false)),this._selectEventsAttached&&(this._selectEventsAttached=false,this.app.xr.off("start",this._onXrStart,this),this.app.xr.off("end",this._onXrEnd,this),this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)),this._target=null;}addElement(e){ -1===this._elements.indexOf(e)&&this._elements.push(e);}removeElement(e){let t=this._elements.indexOf(e);-1!==t&&this._elements.splice(t,1);}_handleUp(e){!this._enabled||aF.isPointerLocked()||(this._calcMouseCoords(e),this._onElementMouseEvent("mouseup",e));}_handleDown(e){!this._enabled||aF.isPointerLocked()||(this._calcMouseCoords(e),this._onElementMouseEvent("mousedown",e));}_handleMove(e){this._enabled&&(this._calcMouseCoords(e),this._onElementMouseEvent("mousemove",e),this._lastX=g,this._lastY=v);}_handleWheel(e){this._enabled&&(this._calcMouseCoords(e),this._onElementMouseEvent("mousewheel",e));}_determineTouchedElements(e){let t={},i=this.app.systems.camera.cameras;for(let s=i.length-1;s>=0;s--){let r=i[s],a=0,n=e.changedTouches.length;for(let i=0;i=0;i--)this._getTargetElementByCoords(t[i],h.x,h.y)!==a||this._clickedEntities[a.entity.getGuid()]||(this._fireEvent("click",new E$(e,a,n,o,l,s)),this._clickedEntities[a.entity.getGuid()]=Date.now());this._fireEvent(e.type,new E$(e,a,n,o,l,s));}}_handleTouchMove(e){if(e.preventDefault(),!this._enabled)return;let t=this._determineTouchedElements(e);for(let i=0,s=e.changedTouches.length;i=0&&(i=a[e],!(s=this._getTargetElementByCoords(i,g,v)));e--);if(this._hoveredElement=s,("mousemove"===e||"mouseup"===e)&&this._pressedElement?this._fireEvent(e,new EK(t,this._pressedElement,i,g,v,this._lastX,this._lastY)):s&&(this._fireEvent(e,new EK(t,s,i,g,v,this._lastX,this._lastY)),"mousedown"===e&&(this._pressedElement=s)),r!==this._hoveredElement&&(r&&this._fireEvent("mouseleave",new EK(t,r,i,g,v,this._lastX,this._lastY)),this._hoveredElement&&this._fireEvent("mouseenter",new EK(t,this._hoveredElement,i,g,v,this._lastX,this._lastY))),"mouseup"===e&&this._pressedElement){if(this._pressedElement===this._hoveredElement){let e=this._hoveredElement.entity.getGuid(),s=!this._clickedEntities;if(this._clickedEntities){let t=this._clickedEntities[e]||0;s=Date.now()-t>300,delete this._clickedEntities[e];}s&&this._fireEvent("click",new EK(t,this._hoveredElement,i,g,v,this._lastX,this._lastY));}this._pressedElement=null;}}_onXrStart(){this.app.xr.on("end",this._onXrEnd,this),this.app.xr.on("update",this._onXrUpdate,this),this.app.xr.input.on("selectstart",this._onSelectStart,this),this.app.xr.input.on("selectend",this._onSelectEnd,this),this.app.xr.input.on("remove",this._onXrInputRemove,this);}_onXrEnd(){this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this);}_onXrUpdate(){if(!this._enabled)return;let e=this.app.xr.input.inputSources;for(let t=0;t=0&&(a=o[e],!(s=this._getTargetElementByRay(Eb,a)));e--);}t._elementEntity=s||null,s?(this._selectedElements[t.id]=s,r=s):delete this._selectedElements[t.id],n!==r&&(n&&this._fireEvent("selectleave",new EZ(i,n,a,t)),r&&this._fireEvent("selectenter",new EZ(i,r,a,t)));let l=this._selectedPressedElements[t.id];"selectmove"===e&&l&&this._fireEvent("selectmove",new EZ(i,l,a,t)),"selectstart"===e&&(this._selectedPressedElements[t.id]=r,r&&this._fireEvent("selectstart",new EZ(i,r,a,t))),!t.elementInput&&l&&(delete this._selectedPressedElements[t.id],n&&this._fireEvent("selectend",new EZ(i,l,a,t))),"selectend"===e&&t.elementInput&&(delete this._selectedPressedElements[t.id],l&&this._fireEvent("selectend",new EZ(i,l,a,t)),l&&l===n&&this._fireEvent("click",new EZ(i,l,a,t)));}_fireEvent(e,t){let i=t.element;for(;i.fire(e,t),!t._stopPropagation&&i.entity.parent&&(i=i.entity.parent.element););}_calcMouseCoords(e){let t=this._target.getBoundingClientRect(),i=Math.floor(t.left),s=Math.floor(t.top);g=e.clientX-i,v=e.clientY-s;}_sortElements(e,t){let i=this.app.scene.layers.sortTransparentLayers(e.layers,t.layers);return 0!==i?i:e.screen&&!t.screen?-1:!e.screen&&t.screen?1:e.screen||t.screen?e.screen.screen.screenSpace&&!t.screen.screen.screenSpace?-1:t.screen.screen.screenSpace&&!e.screen.screen.screenSpace?1:t.drawOrder-e.drawOrder:0}_getTargetElementByCoords(e,t,i){let s=this._calculateRayScreen(t,i,e,EE)?EE:null,r=this._calculateRay3d(t,i,e,Ew)?Ew:null;return this._getTargetElement(e,s,r)}_getTargetElementByRay(e,t){EE.origin.copy(e.origin),EE.direction.copy(e.direction),EE.end.copy(EE.direction).mulScalar(2*t.farClip).add(EE.origin);let i=t.worldToScreen(EE.origin,Ex),s=this._calculateRayScreen(i.x,i.y,t,Ew)?Ew:null;return this._getTargetElement(t,s,EE)}_getTargetElement(e,t,i){let s=null,r=1/0;this._elements.sort(this._sortHandler);for(let a=0,n=this._elements.length;ae.layersSet.has(t)))if(n.screen&&n.screen.screen.screenSpace){if(!t)continue;if(this._checkElement(t,n,true)>=0){s=n;break}}else {if(!i)continue;let e=this._checkElement(i,n,false);if(e>=0&&(e=l&&d<=l+n&&u<=h&&u>=c&&(d=r*(d-l)/n,u=a*(u-c)/o,u=a-u,s.origin.set(d,u,1),s.direction.set(0,0,-1),s.end.copy(s.direction).mulScalar(2).add(s.origin),true)}_calculateRay3d(e,t,i,s){let r=this._target.clientWidth,a=this._target.clientHeight,n=i.rect.z*r,o=i.rect.w*a,l=i.rect.x*r,h=(1-i.rect.y)*a,c=h-o,d=e,u=t;return e>=l&&e<=l+n&&t<=h&&u>=c&&(d=r*(d-l)/n,u=a*(u-c)/o,i.screenToWorld(d,u,i.nearClip,Ex),i.screenToWorld(d,u,i.farClip,ET),s.origin.copy(Ex),s.direction.set(0,0,-1),s.end.copy(ET),true)}_checkElement(e,t,i){let s;if(t.maskedBy&&0>this._checkElement(e,t.maskedBy.element,i))return -1;s=i?EQ.calculateScaleToScreen(t):EQ.calculateScaleToWorld(t);let r=EQ.buildHitCorners(t,i?t.screenCorners:t.worldCorners,s);return function(e,t,i){let s,r;EC.sub2(t,e),EA.sub2(i[0],e),EP.sub2(i[1],e),EI.sub2(i[2],e),ER.cross(EI,EC);let a=EA.dot(ER);if(a>=0){if((s=-EP.dot(ER))<0||(r=Eq(EC,EP,EA))<0)return -1;let e=1/(s+a+r);EL.copy(i[0]).mulScalar(s*e),EM.copy(i[1]).mulScalar(a*e),EO.copy(i[2]).mulScalar(r*e),EF.copy(EL).add(EM).add(EO);}else {if(ED.sub2(i[3],e),(s=ED.dot(ER))<0||(r=Eq(EC,EA,ED))<0)return -1;let t=1/(s+(a=-a)+r);EL.copy(i[0]).mulScalar(s*t),EM.copy(i[3]).mulScalar(a*t),EO.copy(i[2]).mulScalar(r*t),EF.copy(EL).add(EM).add(EO);}return 1e-8>EC.sub2(i[0],i[2]).lengthSq()||1e-8>EC.sub2(i[1],i[3]).lengthSq()?-1:EF.sub(e).lengthSq()}(e.origin,e.end,r)}static buildHitCorners(e,t,i){let s=t;if(e.entity&&e.entity.button){let t=e.entity.button.hitPadding||EY;Ek.copy(e.entity.up),EU.copy(Ek).mulScalar(-1),EV.copy(e.entity.right),Ez.copy(EV).mulScalar(-1),Ek.mulScalar(t.w*i.y),EU.mulScalar(t.y*i.y),EV.mulScalar(t.z*i.x),Ez.mulScalar(t.x*i.x),EG.copy(s[0]).add(EU).add(Ez),EH.copy(s[1]).add(EU).add(EV),EW.copy(s[2]).add(Ek).add(EV),EX.copy(s[3]).add(Ek).add(Ez),s=[EG,EH,EW,EX];}if(i.x<0){let e=s[2].x,t=s[0].x;s[0].x=e,s[1].x=t,s[2].x=t,s[3].x=e;}if(i.y<0){let e=s[2].y,t=s[0].y;s[0].y=e,s[1].y=e,s[2].y=t,s[3].y=t;}if(i.z<0){let e=s[2].x,t=s[2].y,i=s[2].z;s[2].x=s[0].x,s[2].y=s[0].y,s[2].z=s[0].z,s[0].x=e,s[0].y=t,s[0].z=i;}return s}static calculateScaleToScreen(e){let t=e.entity,i=e.screen.screen.scale;for(EB.set(i,i,i);t&&!t.screen;)EB.mul(t.getLocalScale()),t=t.parent;return EB}static calculateScaleToWorld(e){let t=e.entity;for(EB.set(1,1,1);t;)EB.mul(t.getLocalScale()),t=t.parent;return EB}constructor(e,t){this._app=null,this._attached=false,this._target=null,this._enabled=true,this._lastX=0,this._lastY=0,this._upHandler=this._handleUp.bind(this),this._downHandler=this._handleDown.bind(this),this._moveHandler=this._handleMove.bind(this),this._wheelHandler=this._handleWheel.bind(this),this._touchstartHandler=this._handleTouchStart.bind(this),this._touchendHandler=this._handleTouchEnd.bind(this),this._touchcancelHandler=this._touchendHandler,this._touchmoveHandler=this._handleTouchMove.bind(this),this._sortHandler=this._sortElements.bind(this),this._elements=[],this._hoveredElement=null,this._pressedElement=null,this._touchedElements={},this._touchesForWhichTouchLeaveHasFired={},this._selectedElements={},this._selectedPressedElements={},this._useMouse=!t||false!==t.useMouse,this._useTouch=!t||false!==t.useTouch,this._useXr=!t||false!==t.useXr,this._selectEventsAttached=false,k.touch&&(this._clickedEntities={}),this.attach(e);}}ef.prototype.scale=ef.prototype.mulScalar,ed.prototype.scale=ed.prototype.mulScalar,ep.prototype.scale=ep.prototype.mulScalar;let EJ=new ep;Object.defineProperties(iG.prototype,{_glFrameBuffer:{get:function(){return this.impl._glFrameBuffer},set:function(e){}}}),Object.defineProperty(iB,"defaultInstancingFormat",{get:function(){return null}}),Object.defineProperties(ic.prototype,{rgbm:{get:function(){return this.type===tI},set:function(e){this.type=e?tI:tP;}},swizzleGGGR:{get:function(){return this.type===tL},set:function(e){this.type=e?tL:tP;}},_glTexture:{get:function(){return this.impl._glTexture}}}),Object.defineProperty(iz.prototype,"boneLimit",{get:function(){return 1024}}),Object.defineProperty(iz.prototype,"webgl2",{get:function(){return this.isWebGL2}}),Object.defineProperty(iz.prototype,"textureFloatHighPrecision",{get:function(){return true}}),Object.defineProperty(iz.prototype,"extBlendMinmax",{get:function(){return true}}),Object.defineProperty(iz.prototype,"extTextureHalfFloat",{get:function(){return true}}),Object.defineProperty(iz.prototype,"extTextureLod",{get:function(){return true}}),Object.defineProperty(iz.prototype,"textureHalfFloatFilterable",{get:function(){return true}}),Object.defineProperty(iz.prototype,"supportsMrt",{get:function(){return true}}),Object.defineProperty(iz.prototype,"supportsVolumeTextures",{get:function(){return true}}),Object.defineProperty(iz.prototype,"supportsInstancing",{get:function(){return true}}),Object.defineProperty(iz.prototype,"textureHalfFloatUpdatable",{get:function(){return true}}),Object.defineProperty(iz.prototype,"extTextureFloat",{get:function(){return true}}),Object.defineProperty(iz.prototype,"extStandardDerivatives",{get:function(){return true}}),iy.DEFAULT=Object.freeze(new iy);let E0=new iy,E1=new iT;iz.prototype.setBlendFunction=function(e,t){let i=this.blendState;E0.copy(i),E0.setColorBlend(i.colorOp,e,t),E0.setAlphaBlend(i.alphaOp,e,t),this.setBlendState(E0);},iz.prototype.setBlendFunctionSeparate=function(e,t,i,s){let r=this.blendState;E0.copy(r),E0.setColorBlend(r.colorOp,e,t),E0.setAlphaBlend(r.alphaOp,i,s),this.setBlendState(E0);},iz.prototype.setBlendEquation=function(e){let t=this.blendState;E0.copy(t),E0.setColorBlend(e,t.colorSrcFactor,t.colorDstFactor),E0.setAlphaBlend(e,t.alphaSrcFactor,t.alphaDstFactor),this.setBlendState(E0);},iz.prototype.setBlendEquationSeparate=function(e,t){let i=this.blendState;E0.copy(i),E0.setColorBlend(e,i.colorSrcFactor,i.colorDstFactor),E0.setAlphaBlend(t,i.alphaSrcFactor,i.alphaDstFactor),this.setBlendState(E0);},iz.prototype.setColorWrite=function(e,t,i,s){let r=this.blendState;E0.copy(r),E0.setColorWrite(e,t,i,s),this.setBlendState(E0);},iz.prototype.getBlending=function(){return this.blendState.blend},iz.prototype.setBlending=function(e){E0.copy(this.blendState),E0.blend=e,this.setBlendState(E0);},iz.prototype.setDepthWrite=function(e){E1.copy(this.depthState),E1.write=e,this.setDepthState(E1);},iz.prototype.setDepthFunc=function(e){E1.copy(this.depthState),E1.func=e,this.setDepthState(E1);},iz.prototype.setDepthTest=function(e){E1.copy(this.depthState),E1.test=e,this.setDepthState(E1);},iz.prototype.getCullMode=function(){return this.cullMode};let E2=new Proxy({},{get:(e,t)=>n$.get(r.graphicsDevice,tz).get(t),set:(e,t,i)=>(n$.get(r.graphicsDevice,tz).set(t,i),true)});function E3(e,t,i=""){Object.defineProperty(e.prototype,t,{set:function(e){},get:function(){}});}function E4(e,t){Object.defineProperty(ud.prototype,t,{get:function(){return this[e]},set:function(t){this[e]=t;}});}function E5(e){Object.defineProperty(ud.prototype,e,{get:function(){return true},set:function(e){}});}function E6(e,t){"pass"!==e&&Object.defineProperty(d6.prototype,e,{get:function(){return this.litOptions[t||e]},set:function(i){this.litOptions[t||e]=i;}});}Object.defineProperty(dw.prototype,"defaultMaterial",{get:function(){return ol(r.graphicsDevice)}}),Object.defineProperty(dw.prototype,"fogColor",{set:function(e){this.fog.color=e;},get:function(){return this.fog.color}}),Object.defineProperty(dw.prototype,"fogEnd",{set:function(e){this.fog.end=e;},get:function(){return this.fog.end}}),Object.defineProperty(dw.prototype,"fogStart",{set:function(e){this.fog.start=e;},get:function(){return this.fog.start}}),Object.defineProperty(dw.prototype,"fogDensity",{set:function(e){this.fog.density=e;},get:function(){return this.fog.density}}),Object.defineProperty(dw.prototype,"toneMapping",{set:function(e){},get:function(){}}),Object.defineProperty(dw.prototype,"gammaCorrection",{set:function(e){},get:function(){}}),Object.defineProperty(dw.prototype,"rendering",{set:function(e){},get:function(){}}),Object.defineProperty(hT.prototype,"_meshInstances",{get:function(){return null}}),Object.defineProperty(dw.prototype,"drawCalls",{get:function(){return null}}),["128","64","32","16","8","4"].forEach((e,t)=>{Object.defineProperty(dw.prototype,`skyboxPrefiltered${e}`,{get:function(){return this._prefilteredCubemaps[t]},set:function(e){this._prefilteredCubemaps[t]=e,this.updateShaders=true;}});}),Object.defineProperty(dw.prototype,"models",{get:function(){return this._models||(this._models=[]),this._models}}),E3(hy,"renderTarget"),E3(hy,"onPreCull"),E3(hy,"onPreRender"),E3(hy,"onPreRenderOpaque"),E3(hy,"onPreRenderTransparent"),E3(hy,"onPostCull"),E3(hy,"onPostRender"),E3(hy,"onPostRenderOpaque"),E3(hy,"onPostRenderTransparent"),E3(hy,"onDrawCall"),E3(hy,"layerReference"),E3(vy,"onPreCull","Use Scene#EVENT_PRECULL event instead."),E3(vy,"onPostCull","Use Scene#EVENT_POSTCULL event instead."),E3(vy,"onPreRender","Use Scene#EVENT_PRERENDER event instead."),E3(vy,"onPostRender","Use Scene#EVENT_POSTRENDER event instead."),E3(vy,"onPreRenderLayer","Use Scene#EVENT_PRERENDER_LAYER event instead."),E3(vy,"onPostRenderLayer","Use Scene#EVENT_POSTRENDER_LAYER event instead."),hp.prototype.renderComposition=function(e){r.renderComposition(e);},oS.prototype.syncAabb=function(){},hN.prototype.getTarget=function(e){return this.targets[e]},oJ.prototype.getChildren=function(){return this.children},oJ.prototype.getName=function(){return this.name},oJ.prototype.getPath=function(){return this.path},oJ.prototype.getRoot=function(){return this.root},oJ.prototype.getParent=function(){return this.parent},oJ.prototype.setName=function(e){this.name=e;},Object.defineProperty(lw.prototype,"shader",{set:function(e){},get:function(){return null}}),Object.defineProperty(lw.prototype,"blend",{set:function(e){this.blendState.blend=e;},get:function(){return this.blendState.blend}}),Object.defineProperty(ud.prototype,"shininess",{get:function(){return 100*this.gloss},set:function(e){this.gloss=.01*e;}}),Object.defineProperty(ud.prototype,"useGammaTonemap",{get:function(){return this.useTonemap},set:function(e){this.useTonemap=e;}}),Object.defineProperty(ud.prototype,"anisotropy",{get:function(){let e=Math.sign(Math.cos(this.anisotropyRotation*ei.DEG_TO_RAD*2));return this.anisotropyIntensity*e},set:function(e){this.anisotropyIntensity=Math.abs(e),e>=0?this.anisotropyRotation=0:this.anisotropyRotation=90;}}),E5("sheenTint"),E5("diffuseTint"),E5("emissiveTint"),E5("ambientTint"),E4("specularTint","specularMapTint"),E4("aoVertexColor","aoMapVertexColor"),E4("diffuseVertexColor","diffuseMapVertexColor"),E4("specularVertexColor","specularMapVertexColor"),E4("emissiveVertexColor","emissiveMapVertexColor"),E4("metalnessVertexColor","metalnessMapVertexColor"),E4("glossVertexColor","glossMapVertexColor"),E4("opacityVertexColor","opacityMapVertexColor"),E4("lightVertexColor","lightMapVertexColor"),E4("sheenGloss","sheenGlossiess"),E4("clearCoatGloss","clearCostGlossiness"),E6("refraction","useRefraction");let E8=Object.getOwnPropertyNames(new dQ);for(let e in E8)E6(E8[e]);fq.prototype.getAssetById=function(e){return this.get(e)},Object.defineProperty(T5.prototype,"ray",{get:function(){return this._rayLocal}}),Object.defineProperty(T5.prototype,"position",{get:function(){return this._localPosition}}),Object.defineProperty(T5.prototype,"rotation",{get:function(){return this._localRotation}}),Object.defineProperty(EQ.prototype,"wheel",{get:function(){return -2*this.wheelDelta}}),Object.defineProperty(aO.prototype,"wheel",{get:function(){return -2*this.wheelDelta}}),pa.prototype.isFullscreen=function(){return !!document.fullscreenElement},pa.prototype.enableFullscreen=function(e,t,i){e=e||this.graphicsDevice.canvas;let s=function(){t(),document.removeEventListener("fullscreenchange",s);},r=function(){i(),document.removeEventListener("fullscreenerror",r);};t&&document.addEventListener("fullscreenchange",s,false),i&&document.addEventListener("fullscreenerror",r,false),e.requestFullscreen?e.requestFullscreen(Element.ALLOW_KEYBOARD_INPUT):i();},pa.prototype.disableFullscreen=function(e){let t=function(){e(),document.removeEventListener("fullscreenchange",t);};e&&document.addEventListener("fullscreenchange",t,false),document.exitFullscreen();},pa.prototype.getSceneUrl=function(e){let t=this.scenes.find(e);return t?t.url:null},pa.prototype.loadScene=function(e,t){this.scenes.loadScene(e,t);},pa.prototype.loadSceneHierarchy=function(e,t){this.scenes.loadSceneHierarchy(e,t);},pa.prototype.loadSceneSettings=function(e,t){this.scenes.loadSceneSettings(e,t);},gi.prototype.setVisible=function(e){this.enabled=e;},Object.defineProperty(gP.prototype,"bodyType",{get:function(){return this.type},set:function(e){this.type=e;}}),gP.prototype.syncBodyToEntity=function(){this._updateDynamic();},gF.prototype.setGravity=function(){1==arguments.length?this.gravity.copy(arguments[0]):this.gravity.set(arguments[0],arguments[1],arguments[2]);};class E9{begin(e){if(!this.enabled)return;this._frameIndex0){let e=this._frameTimings[this._frameIndex-1];e[1]=t-e[1];}else if(this._timings.length>0){let e=this._timings[this._timings.length-1];e[1]=t-e[1];}if(this._frameIndex>=this._frameTimings.length)this._frameTimings.push([e,t]);else {let i=this._frameTimings[this._frameIndex];i[0]=e,i[1]=t;}this._frameIndex++;}get timings(){return this._timings.slice(0,-1).map(e=>e[1])}constructor(e){this._frameIndex=0,this._frameTimings=[],this._timings=[],this._prevTimings=[],this.unitsName="ms",this.decimalPlaces=1,this.enabled=true,e.on("frameupdate",this.begin.bind(this,"update")),e.on("framerender",this.mark.bind(this,"render")),e.on("frameend",this.mark.bind(this,"other"));}}class E7{get timings(){return this._timings[0]=this.device.gpuProfiler?._frameTime??0,this._timings}constructor(e){this.device=e,e.gpuProfiler&&(e.gpuProfiler.enabled=true),this.enabled=true,this.unitsName="ms",this.decimalPlaces=1,this._timings=[];}}class we{get timings(){return this.values}constructor(e,t,i,s,r){this.app=e,this.values=[],this.statNames=t,this.unitsName=s,this.decimalPlaces=i,this.multiplier=r||1;let a=(e,t)=>e.split(".").reduce((e,t)=>e?e instanceof Map?e.get(t):e[t]:null,t||this);e.on("frameupdate",e=>{for(let e=0;ee+t,0);if(this.avgTotal+=t,this.avgTimer+=e,this.avgCount++,this.maxValue=Math.max(this.maxValue,t),this.avgTimer>this.textRefreshRate&&(this.timingText=(this.avgTotal/this.avgCount).toFixed(this.timer.decimalPlaces),this.maxText=this.maxValue.toFixed(this.timer.decimalPlaces),this.avgTimer=0,this.avgTotal=0,this.avgCount=0,this.maxValue=0),this.enabled){let e=1.5*this.watermark;if(this.sample[0]=Math.floor(t/e*255),this.sample[1]=0,this.sample[2]=0,this.sample[3]=this.watermark/e*255,this.yOffset>=this.texture.height)return;let i=this.texture.lock();if(this.needsClear){let e=this.yOffset*this.texture.width*4;i.fill(0,e,e+4*this.texture.width),this.needsClear=false;}i.set(this.sample,(this.cursor+this.yOffset*this.texture.width)*4),this.texture.unlock(),this.cursor++,this.cursor===this.texture.width&&(this.cursor=0);}}render(e,t,i,s,r){e.quad(t+s,i,-s,r,this.enabled?this.cursor:0,this.enabled?.5+this.yOffset:this.texture.height-1,-s,0,this.texture,this.graphType);}constructor(e,t,i,s,r){this.app=t,this.name=e,this.device=t.graphicsDevice,this.timer=r,this.watermark=i,this.enabled=false,this.textRefreshRate=s,this.avgTotal=0,this.avgTimer=0,this.avgCount=0,this.maxValue=0,this.timingText="",this.maxText="",this.texture=null,this.yOffset=0,this.graphType=0,this.cursor=0,this.sample=new Uint8ClampedArray(4),this.sample.set([0,0,0,255]),this.needsClear=false,this.counter=0,this.app.on("frameupdate",this.update,this);}}class wi{destroy(){this.texture.destroy(),this.texture=null;}render(e,t,i,s){let r=this.placements.get(t);if(r)return e.quad(i+r.l-1,s-r.d+1,r.w+2,r.h+2,r.x-1,this.texture.height-r.y-r.h-1,void 0,void 0,this.texture,1),r.w;let a=0;for(let r=0;r{e.font='10px "Lucida Console", Monaco, monospace',e.textAlign="left",e.textBaseline="alphabetic";},s=document.createElement("canvas"),r=s.getContext("2d",{alpha:true});i(r);let a=new Map,n=5,o=5;t.forEach(e=>{let t=r.measureText(e),i=Math.ceil(-t.actualBoundingBoxLeft),s=Math.ceil(t.actualBoundingBoxRight),l=Math.ceil(t.actualBoundingBoxAscent),h=Math.ceil(t.actualBoundingBoxDescent),c=i+s;n+c+5>=512&&(n=5,o+=16),a.set(e,{l:i,r:s,a:l,d:h,w:c,h:l+h,x:n,y:o}),n+=c+5;}),s.width=512,s.height=ei.nextPowerOfTwo(o+16+5),i(r),r.fillStyle="rgb(0, 0, 0)",r.fillRect(0,0,s.width,s.height),a.forEach((e,t)=>{r.fillStyle="."===t||1===t.length&&t.charCodeAt(0)>=48&&57>=t.charCodeAt(0)?"rgb(255, 240, 100)":"rgb(150, 220, 230)",r.fillText(t,e.x-e.l,e.y+e.a);}),this.placements=a;let l=r.getImageData(0,0,s.width,s.height).data;for(let e=0;e{try{if(typeof WebAssembly=="object"&&typeof WebAssembly.instantiate=="function"){let a=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(a instanceof WebAssembly.Module)return new WebAssembly.Instance(a)instanceof WebAssembly.Instance}}catch{}return!1},i=(a,o)=>{t(null,{workerUrl:URL.createObjectURL(e(a)),module:o,rgbPriority:c.rgbPriority,rgbaPriority:c.rgbaPriority})},r={cache:!0,responseType:"text",retry:c.maxRetries>0,maxRetries:c.maxRetries};if(c.glueUrl&&c.wasmUrl&&s()){let a=null,o=null;Le.get(c.glueUrl,r,(f,u)=>{f?t(f):o?i(u,o):a=u});let l=fetch(c.wasmUrl),h=()=>{l.then(f=>f.arrayBuffer()).then(f=>WebAssembly.compile(f)).then(f=>{a?i(a,f):o=f}).catch(f=>{t(f,null)})};WebAssembly.compileStreaming?WebAssembly.compileStreaming(l).then(f=>{a?i(a,f):o=f}).catch(f=>{h()}):h()}else Le.get(c.fallbackUrl,r,(a,o)=>{a?t(a,null):i(o,null)})},_b=class{constructor(){this.callbacks={},this.queue=[],this.clients=[]}enqueueJob(t,e,s,i){if(this.callbacks.hasOwnProperty(t))this.callbacks[t].push(s);else{this.callbacks[t]=[s];let r={url:t,data:e,options:i};this.clients.length>0?this.clients.shift().run(r):this.queue.push(r)}}enqueueClient(t){this.queue.length>0?t.run(this.queue.shift()):this.clients.push(t)}handleResponse(t,e,s){let i=this.callbacks[t];if(e)for(let r=0;rnew Uint16Array(r)):s.levels=s.levels.map(r=>new Uint8Array(r));for(let r=0;r{let r=i.data;this.queue.handleResponse(r.url,r.err,r.data),this.eager||this.queue.enqueueClient(this)}),this.worker.postMessage({type:"init",config:e}),this.eager=s}run(t){let e=[];t.data instanceof ArrayBuffer&&e.push(t.data),this.worker.postMessage({type:"transcode",url:t.url,format:t.format,data:t.data,options:t.options},e),this.eager&&this.queue.enqueueClient(this)}},aq=1,oq=["etc2","etc1","astc","dxt","pvr","atc"],nq=["astc","dxt","etc2","pvr","atc"],lq=5,Sb=new _b,RG=null,xb=!1;function vb(c){if(!xb){if(!c)c=RG||{};else if(c.lazyInit){RG=c;return}if(!c.glueUrl||!c.wasmUrl||!c.fallbackUrl){let t=Yl.getConfig("BASIS");t&&(c={glueUrl:t.glueUrl,wasmUrl:t.wasmUrl,fallbackUrl:t.fallbackUrl,numWorkers:t.numWorkers})}if(c.glueUrl||c.wasmUrl||c.fallbackUrl){xb=!0;let t=Math.max(1,Math.min(16,c.numWorkers||aq)),e=c.numWorkers===1||(c.hasOwnProperty("eagerWorkers")?c.eagerWorkers:!0);c.rgbPriority=c.rgbPriority||oq,c.rgbaPriority=c.rgbaPriority||nq,c.maxRetries=c.hasOwnProperty("maxRetries")?c.maxRetries:lq,rq(c,(s,i)=>{if(!s)for(let r=0;r{iA(i,t.load,a,e,{isGGGR:(s?.file?.variants?.basis?.opt&8)!==0})||e(`Basis module not found. Asset [${s.name}](${s.getFileUrl()}) basis texture variant will not be loaded.`)};ae.fetchArrayBuffer(t.load,(a,o)=>{a?e(a):r(o)},s,this.maxRetries)}open(t,e,s,i={}){let r=i.srgb?Cn(e.format):e.format,a=new Z(s,{name:t,addressU:e.cubemap?1:0,addressV:e.cubemap?1:0,width:e.width,height:e.height,format:r,cubemap:e.cubemap,levels:e.levels,...i});return a.upload(),a}};var aA=class extends nr{constructor(t,e){super(),this.crossOrigin=t.prefix?"anonymous":null,this.maxRetries=0,this.device=e}load(t,e,s){let i=!!s?.file?.contents;if(i){if(this.device.supportsImageBitmap){this._loadImageBitmapFromBlob(new Blob([s.file.contents]),e);return}t={load:URL.createObjectURL(new Blob([s.file.contents])),original:t.original}}let r=(o,l)=>{i&&URL.revokeObjectURL(t.load),e(o,l)},a;s&&s.options&&s.options.hasOwnProperty("crossOrigin")?a=s.options.crossOrigin:Ja.test(t.load)&&(a=this.crossOrigin),this.device.supportsImageBitmap?this._loadImageBitmap(t.load,t.original,a,r,s):this._loadImage(t.load,t.original,a,r,s)}open(t,e,s,i={}){let r=new Z(s,{name:t,width:e.width,height:e.height,format:i.srgb?st:ce,...i});return r.setSource(e),r}_loadImage(t,e,s,i,r){let a=new Image;s&&(a.crossOrigin=s);let o=0,l=this.maxRetries,h,f=1024*1024;r?.fire("progress",0,f),a.onload=function(){r?.fire("progress",f,f),i(null,a)},a.onerror=function(){if(!h)if(l>0&&++o<=l){let u=Math.pow(2,o)*100,p=t.indexOf("?")>=0?"&":"?";h=setTimeout(()=>{a.src=`${t+p}retry=${Date.now()}`,h=null},u)}else i(`Error loading Texture from: '${e}'`)},a.src=t}_loadImageBitmap(t,e,s,i,r){let a={cache:!0,responseType:"blob",retry:this.maxRetries>0,maxRetries:this.maxRetries,progress:r};Le.get(t,a,(o,l)=>{o?i(o):this._loadImageBitmapFromBlob(l,i)})}_loadImageBitmapFromBlob(t,e){createImageBitmap(t,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(s=>e(null,s)).catch(s=>e(s))}};var Tb=[1481919403,3140563232,169478669],cq={33776:To,33778:Ql,33779:Gr,36196:Eo,37492:Jl,37496:ec,35840:Ao,35841:Vr,35842:Co,35843:Hr,32849:Ss,32856:ce,35905:yo,35907:st,35898:Gi,34843:vn,34842:Me};function hq(c,t,e,s){return c===Gi?new Uint32Array(t,e,s/4):new Uint8Array(t,e,s)}var oA=class extends nr{constructor(t){super(),this.maxRetries=0}load(t,e,s){ae.fetchArrayBuffer(t.load,e,s,this.maxRetries)}open(t,e,s,i={}){let r=this.parse(e);if(!r)return null;let a=i.srgb?Cn(r.format):r.format,o=new Z(s,{name:t,addressU:r.cubemap?1:0,addressV:r.cubemap?1:0,width:r.width,height:r.height,format:a,cubemap:r.cubemap,levels:r.levels,...i});return o.upload(),o}parse(t){let e=new Uint32Array(t);if(Tb[0]!==e[0]||Tb[1]!==e[1]||Tb[2]!==e[2])return null;let s={endianness:e[3],glType:e[4],glTypeSize:e[5],glFormat:e[6],glInternalFormat:e[7],glBaseInternalFormat:e[8],pixelWidth:e[9],pixelHeight:e[10],pixelDepth:e[11],numberOfArrayElements:e[12],numberOfFaces:e[13],numberOfMipmapLevels:e[14],bytesOfKeyValueData:e[15]};if(s.pixelDepth>1||s.numberOfArrayElements!==0)return null;let i=cq[s.glInternalFormat];if(i===void 0)return null;let r=16+s.bytesOfKeyValueData/4,a=s.numberOfFaces>1,o=[];for(let l=0;l<(s.numberOfMipmapLevels||1);l++){let h=e[r++];a&&o.push([]);let f=a?o[l]:o;for(let u=0;u<(a?6:1);++u)f.push(hq(i,t,r*4,h)),r+=h+3>>2}return{format:i,width:s.pixelWidth,height:s.pixelHeight,levels:o,cubemap:a}}};var fq={KHR_DF_MODEL_ETC1S:163,KHR_DF_MODEL_UASTC:166},nA=class extends nr{constructor(t,e){super(),this.maxRetries=0,this.device=e}load(t,e,s){ae.fetchArrayBuffer(t.load,(i,r)=>{i?e(i,r):this.parse(r,t,e,s)},s,this.maxRetries)}open(t,e,s,i={}){let r=i.srgb?Cn(e.format):e.format,a=new Z(s,{name:t,addressU:e.cubemap?1:0,addressV:e.cubemap?1:0,width:e.width,height:e.height,format:r,cubemap:e.cubemap,levels:e.levels,...i});return a.upload(),a}parse(t,e,s,i){let r=new Kl(t),a=[r.readU32be(),r.readU32be(),r.readU32be()];if(a[0]!==2873840728||a[1]!==540160187||a[2]!==218765834)return null;let o={vkFormat:r.readU32(),typeSize:r.readU32(),pixelWidth:r.readU32(),pixelHeight:r.readU32(),pixelDepth:r.readU32(),layerCount:r.readU32(),faceCount:r.readU32(),levelCount:r.readU32(),supercompressionScheme:r.readU32()},l={dfdByteOffset:r.readU32(),dfdByteLength:r.readU32(),kvdByteOffset:r.readU32(),kvdByteLength:r.readU32(),sgdByteOffset:r.readU64(),sgdByteLength:r.readU64()},h=[];for(let d=0;d1,...i});let G=128,M=d?6:1,H,U=4,L=4,b=f===p?8:16,N,k,z;for(let V=0;V32767)return this._readPixelsFlat(t,e,s);let r=[0,0,0,0];if(t.readArray(r),r[0]!==2||r[1]!==2||(r[2]&128)!==0)return t.skip(-4),this._readPixelsFlat(t,e,s);let a=new ArrayBuffer(e*s*4),o=new Uint8Array(a),l=i?0:e*4*(s-1),h,f,u,d,p,m;for(f=0;f128){if(p-=128,h+p>e)return null;for(m=t.readU8(),u=0;ue)return null;for(u=0;u>1),l=Math.max(1,r>>1),h=new a.constructor(o*l*4),f=Math.floor(i/o),u=Math.floor(r/l),d=f*u;for(let p=0;p>i-1),a=Math.max(1,c._height>>i-1);if(c._cubemap){let o=[];for(let l=0;l<6;++l)o.push(s(r,a,c._levels[i-1][l]));c._levels.push(o)}else c._levels.push(s(r,a,c._levels[i-1]))}c._levelsUpdated=c._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0]},X_=class extends Re{constructor(t){super(t,"texture");let e=t.assets,s=t.graphicsDevice;this._device=s,this._assets=e,this.imgParser=new aA(e,s),this.parsers={dds:new lA(e),ktx:new oA(e),ktx2:new nA(e,s),basis:new rA(e,s),hdr:new cA(e)}}set crossOrigin(t){this.imgParser.crossOrigin=t}get crossOrigin(){return this.imgParser.crossOrigin}set maxRetries(t){this.imgParser.maxRetries=t;for(let e in this.parsers)this.parsers.hasOwnProperty(e)&&(this.parsers[e].maxRetries=t)}get maxRetries(){return this.imgParser.maxRetries}_getUrlWithoutParams(t){return t.indexOf("?")>=0?t.split("?")[0]:t}_getParser(t){let e=xe.getExtension(this._getUrlWithoutParams(t)).toLowerCase().replace(".","");return this.parsers[e]||this.imgParser}_getTextureOptions(t){let e={};if(t){t.name?.length>0&&(e.name=t.name);let s=t.data;s.hasOwnProperty("minfilter")&&(e.minFilter=DG[s.minfilter]),s.hasOwnProperty("magfilter")&&(e.magFilter=DG[s.magfilter]),s.hasOwnProperty("addressu")&&(e.addressU=bG[s.addressu]),s.hasOwnProperty("addressv")&&(e.addressV=bG[s.addressv]),s.hasOwnProperty("mipmaps")&&(e.mipmaps=s.mipmaps),s.hasOwnProperty("anisotropy")&&(e.anisotropy=s.anisotropy),s.hasOwnProperty("flipY")&&(e.flipY=!!s.flipY),s.hasOwnProperty("srgb")&&(e.srgb=!!s.srgb),e.type=Gt,s.hasOwnProperty("type")?e.type=uq[s.type]:s.hasOwnProperty("rgbm")&&s.rgbm?e.type=_i:t.file&&(t.file.opt&8)!==0&&(e.type=Rn)}return e}load(t,e,s){typeof t=="string"&&(t={load:t,original:t}),this._getParser(t.original).load(t,e,s)}open(t,e,s){if(!t)return;let i=this._getTextureOptions(s),r=this._getParser(t).open(t,e,this._device,i);return r===null?r=new Z(this._device,{width:4,height:4,format:Ss}):(dq(r),e.unswizzledGGGR&&(s.file.variants.basis.opt&=-9)),r}patch(t,e){let s=t.resource;if(!s)return;let i=this._getTextureOptions(t);for(let r of Object.keys(i))s[r]=i[r]}};var yb="inline",Eb="immersive-vr",bl="immersive-ar",hA="viewer",pq="local",mq="local-floor",_q="bounded-floor",gq="unbounded",Sq="gaze",xq="screen",vq="tracked-pointer",Tq="none",yq="left",Eq="right",Aq="none",Ab="left",Cq="right",Pq="point",wq="plane",Iq="mesh",Cb="cpu-optimized",ox="gpu-optimized",nx="luminance-alpha",lx="unsigned-short",cx="float32";var Y_=class{constructor(t){n(this,"_manager");n(this,"_supported",ue.browser&&!!window.XRDOMOverlayState);n(this,"_root",null);this._manager=t}get supported(){return this._supported}get available(){return this._supported&&this._manager.active&&this._manager._session.domOverlayState!==null}get state(){return!this._supported||!this._manager.active||!this._manager._session.domOverlayState?null:this._manager._session.domOverlayState.type}set root(t){!this._supported||this._manager.active||(this._root=t)}get root(){return this._root}};var fA=[],LG=[],Ah=class extends J{constructor(e,s,i,r=null){super();n(this,"manager");n(this,"_xrHitTestSource");n(this,"_transient");n(this,"_inputSource");this.manager=e,this._xrHitTestSource=s,this._transient=i,this._inputSource=r}remove(){if(!this._xrHitTestSource)return;let e=this.manager.hitTest.sources,s=e.indexOf(this);s!==-1&&e.splice(s,1),this.onStop()}onStop(){this._xrHitTestSource.cancel(),this._xrHitTestSource=null,this.fire("remove"),this.manager.hitTest.fire("remove",this)}update(e){if(this._transient){let s=e.getHitTestResultsForTransientInput(this._xrHitTestSource);for(let i=0;i=r||(r=u,a=e[h],o.copy(f.transform.position),l.copy(f.transform.orientation))}this.fire("result",o,l,s||this._inputSource,a),this.manager.hitTest.fire("result",this,o,l,s||this._inputSource,a),fA.push(i),fA.push(o),LG.push(l)}};n(Ah,"EVENT_REMOVE","remove"),n(Ah,"EVENT_RESULT","result");var _a=class extends J{constructor(e){super();n(this,"manager");n(this,"_supported",ue.browser&&!!(window.XRSession&&window.XRSession.prototype.requestHitTestSource));n(this,"_available",!1);n(this,"_checkingAvailability",!1);n(this,"sources",[]);this.manager=e,this._supported&&(this.manager.on("start",this._onSessionStart,this),this.manager.on("end",this._onSessionEnd,this))}_onSessionStart(){if(this.manager.session.enabledFeatures){let e=this.manager.session.enabledFeatures.indexOf("hit-test")!==-1;if(!e)return;this._available=e,this.fire("available")}else this._checkingAvailability||(this._checkingAvailability=!0,this.manager.session.requestReferenceSpace(hA).then(e=>{this.manager.session.requestHitTestSource({space:e}).then(s=>{s.cancel(),this.manager.active&&(this._available=!0,this.fire("available"))}).catch(()=>{})}).catch(()=>{}))}_onSessionEnd(){if(this._available){this._available=!1;for(let e=0;e{if(!this.manager.session){let o=new Error("XR Session is not started (2)");r&&r(o),this.fire("error",o);return}this.manager.session.requestHitTestSource({space:a,entityTypes:e.entityTypes||void 0,offsetRay:s}).then(o=>{this._onHitTestSource(o,!1,e.inputSource,r)}).catch(o=>{r&&r(o),this.fire("error",o)})}).catch(a=>{r&&r(a),this.fire("error",a)}):this.manager.session.requestHitTestSourceForTransientInput({profile:e.profile,entityTypes:e.entityTypes||void 0,offsetRay:s}).then(a=>{this._onHitTestSource(a,!0,e.inputSource,r)}).catch(a=>{r&&r(a),this.fire("error",a)})}_onHitTestSource(e,s,i,r){if(!this.manager.session){e.cancel();let o=new Error("XR Session is not started (3)");r&&r(o),this.fire("error",o);return}let a=new Ah(this.manager,e,s,i??null);this.sources.push(a),r&&r(null,a),this.fire("add",a)}update(e){if(this._available)for(let s=0;s(this._bitmap=e,{image:this._bitmap,widthInMeters:this._width}))}destroy(){this._image=null,this._pose=null,this._bitmap&&(this._bitmap.close(),this._bitmap=null)}getPosition(){return this._pose&&this._position.copy(this._pose.transform.position),this._position}getRotation(){return this._pose&&this._rotation.copy(this._pose.transform.orientation),this._rotation}};n(Ch,"EVENT_TRACKED","tracked"),n(Ch,"EVENT_UNTRACKED","untracked");var Bu=class extends J{constructor(e){super();n(this,"_manager");n(this,"_supported",ue.browser&&!!window.XRImageTrackingResult);n(this,"_available",!1);n(this,"_images",[]);this._manager=e,this._supported&&(this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this))}add(e,s){if(!this._supported||this._manager.active)return null;let i=new Ch(e,s);return this._images.push(i),i}remove(e){if(this._manager.active)return;let s=this._images.indexOf(e);s!==-1&&(e.destroy(),this._images.splice(s,1))}_onSessionStart(){this._manager.session.getTrackedImageScores().then(e=>{this._available=!0;for(let s=0;s{this._available=!1,this.fire("error",e)})}_onSessionEnd(){this._available=!1;for(let e=0;es.prepare())).then(s=>{e(null,s)}).catch(s=>{e(s,null)}):e(null,null)}update(e){if(!this._available)return;let s=e.getImageTrackingResults(),i={};for(let r=0;r0&&(NG.sub2(this._localPosition,this._localPositionLast).divScalar(o),this._linearVelocity.lerp(this._linearVelocity,NG,.15))}else this._velocitiesAvailable=!1}let i=e.getPose(this._xrInputSource.targetRaySpace,this._manager._referenceSpace);i&&(this._dirtyRay=!0,this._rayLocal.origin.copy(i.transform.position),this._rayLocal.direction.set(0,0,-1),BG.copy(i.transform.orientation),BG.transformVector(this._rayLocal.direction,this._rayLocal.direction))}}_updateTransforms(){this._dirtyLocal&&(this._dirtyLocal=!1,this._localTransform.setTRS(this._localPosition,this._localRotation,x.ONE));let e=this._manager.camera.parent;e?this._worldTransform.mul2(e.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform)}_updateRayTransforms(){let e=this._dirtyRay;this._dirtyRay=!1;let s=this._manager.camera.parent;if(s){let i=s.getWorldTransform();i.getTranslation(this._position),this._rotation.setFromMat4(i),this._rotation.transformVector(this._rayLocal.origin,this._ray.origin),this._ray.origin.add(this._position),this._rotation.transformVector(this._rayLocal.direction,this._ray.direction)}else e&&(this._ray.origin.copy(this._rayLocal.origin),this._ray.direction.copy(this._rayLocal.direction))}getPosition(){return this._grip?(this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position):null}getLocalPosition(){return this._localPosition}getRotation(){return this._grip?(this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation):null}getLocalRotation(){return this._localRotation}getLinearVelocity(){return this._velocitiesAvailable?this._linearVelocity:null}getOrigin(){return this._updateRayTransforms(),this._ray.origin}getDirection(){return this._updateRayTransforms(),this._ray.direction}hitTestStart(e={}){e.inputSource=this,e.profile=this._xrInputSource.profiles[0];let s=e.callback;e.callback=(i,r)=>{r&&this.onHitTestSourceAdd(r),s&&s(i,r)},this._manager.hitTest.start(e)}onHitTestSourceAdd(e){this._hitTestSources.push(e),this.fire("hittest:add",e),e.on("result",(s,i,r,a)=>{r===this&&this.fire("hittest:result",e,s,i,a)}),e.once("remove",()=>{this.onHitTestSourceRemove(e),this.fire("hittest:remove",e)})}onHitTestSourceRemove(e){let s=this._hitTestSources.indexOf(e);s!==-1&&this._hitTestSources.splice(s,1)}};n(Es,"EVENT_REMOVE","remove"),n(Es,"EVENT_SELECT","select"),n(Es,"EVENT_SELECTSTART","selectstart"),n(Es,"EVENT_SELECTEND","selectend"),n(Es,"EVENT_SQUEEZE","squeeze"),n(Es,"EVENT_SQUEEZESTART","squeezestart"),n(Es,"EVENT_SQUEEZEEND","squeezeend"),n(Es,"EVENT_HITTESTADD","hittest:add"),n(Es,"EVENT_HITTESTREMOVE","hittest:remove"),n(Es,"EVENT_HITTESTRESULT","hittest:result");var lr=class extends J{constructor(e){super();n(this,"manager");n(this,"_inputSources",[]);n(this,"_onInputSourcesChangeEvt");n(this,"velocitiesSupported",!1);this.manager=e,this.velocitiesSupported=!!(ue.browser&&window.XRPose?.prototype?.hasOwnProperty("linearVelocity")),this._onInputSourcesChangeEvt=s=>{this._onInputSourcesChange(s)},this.manager.on("start",this._onSessionStart,this),this.manager.on("end",this._onSessionEnd,this)}_onSessionStart(){let e=this.manager.session;e.addEventListener("inputsourceschange",this._onInputSourcesChangeEvt),e.addEventListener("select",i=>{let r=this._getByInputSource(i.inputSource);r.update(i.frame),r.fire("select",i),this.fire("select",r,i)}),e.addEventListener("selectstart",i=>{let r=this._getByInputSource(i.inputSource);r.update(i.frame),r._selecting=!0,r.fire("selectstart",i),this.fire("selectstart",r,i)}),e.addEventListener("selectend",i=>{let r=this._getByInputSource(i.inputSource);r.update(i.frame),r._selecting=!1,r.fire("selectend",i),this.fire("selectend",r,i)}),e.addEventListener("squeeze",i=>{let r=this._getByInputSource(i.inputSource);r.update(i.frame),r.fire("squeeze",i),this.fire("squeeze",r,i)}),e.addEventListener("squeezestart",i=>{let r=this._getByInputSource(i.inputSource);r.update(i.frame),r._squeezing=!0,r.fire("squeezestart",i),this.fire("squeezestart",r,i)}),e.addEventListener("squeezeend",i=>{let r=this._getByInputSource(i.inputSource);r.update(i.frame),r._squeezing=!1,r.fire("squeezeend",i),this.fire("squeezeend",r,i)});let s=e.inputSources;for(let i=0;i{let i=this._lightProbeRequested;this._lightProbeRequested=!1,this._manager.active?i&&(this._lightProbe=s):this.fire("error",new Error("XR session is not active"))}).catch(s=>{this._lightProbeRequested=!1,this.fire("error",s)})}end(){this._lightProbeRequested=!1,this._lightProbe=null,this._available=!1}update(e){if(!this._lightProbe)return;let s=e.getLightEstimate(this._lightProbe);if(!s)return;this._available||(this._available=!0,this.fire("available"));let i=s.primaryLightIntensity;this._intensity=Math.max(1,Math.max(i.x,Math.max(i.y,i.z))),j_.copy(i).mulScalar(1/this._intensity),this._color.set(j_.x,j_.y,j_.z),j_.set(0,0,0),UG.copy(s.primaryLightDirection),Pb.setLookAt(UG,j_,x.UP),kG.setFromAxisAngle(x.RIGHT,90),Pb.mul(kG),this._rotation.setFromMat4(Pb),this._sphericalHarmonics.set(s.sphericalHarmonicsCoefficients)}get supported(){return this._supported}get available(){return this._available}get intensity(){return this._available?this._intensity:null}get color(){return this._available?this._color:null}get rotation(){return this._available?this._rotation:null}get sphericalHarmonics(){return this._available?this._sphericalHarmonics:null}};n(wh,"EVENT_AVAILABLE","available"),n(wh,"EVENT_ERROR","error");var bq=0,Ih=class extends J{constructor(e,s){super();n(this,"_id");n(this,"_planeDetection");n(this,"_xrPlane");n(this,"_lastChangedTime");n(this,"_orientation");n(this,"_position",new x);n(this,"_rotation",new $);this._id=++bq,this._planeDetection=e,this._xrPlane=s,this._lastChangedTime=s.lastChangedTime,this._orientation=s.orientation}destroy(){this._xrPlane&&(this._xrPlane=null,this.fire("remove"))}update(e){let s=this._planeDetection._manager,i=e.getPose(this._xrPlane.planeSpace,s._referenceSpace);i&&(this._position.copy(i.transform.position),this._rotation.copy(i.transform.orientation)),this._lastChangedTime!==this._xrPlane.lastChangedTime&&(this._lastChangedTime=this._xrPlane.lastChangedTime,this.fire("change"))}getPosition(){return this._position}getRotation(){return this._rotation}get id(){return this._id}get orientation(){return this._orientation}get points(){return this._xrPlane.polygon}get label(){return this._xrPlane.semanticLabel||""}};n(Ih,"EVENT_REMOVE","remove"),n(Ih,"EVENT_CHANGE","change");var on=class extends J{constructor(e){super();n(this,"_manager");n(this,"_supported",ue.browser&&!!window.XRPlane);n(this,"_available",!1);n(this,"_planesIndex",new Map);n(this,"_planes",[]);this._manager=e,this._supported&&(this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this))}_onSessionStart(){this._manager.session.enabledFeatures&&this._manager.session.enabledFeatures.indexOf("plane-detection")!==-1&&(this._available=!0,this.fire("available"))}_onSessionEnd(){for(let e=0;e{this._uuid=s,this._anchors._indexByUuid.set(this._uuid,this),e?.(null,s);for(let i of this._uuidRequests)i(null,s);this._uuidRequests=null,this.fire("persist",s)}).catch(s=>{e?.(s,null);for(let i of this._uuidRequests)i(s,null);this._uuidRequests=null})}forget(e){if(!this._uuid){e?.(new Error("Anchor is not persistent"));return}this._anchors.forget(this._uuid,s=>{this._uuid=null,e?.(s),this.fire("forget")})}get uuid(){return this._uuid}get persistent(){return!!this._uuid}};n(nn,"EVENT_DESTROY","destroy"),n(nn,"EVENT_CHANGE","change"),n(nn,"EVENT_PERSIST","persist"),n(nn,"EVENT_FORGET","forget");var oo=class extends J{constructor(e){super();n(this,"manager");n(this,"_supported",ue.browser&&!!window.XRAnchor);n(this,"_available",!1);n(this,"_checkingAvailability",!1);n(this,"_persistence",ue.browser&&!!window?.XRSession?.prototype.restorePersistentAnchor);n(this,"_creationQueue",[]);n(this,"_index",new Map);n(this,"_indexByUuid",new Map);n(this,"_list",[]);n(this,"_callbacksAnchors",new Map);this.manager=e,this._supported&&(this.manager.on("start",this._onSessionStart,this),this.manager.on("end",this._onSessionEnd,this))}_onSessionStart(){let e=this.manager.session.enabledFeatures?.indexOf("anchors")>=0;e&&(this._available=e,this.fire("available"))}_onSessionEnd(){if(!this._available)return;this._available=!1;for(let s=0;s{let o=this._createAnchor(a);i?.(null,o),this.fire("add",o)}).catch(a=>{i?.(a,null),this.fire("error",a)})}else this._creationQueue.push({transform:new XRRigidTransform(e,s),callback:i})}restore(e,s){if(!this._available){s?.(new Error("Anchors API is not available"),null);return}if(!this._persistence){s?.(new Error("Anchor Persistence is not supported"),null);return}if(!this.manager.active){s?.(new Error("WebXR session is not active"),null);return}this.manager.session.restorePersistentAnchor(e).then(i=>{let r=this._createAnchor(i,e);s?.(null,r),this.fire("add",r)}).catch(i=>{s?.(i,null),this.fire("error",i)})}forget(e,s){if(!this._available){s?.(new Error("Anchors API is not available"));return}if(!this._persistence){s?.(new Error("Anchor Persistence is not supported"));return}if(!this.manager.active){s?.(new Error("WebXR session is not active"));return}this.manager.session.deletePersistentAnchor(e).then(()=>{s?.(null)}).catch(i=>{s?.(i),this.fire("error",i)})}update(e){if(!this._available){!this.manager.session.enabledFeatures&&!this._checkingAvailability&&(this._checkingAvailability=!0,e.createAnchor(new XRRigidTransform,this.manager._referenceSpace).then(s=>{s.delete(),this.manager.active&&(this._available=!0,this.fire("available"))}).catch(()=>{}));return}if(this._creationQueue.length){for(let s=0;s{i.callback&&this._callbacksAnchors.set(r,i.callback)}).catch(r=>{i.callback&&i.callback(r,null),this.fire("error",r)})}this._creationQueue.length=0}for(let[s,i]of this._index)e.trackedAnchors.has(s)||(this._index.delete(s),i.destroy());for(let s=0;s{this._deviceAvailabilityCheck()}),this._deviceAvailabilityCheck())}get graphicsBinding(){return this.xrBridge?.graphicsBinding??null}destroy(){this.xrBridge&&(this.xrBridge.destroy(),this.xrBridge=null)}start(e,s,i,r){let a=r;if(typeof r=="object"&&(a=r.callback),!this._available[s]){Yx("WebXR"),a&&a(new Error("XR is not available"));return}if(this._session){a&&a(new Error("XR session is already started"));return}this._camera=e,this._camera.camera.xr=this,this._type=s,this._spaceType=i,this._framebufferScaleFactor=r?.framebufferScaleFactor??1,this._setClipPlanes(e.nearClip,e.farClip);let o={requiredFeatures:[i],optionalFeatures:[]};if(this.app.graphicsDevice?.isWebGPU&&o.requiredFeatures.push("webgpu"),s===bl){if(o.optionalFeatures.push("light-estimation"),o.optionalFeatures.push("hit-test"),r&&(r.imageTracking&&this.imageTracking.supported&&o.optionalFeatures.push("image-tracking"),r.planeDetection&&o.optionalFeatures.push("plane-detection"),r.meshDetection&&o.optionalFeatures.push("mesh-detection")),this.domOverlay.supported&&this.domOverlay.root&&(o.optionalFeatures.push("dom-overlay"),o.domOverlay={root:this.domOverlay.root}),r&&r.anchors&&this.anchors.supported&&o.optionalFeatures.push("anchors"),r&&r.depthSensing&&this.views.supportedDepth){o.optionalFeatures.push("depth-sensing");let h=[],f=[];if(h.push(ox,Cb),f.push(cx,nx,lx),r.depthSensing.usagePreference){let u=h.indexOf(r.depthSensing.usagePreference);u!==-1&&h.splice(u,1),h.unshift(r.depthSensing.usagePreference)}if(r.depthSensing.dataFormatPreference){let u=f.indexOf(r.depthSensing.dataFormatPreference);u!==-1&&f.splice(u,1),f.unshift(r.depthSensing.dataFormatPreference)}o.depthSensing={usagePreference:h,dataFormatPreference:f}}r&&r.cameraColor&&this.views.supportedColor&&o.optionalFeatures.push("camera-access")}o.optionalFeatures.push("hand-tracking"),r&&r.optionalFeatures&&(o.optionalFeatures=o.optionalFeatures.concat(r.optionalFeatures)),this.imageTracking.supported&&this.imageTracking.images.length?this.imageTracking.prepareImages((h,f)=>{if(h){a&&a(h),this.fire("error",h);return}f!==null&&(o.trackedImages=f),this._onStartOptionsReady(s,i,o,a)}):this._onStartOptionsReady(s,i,o,a)}_onStartOptionsReady(e,s,i,r){navigator.xr.requestSession(e,i).then(a=>{this._onSessionStart(a,s,r)}).catch(a=>{this._camera.camera.xr=null,this._camera=null,this._type=null,this._spaceType=null,r&&r(a),this.fire("error",a)})}end(e){if(!this._session){e&&e(new Error("XR Session is not initialized"));return}this.xrBridge?.releasePresentation(),e&&this.once("end",e),this._session.end()}isAvailable(e){return this._available[e]}_deviceAvailabilityCheck(){for(let e in this._available)this._sessionSupportCheck(e)}initiateRoomCapture(e){if(!this._session){e(new Error("Session is not active"));return}if(!this._session.initiateRoomCapture){e(new Error("Session does not support manual room capture"));return}this._session.initiateRoomCapture().then(()=>{e&&e(null)}).catch(s=>{e&&e(s)})}updateTargetFrameRate(e,s){if(!this._session?.updateTargetFrameRate){s?.(new Error("unable to update frameRate"));return}this._session.updateTargetFrameRate(e).then(()=>{s?.()}).catch(i=>{s?.(i)})}_sessionSupportCheck(e){navigator.xr.isSessionSupported(e).then(s=>{this._available[e]!==s&&(this._available[e]=s,this.fire("available",e,s),this.fire(`available:${e}`,s))}).catch(s=>{this.fire("error",s)})}_onSessionStart(e,s,i){let r=!1;this._session=e,this.xrBridge=new pA(this.app.graphicsDevice,this);let a=()=>{this.fire("visibility:change",e.visibilityState)},o=()=>{this._setClipPlanes(this._camera.nearClip,this._camera.farClip)},l=()=>{this.fire("frameratechange",this._session?.frameRate)},h=()=>{this._camera&&(this._camera.off("set_nearClip",o),this._camera.off("set_farClip",o),this._camera.camera.xr=null,this._camera=null),e.removeEventListener("end",h),e.removeEventListener("visibilitychange",a),e.removeEventListener("frameratechange",l),r||this.fire("end"),this.xrBridge&&(this.xrBridge.destroy(),this.xrBridge=null),this._session=null,this._referenceSpace=null,this._width=0,this._height=0,this._type=null,this._spaceType=null,this.app.systems&&this.app.requestAnimationFrame()};e.addEventListener("end",h),e.addEventListener("visibilitychange",a),this._camera.on("set_nearClip",o),this._camera.on("set_farClip",o);let u=this.app.graphicsDevice.maxPixelRatio/window.devicePixelRatio*this._framebufferScaleFactor;this.xrBridge.attachPresentation(this._session,{framebufferScaleFactor:u,depthNear:this._depthNear,depthFar:this._depthFar,onBindingError:d=>{this.fire("error",d)}}),this.session.supportedFrameRates?this._supportedFrameRates=Array.from(this.session.supportedFrameRates):this._supportedFrameRates=null,this._session.addEventListener("frameratechange",l),e.requestReferenceSpace(s).then(d=>{this._referenceSpace=d,this.app.requestAnimationFrame(),i&&i(null),this.fire("start")}).catch(d=>{r=!0,e.end(),i&&i(d),this.fire("error",d)})}_setClipPlanes(e,s){this._depthNear===e&&this._depthFar===s||(this._depthNear=e,this._depthFar=s,this._session&&this._session.updateRenderState({depthNear:this._depthNear,depthFar:this._depthFar}))}update(e){if(!this._session)return!1;this.xrBridge.getFramebufferSize(e,this._framebufferSize);let s=this._framebufferSize.x,i=this._framebufferSize.y;(this._width!==s||this._height!==i)&&(this._width=s,this._height=i,this.app.graphicsDevice.setResolution(s,i));let r=e.getViewerPose(this._referenceSpace);if(!r)return!1;let a=this.views.list.length;this.views.update(e,r.views);let o=r.transform.position,l=r.transform.orientation;if(this._localPosition.set(o.x,o.y,o.z),this._localRotation.set(l.x,l.y,l.z,l.w),a===0&&this.views.list.length>0){let h=new W,f=this.views.list[0];h.copy(f.projMat);let u=h.data,d=2*Math.atan(1/u[5])*180/Math.PI,p=u[5]/u[0],m=u[14]/(u[10]+1),_=u[14]/(u[10]-1);this._camera.camera.setXrProperties({aspectRatio:p,farClip:m,fov:d,horizontalFov:!1,nearClip:_})}return this._camera.camera._node.setLocalPosition(this._localPosition),this._camera.camera._node.setLocalRotation(this._localRotation),this.input.update(e),this._type===bl&&(this.hitTest.supported&&this.hitTest.update(e),this.lightEstimation.supported&&this.lightEstimation.update(e),this.imageTracking.supported&&this.imageTracking.update(e),this.anchors.supported&&this.anchors.update(e),this.planeDetection.supported&&this.planeDetection.update(e),this.meshDetection.supported&&this.meshDetection.update(e)),this.fire("update",e),this.xrBridge.beginFrame(e,this._referenceSpace),!0}get supported(){return this._supported}get active(){return!!this._session}get type(){return this._type}get spaceType(){return this._spaceType}get session(){return this._session}get frameRate(){return this._session?.frameRate??null}get supportedFrameRates(){return this._supportedFrameRates}get framebufferScaleFactor(){return this._framebufferScaleFactor}set fixedFoveation(e){let s=this.xrBridge?.presentationLayer;(s?.fixedFoveation??null)!==null&&(this.app.graphicsDevice.samples>1,s.fixedFoveation=e)}get fixedFoveation(){return this.xrBridge?.presentationLayer?.fixedFoveation??null}get camera(){return this._camera?this._camera.entity:null}get visibilityState(){return this._session?this._session.visibilityState:null}};n(no,"EVENT_AVAILABLE","available"),n(no,"EVENT_START","start"),n(no,"EVENT_END","end"),n(no,"EVENT_UPDATE","update"),n(no,"EVENT_ERROR","error");var mA=class extends Pi{constructor(t,e={}){super(t);let s=new Tm;s.graphicsDevice=e.graphicsDevice??this.createDevice(t,e),this.addComponentSystems(s),this.addResourceHandles(s),s.elementInput=e.elementInput,s.keyboard=e.keyboard,s.mouse=e.mouse,s.touch=e.touch,s.gamepads=e.gamepads,s.scriptPrefix=e.scriptPrefix,s.assetPrefix=e.assetPrefix,s.scriptsOrder=e.scriptsOrder,s.soundManager=new tp,s.lightmapper=Em,s.batchManager=Rp,s.xr=no,this.init(s)}createDevice(t,e){return e.graphicsDeviceOptions||(e.graphicsDeviceOptions={}),ue.browser&&navigator.xr&&(e.graphicsDeviceOptions.xrCompatible=!0),e.graphicsDeviceOptions.alpha=e.graphicsDeviceOptions.alpha||!1,new pc(t,e.graphicsDeviceOptions)}addComponentSystems(t){t.componentSystems=[Al,Fm,Gm,Pm,Rm,Xm,qm,o_,n_,h_,s_,bm,jm,Jm,zm,Lm,e_,t_,i_,Wm,Vm,r_,vh]}addResourceHandles(t){t.resourceHandlers=[g_,v_,T_,y_,B_,N_,X_,H_,O_,E_,k_,U_,I_,M_,w_,z_,L_,R_,b_,A_,W_,G_,V_,P_,D_]}};var _A=class extends J{constructor(e,s){super();n(this,"_assets",new Set);n(this,"_loadingAssets",new Set);n(this,"_waitingAssets",new Set);n(this,"_loading",!1);n(this,"_loaded",!1);n(this,"_failed",[]);this._registry=s,e.forEach(i=>{if(i instanceof ae)i.registry||(i.registry=s),this._assets.add(i);else{let r=s.get(i);r?this._assets.add(r):this._waitForAsset(i)}})}destroy(){this._registry.off("load",this._onLoad),this._registry.off("error",this._onError),this._waitingAssets.forEach(e=>{this._registry.off(`add:${e}`,this._onAddAsset)}),this.off("progress"),this.off("load")}_assetHasDependencies(e){return e.type==="model"&&e.file?.url&&e.file.url&&e.file.url.match(/.json$/g)}load(e,s){if(this._loading)return;this._loading=!0,this._callback=e,this._scope=s,this._registry.on("load",this._onLoad,this),this._registry.on("error",this._onError,this);let i=!1;this._assets.forEach(r=>{r.loaded||(i=!0,this._assetHasDependencies(r)&&this._registry.loadFromUrl(r.file.url,r.type,(a,o)=>{if(a){this._onError(a,r);return}this._onLoad(r)}),this._loadingAssets.add(r),this._registry.add(r))}),this._loadingAssets.forEach(r=>{this._assetHasDependencies(r)||this._registry.load(r)}),!i&&this._waitingAssets.size===0&&this._loadingComplete()}ready(e,s=this){this._loaded?e.call(s,Array.from(this._assets)):this.once("load",i=>{e.call(s,i)})}_loadingComplete(){this._loaded||(this._loaded=!0,this._registry.off("load",this._onLoad,this),this._registry.off("error",this._onError,this),this._failed.length?(this._callback&&this._callback.call(this._scope,"Failed to load some assets",this._failed),this.fire("error",this._failed)):(this._callback&&this._callback.call(this._scope),this.fire("load",Array.from(this._assets))))}_onLoad(e){this._loadingAssets.has(e)&&(this.fire("progress",e),this._loadingAssets.delete(e)),this._loadingAssets.size===0&&setTimeout(()=>{this._loadingComplete()},0)}_onError(e,s){this._loadingAssets.has(s)&&(this._failed.push(s),this._loadingAssets.delete(s)),this._loadingAssets.size===0&&setTimeout(()=>{this._loadingComplete()},0)}_onAddAsset(e){this._waitingAssets.delete(e),this._assets.add(e),e.loaded||(this._loadingAssets.add(e),this._registry.load(e))}_waitForAsset(e){this._waitingAssets.add(e),this._registry.once(`add:${e}`,this._onAddAsset,this)}};var zG=4096,GG=512,wb=class{constructor(t,e,s,i){this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=s,this.texture=new Z(t,{name:i,format:st,width:e,height:s,mipmaps:!0,minFilter:5,magFilter:1,addressU:1,addressV:1,levels:[this.canvas]}),this.ctx=this.canvas.getContext("2d",{alpha:!0})}destroy(){this.texture.destroy()}clear(t){let{width:e,height:s}=this.canvas;this.ctx.clearRect(0,0,e,s),this.ctx.fillStyle=t,this.ctx.fillRect(0,0,e,s)}},gA=class extends J{constructor(t,e={}){super(),this.type="bitmap",this.app=t,this.intensity=0,this.fontWeight=e.fontWeight||"normal",this.fontSize=parseInt(e.fontSize,10),this.glyphSize=this.fontSize,this.fontName=e.fontName||"Arial",this.color=e.color||new F(1,1,1),this.padding=e.padding||0,this.width=Math.min(zG,e.width||GG),this.height=Math.min(zG,e.height||GG),this.atlases=[],this.chars="",this.data={}}createTextures(t){let e=this._normalizeCharsSet(t);if(e.length!==this.chars.length){this._renderAtlas(e);return}for(let s=0;s0&&this._renderAtlas(this.chars.concat(s))}destroy(){this.atlases.forEach(t=>t.destroy()),this.chars=null,this.color=null,this.data=null,this.fontName=null,this.fontSize=null,this.glyphSize=null,this.intensity=null,this.atlases=null,this.type=null,this.fontWeight=null}_colorToRgbString(t,e){let s,i=Math.round(255*t.r),r=Math.round(255*t.g),a=Math.round(255*t.b);return e?s=`rgba(${i}, ${r}, ${a}, ${t.a})`:s=`rgb(${i}, ${r}, ${a})`,s}renderCharacter(t,e,s,i,r){t.fillStyle=r,t.fillText(e,s,i)}_getAtlas(t){return t>=this.atlases.length&&(this.atlases[t]=new wb(this.app.graphicsDevice,this.width,this.height,`font-atlas-${this.fontName}-${t}`)),this.atlases[t]}_renderAtlas(t){this.chars=t;let e=this.width,s=this.height,i=this._colorToRgbString(this.color,!1),r=this.color.a;this.color.a=1/255;let a=this._colorToRgbString(this.color,!0);this.color.a=r;let o="center",l="alphabetic",h=0,f=this._getAtlas(h++);f.clear(a),this.data=this._createJson(this.chars,this.fontName,e,s);let u=Nr.getSymbols(this.chars.join("")),d=0,p=0,m={};for(let E=0;EA&&(A=this.fontSize*this.fontSize/w,f.ctx.font=`${this.fontWeight} ${A.toString()}px ${this.fontName}`,w=this.fontSize),this.renderCharacter(f.ctx,y,C+g,v+T,i);let I=this.padding+(this.glyphSize-w)/2,D=-this.padding+m[y].descent-p,O=w;this._addChar(this.data,y,P,C,v,_,S,I,D,O,h-1,e,s),C+=_,C+_>e&&(C=0,v+=S,v+S>s&&(f=this._getAtlas(h++),f.clear(a),v=0))}this.atlases.splice(h).forEach(E=>E.destroy()),this.atlases.forEach(E=>E.texture.upload()),this.fire("render")}_createJson(t,e,s,i){return{version:3,intensity:this.intensity,info:{face:e,width:s,height:i,maps:[{width:s,height:i}]},chars:{}}}_addChar(t,e,s,i,r,a,o,l,h,f,u,d,p){t.info.maps.lengtht.texture)}};var hx=[],Dq=[[],[],[]],Lq=new Float32Array(2),$_=class extends yt{constructor(e,s){super(e);n(this,"viewBindGroups",[]);n(this,"blendState",Oe.NOBLEND);n(this,"camera");n(this,"scene");n(this,"layers");n(this,"mapping");n(this,"depth");n(this,"_qualifiedLayerIndices",[]);n(this,"_pickMeshInstances",new Map);this.renderer=s}destroy(){this.viewBindGroups.forEach(e=>{e.defaultUniformBuffer.destroy(),e.destroy()}),this.viewBindGroups.length=0}update(e,s,i,r,a){this.camera=e,this.scene=s,this.layers=i,this.mapping=r,this.depth=a,s.clusteredLightingEnabled&&(this.emptyWorldClusters=this.renderer.worldClustersAllocator.empty)}before(){this._qualifiedLayerIndices.length=0,this._pickMeshInstances.clear();let{camera:e,scene:s,layers:i}=this,r=s.layers.layerList,a=s.layers.subLayerEnabled,o=this.renderer.gsplatDirector,l=this.renderTarget?.width??1,h=this.renderTarget?.height??1;for(let f=0;f0){let _=r.clusteredLightingEnabled;_&&this.emptyWorldClusters.activate(),s.setCameraUniforms(i.camera,o),s.dispatchGlobalLights(r),e.scope.resolve("shadowAtlasParams").setValue(Lq),e.supportsUniformBuffers&&(s.initViewBindGroupFormat(_),s.setupViewUniformBuffers(this.viewBindGroups,s.viewUniformFormat,s.viewBindGroupFormat,null));let S=this.depth?Sp:ta;s.renderForward(i.camera,o,hx,Dq,S,g=>{e.setBlendState(this.blendState)}),hx.length=0}}}};var Ib=new Set,Mq=new Q,VG=new Float32Array(1),Oq=new Int32Array(VG.buffer),SA=class{constructor(t,e,s,i=!1){n(this,"device");n(this,"renderPass");n(this,"depth");n(this,"width");n(this,"height");n(this,"renderTarget",null);n(this,"colorBuffer",null);n(this,"depthBuffer",null);n(this,"renderTargetDepth",null);n(this,"mapping",new Map);n(this,"deviceValid",!0);this.device=t.graphicsDevice,this.renderPass=new $_(this.device,t.renderer),this.depth=i,this.width=0,this.height=0,this.resize(e,s),this.allocateRenderTarget(),this.device.on("destroy",()=>{this.deviceValid=!1})}destroy(){this.releaseRenderTarget(),this.renderPass?.destroy()}getSelection(t,e,s=1,i=1){let r=this.device;if(r.isWebGPU)return[];e=this.renderTarget.height-(e+i);let a=this.sanitizeRect(t,e,s,i);r.setRenderTarget(this.renderTarget),r.updateBegin();let o=new Uint8Array(4*a.z*a.w);return r.readPixels(a.x,a.y,a.z,a.w,o),r.updateEnd(),this.decodePixels(o,this.mapping)}getSelectionAsync(t,e,s=1,i=1){return!this.renderTarget||!this.renderTarget.colorBuffer?Promise.resolve([]):this._readTexture(this.renderTarget.colorBuffer,t,e,s,i,this.renderTarget).then(r=>this.decodePixels(r,this.mapping))}_readTexture(t,e,s,i,r,a){this.device?.isWebGL2&&(s=a.height-(s+r));let o=this.sanitizeRect(e,s,i,r);return t.read(o.x,o.y,o.z,o.w,{immediate:!0,renderTarget:a})}async getWorldPointAsync(t,e){let s=this.renderPass.camera;if(!s)return null;let r=new W().mul2(s.camera.projectionMatrix,s.camera.viewMatrix).invert(),a=s.nearClip,o=s.farClip,l=s.projection===ni,h=await this.getPointDepthAsync(t,e);if(h===null)return null;let f=l?h:o*h/(h*(o-a)+a),u=new Q(t/this.width*2-1,(1-e/this.height)*2-1,f*2-1,1);return r.transformVec4(u,u),u.mulScalar(1/u.w),new x(u.x,u.y,u.z)}async getPointDepthAsync(t,e){if(!this.depthBuffer)return null;let s=await this._readTexture(this.depthBuffer,t,e,1,1,this.renderTargetDepth),i=(s[0]<<24|s[1]<<16|s[2]<<8|s[3])>>>0;return i===4294967295?null:(Oq[0]=i,VG[0])}sanitizeRect(t,e,s,i){let r=this.renderTarget.width,a=this.renderTarget.height;return t=R.clamp(Math.floor(t),0,r-1),e=R.clamp(Math.floor(e),0,a-1),s=Math.floor(Math.max(s,1)),s=Math.min(s,r-t),i=Math.floor(Math.max(i,1)),i=Math.min(i,a-e),Mq.set(t,e,s,i)}decodePixels(t,e){let s=[];if(this.deviceValid){let i=t.length;for(let r=0;r>>0;f!==4294967295&&Ib.add(e.get(f))}Ib.forEach(r=>{r&&s.push(r)}),Ib.clear()}return s}createTexture(t){return Z.createDataTexture2D(this.device,t,this.width,this.height,ce)}allocateRenderTarget(){this.colorBuffer=this.createTexture("pick");let t=[this.colorBuffer];this.depth&&(this.depthBuffer=this.createTexture("pick-depth"),t.push(this.depthBuffer),this.renderTargetDepth=new me({colorBuffer:this.depthBuffer,depth:!1})),this.renderTarget=new me({colorBuffers:t,depth:!0})}releaseRenderTarget(){this.renderTarget?.destroyTextureBuffers(),this.renderTarget?.destroy(),this.renderTarget=null,this.renderTargetDepth?.destroy(),this.renderTargetDepth=null,this.colorBuffer=null,this.depthBuffer=null}prepare(t,e,s){s instanceof Dt&&(s=[s]),this.renderTarget?.resize(this.width,this.height),this.renderTargetDepth?.resize(this.width,this.height),this.mapping.clear();let i=this.renderPass;i.init(this.renderTarget),i.setClearColor(F.WHITE),i.depthStencilOps.clearDepth=!0,i.update(t,e,s,this.mapping,this.depth),i.render()}resize(t,e){this.width=Math.floor(t),this.height=Math.floor(e)}};var xA=class extends Re{constructor(t){super(t,"scenesettings")}load(t,e){Eh.load(t,this.maxRetries,e)}open(t,e){return e.settings}};var bh,Dh,Rb=new x,HG=new x,Dl=new ws,dx=new ws,Mb=new ws;Dl.end=new x;dx.end=new x;Mb.end=new x;var Z_=new x,vA=new x,bb=new x,WG=new x,Db=new x,TA=new x,yA=new x,EA=new x,AA=new x,Lb=new x,Fq=new x,Q_=new x,fx=new x,CA=new x,PA=new x,ux=new x,XG=new x,YG=new x,KG=new x,jG=new x,Nq=new Q;function qG(c,t,e){return Fq.cross(c,t).dot(e)}function Bq(c,t,e){Z_.sub2(t,c),vA.sub2(e[0],c),bb.sub2(e[1],c),WG.sub2(e[2],c),TA.cross(WG,Z_);let s=vA.dot(TA),i,r;if(s>=0){if(i=-bb.dot(TA),i<0||(r=qG(Z_,bb,vA),r<0))return-1;let a=1/(i+s+r);yA.copy(e[0]).mulScalar(i*a),EA.copy(e[1]).mulScalar(s*a),AA.copy(e[2]).mulScalar(r*a),Lb.copy(yA).add(EA).add(AA)}else{if(Db.sub2(e[3],c),i=Db.dot(TA),i<0||(r=qG(Z_,vA,Db),r<0))return-1;s=-s;let a=1/(i+s+r);yA.copy(e[0]).mulScalar(i*a),EA.copy(e[3]).mulScalar(s*a),AA.copy(e[2]).mulScalar(r*a),Lb.copy(yA).add(EA).add(AA)}return Z_.sub2(e[0],e[2]).lengthSq()<1e-4*1e-4||Z_.sub2(e[1],e[3]).lengthSq()<1e-4*1e-4?-1:Lb.sub(c).lengthSq()}var Gu=class{constructor(t,e,s){this.event=t,this.element=e,this.camera=s,this._stopPropagation=!1}stopPropagation(){this._stopPropagation=!0,this.event&&(this.event.stopImmediatePropagation(),this.event.stopPropagation())}},Ll=class extends Gu{constructor(t,e,s,i,r,a,o){super(t,e,s),this.x=i,this.y=r,this.ctrlKey=t.ctrlKey||!1,this.altKey=t.altKey||!1,this.shiftKey=t.shiftKey||!1,this.metaKey=t.metaKey||!1,this.button=t.button,qi.isPointerLocked()?(this.dx=t.movementX||t.webkitMovementX||t.mozMovementX||0,this.dy=t.movementY||t.webkitMovementY||t.mozMovementY||0):(this.dx=i-a,this.dy=r-o),this.wheelDelta=0,t.type==="wheel"&&(t.deltaY>0?this.wheelDelta=1:t.deltaY<0&&(this.wheelDelta=-1))}},Ml=class extends Gu{constructor(t,e,s,i,r,a){super(t,e,s),this.touches=t.touches,this.changedTouches=t.changedTouches,this.x=i,this.y=r,this.touch=a}},ga=class extends Gu{constructor(t,e,s,i){super(t,e,s),this.inputSource=i}},J_=class c{constructor(t,e){this._app=null,this._attached=!1,this._target=null,this._enabled=!0,this._lastX=0,this._lastY=0,this._upHandler=this._handleUp.bind(this),this._downHandler=this._handleDown.bind(this),this._moveHandler=this._handleMove.bind(this),this._wheelHandler=this._handleWheel.bind(this),this._touchstartHandler=this._handleTouchStart.bind(this),this._touchendHandler=this._handleTouchEnd.bind(this),this._touchcancelHandler=this._touchendHandler,this._touchmoveHandler=this._handleTouchMove.bind(this),this._sortHandler=this._sortElements.bind(this),this._elements=[],this._hoveredElement=null,this._pressedElement=null,this._touchedElements={},this._touchesForWhichTouchLeaveHasFired={},this._selectedElements={},this._selectedPressedElements={},this._useMouse=!e||e.useMouse!==!1,this._useTouch=!e||e.useTouch!==!1,this._useXr=!e||e.useXr!==!1,this._selectEventsAttached=!1,ue.touch&&(this._clickedEntities={}),this.attach(t)}set enabled(t){this._enabled=t}get enabled(){return this._enabled}set app(t){this._app=t}get app(){return this._app||ys()}attach(t){this._attached&&(this._attached=!1,this.detach()),this._target=t,this._attached=!0;let e=ue.passiveEvents?{passive:!0}:!1;this._useMouse&&(window.addEventListener("mouseup",this._upHandler,e),window.addEventListener("mousedown",this._downHandler,e),window.addEventListener("mousemove",this._moveHandler,e),window.addEventListener("wheel",this._wheelHandler,e)),this._useTouch&&ue.touch&&(this._target.addEventListener("touchstart",this._touchstartHandler,e),this._target.addEventListener("touchend",this._touchendHandler,!1),this._target.addEventListener("touchmove",this._touchmoveHandler,!1),this._target.addEventListener("touchcancel",this._touchcancelHandler,!1)),this.attachSelectEvents()}attachSelectEvents(){!this._selectEventsAttached&&this._useXr&&this.app&&this.app.xr&&this.app.xr.supported&&(this._clickedEntities||(this._clickedEntities={}),this._selectEventsAttached=!0,this.app.xr.on("start",this._onXrStart,this))}detach(){if(!this._attached)return;this._attached=!1;let t=ue.passiveEvents?{passive:!0}:!1;this._useMouse&&(window.removeEventListener("mouseup",this._upHandler,t),window.removeEventListener("mousedown",this._downHandler,t),window.removeEventListener("mousemove",this._moveHandler,t),window.removeEventListener("wheel",this._wheelHandler,t)),this._useTouch&&(this._target.removeEventListener("touchstart",this._touchstartHandler,t),this._target.removeEventListener("touchend",this._touchendHandler,!1),this._target.removeEventListener("touchmove",this._touchmoveHandler,!1),this._target.removeEventListener("touchcancel",this._touchcancelHandler,!1)),this._selectEventsAttached&&(this._selectEventsAttached=!1,this.app.xr.off("start",this._onXrStart,this),this.app.xr.off("end",this._onXrEnd,this),this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)),this._target=null}addElement(t){this._elements.indexOf(t)===-1&&this._elements.push(t)}removeElement(t){let e=this._elements.indexOf(t);e!==-1&&this._elements.splice(e,1)}_handleUp(t){this._enabled&&(qi.isPointerLocked()||(this._calcMouseCoords(t),this._onElementMouseEvent("mouseup",t)))}_handleDown(t){this._enabled&&(qi.isPointerLocked()||(this._calcMouseCoords(t),this._onElementMouseEvent("mousedown",t)))}_handleMove(t){this._enabled&&(this._calcMouseCoords(t),this._onElementMouseEvent("mousemove",t),this._lastX=bh,this._lastY=Dh)}_handleWheel(t){this._enabled&&(this._calcMouseCoords(t),this._onElementMouseEvent("mousewheel",t))}_determineTouchedElements(t){let e={},s=this.app.systems.camera.cameras;for(let i=s.length-1;i>=0;i--){let r=s[i],a=0,o=t.changedTouches.length;for(let l=0;l=0;d--)this._getTargetElementByCoords(e[d],u.x,u.y)===o&&(this._clickedEntities[o.entity.guid]||(this._fireEvent("click",new Ml(t,o,l,h,f,r)),this._clickedEntities[o.entity.guid]=Date.now()));this._fireEvent(t.type,new Ml(t,o,l,h,f,r))}}_handleTouchMove(t){if(t.preventDefault(),!this._enabled)return;let e=this._determineTouchedElements(t);for(let s=0,i=t.changedTouches.length;s=0&&(a=r[o],s=this._getTargetElementByCoords(a,bh,Dh),!s);o--);if(this._hoveredElement=s,(t==="mousemove"||t==="mouseup")&&this._pressedElement?this._fireEvent(t,new Ll(e,this._pressedElement,a,bh,Dh,this._lastX,this._lastY)):s&&(this._fireEvent(t,new Ll(e,s,a,bh,Dh,this._lastX,this._lastY)),t==="mousedown"&&(this._pressedElement=s)),i!==this._hoveredElement&&(i&&this._fireEvent("mouseleave",new Ll(e,i,a,bh,Dh,this._lastX,this._lastY)),this._hoveredElement&&this._fireEvent("mouseenter",new Ll(e,this._hoveredElement,a,bh,Dh,this._lastX,this._lastY))),t==="mouseup"&&this._pressedElement){if(this._pressedElement===this._hoveredElement){let o=this._hoveredElement.entity.guid,l=!this._clickedEntities;if(this._clickedEntities){let h=this._clickedEntities[o]||0;l=Date.now()-h>300,delete this._clickedEntities[o]}l&&this._fireEvent("click",new Ll(e,this._hoveredElement,a,bh,Dh,this._lastX,this._lastY))}this._pressedElement=null}}_onXrStart(){this.app.xr.on("end",this._onXrEnd,this),this.app.xr.on("update",this._onXrUpdate,this),this.app.xr.input.on("selectstart",this._onSelectStart,this),this.app.xr.input.on("selectend",this._onSelectEnd,this),this.app.xr.input.on("remove",this._onXrInputRemove,this)}_onXrEnd(){this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)}_onXrUpdate(){if(!this._enabled)return;let t=this.app.xr.input.inputSources;for(let e=0;e=0&&(l=o[f],i=this._getTargetElementByRay(Mb,l),!i);f--);}e._elementEntity=i||null,i?(this._selectedElements[e.id]=i,a=i):delete this._selectedElements[e.id],r!==a&&(r&&this._fireEvent("selectleave",new ga(s,r,l,e)),a&&this._fireEvent("selectenter",new ga(s,a,l,e)));let h=this._selectedPressedElements[e.id];t==="selectmove"&&h&&this._fireEvent("selectmove",new ga(s,h,l,e)),t==="selectstart"&&(this._selectedPressedElements[e.id]=a,a&&this._fireEvent("selectstart",new ga(s,a,l,e))),!e.elementInput&&h&&(delete this._selectedPressedElements[e.id],r&&this._fireEvent("selectend",new ga(s,h,l,e))),t==="selectend"&&e.elementInput&&(delete this._selectedPressedElements[e.id],h&&this._fireEvent("selectend",new ga(s,h,l,e)),h&&h===r&&this._fireEvent("click",new ga(s,h,l,e)))}_fireEvent(t,e){let s=e.element;for(;s.fire(t,e),!(e._stopPropagation||!s.entity.parent||(s=s.entity.parent.element,!s)););}_calcMouseCoords(t){let e=this._target.getBoundingClientRect(),s=Math.floor(e.left),i=Math.floor(e.top);bh=t.clientX-s,Dh=t.clientY-i}_sortElements(t,e){let s=this.app.scene.layers.sortTransparentLayers(t.layers,e.layers);return s!==0?s:t.screen&&!e.screen?-1:!t.screen&&e.screen?1:!t.screen&&!e.screen?0:t.screen.screen.screenSpace&&!e.screen.screen.screenSpace?-1:e.screen.screen.screenSpace&&!t.screen.screen.screenSpace?1:e.drawOrder-t.drawOrder}_getTargetElementByCoords(t,e,s){let i=this._calculateRayScreen(e,s,t,Dl)?Dl:null,r=this._calculateRay3d(e,s,t,dx)?dx:null;return this._getTargetElement(t,i,r)}_getTargetElementByRay(t,e){Dl.origin.copy(t.origin),Dl.direction.copy(t.direction),Dl.end.copy(Dl.direction).mulScalar(e.farClip*2).add(Dl.origin);let s=Dl,i=e.worldToScreen(s.origin,Rb),r=this._calculateRayScreen(i.x,i.y,e,dx)?dx:null;return this._getTargetElement(e,r,s)}_getTargetElement(t,e,s){let i=null,r=1/0;this._elements.sort(this._sortHandler);for(let a=0,o=this._elements.length;at.layersSet.has(h)))if(l.screen&&l.screen.screen.screenSpace){if(!e)continue;if(this._checkElement(e,l,!0)>=0){i=l;break}}else{if(!s)continue;let h=this._checkElement(s,l,!1);if(h>=0&&(h=h&&p<=f&&m<=u&&m>=d?(p=r*(p-h)/o,m=a*(m-d)/l,m=a-m,i.origin.set(p,m,1),i.direction.set(0,0,-1),i.end.copy(i.direction).mulScalar(2).add(i.origin),!0):!1}_calculateRay3d(t,e,s,i){let r=this._target.clientWidth,a=this._target.clientHeight,o=s.rect.z*r,l=s.rect.w*a,h=s.rect.x*r,f=h+o,u=(1-s.rect.y)*a,d=u-l,p=t,m=e;return t>=h&&t<=f&&e<=u&&m>=d?(p=r*(p-h)/o,m=a*(m-d)/l,s.screenToWorld(p,m,s.nearClip,Rb),s.screenToWorld(p,m,s.farClip,HG),i.origin.copy(Rb),i.direction.set(0,0,-1),i.end.copy(HG),!0):!1}_checkElement(t,e,s){if(e.maskedBy&&this._checkElement(t,e.maskedBy.element,s)<0)return-1;let i;s?i=c.calculateScaleToScreen(e):i=c.calculateScaleToWorld(e);let r=c.buildHitCorners(e,s?e.screenCorners:e.worldCorners,i);return Bq(t.origin,t.end,r)}static buildHitCorners(t,e,s){let i=e;if(t.entity&&t.entity.button){let a=t.entity.button.hitPadding||Nq;fx.copy(t.entity.up),CA.copy(fx).mulScalar(-1),ux.copy(t.entity.right),PA.copy(ux).mulScalar(-1),fx.mulScalar(a.w*s.y),CA.mulScalar(a.y*s.y),ux.mulScalar(a.z*s.x),PA.mulScalar(a.x*s.x),XG.copy(i[0]).add(CA).add(PA),YG.copy(i[1]).add(CA).add(ux),KG.copy(i[2]).add(fx).add(ux),jG.copy(i[3]).add(fx).add(PA),i=[XG,YG,KG,jG]}if(s.x<0){let a=i[2].x,o=i[0].x;i[0].x=a,i[1].x=o,i[2].x=o,i[3].x=a}if(s.y<0){let a=i[2].y,o=i[0].y;i[0].y=a,i[1].y=a,i[2].y=o,i[3].y=o}if(s.z<0){let a=i[2].x,o=i[2].y,l=i[2].z;i[2].x=i[0].x,i[2].y=i[0].y,i[2].z=i[0].z,i[0].x=a,i[0].y=o,i[0].z=l}return i}static calculateScaleToScreen(t){let e=t.entity,s=t.screen.screen.scale;for(Q_.set(s,s,s);e&&!e.screen;)Q_.mul(e.getLocalScale()),e=e.parent;return Q_}static calculateScaleToWorld(t){let e=t.entity;for(Q_.set(1,1,1);e;)Q_.mul(e.getLocalScale()),e=e.parent;return Q_}};B.prototype.scale=B.prototype.mulScalar;x.prototype.scale=x.prototype.mulScalar;Q.prototype.scale=Q.prototype.mulScalar;var Uq=vo,kq=ya,zq=xn,Gq=Ea,Vq=Ss,Hq=ce,Wq=yo,Xq=st,Yq=11,Kq=12,jq=11,qq=12,$q="1.51",Zq="1.55",Qq="1.56",Jq="1.57",e$="1.58",t$="1.60",s$="1.62",i$="1.65",r$="1.70",a$="2.1",o$="2.3",n$="2.5",l$="2.6",c$="2.7",h$="2.8",f$=new Q;function u$(c,t){return _e.fromGeometry(c,new wr(t))}function d$(c,t){return _e.fromGeometry(c,new $a(t))}function p$(c,t){return _e.fromGeometry(c,new ci(t))}function m$(c,t){return _e.fromGeometry(c,new Za(t))}function _$(c,t){return _e.fromGeometry(c,new Yc(t))}function g$(c,t){return _e.fromGeometry(c,new qa(t))}function S$(c,t){return _e.fromGeometry(c,new Ci(t))}function x$(c,t,e={}){let s=new Jt;return s.positions=t,s.normals=e.normals,s.tangents=e.tangents,s.colors=e.colors,s.uvs=e.uvs,s.uvs1=e.uvs1,s.blendIndices=e.blendIndices,s.blendWeights=e.blendWeights,s.indices=e.indices,_e.fromGeometry(c,s,e)}function v$(c,t,e,s,i){let r;if(i){let a=t?t.width:c.width,o=t?t.height:c.height;r=f$.set(i.x*a,i.y*o,i.z*a,i.w*o)}Qt(c,t,s,r)}Object.defineProperties(me.prototype,{_glFrameBuffer:{get:function(){return this.impl._glFrameBuffer},set:function(c){}}});Object.defineProperty(Ft,"defaultInstancingFormat",{get:function(){return null}});Object.defineProperties(Z.prototype,{rgbm:{get:function(){return this.type===_i},set:function(c){this.type=c?_i:Gt}},swizzleGGGR:{get:function(){return this.type===Rn},set:function(c){this.type=c?Rn:Gt}},_glTexture:{get:function(){return this.impl._glTexture}}});Object.defineProperty(tt.prototype,"boneLimit",{get:function(){return 1024}});Object.defineProperty(tt.prototype,"webgl2",{get:function(){return this.isWebGL2}});Object.defineProperty(tt.prototype,"textureFloatHighPrecision",{get:function(){return!0}});Object.defineProperty(tt.prototype,"extBlendMinmax",{get:function(){return!0}});Object.defineProperty(tt.prototype,"extTextureHalfFloat",{get:function(){return!0}});Object.defineProperty(tt.prototype,"extTextureLod",{get:function(){return!0}});Object.defineProperty(tt.prototype,"textureHalfFloatFilterable",{get:function(){return!0}});Object.defineProperty(tt.prototype,"supportsMrt",{get:function(){return!0}});Object.defineProperty(tt.prototype,"supportsVolumeTextures",{get:function(){return!0}});Object.defineProperty(tt.prototype,"supportsInstancing",{get:function(){return!0}});Object.defineProperty(tt.prototype,"textureHalfFloatUpdatable",{get:function(){return!0}});Object.defineProperty(tt.prototype,"extTextureFloat",{get:function(){return!0}});Object.defineProperty(tt.prototype,"extStandardDerivatives",{get:function(){return!0}});Oe.DEFAULT=Object.freeze(new Oe);var ss=new Oe,Ol=new Pt;tt.prototype.setBlendFunction=function(c,t){let e=this.blendState;ss.copy(e),ss.setColorBlend(e.colorOp,c,t),ss.setAlphaBlend(e.alphaOp,c,t),this.setBlendState(ss)};tt.prototype.setBlendFunctionSeparate=function(c,t,e,s){let i=this.blendState;ss.copy(i),ss.setColorBlend(i.colorOp,c,t),ss.setAlphaBlend(i.alphaOp,e,s),this.setBlendState(ss)};tt.prototype.setBlendEquation=function(c){let t=this.blendState;ss.copy(t),ss.setColorBlend(c,t.colorSrcFactor,t.colorDstFactor),ss.setAlphaBlend(c,t.alphaSrcFactor,t.alphaDstFactor),this.setBlendState(ss)};tt.prototype.setBlendEquationSeparate=function(c,t){let e=this.blendState;ss.copy(e),ss.setColorBlend(c,e.colorSrcFactor,e.colorDstFactor),ss.setAlphaBlend(t,e.alphaSrcFactor,e.alphaDstFactor),this.setBlendState(ss)};tt.prototype.setColorWrite=function(c,t,e,s){let i=this.blendState;ss.copy(i),ss.setColorWrite(c,t,e,s),this.setBlendState(ss)};tt.prototype.getBlending=function(){return this.blendState.blend};tt.prototype.setBlending=function(c){ss.copy(this.blendState),ss.blend=c,this.setBlendState(ss)};tt.prototype.setDepthWrite=function(c){Ol.copy(this.depthState),Ol.write=c,this.setDepthState(Ol)};tt.prototype.setDepthFunc=function(c){Ol.copy(this.depthState),Ol.func=c,this.setDepthState(Ol)};tt.prototype.setDepthTest=function(c){Ol.copy(this.depthState),Ol.test=c,this.setDepthState(Ol)};tt.prototype.getCullMode=function(){return this.cullMode};var T$=fl,y$=ul,E$=Xa,A$=new Proxy({},{get(c,t){return ne.get(ys().graphicsDevice,fe).get(t)},set(c,t,e){return ne.get(ys().graphicsDevice,fe).set(t,e),!0}});Object.defineProperty(Bt.prototype,"defaultMaterial",{get:function(){return ra(ys().graphicsDevice)}});Object.defineProperty(Bt.prototype,"fogColor",{set:function(c){this.fog.color=c},get:function(){return this.fog.color}});Object.defineProperty(Bt.prototype,"fogEnd",{set:function(c){this.fog.end=c},get:function(){return this.fog.end}});Object.defineProperty(Bt.prototype,"fogStart",{set:function(c){this.fog.start=c},get:function(){return this.fog.start}});Object.defineProperty(Bt.prototype,"fogDensity",{set:function(c){this.fog.density=c},get:function(){return this.fog.density}});Object.defineProperty(Bt.prototype,"toneMapping",{set:function(c){},get:function(){}});Object.defineProperty(Bt.prototype,"gammaCorrection",{set:function(c){},get:function(){}});Object.defineProperty(Bt.prototype,"rendering",{set:function(c){},get:function(){}});Object.defineProperty(ol.prototype,"_meshInstances",{get:function(){return null}});Object.defineProperty(Bt.prototype,"drawCalls",{get:function(){return null}});["128","64","32","16","8","4"].forEach((c,t)=>{Object.defineProperty(Bt.prototype,`skyboxPrefiltered${c}`,{get:function(){return this._prefilteredCubemaps[t]},set:function(e){this._prefilteredCubemaps[t]=e,this.updateShaders=!0}})});Object.defineProperty(Bt.prototype,"models",{get:function(){return this._models||(this._models=[]),this._models}});function hi(c,t,e=""){Object.defineProperty(c.prototype,t,{set:function(s){},get:function(){}})}hi(Dt,"renderTarget");hi(Dt,"onPreCull");hi(Dt,"onPreRender");hi(Dt,"onPreRenderOpaque");hi(Dt,"onPreRenderTransparent");hi(Dt,"onPostCull");hi(Dt,"onPostRender");hi(Dt,"onPostRenderOpaque");hi(Dt,"onPostRenderTransparent");hi(Dt,"onDrawCall");hi(Dt,"layerReference");hi(ar,"onPreCull","Use Scene#EVENT_PRECULL event instead.");hi(ar,"onPostCull","Use Scene#EVENT_POSTCULL event instead.");hi(ar,"onPreRender","Use Scene#EVENT_PRERENDER event instead.");hi(ar,"onPostRender","Use Scene#EVENT_POSTRENDER event instead.");hi(ar,"onPreRenderLayer","Use Scene#EVENT_PRERENDER_LAYER event instead.");hi(ar,"onPostRenderLayer","Use Scene#EVENT_POSTRENDER_LAYER event instead.");Bc.prototype.renderComposition=function(c){ys().renderComposition(c)};we.prototype.syncAabb=function(){};Ko.prototype.getTarget=function(c){return this.targets[c]};Pe.prototype.getChildren=function(){return this.children};Pe.prototype.getName=function(){return this.name};Pe.prototype.getPath=function(){return this.path};Pe.prototype.getRoot=function(){return this.root};Pe.prototype.getParent=function(){return this.parent};Pe.prototype.setName=function(c){this.name=c};Object.defineProperty(Us.prototype,"shader",{set:function(c){},get:function(){return null}});Object.defineProperty(Us.prototype,"blend",{set:function(c){this.blendState.blend=c},get:function(){return this.blendState.blend}});Object.defineProperty(it.prototype,"shininess",{get:function(){return this.gloss*100},set:function(c){this.gloss=c*.01}});Object.defineProperty(it.prototype,"useGammaTonemap",{get:function(){return this.useTonemap},set:function(c){this.useTonemap=c}});Object.defineProperty(it.prototype,"anisotropy",{get:function(){let c=Math.sign(Math.cos(this.anisotropyRotation*R.DEG_TO_RAD*2));return this.anisotropyIntensity*c},set:function(c){this.anisotropyIntensity=Math.abs(c),c>=0?this.anisotropyRotation=0:this.anisotropyRotation=90}});function lo(c,t){Object.defineProperty(it.prototype,t,{get:function(){return this[c]},set:function(e){this[c]=e}})}function wA(c){Object.defineProperty(it.prototype,c,{get:function(){return!0},set:function(t){}})}wA("sheenTint");wA("diffuseTint");wA("emissiveTint");wA("ambientTint");lo("specularTint","specularMapTint");lo("aoVertexColor","aoMapVertexColor");lo("diffuseVertexColor","diffuseMapVertexColor");lo("specularVertexColor","specularMapVertexColor");lo("emissiveVertexColor","emissiveMapVertexColor");lo("metalnessVertexColor","metalnessMapVertexColor");lo("glossVertexColor","glossMapVertexColor");lo("opacityVertexColor","opacityMapVertexColor");lo("lightVertexColor","lightMapVertexColor");lo("sheenGloss","sheenGlossiess");lo("clearCoatGloss","clearCostGlossiness");function ZG(c,t){c!=="pass"&&Object.defineProperty(tr.prototype,c,{get:function(){return this.litOptions[t||c]},set:function(e){this.litOptions[t||c]=e}})}ZG("refraction","useRefraction");var C$=new Xa,$G=Object.getOwnPropertyNames(C$);for(let c in $G)ZG($G[c]);ha.prototype.getAssetById=function(c){return this.get(c)};Object.defineProperty(Es.prototype,"ray",{get:function(){return this._rayLocal}});Object.defineProperty(Es.prototype,"position",{get:function(){return this._localPosition}});Object.defineProperty(Es.prototype,"rotation",{get:function(){return this._localRotation}});var P$="keydown",w$="keyup",I$="mousedown",R$="mousemove",b$="mouseup",D$="mousewheel",L$="touchstart",M$="touchend",O$="touchmove",F$="touchcancel",N$="gamepadconnected",B$="gamepaddisconnected",U$="select",k$="selectstart",z$="selectend";Object.defineProperty(J_.prototype,"wheel",{get:function(){return this.wheelDelta*-2}});Object.defineProperty(za.prototype,"wheel",{get:function(){return this.wheelDelta*-2}});var G$=Sl,V$=Ui,H$=tn,W$=1,X$=2,Y$=4,K$=1,j$=2,q$=3,$$=4,Z$=5;Pi.prototype.isFullscreen=function(){return!!document.fullscreenElement};Pi.prototype.enableFullscreen=function(c,t,e){c=c||this.graphicsDevice.canvas;let s=function(){t(),document.removeEventListener("fullscreenchange",s)},i=function(){e(),document.removeEventListener("fullscreenerror",i)};t&&document.addEventListener("fullscreenchange",s,!1),e&&document.addEventListener("fullscreenerror",i,!1),c.requestFullscreen?c.requestFullscreen(Element.ALLOW_KEYBOARD_INPUT):e()};Pi.prototype.disableFullscreen=function(c){let t=function(){c(),document.removeEventListener("fullscreenchange",t)};c&&document.addEventListener("fullscreenchange",t,!1),document.exitFullscreen()};Pi.prototype.getSceneUrl=function(c){let t=this.scenes.find(c);return t?t.url:null};Pi.prototype.loadScene=function(c,t){this.scenes.loadScene(c,t)};Pi.prototype.loadSceneHierarchy=function(c,t){this.scenes.loadSceneHierarchy(c,t)};Pi.prototype.loadSceneSettings=function(c,t){this.scenes.loadSceneSettings(c,t)};Tl.prototype.setVisible=function(c){this.enabled=c};Object.defineProperty(Js.prototype,"bodyType",{get:function(){return this.type},set:function(c){this.type=c}});Js.prototype.syncBodyToEntity=function(){this._updateDynamic()};Al.prototype.setGravity=function(){arguments.length===1?this.gravity.copy(arguments[0]):this.gravity.set(arguments[0],arguments[1],arguments[2])};var IA=class{constructor(t){this._frameIndex=0,this._frameTimings=[],this._timings=[],this._prevTimings=[],this.unitsName="ms",this.decimalPlaces=1,this.enabled=!0,t.on("frameupdate",this.begin.bind(this,"update")),t.on("framerender",this.mark.bind(this,"render")),t.on("frameend",this.mark.bind(this,"other"))}begin(t){if(!this.enabled)return;this._frameIndex0){let s=this._frameTimings[this._frameIndex-1];s[1]=e-s[1]}else if(this._timings.length>0){let s=this._timings[this._timings.length-1];s[1]=e-s[1]}if(this._frameIndex>=this._frameTimings.length)this._frameTimings.push([t,e]);else{let s=this._frameTimings[this._frameIndex];s[0]=t,s[1]=e}this._frameIndex++}get timings(){return this._timings.slice(0,-1).map(t=>t[1])}};var RA=class{constructor(t){this.device=t,t.gpuProfiler&&(t.gpuProfiler.enabled=!0),this.enabled=!0,this.unitsName="ms",this.decimalPlaces=1,this._timings=[]}get timings(){return this._timings[0]=this.device.gpuProfiler?._frameTime??0,this._timings}};var eg=class{constructor(t,e,s,i,r){this.app=t,this.values=[],this.statNames=e,this.unitsName=i,this.decimalPlaces=s,this.multiplier=r||1;let a=(o,l)=>o.split(".").reduce((h,f)=>h?h instanceof Map?h.get(f):h[f]:null,l||this);t.on("frameupdate",o=>{for(let l=0;li+r,0);if(this.avgTotal+=s,this.avgTimer+=t,this.avgCount++,this.maxValue=Math.max(this.maxValue,s),this.avgTimer>this.textRefreshRate&&(this.timingText=(this.avgTotal/this.avgCount).toFixed(this.timer.decimalPlaces),this.maxText=this.maxValue.toFixed(this.timer.decimalPlaces),this.avgTimer=0,this.avgTotal=0,this.avgCount=0,this.maxValue=0),this.enabled){let i=1.5*this.watermark;if(this.sample[0]=Math.floor(s/i*255),this.sample[1]=0,this.sample[2]=0,this.sample[3]=this.watermark/i*255,this.yOffset>=this.texture.height)return;let r=this.texture.lock();if(this.needsClear){let a=this.yOffset*this.texture.width*4;r.fill(0,a,a+this.texture.width*4),this.needsClear=!1}r.set(this.sample,(this.cursor+this.yOffset*this.texture.width)*4),this.texture.unlock(),this.cursor++,this.cursor===this.texture.width&&(this.cursor=0)}}render(t,e,s,i,r){t.quad(e+i,s,-i,r,this.enabled?this.cursor:0,this.enabled?.5+this.yOffset:this.texture.height-1,-i,0,this.texture,this.graphType)}};var bA=class{constructor(t,e){let s=p=>{p.font='10px "Lucida Console", Monaco, monospace',p.textAlign="left",p.textBaseline="alphabetic"},i=p=>p==="."||p.length===1&&p.charCodeAt(0)>=48&&p.charCodeAt(0)<=57,r=document.createElement("canvas"),a=r.getContext("2d",{alpha:!0});s(a);let o=new Map,l=5,h=512,f=l,u=l;e.forEach(p=>{let m=a.measureText(p),_=Math.ceil(-m.actualBoundingBoxLeft),S=Math.ceil(m.actualBoundingBoxRight),g=Math.ceil(m.actualBoundingBoxAscent),T=Math.ceil(m.actualBoundingBoxDescent),C=_+S,v=g+T;f+C+l>=h&&(f=l,u+=16),o.set(p,{l:_,r:S,a:g,d:T,w:C,h:v,x:f,y:u}),f+=C+l}),r.width=512,r.height=R.nextPowerOfTwo(u+16+l),s(a),a.fillStyle="rgb(0, 0, 0)",a.fillRect(0,0,r.width,r.height),o.forEach((p,m)=>{a.fillStyle=i(m)?"rgb(255, 240, 100)":"rgb(150, 220, 230)",a.fillText(m,p.x-p.l,p.y+p.a)}),this.placements=o;let d=a.getImageData(0,0,r.width,r.height).data;for(let p=0;p 0.5) { - graphColor = vec3(${wa}); + graphColor = vec3(${eV}); } else if (wordFlag > 0.2) { - graphColor = vec3(${wr}); + graphColor = vec3(${JG}); } vec4 graphSample = texture2D(graphTex, uv0.xy); vec4 graph; if (uv0.w < graphSample.r) graph = vec4(graphColor, 1.0); else { - vec3 bgColor = vec3(${wn}); + vec3 bgColor = vec3(${tV}); if (wordFlag > 0.5) { - bgColor = vec3(${wl}); + bgColor = vec3(${iV}); } else if (wordFlag > 0.2) { - bgColor = vec3(${wo}); + bgColor = vec3(${sV}); } graph = vec4(bgColor, 1.0); } @@ -16975,7 +17710,7 @@ ${t.stack}`)):s+=`: ${t}`,i(s);}else i(t,s);});}}class xz extends fQ{load(e,t){x gl_FragColor = graph * clr; } } -`,wu=` +`,t9=` varying uv0: vec4f; varying wordFlag: f32; uniform clr: vec4f; @@ -16985,22 +17720,22 @@ ${t.stack}`)):s+=`: ${t}`,i(s);}else i(t,s);});}}class xz extends fQ{load(e,t){x var wordsTex_sampler : sampler; @fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput { var uv0: vec4f = input.uv0; - var graphColor: vec3f = vec3f(${ws}); + var graphColor: vec3f = vec3f(${QG}); if (input.wordFlag > 0.5) { - graphColor = vec3f(${wa}); + graphColor = vec3f(${eV}); } else if (input.wordFlag > 0.2) { - graphColor = vec3f(${wr}); + graphColor = vec3f(${JG}); } var graphSample: vec4f = textureSample(graphTex, graphTex_sampler, uv0.xy); var graph: vec4f; if (uv0.w < graphSample.r) { graph = vec4f(graphColor, 1.0); } else { - var bgColor: vec3f = vec3f(${wn}); + var bgColor: vec3f = vec3f(${tV}); if (input.wordFlag > 0.5) { - bgColor = vec3f(${wl}); + bgColor = vec3f(${iV}); } else if (input.wordFlag > 0.2) { - bgColor = vec3f(${wo}); + bgColor = vec3f(${sV}); } graph = vec4f(bgColor, 1.0); } @@ -17013,7 +17748,7 @@ ${t.stack}`)):s+=`: ${t}`,i(s);}else i(t,s);});}}class xz extends fQ{load(e,t){x } return output; } -`;class wf{quad(e,t,i,s,r,a,n,o,l,h=0){if(this.quads>=this.maxQuads)return;let c=this.targetSize.width,d=this.targetSize.height,u=e/c,f=t/d,p=(e+i)/c,m=(t+s)/d,_=l.width,g=l.height,v=r/_,S=a/g,y=(r+(n??i))/_,x=(a+(o??s))/g;this.data.set([u,f,h,v,S,0,0,p,f,h,y,S,1,0,p,m,h,y,x,1,1,u,m,h,v,x,0,1],28*this.quads),this.quads++,this.prim.count+=6;}startFrame(){this.quads=0,this.prim.count=0,this.targetSize.width=this.device.canvas.scrollWidth,this.targetSize.height=this.device.canvas.scrollHeight;}render(e,t,i,s,r,a){this.buffer.setData(this.data.buffer),this.uniforms.clr.set(r,0),this.material.setParameter("clr",this.uniforms.clr),this.material.setParameter("graphTex",i),this.material.setParameter("wordsTex",s),e.drawMeshInstance(this.meshInstance,t);}constructor(e,t=2048){let i=new iB(e,[{semantic:e8,components:3,type:6},{semantic:tr,components:4,type:6}]),s=new Uint16Array(6*t);for(let e=0;ee.destroy()),this.gpuPassGraphs.clear(),this.cpuGraphs.clear(),this.vramGraphs.clear(),this.wordAtlas.destroy(),this.texture.destroy(),this.div.remove();}static getDefaultOptions(e=[]){let t={sizes:[{width:100,height:16,spacing:0,graphs:false},{width:128,height:32,spacing:2,graphs:true},{width:256,height:64,spacing:2,graphs:true}],startSizeIndex:0,textRefreshRate:500,cpu:{enabled:true,watermark:33},gpu:{enabled:true,watermark:33},stats:[{name:"Frame",stats:["frame.ms"],decimalPlaces:1,unitsName:"ms",watermark:33},{name:"DrawCalls",stats:["drawCalls.total"],watermark:1e3},{name:"VRAM",stats:["vram.totalUsed"],decimalPlaces:1,multiplier:1/1048576,unitsName:"MB",watermark:1024}],gpuTimingMinSize:1,cpuTimingMinSize:1,vramTimingMinSize:1};if(e.length>0){let i=t.stats.findIndex(e=>"Frame"===e.name),s=-1!==i?i+1:t.stats.length,r=e.flatMap(e=>w_.statPresets[e]??[]).reverse();t.stats.splice(s,0,...r);}return t}set activeSizeIndex(e){this._activeSizeIndex=e,this.gspacing=this.sizes[e].spacing,this.resize(this.sizes[e].width,this.sizes[e].height,this.sizes[e].graphs),this.opacity=e>0?.85:.7,e{if("VRAM"===t.name){let s=new we(e,t.stats,t.decimalPlaces,t.unitsName,t.multiplier),r=new wt(t.name,e,t.watermark,i.textRefreshRate,s);this.graphs.push(r);}}),i.cpu.enabled){let t=new E9(e),s=new wt("CPU",e,i.cpu.watermark,i.textRefreshRate,t);s.graphType=.66,this.graphs.push(s);}if(i.gpu.enabled){let s=new E7(t),r=new wt("GPU",e,i.gpu.watermark,i.textRefreshRate,s);r.graphType=.33,this.graphs.push(r);}i.stats&&i.stats.forEach(t=>{if("VRAM"===t.name)return;let s=new we(e,t.stats,t.decimalPlaces,t.unitsName,t.multiplier),r=new wt(t.name,e,t.watermark,i.textRefreshRate,s);this.graphs.push(r);}),this.texture=new ic(t,{name:"mini-stats-graph-texture",width:1,height:1,mipmaps:false,minFilter:0,magFilter:0,addressU:0,addressV:0}),this.graphs.forEach(e=>{e.texture=this.texture,this.allocateRow(e);});}render(){let e=this.graphs,t=this.wordAtlas,i=this.render2d,s=this.width,r=this.height,a=this.gspacing;i.startFrame();for(let n=0;n0){h+=5,h+=t.render(i,"max",h,l),h+=5;let e=o.maxText;for(let s=0;se.loseContext());}updateSubStats(e,t,i,s,r){let a=[];for(let[t,n]of e)(i instanceof Map?i.get(t)||0:i[t]||0)>0?n.lastNonZeroFrame=this.frameIndex:r>0&&"gpu"===s&&this.frameIndex-n.lastNonZeroFrame>r&&a.push(t);for(let t of a){let i=e.get(t);if(i){let s=this.graphs.indexOf(i.graph);-1!==s&&this.graphs.splice(s,1),this.freeRow(i.graph),i.graph.destroy(),e.delete(t);}}let n=i instanceof Map?i:Object.entries(i),o=this.graphs.find(e=>e.name===t);for(let[i,a]of n)if(!e.has(i)){if(("gpu"===s||wm.has(i))&&0===a)continue;let n=i;"frame"===s&&(n=wp[i]||i);let l=` ${n}`,h=o?.watermark??10,c="vram"===s?"MB":"ms",d="vram"===s?1/1048576:1,u=`${s}.${i}`,f=new we(this.app,[u],1,c,d),p=new wt(l,this.app,h,this.textRefreshRate,f);"gpu"===s?p.graphType=.33:"frame"===s&&(p.graphType=.66),p.texture=this.texture,this.allocateRow(p),p.enabled=this.sizes[this._activeSizeIndex].graphs;let m=this.graphs.findIndex(e=>e.name===t);-1===m&&(m=0);let _=m;for(let e=m-1;e>=0;e--)if(this.graphs[e].name.startsWith(" "))_=e;else break;this.graphs.splice(_,0,p),e.set(i,{graph:p,lastNonZeroFrame:a>0?this.frameIndex:this.frameIndex-r-1});}if(o)for(let t of e.values())t.graph.watermark=o.watermark;}allocateRow(e){let t;return this.freeRows.length>0?t=this.freeRows.pop():(t=this.nextRowIndex++,this.ensureTextureHeight(this.nextRowIndex)),this.graphRows.set(e,t),e.yOffset=t,e.needsClear=true,t}freeRow(e){let t=this.graphRows.get(e);void 0!==t&&(this.freeRows.push(t),this.graphRows.delete(e));}clearSubGraphs(e,t,i){for(let t of e.values()){let e=this.graphs.indexOf(t.graph);-1!==e&&this.graphs.splice(e,1),this.freeRow(t.graph),t.graph.destroy();}if(e.clear(),t){let e=this.graphs.find(e=>e.name===t);e&&(e.graphType=i);}}ensureTextureHeight(e){let t=this.sizes[this.sizes.length-1].width,i=ei.nextPowerOfTwo(t),s=ei.nextPowerOfTwo(e);s>this.texture.height&&this.texture.resize(i,s);}postRender(){if(this._enabled){if(this.render(),this._activeSizeIndex>=this.gpuTimingMinSize){let e=this.app.stats.gpu;e&&this.updateSubStats(this.gpuPassGraphs,"GPU",e,"gpu",240);}if(this._activeSizeIndex>=this.cpuTimingMinSize){let e={scriptUpdate:this.app.stats.frame.scriptUpdate,scriptPostUpdate:this.app.stats.frame.scriptPostUpdate,animUpdate:this.app.stats.frame.animUpdate,physicsTime:this.app.stats.frame.physicsTime,renderTime:this.app.stats.frame.renderTime,gsplatSort:this.app.stats.frame.gsplatSort};this.updateSubStats(this.cpuGraphs,"CPU",e,"frame",240);}if(this._activeSizeIndex>=this.vramTimingMinSize){let e=this.app.stats.vram,t={tex:e.tex,geom:e.geom};this.device.isWebGPU&&(t.buffers=e.buffers),this.updateSubStats(this.vramGraphs,"VRAM",t,"vram",0);}}this.frameIndex++;}constructor(e,t=w_.getDefaultOptions()){let i=e.graphicsDevice;this.graphRows=new Map,this.freeRows=[],this.nextRowIndex=0,this.sizes=t.sizes,this.initGraphs(e,i,t);let s=new Set(["","ms","0","1","2","3","4","5","6","7","8","9",".","-"," "].concat(this.graphs.map(e=>e.name)).concat(t.stats?t.stats.map(e=>e.unitsName):[]).filter(e=>!!e));for(let e=97;e<=122;e++)s.add(String.fromCharCode(e));for(let e=65;e<=90;e++)s.add(String.fromCharCode(e));this.wordAtlas=new wi(i,s),this._activeSizeIndex=t.startSizeIndex;let r=t.gpuTimingMinSize??1,a=t.cpuTimingMinSize??1,n=t.vramTimingMinSize??1;if(r{this.opacity=1;}),o.addEventListener("mouseleave",e=>{this.opacity=this._activeSizeIndex>0?.85:.7;}),o.addEventListener("click",e=>{e.preventDefault(),this._enabled&&(this.activeSizeIndex=(this.activeSizeIndex+1)%this.sizes.length,this.resize(this.sizes[this.activeSizeIndex].width,this.sizes[this.activeSizeIndex].height,this.sizes[this.activeSizeIndex].graphs));}),i.on("resizecanvas",this.updateDiv,this),i.on("losecontext",this.loseContext,this),e.on("postrender",this.postRender,this),this.app=e,this.drawLayer=e.scene.layers.getLayerById(4),this.device=i,this.render2d=new wf(i),this.div=o,this.width=0,this.height=0,this.gspacing=2,this.clr=[1,1,1,t.startSizeIndex>0?.85:.7],this._enabled=true,this.gpuTimingMinSize=r,this.gpuPassGraphs=new Map,this.cpuTimingMinSize=a,this.cpuGraphs=new Map,this.vramTimingMinSize=n,this.vramGraphs=new Map,this.frameIndex=0,this.textRefreshRate=t.textRefreshRate,this.activeSizeIndex=this._activeSizeIndex;}}w_.statPresets={gsplats:[{name:"GSplats",stats:["frame.gsplats"],decimalPlaces:3,multiplier:1e-6,unitsName:"M",watermark:10}],gsplatsCopy:[{name:"GsplatsCopy",stats:["frame.gsplatBufferCopy"],decimalPlaces:1,multiplier:1,unitsName:"%",watermark:100}]};let wg=` +`,DA=class{constructor(t,e=2048){let s=new Ft(t,[{semantic:ee,components:3,type:ye},{semantic:_t,components:4,type:ye}]),i=new Uint16Array(e*6);for(let a=0;a=this.maxQuads)return;let u=this.targetSize.width,d=this.targetSize.height,p=t/u,m=e/d,_=(t+s)/u,S=(e+i)/d,g=h.width,T=h.height,C=r/g,v=a/T,E=(r+(o??s))/g,y=(a+(l??i))/T;this.data.set([p,m,f,C,v,0,0,_,m,f,E,v,1,0,_,S,f,E,y,1,1,p,S,f,C,y,0,1],28*this.quads),this.quads++,this.prim.count+=6}startFrame(){this.quads=0,this.prim.count=0,this.targetSize.width=this.device.canvas.scrollWidth,this.targetSize.height=this.device.canvas.scrollHeight}render(t,e,s,i,r,a){this.buffer.setData(this.data.buffer),this.uniforms.clr.set(r,0),this.material.setParameter("clr",this.uniforms.clr),this.material.setParameter("graphTex",s),this.material.setParameter("wordsTex",i),t.drawMeshInstance(this.meshInstance,e)}};var s9={animUpdate:"anim",physicsTime:"physics",renderTime:"render",gsplatSort:"gsplatSort"},i9=new Set(["physicsTime","animUpdate","gsplatSort"]),px=class px{constructor(t,e=px.getDefaultOptions()){let s=t.graphicsDevice;this.graphRows=new Map,this.freeRows=[],this.nextRowIndex=0,this.sizes=e.sizes,this.initGraphs(t,s,e);let i=new Set(["","ms","0","1","2","3","4","5","6","7","8","9",".","-"," "].concat(this.graphs.map(h=>h.name)).concat(e.stats?e.stats.map(h=>h.unitsName):[]).filter(h=>!!h));for(let h=97;h<=122;h++)i.add(String.fromCharCode(h));for(let h=65;h<=90;h++)i.add(String.fromCharCode(h));this.wordAtlas=new bA(s,i),this._activeSizeIndex=e.startSizeIndex;let r=e.gpuTimingMinSize??1,a=e.cpuTimingMinSize??1,o=e.vramTimingMinSize??1;if(r{this.opacity=1}),l.addEventListener("mouseleave",h=>{this.opacity=this._activeSizeIndex>0?.85:.7}),l.addEventListener("click",h=>{h.preventDefault(),this._enabled&&(this.activeSizeIndex=(this.activeSizeIndex+1)%this.sizes.length,this.resize(this.sizes[this.activeSizeIndex].width,this.sizes[this.activeSizeIndex].height,this.sizes[this.activeSizeIndex].graphs))}),s.on("resizecanvas",this.updateDiv,this),s.on("losecontext",this.loseContext,this),t.on("postrender",this.postRender,this),this.app=t,this.drawLayer=t.scene.layers.getLayerById(Va),this.device=s,this.render2d=new DA(s),this.div=l,this.width=0,this.height=0,this.gspacing=2,this.clr=[1,1,1,e.startSizeIndex>0?.85:.7],this._enabled=!0,this.gpuTimingMinSize=r,this.gpuPassGraphs=new Map,this.cpuTimingMinSize=a,this.cpuGraphs=new Map,this.vramTimingMinSize=o,this.vramGraphs=new Map,this.frameIndex=0,this.textRefreshRate=e.textRefreshRate,this.activeSizeIndex=this._activeSizeIndex}destroy(){this.device.off("resizecanvas",this.updateDiv,this),this.device.off("losecontext",this.loseContext,this),this.app.off("postrender",this.postRender,this),this.graphs.forEach(t=>t.destroy()),this.gpuPassGraphs.clear(),this.cpuGraphs.clear(),this.vramGraphs.clear(),this.wordAtlas.destroy(),this.texture.destroy(),this.div.remove()}static getDefaultOptions(t=[]){let e={sizes:[{width:100,height:16,spacing:0,graphs:!1},{width:128,height:32,spacing:2,graphs:!0},{width:256,height:64,spacing:2,graphs:!0}],startSizeIndex:0,textRefreshRate:500,cpu:{enabled:!0,watermark:33},gpu:{enabled:!0,watermark:33},stats:[{name:"Frame",stats:["frame.ms"],decimalPlaces:1,unitsName:"ms",watermark:33},{name:"DrawCalls",stats:["drawCalls.total"],watermark:1e3},{name:"VRAM",stats:["vram.totalUsed"],decimalPlaces:1,multiplier:95367431640625e-20,unitsName:"MB",watermark:1024}],gpuTimingMinSize:1,cpuTimingMinSize:1,vramTimingMinSize:1};if(t.length>0){let s=e.stats.findIndex(a=>a.name==="Frame"),i=s!==-1?s+1:e.stats.length,r=t.flatMap(a=>px.statPresets[a]??[]).reverse();e.stats.splice(i,0,...r)}return e}set activeSizeIndex(t){this._activeSizeIndex=t,this.gspacing=this.sizes[t].spacing,this.resize(this.sizes[t].width,this.sizes[t].height,this.sizes[t].graphs),this.opacity=t>0?.85:.7,t{if(i.name==="VRAM"){let r=new eg(t,i.stats,i.decimalPlaces,i.unitsName,i.multiplier),a=new Lh(i.name,t,i.watermark,s.textRefreshRate,r);this.graphs.push(a)}}),s.cpu.enabled){let i=new IA(t),r=new Lh("CPU",t,s.cpu.watermark,s.textRefreshRate,i);r.graphType=.66,this.graphs.push(r)}if(s.gpu.enabled){let i=new RA(e),r=new Lh("GPU",t,s.gpu.watermark,s.textRefreshRate,i);r.graphType=.33,this.graphs.push(r)}s.stats&&s.stats.forEach(i=>{if(i.name==="VRAM")return;let r=new eg(t,i.stats,i.decimalPlaces,i.unitsName,i.multiplier),a=new Lh(i.name,t,i.watermark,s.textRefreshRate,r);this.graphs.push(a)}),this.texture=new Z(e,{name:"mini-stats-graph-texture",width:1,height:1,mipmaps:!1,minFilter:0,magFilter:0,addressU:0,addressV:0}),this.graphs.forEach(i=>{i.texture=this.texture,this.allocateRow(i)})}render(){let t=this.graphs,e=this.wordAtlas,s=this.render2d,i=this.width,r=this.height,a=this.gspacing;s.startFrame();for(let o=0;o0){f+=5,f+=e.render(s,"max",f,h),f+=5;let d=l.maxText;for(let p=0;pt.loseContext())}updateSubStats(t,e,s,i,r){let a=[];for(let[h,f]of t)(s instanceof Map?s.get(h)||0:s[h]||0)>0?f.lastNonZeroFrame=this.frameIndex:r>0&&i==="gpu"&&this.frameIndex-f.lastNonZeroFrame>r&&a.push(h);for(let h of a){let f=t.get(h);if(f){let u=this.graphs.indexOf(f.graph);u!==-1&&this.graphs.splice(u,1),this.freeRow(f.graph),f.graph.destroy(),t.delete(h)}}let o=s instanceof Map?s:Object.entries(s),l=this.graphs.find(h=>h.name===e);for(let[h,f]of o)if(!t.has(h)){if((i==="gpu"||i9.has(h))&&f===0)continue;let d=h;i==="frame"&&(d=s9[h]||h);let p=` ${d}`,m=l?.watermark??10,_=1,S=i==="vram"?"MB":"ms",g=i==="vram"?1/(1024*1024):1,T=`${i}.${h}`,C=new eg(this.app,[T],_,S,g),v=new Lh(p,this.app,m,this.textRefreshRate,C);i==="gpu"?v.graphType=.33:i==="frame"&&(v.graphType=.66),v.texture=this.texture,this.allocateRow(v);let E=this.sizes[this._activeSizeIndex];v.enabled=E.graphs;let y=this.graphs.findIndex(A=>A.name===e);y===-1&&(y=0);let P=y;for(let A=y-1;A>=0&&this.graphs[A].name.startsWith(" ");A--)P=A;this.graphs.splice(P,0,v),t.set(h,{graph:v,lastNonZeroFrame:f>0?this.frameIndex:this.frameIndex-r-1})}if(l)for(let h of t.values())h.graph.watermark=l.watermark}allocateRow(t){let e;return this.freeRows.length>0?e=this.freeRows.pop():(e=this.nextRowIndex++,this.ensureTextureHeight(this.nextRowIndex)),this.graphRows.set(t,e),t.yOffset=e,t.needsClear=!0,e}freeRow(t){let e=this.graphRows.get(t);e!==void 0&&(this.freeRows.push(e),this.graphRows.delete(t))}clearSubGraphs(t,e,s){for(let i of t.values()){let r=this.graphs.indexOf(i.graph);r!==-1&&this.graphs.splice(r,1),this.freeRow(i.graph),i.graph.destroy()}if(t.clear(),e){let i=this.graphs.find(r=>r.name===e);i&&(i.graphType=s)}}ensureTextureHeight(t){let e=this.sizes[this.sizes.length-1].width,s=R.nextPowerOfTwo(e),i=R.nextPowerOfTwo(t);i>this.texture.height&&this.texture.resize(s,i)}postRender(){if(this._enabled){if(this.render(),this._activeSizeIndex>=this.gpuTimingMinSize){let t=this.app.stats.gpu;t&&this.updateSubStats(this.gpuPassGraphs,"GPU",t,"gpu",240)}if(this._activeSizeIndex>=this.cpuTimingMinSize){let t={scriptUpdate:this.app.stats.frame.scriptUpdate,scriptPostUpdate:this.app.stats.frame.scriptPostUpdate,animUpdate:this.app.stats.frame.animUpdate,physicsTime:this.app.stats.frame.physicsTime,renderTime:this.app.stats.frame.renderTime,gsplatSort:this.app.stats.frame.gsplatSort};this.updateSubStats(this.cpuGraphs,"CPU",t,"frame",240)}if(this._activeSizeIndex>=this.vramTimingMinSize){let t=this.app.stats.vram,e={tex:t.tex,geom:t.geom};this.device.isWebGPU&&(e.buffers=t.buffers),this.updateSubStats(this.vramGraphs,"VRAM",e,"vram",0)}}this.frameIndex++}};n(px,"statPresets",{gsplats:[{name:"GSplats",stats:["frame.gsplats"],decimalPlaces:3,multiplier:1/1e6,unitsName:"M",watermark:10}],gsplatsCopy:[{name:"GsplatsCopy",stats:["frame.gsplatBufferCopy"],decimalPlaces:1,multiplier:1,unitsName:"%",watermark:100}]});var LA=px;var r9=` varying vec2 vUv0; uniform vec2 uOffset; uniform float uSrcMultiplier; @@ -17038,7 +17773,7 @@ ${t.stack}`)):s+=`: ${t}`,i(s);}else i(t,s);});}}class xz extends fQ{load(e,t){x diff = max(diff, length(firstTexel.rgb - pixel.rgb)); gl_FragColor = vec4(texel.rgb, min(diff, 1.0)); } -`,wv=` +`,a9=` varying vUv0: vec2f; uniform uOffset: vec2f; uniform uSrcMultiplier: f32; @@ -17067,15 +17802,114 @@ ${t.stack}`)):s+=`: ${t}`,i(s);}else i(t,s);});}}class xz extends fQ{load(e,t){x output.color = vec4f(texel.rgb, min(diff, 1.0)); return output; } -`,wS=new Float32Array(2),wy=new es;class wx{textureToCanvas(e,t={}){let i=e.getSource();if("u">typeof HTMLImageElement&&i instanceof HTMLImageElement||"u">typeof HTMLCanvasElement&&i instanceof HTMLCanvasElement||"u">typeof OffscreenCanvas&&i instanceof OffscreenCanvas||"u">typeof ImageBitmap&&i instanceof ImageBitmap){let{width:e,height:s}=this.calcTextureSize(i.width,i.height,t.maxTextureSize),r=document.createElement("canvas");r.width=e,r.height=s;let a=r.getContext("2d");if(null===a)return Promise.resolve(void 0);if(a.drawImage(i,0,0,r.width,r.height),t.color){let{r:i,g:r,b:n}=t.color,o=a.getImageData(0,0,e,s),l=o.data;for(let e=0;e{n.destroy(),o.destroy();let t=new Uint8ClampedArray(r*a*4);t.set(e);let i=new ImageData(t,r,a),s=document.createElement("canvas");s.width=r,s.height=a;let l=s.getContext("2d");return l?(l.putImageData(i,0,0),Promise.resolve(s)):Promise.resolve(void 0)})}calcTextureSize(e,t,i){if(i){let s=Math.min(i/Math.max(e,t),1);e=Math.round(e*s),t=Math.round(t*s);}return {width:e,height:t}}}var wT=Uint8Array,wE=Uint16Array,ww=Int32Array,wb=new wT([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),wC=new wT([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),wA=new wT([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),wP=function(e,t){for(var i=new wE(31),s=0;s<31;++s)i[s]=t+=1<>1|(21845&wO)<<1;wF=(61680&(wF=(52428&wF)>>2|(13107&wF)<<2))>>4|(3855&wF)<<4,wM[wO]=((65280&wF)>>8|(255&wF)<<8)>>1;}for(var wN=function(e,t,i){for(var s,r=e.length,a=0,n=new wE(t);a>l]=h;}else for(a=0,s=new wE(r);a>15-e[a]);return s},wB=new wT(288),wO=0;wO<144;++wO)wB[wO]=8;for(var wO=144;wO<256;++wO)wB[wO]=9;for(var wO=256;wO<280;++wO)wB[wO]=7;for(var wO=280;wO<288;++wO)wB[wO]=8;for(var wk=new wT(32),wO=0;wO<32;++wO)wk[wO]=5;var wU=wN(wB,9,0);wN(wB,9,1);var wz=wN(wk,5,0);wN(wk,5,1);var wV=function(e){return (e+7)/8|0},wG=function(e,t,i){return (null==i||i>e.length)&&(i=e.length),new wT(e.subarray(t,i))},wH=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],wW=function(e,t,i){var s=Error(t||wH[e]);if(s.code=e,Error.captureStackTrace&&Error.captureStackTrace(s,wW),!i)throw s;return s},wX=function(e,t,i){i<<=7&t;var s=t/8|0;e[s]|=i,e[s+1]|=i>>8;},wY=function(e,t,i){i<<=7&t;var s=t/8|0;e[s]|=i,e[s+1]|=i>>8,e[s+2]|=i>>16;},wq=function(e,t){for(var i=[],s=0;su&&(u=a[s].s);var f=new wE(u+1),p=wj(i[c-1],f,0);if(p>t){var s=0,m=0,_=p-t,g=1<<_;for(a.sort(function(e,t){return f[t.s]-f[e.s]||e.f-t.f});st)m+=g-(1<>=_;m>0;){var S=a[s].s;f[S]=0&&m;--s){var y=a[s].s;f[y]==t&&(--f[y],++m);}p=t;}return {t:new wT(f),l:p}},wj=function(e,t,i){return -1==e.s?Math.max(wj(e.l,t,i+1),wj(e.r,t,i+1)):t[e.s]=i},wK=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new wE(++t),s=0,r=e[0],a=1,n=function(e){i[s++]=e;},o=1;o<=t;++o)if(e[o]==r&&o!=t)++a;else {if(!r&&a>2){for(;a>138;a-=138)n(32754);a>2&&(n(a>10?a-11<<5|28690:a-3<<5|12305),a=0);}else if(a>3){for(n(r),--a;a>6;a-=6)n(8304);a>2&&(n(a-3<<5|8208),a=0);}for(;a--;)n(r);a=1,r=e[o];}return {c:i.subarray(0,s),n:t}},w$=function(e,t){for(var i=0,s=0;s>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var a=0;a4&&!D[wA[L-1]];--L);var M=h+5<<3,O=w$(r,wB)+w$(a,wk)+n,F=w$(r,_)+w$(a,S)+n+14+3*L+w$(A,D)+2*A[16]+3*A[17]+7*A[18];if(l>=0&&M<=O&&M<=F)return wZ(t,c,e.subarray(l,l+h));if(wX(t,c,1+(F15&&(wX(t,c,U[P]>>5&127),c+=U[P]>>12);}}else d=wU,u=wB,f=wz,p=wk;for(var P=0;P255){var z=V>>18&31;wY(t,c,d[z+257]),c+=u[z+257],z>7&&(wX(t,c,V>>23&31),c+=wb[z]);var G=31&V;wY(t,c,f[G]),c+=p[G],G>3&&(wY(t,c,V>>5&8191),c+=wC[G]);}else wY(t,c,d[V]),c+=u[V];}return wY(t,c,d[256]),c+u[256]},wJ=new ww([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),w0=new wT(0),w1=function(e,t,i,s,r,a){var n=a.z||e.length,o=new wT(s+n+5*(1+Math.ceil(n/7e3))+r),l=o.subarray(s,o.length-r),h=a.l,c=7&(a.r||0);if(t){c&&(l[0]=a.r>>3);for(var d=wJ[t-1],u=d>>13,f=8191&d,p=(1<7e3||C>24576)&&(L>423||!h)){c=wQ(e,l,0,y,x,T,w,C,P,b-P,c),C=E=w=0,P=b;for(var M=0;M<286;++M)x[M]=0;for(var M=0;M<30;++M)T[M]=0;}var O=2,F=0,N=f,B=D-R&32767;if(L>2&&I==S(b-B))for(var k=Math.min(u,L)-1,U=Math.min(32767,b),z=Math.min(258,L);B<=U&&--N&&D!=R;){if(e[b+O]==e[b+O-B]){for(var V=0;VO){if(O=V,F=B,V>k)break;for(var G=Math.min(B,V-2),H=0,M=0;MH&&(H=Y,R=W);}}}R=m[D=R],B+=D-R&32767;}if(F){y[C++]=0x10000000|wR[O]<<18|wL[F];var q=31&wR[O],j=31&wL[F];w+=wb[q]+wC[j],++x[257+q],++T[j],A=b+O,++E;}else y[C++]=e[b],++x[e[b]];}}for(b=Math.max(b,A);b=n&&(l[c/8|0]=h,K=n),c=wZ(l,c+1,e.subarray(b,K));}a.i=n;}return wG(o,0,s+wV(c)+r)},w2=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var i=t,s=9;--s;)i=(1&i&&-306674912)^i>>>1;e[t]=i;}return e}(),w3=function(){var e=-1;return {p:function(t){for(var i=e,s=0;s>>8;e=i;},d:function(){return ~e}}},w4=function(e,t,i,s,r){if(!r&&(r={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),n=new wT(a.length+e.length);n.set(a),n.set(e,a.length),e=n,r.w=a.length;}return w1(e,null==t.level?6:t.level,null==t.mem?r.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,i,s,r)},w5=function(e,t){var i={};for(var s in e)i[s]=e[s];for(var s in t)i[s]=t[s];return i},w6=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8;},w8=function(e,t,i,s){for(var r in e){var a=e[r],n=t+r,o=s;Array.isArray(a)&&(o=w5(s,a[1]),a=a[0]),a instanceof wT?i[n]=[a,o]:(i[n+="/"]=[new wT(0),o],w8(a,n,i,s));}},w9="u">typeof TextEncoder&&new TextEncoder,w7="u">typeof TextDecoder&&new TextDecoder;try{w7.decode(w0,{stream:!0});}catch(e){}function be(e,t){if(w9)return w9.encode(e);for(var i,s=e.length,r=new wT(e.length+(e.length>>1)),a=0,n=function(e){r[a++]=e;},i=0;ir.length){var o=new wT(a+8+(s-i<<1));o.set(r),r=o;}var l=e.charCodeAt(i);l<128||t?n(l):(l<2048?n(192|l>>6):(l>55295&&l<57344?(n(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++i))>>18),n(128|l>>12&63)):n(224|l>>12),n(128|l>>6&63)),n(128|63&l));}return wG(r,0,a)}var bt=function(e){var t=0;if(e)for(var i in e){var s=e[i].length;s>65535&&wW(9),t+=s+4;}return t},bi=function(e,t,i,s,r,a,n,o){var l=s.length,h=i.extra,c=o&&o.length,d=bt(h);w6(e,t,null!=n?0x2014b50:0x4034b50),t+=4,null!=n&&(e[t++]=20,e[t++]=i.os),e[t]=20,t+=2,e[t++]=i.flag<<1|(a<0&&8),e[t++]=r&&8,e[t++]=255&i.compression,e[t++]=i.compression>>8;var u=new Date(null==i.mtime?Date.now():i.mtime),f=u.getFullYear()-1980;if((f<0||f>119)&&wW(10),w6(e,t,f<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),t+=4,-1!=a&&(w6(e,t,i.crc),w6(e,t+4,a<0?-a-2:a),w6(e,t+8,i.size)),w6(e,t+12,l),w6(e,t+14,d),t+=16,null!=n&&(w6(e,t,c),w6(e,t+6,i.attrs),w6(e,t+10,n),t+=14),e.set(s,t),t+=l,d)for(var p in h){var m=h[p],_=m.length;w6(e,t,+p),w6(e,t+2,_),e.set(m,t+4),t+=4+_;}return c&&(e.set(o,t),t+=c),t},bs=function(e,t,i,s,r){w6(e,t,0x6054b50),w6(e,t+8,i),w6(e,t+10,i),w6(e,t+12,s),w6(e,t+16,r);};let br="root",ba=`#usda 1.0 +`,tg=new Float32Array(2),MA=new F,OA=class{constructor(t,e,s=-1){this.app=t,this.renderingLayer=e??t.scene.layers.getLayerByName("Immediate"),this.rt=this.createRenderTarget("OutlineTexture",1,1,!0),this.outlineCameraEntity=new Ne("OutlineCamera"),this.outlineCameraEntity.addComponent("camera",{layers:[this.renderingLayer.id],priority:s,clearColor:new F(0,0,0,0),renderTarget:this.rt}),this.outlineShaderPass=this.outlineCameraEntity.camera.setShaderPass("OutlineShaderPass"),this.postRender=a=>{this.outlineCameraEntity.camera===a&&this.onPostRender()},t.scene.on("postrender",this.postRender),this.app.root.addChild(this.outlineCameraEntity),this.tempRt=this.createRenderTarget("OutlineTempTexture",1,1,!1),this.blendState=new Oe(!0,0,6,8);let i=this.app.graphicsDevice;this.shaderExtend=Se.createShader(i,{uniqueName:"OutlineExtendShader",attributes:{vertex_position:ee},vertexChunk:"fullscreenQuadVS",fragmentGLSL:r9,fragmentWGSL:a9}),this.shaderBlend=Se.createShader(i,{uniqueName:"OutlineBlendShader",attributes:{vertex_position:ee},vertexChunk:"fullscreenQuadVS",fragmentChunk:"outputTex2DPS"}),this.quadRenderer=new hs(this.shaderBlend),this.whiteTex=new Z(i,{name:"OutlineWhiteTexture",width:1,height:1,format:st,mipmaps:!1}),this.whiteTex.lock().set(new Uint8Array([255,255,255,255])),this.whiteTex.unlock()}destroy(){this.whiteTex.destroy(),this.whiteTex=null,this.outlineCameraEntity.destroy(),this.outlineCameraEntity=null,this.rt.destroyTextureBuffers(),this.rt.destroy(),this.rt=null,this.tempRt.destroyTextureBuffers(),this.tempRt.destroy(),this.tempRt=null,this.app.scene.off("postrender",this.postRender),this.quadRenderer?.destroy(),this.quadRenderer=null}getMeshInstances(t,e){let s=[];return t&&((e?t.findComponents("render"):t.render?[t.render]:[]).forEach(a=>{a.meshInstances&&s.push(...a.meshInstances)}),(e?t.findComponents("model"):t.model?[t.model]:[]).forEach(a=>{a.meshInstances&&s.push(...a.meshInstances)})),s}addEntity(t,e,s=!0){let i=this.getMeshInstances(t,s);i.forEach(r=>{if(r.material instanceof it){let a=this.outlineShaderPass;r.material.onUpdateShader=l=>{if(l.pass===a){let h=new tr;return h.defines=l.defines,h.opacityMap=l.opacityMap,h.opacityMapUv=l.opacityMapUv,h.opacityMapChannel=l.opacityMapChannel,h.opacityMapTransform=l.opacityMapTransform,h.opacityVertexColor=l.opacityVertexColor,h.opacityVertexColorChannel=l.opacityVertexColorChannel,h.litOptions.vertexColors=l.litOptions.vertexColors,h.litOptions.alphaTest=l.litOptions.alphaTest,h.litOptions.skin=l.litOptions.skin,h.litOptions.batch=l.litOptions.batch,h.litOptions.useInstancing=l.litOptions.useInstancing,h.litOptions.useMorphPosition=l.litOptions.useMorphPosition,h.litOptions.useMorphNormal=l.litOptions.useMorphNormal,h.litOptions.useMorphTextureBasedInt=l.litOptions.useMorphTextureBasedInt,h.litOptions.opacityFadesSpecular=l.litOptions.opacityFadesSpecular,h}return l},MA.linear(e);let o=new Float32Array([MA.r,MA.g,MA.b]);r.setParameter("material_emissive",o,1<{i.material instanceof it&&(i.material.onUpdateShader=null,i.deleteParameter("material_emissive"))})}removeAllEntities(){this.renderingLayer.clearMeshInstances()}blendOutlines(){let t=this.app.graphicsDevice;t.scope.resolve("source").setValue(this.rt.colorBuffer),t.setDrawStates(this.blendState),this.quadRenderer.render()}onPostRender(){let t=this.app.graphicsDevice,e=t.scope.resolve("uOffset"),s=t.scope.resolve("source"),i=t.scope.resolve("uSrcMultiplier"),{rt:r,tempRt:a,shaderExtend:o}=this,{width:l,height:h}=r;tg[0]=1/l/2,tg[1]=0,e.setValue(tg),s.setValue(r.colorBuffer),i.setValue(0),Qt(t,a,o),tg[0]=0,tg[1]=1/h/2,e.setValue(tg),s.setValue(a.colorBuffer),i.setValue(1),Qt(t,r,o)}createRenderTarget(t,e,s,i){let r=new Z(this.app.graphicsDevice,{name:t,width:e,height:s,format:st,mipmaps:!1,addressU:1,addressV:1,minFilter:5,magFilter:1});return new me({colorBuffer:r,depth:i,flipY:this.app.graphicsDevice.isWebGPU})}updateRenderTarget(t){let e=t.renderTarget?.width??this.app.graphicsDevice.width,s=t.renderTarget?.height??this.app.graphicsDevice.height,i=this.outlineCameraEntity.camera;(!i.renderTarget||i.renderTarget.width!==e||i.renderTarget.height!==s)&&(this.rt.resize(e,s),this.tempRt.resize(e,s))}frameUpdate(t,e,s){let i=t.camera;this.updateRenderTarget(i);let r=this.app.scene.on("prerender:layer",(o,l,h)=>{i===o&&h===s&&l===e&&(this.blendOutlines(),r.off())});this.outlineCameraEntity.setLocalPosition(t.getPosition()),this.outlineCameraEntity.setLocalRotation(t.getRotation());let a=this.outlineCameraEntity.camera;a.projection=i.projection,a.horizontalFov=i.horizontalFov,a.fov=i.fov,a.orthoHeight=i.orthoHeight,a.nearClip=i.nearClip,a.farClip=i.farClip}};var sg=class{constructor(){}textureToCanvas(t,e={}){let s=t.getSource();if(typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&s instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&s instanceof ImageBitmap){let{width:u,height:d}=this.calcTextureSize(s.width,s.height,e.maxTextureSize),p=document.createElement("canvas");p.width=u,p.height=d;let m=p.getContext("2d");if(m===null)return Promise.resolve(void 0);if(m.drawImage(s,0,0,p.width,p.height),e.color){let{r:_,g:S,b:g}=e.color,T=m.getImageData(0,0,u,d),C=T.data;for(let v=0;v{l.destroy(),h.destroy();let d=new Uint8ClampedArray(r*a*4);d.set(u);let p=new ImageData(d,r,a),m=document.createElement("canvas");m.width=r,m.height=a;let _=m.getContext("2d");return _?(_.putImageData(p,0,0),Promise.resolve(m)):Promise.resolve(void 0)})}calcTextureSize(t,e,s){if(s){let i=Math.min(s/Math.max(t,e),1);t=Math.round(t*i),e=Math.round(e*i)}return{width:t,height:e}}};var wi=Uint8Array,Or=Uint16Array,kb=Int32Array,zb=new wi([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Gb=new wi([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),rV=new wi([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),hV=function(c,t){for(var e=new Or(31),s=0;s<31;++s)e[s]=t+=1<>1|(ht&21845)<<1,Fl=(Fl&52428)>>2|(Fl&13107)<<2,Fl=(Fl&61680)>>4|(Fl&3855)<<4,Nb[ht]=((Fl&65280)>>8|(Fl&255)<<8)>>1;var Fl,ht,gx=(function(c,t,e){for(var s=c.length,i=0,r=new Or(t);i>l]=h}else for(o=new Or(s),i=0;i>15-c[i]);return o}),Vu=new wi(288);for(ht=0;ht<144;++ht)Vu[ht]=8;var ht;for(ht=144;ht<256;++ht)Vu[ht]=9;var ht;for(ht=256;ht<280;++ht)Vu[ht]=7;var ht;for(ht=280;ht<288;++ht)Vu[ht]=8;var ht,FA=new wi(32);for(ht=0;ht<32;++ht)FA[ht]=5;var ht,n9=gx(Vu,9,0);var l9=gx(FA,5,0);var dV=function(c){return(c+7)/8|0},pV=function(c,t,e){return(t==null||t<0)&&(t=0),(e==null||e>c.length)&&(e=c.length),new wi(c.subarray(t,e))};var c9=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],BA=function(c,t,e){var s=new Error(t||c9[c]);if(s.code=c,Error.captureStackTrace&&Error.captureStackTrace(s,BA),!e)throw s;return s};var Nl=function(c,t,e){e<<=t&7;var s=t/8|0;c[s]|=e,c[s+1]|=e>>8},mx=function(c,t,e){e<<=t&7;var s=t/8|0;c[s]|=e,c[s+1]|=e>>8,c[s+2]|=e>>16},Ob=function(c,t){for(var e=[],s=0;sd&&(d=r[s].s);var p=new Or(d+1),m=Bb(e[f-1],p,0);if(m>t){var s=0,_=0,S=m-t,g=1<t)_+=g-(1<>=S;_>0;){var C=r[s].s;p[C]=0&&_;--s){var v=r[s].s;p[v]==t&&(--p[v],++_)}m=t}return{t:new wi(p),l:m}},Bb=function(c,t,e){return c.s==-1?Math.max(Bb(c.l,t,e+1),Bb(c.r,t,e+1)):t[c.s]=e},oV=function(c){for(var t=c.length;t&&!c[--t];);for(var e=new Or(++t),s=0,i=c[0],r=1,a=function(l){e[s++]=l},o=1;o<=t;++o)if(c[o]==i&&o!=t)++r;else{if(!i&&r>2){for(;r>138;r-=138)a(32754);r>2&&(a(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(a(i),--r;r>6;r-=6)a(8304);r>2&&(a(r-3<<5|8208),r=0)}for(;r--;)a(i);r=1,i=c[o]}return{c:e.subarray(0,s),n:t}},_x=function(c,t){for(var e=0,s=0;s>8,c[i+2]=c[i]^255,c[i+3]=c[i+1]^255;for(var r=0;r4&&!I[rV[O-1]];--O);var G=h+5<<3,M=_x(i,Vu)+_x(r,FA)+a,H=_x(i,d)+_x(r,_)+a+14+3*O+_x(P,I)+2*P[16]+3*P[17]+7*P[18];if(l>=0&&G<=M&&G<=H)return mV(t,f,c.subarray(l,l+h));var U,L,b,N;if(Nl(t,f,1+(H15&&(Nl(t,f,q[A]>>5&127),f+=q[A]>>12)}}else U=n9,L=Vu,b=l9,N=FA;for(var A=0;A255){var re=te>>18&31;mx(t,f,U[re+257]),f+=L[re+257],re>7&&(Nl(t,f,te>>23&31),f+=zb[re]);var j=te&31;mx(t,f,b[j]),f+=N[j],j>3&&(mx(t,f,te>>5&8191),f+=Gb[j])}else mx(t,f,U[te]),f+=L[te]}return mx(t,f,U[256]),f+L[256]},h9=new kb([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),_V=new wi(0),f9=function(c,t,e,s,i,r){var a=r.z||c.length,o=new wi(s+a+5*(1+Math.ceil(a/7e3))+i),l=o.subarray(s,o.length-i),h=r.l,f=(r.r||0)&7;if(t){f&&(l[0]=r.r>>3);for(var u=h9[t-1],d=u>>13,p=u&8191,m=(1<7e3||I>24576)&&(U>423||!h)){f=nV(c,l,0,v,E,y,A,I,O,w-O,f),I=P=A=0,O=w;for(var L=0;L<286;++L)E[L]=0;for(var L=0;L<30;++L)y[L]=0}var b=2,N=0,k=p,z=M-H&32767;if(U>2&&G==C(w-z))for(var V=Math.min(d,U)-1,q=Math.min(32767,w),re=Math.min(258,U);z<=q&&--k&&M!=H;){if(c[w+b]==c[w+b-z]){for(var te=0;teb){if(b=te,N=z,te>V)break;for(var j=Math.min(z,te-2),oe=0,L=0;Loe&&(oe=ot,H=be)}}}M=H,H=_[M],z+=M-H&32767}if(N){v[I++]=268435456|Fb[b]<<18|aV[N];var Ve=Fb[b]&31,Lt=aV[N]&31;A+=zb[Ve]+Gb[Lt],++E[257+Ve],++y[Lt],D=w+b,++P}else v[I++]=c[w],++E[c[w]]}}for(w=Math.max(w,D);w=a&&(l[f/8|0]=h,Vs=a),f=mV(l,f+1,c.subarray(w,Vs))}r.i=a}return pV(o,0,s+dV(f)+i)},u9=(function(){for(var c=new Int32Array(256),t=0;t<256;++t){for(var e=t,s=9;--s;)e=(e&1&&-306674912)^e>>>1;c[t]=e}return c})(),d9=function(){var c=-1;return{p:function(t){for(var e=c,s=0;s>>8;c=e},d:function(){return~c}}};var p9=function(c,t,e,s,i){if(!i&&(i={l:1},t.dictionary)){var r=t.dictionary.subarray(-32768),a=new wi(r.length+c.length);a.set(r),a.set(c,r.length),c=a,i.w=r.length}return f9(c,t.level==null?6:t.level,t.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(c.length)))*1.5):20:12+t.mem,e,s,i)},gV=function(c,t){var e={};for(var s in c)e[s]=c[s];for(var s in t)e[s]=t[s];return e};var fi=function(c,t,e){for(;e;++t)c[t]=e,e>>>=8};function m9(c,t){return p9(c,t||{},0,0)}var SV=function(c,t,e,s){for(var i in c){var r=c[i],a=t+i,o=s;Array.isArray(r)&&(o=gV(s,r[1]),r=r[0]),ArrayBuffer.isView(r)?e[a]=[r,o]:(e[a+="/"]=[new wi(0),o],SV(r,a,e,s))}},lV=typeof TextEncoder<"u"&&new TextEncoder,_9=typeof TextDecoder<"u"&&new TextDecoder,g9=0;try{_9.decode(_V,{stream:!0}),g9=1}catch{}function NA(c,t){if(t){for(var e=new wi(c.length),s=0;s>1)),a=0,o=function(f){r[a++]=f},s=0;sr.length){var l=new wi(a+8+(i-s<<1));l.set(r),r=l}var h=c.charCodeAt(s);h<128||t?o(h):h<2048?(o(192|h>>6),o(128|h&63)):h>55295&&h<57344?(h=65536+(h&1047552)|c.charCodeAt(++s)&1023,o(240|h>>18),o(128|h>>12&63),o(128|h>>6&63),o(128|h&63)):(o(224|h>>12),o(128|h>>6&63),o(128|h&63))}return pV(r,0,a)}var Ub=function(c){var t=0;if(c)for(var e in c){var s=c[e].length;s>65535&&BA(9),t+=s+4}return t},cV=function(c,t,e,s,i,r,a,o){var l=s.length,h=e.extra,f=o&&o.length,u=Ub(h);fi(c,t,a!=null?33639248:67324752),t+=4,a!=null&&(c[t++]=20,c[t++]=e.os),c[t]=20,t+=2,c[t++]=e.flag<<1|(r<0&&8),c[t++]=i&&8,c[t++]=e.compression&255,c[t++]=e.compression>>8;var d=new Date(e.mtime==null?Date.now():e.mtime),p=d.getFullYear()-1980;if((p<0||p>119)&&BA(10),fi(c,t,p<<25|d.getMonth()+1<<21|d.getDate()<<16|d.getHours()<<11|d.getMinutes()<<5|d.getSeconds()>>1),t+=4,r!=-1&&(fi(c,t,e.crc),fi(c,t+4,r<0?-r-2:r),fi(c,t+8,e.size)),fi(c,t+12,l),fi(c,t+14,u),t+=16,a!=null&&(fi(c,t,f),fi(c,t+6,e.attrs),fi(c,t+10,a),t+=14),c.set(s,t),t+=l,u)for(var m in h){var _=h[m],S=_.length;fi(c,t,+m),fi(c,t+2,S),c.set(_,t+4),t+=4+S}return f&&(c.set(o,t),t+=f),t},S9=function(c,t,e,s,i){fi(c,t,101010256),fi(c,t+8,e),fi(c,t+10,e),fi(c,t+12,s),fi(c,t+16,i)};function xV(c,t){t||(t={});var e={},s=[];SV(c,"",e,t);var i=0,r=0;for(var a in e){var o=e[a],l=o[0],h=o[1],f=h.level==0?0:8,u=NA(a),d=u.length,p=h.comment,m=p&&NA(p),_=m&&m.length,S=Ub(h.extra);d>65535&&BA(11);var g=f?m9(l,h):l,T=g.length,C=d9();C.p(l),s.push(gV(h,{size:l.length,crc:C.d(),c:g,f:u,m,u:d!=a.length||m&&p.length!=_,o:i,compression:f})),i+=30+d+S+T,r+=76+2*(d+S)+(_||0)+T}for(var v=new wi(r+22),E=i,y=r-i,P=0;P` ${e} inputs:${t} = ${i}`,bo=e=>{switch(e){case 0:return 5120;case 1:return 5121;case 2:return 5122;case 3:return 5123;case 4:return 5124;case 5:return 5125;case 6:return 5126}return 0},bl=function(e){switch(e){case 0:return 9728;case 1:return 9729;case 2:return 9984;case 4:return 9985;case 3:return 9986;case 5:return 9987}return 0},bh=function(e){switch(e){case 1:return 33071;case 2:return 33648;case 0:return 10497}return 0},bc=["anisotropyMap","clearCoatGlossMap","clearCoatMap","clearCoatNormalMap","colorMap","diffuseMap","emissiveMap","iridescenceMap","iridescenceThicknessMap","metalnessMap","normalMap","refractionMap","sheenGlossMap","sheenMap","specularityFactorMap","specularMap","thicknessMap"];class bd extends wx{collectResources(e){let t={buffers:[],cameras:[],entities:[],materials:[],skins:[],textures:[],entityMeshInstances:[],bufferViewMap:new Map,compressableTexture:new Set},{materials:i,buffers:s,entityMeshInstances:r,textures:a}=t;e.forEach(e=>{t.entities.push(e);});let n=e=>{e.forEach(e=>{let n=e.material;0>i.indexOf(n)&&(t.materials.push(n),bc.forEach(e=>{let i=n[e];i&&0>a.indexOf(i)&&("normalMap"!==e&&t.compressableTexture.add(i),a.push(i));}));let o=e.node,l=r.find(e=>e.node===o);l||(l={node:o,meshInstances:[]},r.push(l)),l.meshInstances.push(e);let h=e.mesh,c=h.vertexBuffer;0>s.indexOf(c)&&s.unshift(c);let d=h.indexBuffer[0];0>s.indexOf(d)&&s.push(d),h.skin&&0>t.skins.indexOf(h.skin)&&t.skins.push(h.skin);});};return t.entities.forEach(e=>{e.camera&&t.cameras.push(e.camera),e.render&&e.render.enabled&&n(e.render.meshInstances),e.model&&e.model.enabled&&e.model.meshInstances&&n(e.model.meshInstances);}),t}writeBufferViews(e,t){for(let i of(t.bufferViews=[],e.buffers))bd.writeBufferView(e,t,i);}static writeBufferView(e,t,i){let s;t.buffers=t.buffers??[],t.buffers[0]=t.buffers[0]??{byteLength:0};let r=t.buffers[0];r.byteLength=ei.roundUp(r.byteLength,4);let a=r.byteLength,n=(e,i,s,r)=>{let a={buffer:0,byteLength:i,byteOffset:s};return (34962===e||34963===e)&&(a.target=e),void 0!==r&&(a.byteStride=r),t.bufferViews.push(a)-1};if(i instanceof iR){s=i.lock();let t=i.getFormat();if(t.interleaved){let r=n(34962,s.byteLength,a,t.size);e.bufferViewMap.set(i,[r]);}else {let s=[];for(let e of t.elements){let i=n(34962,e.size*t.vertexCount,a+e.offset,e.size);s.push(i);}e.bufferViewMap.set(i,s);}}else if(i instanceof iw){let t=n(34963,(s=i.lock()).byteLength,a);e.bufferViewMap.set(i,[t]);}else {let t=n(void 0,(s=i).byteLength,a);e.bufferViewMap.set(i,[t]);}r.byteLength+=s.byteLength;}writeCameras(e,t){e.cameras.length>0&&(t.cameras=e.cameras.map(e=>{let t=e.projection,i=e.nearClip,s=e.farClip,r={};if(1===t)r.type="orthographic",r.orthographic={xmag:1,ymag:1,znear:i,zfar:s};else {let t=e.fov;r.type="perspective",r.perspective={yfov:t*ei.DEG_TO_RAD,znear:i,zfar:s};}return r}));}attachTexture(e,t,i,s,r,a){let n=t[r];if(n){let o=e.textures.indexOf(n);i[s]={index:o};let l=t[`${r}Tiling`],h=t[`${r}Offset`],c=t[`${r}Rotation`];(l&&!l.equals(ef.ONE)||h&&!h.equals(ef.ZERO)||0!==c)&&(i[s].extensions={KHR_texture_transform:{}},a.extensionsUsed=a.extensionsUsed??[],a.extensionsUsed.includes("KHR_texture_transform")||a.extensionsUsed.push("KHR_texture_transform"),a.extensionsRequired=a.extensionsRequired??[],a.extensionsRequired.includes("KHR_texture_transform")||a.extensionsRequired.push("KHR_texture_transform"),l&&!l.equals(ef.ONE)&&(i[s].extensions.KHR_texture_transform.scale=[l.x,l.y]),h&&!h.equals(ef.ZERO)&&(i[s].extensions.KHR_texture_transform.offset=[h.x,h.y-1+l.y]),0!==c&&(i[s].extensions.KHR_texture_transform.rotation=c*ei.DEG_TO_RAD));}}addExtension(e,t,i,s={}){t.extensions=t.extensions||{},t.extensions[i]=s,e.extensionsUsed=e.extensionsUsed??[],e.extensionsUsed.includes(i)||e.extensionsUsed.push(i);}writeStandardMaterial(e,t,i,s){let{diffuse:r,emissive:a,opacity:n,metalness:o,gloss:l,glossInvert:h}=t,c=i.pbrMetallicRoughness,d=t.useLighting?r:a;if(!d.equals(es.WHITE)||1!==n){let{r:e,g:t,b:i}=d.clone().linear();c.baseColorFactor=[e,t,i,n];}t.useMetalness?1!==o&&(c.metallicFactor=o):c.metallicFactor=0;let u=h?l:1-l;if(1!==u&&(c.roughnessFactor=u),this.attachTexture(e,t,c,"baseColorTexture",t.useLighting?"diffuseMap":"emissiveMap",s),this.attachTexture(e,t,c,"metallicRoughnessTexture","metalnessMap",s),t.useLighting&&!a.equals(es.BLACK)){let{r:e,g:t,b:s}=a.clone().linear();i.emissiveFactor=[e,t,s];}if(t.enableGGXSpecular&&(0!==t.anisotropyIntensity||0!==t.anisotropyRotation||t.anisotropyMap)){let r={};0!==t.anisotropyIntensity&&(r.anisotropyStrength=t.anisotropyIntensity),0!==t.anisotropyRotation&&(r.anisotropyRotation=t.anisotropyRotation*ei.DEG_TO_RAD),this.attachTexture(e,t,r,"anisotropyTexture","anisotropyMap",s),Object.keys(r).length>0&&this.addExtension(s,i,"KHR_materials_anisotropy",r);}if(t.clearCoat>0){let r={clearcoatFactor:Math.min(4*t.clearCoat,1)};0!==t.clearCoatGloss&&(r.clearcoatRoughnessFactor=t.clearCoatGloss),this.attachTexture(e,t,r,"clearcoatTexture","clearCoatMap",s),this.attachTexture(e,t,r,"clearcoatRoughnessTexture","clearCoatGlossMap",s),t.clearCoatNormalMap&&(this.attachTexture(e,t,r,"clearcoatNormalTexture","clearCoatNormalMap",s),1!==t.clearCoatBumpiness&&(r.clearcoatNormalTexture.scale=t.clearCoatBumpiness)),this.addExtension(s,i,"KHR_materials_clearcoat",r);}if(0!==t.dispersion&&this.addExtension(s,i,"KHR_materials_dispersion",{dispersion:t.dispersion}),t.useLighting&&1!==t.emissiveIntensity&&this.addExtension(s,i,"KHR_materials_emissive_strength",{emissiveStrength:t.emissiveIntensity}),t.refractionIndex!==1/1.5&&t.refractionIndex>0&&this.addExtension(s,i,"KHR_materials_ior",{ior:1/t.refractionIndex}),t.useIridescence){let r={};0!==t.iridescence&&(r.iridescenceFactor=t.iridescence),1.3!==t.iridescenceRefractionIndex&&(r.iridescenceIor=t.iridescenceRefractionIndex),100!==t.iridescenceThicknessMin&&(r.iridescenceThicknessMinimum=t.iridescenceThicknessMin),400!==t.iridescenceThicknessMax&&(r.iridescenceThicknessMaximum=t.iridescenceThicknessMax),this.attachTexture(e,t,r,"iridescenceTexture","iridescenceMap",s),this.attachTexture(e,t,r,"iridescenceThicknessTexture","iridescenceThicknessMap",s),Object.keys(r).length>0&&this.addExtension(s,i,"KHR_materials_iridescence",r);}if(t.useSheen){let r={};if(!t.sheen.equals(es.BLACK)){let{r:e,g:i,b:s}=t.sheen.clone().linear();r.sheenColorFactor=[e,i,s];}0!==t.sheenGloss&&(r.sheenRoughnessFactor=t.sheenGloss),this.attachTexture(e,t,r,"sheenColorTexture","sheenMap",s),this.attachTexture(e,t,r,"sheenRoughnessTexture","sheenGlossMap",s),Object.keys(r).length>0&&this.addExtension(s,i,"KHR_materials_sheen",r);}if(t.useMetalnessSpecularColor||!t.useMetalness){let r={};if(!t.specular.equals(es.WHITE)){let{r:e,g:i,b:s}=t.specular.clone().linear();r.specularColorFactor=[e,i,s];}1!==t.specularityFactor&&(r.specularFactor=t.specularityFactor),this.attachTexture(e,t,r,"specularColorTexture","specularMap",s),this.attachTexture(e,t,r,"specularTexture","specularityFactorMap",s),Object.keys(r).length>0&&this.addExtension(s,i,"KHR_materials_specular",r);}if(t.useDynamicRefraction&&(0!==t.refraction||t.refractionMap)){let r={};0!==t.refraction&&(r.transmissionFactor=t.refraction),this.attachTexture(e,t,r,"transmissionTexture","refractionMap",s),Object.keys(r).length>0&&this.addExtension(s,i,"KHR_materials_transmission",r);}if(t.useLighting||this.addExtension(s,i,"KHR_materials_unlit"),t.useDynamicRefraction&&(0!==t.thickness||0!==t.attenuationDistance||!t.attenuation.equals(es.WHITE)||t.thicknessMap)){let r={};if(0!==t.thickness&&(r.thicknessFactor=t.thickness),0!==t.attenuationDistance&&(r.attenuationDistance=t.attenuationDistance),!t.attenuation.equals(es.WHITE)){let{r:e,g:i,b:s}=t.attenuation.clone().linear();r.attenuationColor=[e,i,s];}this.attachTexture(e,t,r,"thicknessTexture","thicknessMap",s),Object.keys(r).length>0&&this.addExtension(s,i,"KHR_materials_volume",r);}}writeMaterials(e,t){e.materials.length>0&&(t.materials=e.materials.map(i=>{let{name:s,blendType:r,cull:a,alphaTest:n}=i,o={pbrMetallicRoughness:{}};return s&&s.length>0&&(o.name=s),i instanceof ud&&this.writeStandardMaterial(e,i,o,t),2===r?o.alphaMode="BLEND":3===r&&0!==n&&(o.alphaMode="MASK",o.alphaCutoff=n),0===a&&(o.doubleSided=true),this.attachTexture(e,i,o,"normalTexture","normalMap",t),this.attachTexture(e,i,o,"occlusionTexture","aoMap",t),this.attachTexture(e,i,o,"emissiveTexture","emissiveMap",t),o}));}writeNodes(e,t){e.entities.length>0&&(t.nodes=e.entities.map(t=>{let i=t.name,s=t.getLocalPosition(),r=t.getLocalRotation(),a=t.getLocalScale(),n={};i&&i.length>0&&(n.name=i),s.equals(ed.ZERO)||(n.translation=[s.x,s.y,s.z]),r.equals(ex.IDENTITY)||(n.rotation=[r.x,r.y,r.z,r.w]),a.equals(ed.ONE)||(n.scale=[a.x,a.y,a.z]),t.camera&&t.camera.enabled&&(n.camera=e.cameras.indexOf(t.camera));let o=e.entityMeshInstances.find(e=>e.node===t);if(o){n.mesh=e.entityMeshInstances.indexOf(o);let t=o.meshInstances[0];t&&t.mesh.skin&&(n.skin=e.skins.indexOf(t.mesh.skin));}return t.children.length>0&&(n.children=[],t.children.forEach(t=>{n.children.push(e.entities.indexOf(t));})),n}));}writeMeshes(e,t,i){e.entityMeshInstances.length>0&&(t.accessors=[],t.meshes=[],e.entityMeshInstances.forEach(s=>{let r={primitives:[]};s.meshInstances.forEach(s=>{let a=bd.createPrimitive(e,t,s.mesh,i);a.material=e.materials.indexOf(s.material),r.primitives.push(a);}),t.meshes.push(r);}));}static createPrimitive(e,t,i,s={}){let r={attributes:{}},{vertexBuffer:a}=i,{format:n}=a,{interleaved:o,elements:l}=n,h=a.getNumVertices();l.forEach((n,l)=>{let c=(e=>{switch(e){case e8:return "POSITION";case e9:return "NORMAL";case e7:return "TANGENT";case ti:return "COLOR_0";case tt:return "JOINTS_0";case te:return "WEIGHTS_0";case tr:return "TEXCOORD_0";case ta:return "TEXCOORD_1";case tn:return "TEXCOORD_2";case to:return "TEXCOORD_3";case tl:return "TEXCOORD_4";case th:return "TEXCOORD_5";case tc:return "TEXCOORD_6";case td:return "TEXCOORD_7"}return ""})(n.name);if(s.stripUnusedAttributes){let t=true;if(c.startsWith("TEXCOORD_")){let i=parseInt(c.split("_")[1],10);t=e.materials.some(e=>bc.some(t=>e[t]&&(0===i||e[`${t}Tiling`]?.uv===i)));}if("COLOR_0"===c&&(t=e.materials.some(e=>e.vertexColors)),"TANGENT"===c&&(t=e.materials.some(e=>e.normalMap)),("JOINTS_0"===c||"WEIGHTS_0"===c)&&(t=e.entityMeshInstances.some(e=>e.meshInstances.some(e=>e.mesh.skin))),!t)return}let d=e.bufferViewMap.get(a);d||(bd.writeBufferView(e,t,a),e.buffers.push(a),d=e.bufferViewMap.get(a));let u={bufferView:d[o?0:l],byteOffset:o?n.offset:0,componentType:bo(n.dataType),type:(e=>{switch(e){case 1:return "SCALAR";case 2:return "VEC2";case 3:return "VEC3";case 4:return "VEC4"}return 0})(n.numComponents),count:h},f=t.accessors.push(u)-1;if(r.attributes[c]=f,n.name===e8){let e=[];i.getPositions(e);let t=new ed,s=new ed;eA.computeMinMax(e,t,s),u.min=[t.x,t.y,t.z],u.max=[s.x,s.y,s.z];}});let c=i.indexBuffer[0];if(c){let i=e.bufferViewMap.get(c);i||(bd.writeBufferView(e,t,c),e.buffers.push(c),i=e.bufferViewMap.get(c));let s={bufferView:i[0],componentType:(e=>{switch(e){case 0:return 5121;case 1:return 5123;case 2:return 5125}return 0})(c.getFormat()),count:c.getNumIndices(),type:"SCALAR"};r.indices=t.accessors.push(s)-1;}return r}writeSkins(e,t){e.skins.length>0&&(t.skins=e.skins.map(i=>{let s=new Float32Array(16*i.inverseBindPose.length);for(let e=0;e{let i=e.entities.find(e=>e.name===t);return e.entities.indexOf(i)})}}));}convertTextures(e,t){let i={maxTextureSize:t.maxTextureSize},s=[];return e.forEach(e=>{let t=this.textureToCanvas(e,i);t.then(e=>new Promise(t=>t(e))),s.push(t);}),s}writeTextures(e,t,i,s){let r=e.textures,a=[];for(let s=0;s{let t=new FileReader;return t.readAsArrayBuffer(e),new Promise(e=>{t.onloadend=()=>{e(t);};})}).then(t=>{let r=this.getPaddedArrayBuffer(t.result);bd.writeBufferView(e,i,r),e.buffers.push(r);let a=e.bufferViewMap.get(r);i.images[s]={mimeType:l,bufferView:a[0]},i.samplers[s]={minFilter:bl(n.minFilter),magFilter:bl(n.magFilter),wrapS:bh(n.addressU),wrapT:bh(n.addressV)},i.textures[s]={sampler:s,source:s};}));}return Promise.all(a)}getBlob(e,t){if(void 0!==e.toBlob)return new Promise(i=>{e.toBlob(i,t);});let i=1;return "image/jpeg"===t&&(i=.92),e.convertToBlob({type:t,quality:i})}getPaddedArrayBuffer(e,t=0){let i=ei.roundUp(e.byteLength,4);if(i!==e.byteLength){let s=new Uint8Array(i);if(s.set(new Uint8Array(e)),0!==t)for(let r=e.byteLength;r{let s={asset:{version:"2.0",generator:"PlayCanvas GltfExporter"},scenes:[{nodes:[0]}],images:[],samplers:[],textures:[],scene:0};return this.writeBufferViews(e,s),this.writeCameras(e,s),this.writeMeshes(e,s,t),this.writeMaterials(e,s),this.writeNodes(e,s,t),this.writeSkins(e,s),await this.writeTextures(e,i,s,t),s.images.length||delete s.images,s.samplers.length||delete s.samplers,s.textures.length||delete s.textures,s})}build(e,t={}){let i=this.collectResources(e);return this.buildJson(i,t).then(e=>{let t=new TextEncoder().encode(JSON.stringify(e)),s=t.length,r=4-(3&s)&3,a=e.buffers.reduce((e,t)=>ei.roundUp(e+t.byteLength,4),0),n=20+s+r;a>0&&(n+=8+a);let o=new ArrayBuffer(n),l=new DataView(o);l.setUint32(0,0x46546c67,true),l.setUint32(4,2,true),l.setUint32(8,n,true),l.setUint32(12,s+r,true),l.setUint32(16,0x4e4f534a,true);let h=20;new Uint8Array(o,20,s).set(t),h+=s;for(let e=0;e0&&(l.setUint32(h,a,true),l.setUint32(h+4,5130562,true),h+=8,i.buffers.forEach(t=>{let s,r=i.bufferViewMap.get(t)[0],a=e.bufferViews[r].byteOffset;if(t instanceof ArrayBuffer)s=new Uint8Array(t);else {let e=t.lock();s=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);}new Uint8Array(o,h+a,s.byteLength).set(s);})),Promise.resolve(o)})}}let bu="none",bf="lighting",bp="combine";var bm=` +`,v9=c=>` +def "Materials" +{ + ${c.join(` +`)} +} +`,T9=(c,t,e,s,i,r)=>` +def "Mesh" +{ + def Mesh "Mesh" + { + int[] faceVertexCounts = [${c}] + int[] faceVertexIndices = [${t}] + normal3f[] normals = [${e}] ( + interpolation = "vertex" + ) + point3f[] points = [${s}] + texCoord2f[] primvars:st = [${i}] ( + interpolation = "vertex" + ) + texCoord2f[] primvars:st1 = [${r}] ( + interpolation = "vertex" + ) + uniform token subdivisionScheme = "none" + } +} +`,y9=(c,t,e,s)=>` +def Xform "${c}" ( + prepend references = ${t} +) +{ + matrix4d xformOp:transform = ${e} + uniform token[] xformOpOrder = ["xformOp:transform"] + + rel material:binding = ${s} +} +`,TV=(c,t,e)=>` ${c} inputs:${t} = ${e}`,UA=class extends sg{constructor(){super(...arguments);n(this,"meshMap");n(this,"materialMap");n(this,"materials");n(this,"textureMap");n(this,"nodeNames");n(this,"files")}init(){this.meshMap=new Map,this.textureMap=new Map,this.materialMap=new Map,this.materials=[],this.files={},this.nodeNames=new Set}done(){this.meshMap=null,this.textureMap=null,this.materialMap=null,this.materials=null,this.files=null,this.nodeNames=null}build(e,s={}){this.init(),this.addFile(null,vV);let i=[];e&&e.findComponents("render").forEach(u=>{i.push(...u.meshInstances)});let r="";i.forEach(f=>{r+=this.buildMeshInstance(f)}),r+=v9(this.materials),this.addFile(null,vV,"",r);let a={maxTextureSize:s.maxTextureSize},o=Array.from(this.textureMap.keys()),l=[];for(let f=0;f_?new Promise(S=>_.toBlob(S,d,1)).then(S=>S.arrayBuffer()):new Promise(S=>S(null)));l.push(m)}return Promise.all(l).then(f=>{f.forEach((d,p)=>{let m=o[p],_=this.getTextureFileIds(m);this.files[_.fileName]=new Uint8Array(d)}),this.alignFiles();let u=xV(this.files,{level:0});return this.done(),u})}alignFiles(){let e=0;for(let s in this.files){let i=this.files[s],r=34+s.length;e+=r;let a=e&63;if(a!==4){let o=64-a,l=new Uint8Array(o);this.files[s]=[i,{extra:{12345:l}}]}e=i.length}}getFileIds(e,s,i,r="usda"){let a=`${e?`${e}/`:""}${s}.${r}`,o=`@./${a}@`;return{name:s,fileName:a,refName:o}}getTextureFileIds(e){return this.getFileIds("texture",`Texture_${e.id}`,"Texture","png")}addFile(e,s,i="",r=""){let a=null;r&&(r=`${x9} +${r}`,a=NA(r));let o=this.getFileIds(e,s,i);return this.files[o.fileName]=a,o.refName}getMaterialRef(e){let s=this.materialMap.get(e);return s||(s=this.buildMaterial(e),this.materialMap.set(e,s)),s}getMeshRef(e){let s=this.meshMap.get(e);return s||(s=this.buildMesh(e),this.meshMap.set(e,s)),s}buildArray2(e){let s=[],i=e.length;for(let r=0;r`<${i}${p}>`,a=(p,m,_,S,g,T,C,v)=>` + def Shader "Transform2d_${_}" ( + sdrMetadata = { + string role = "math" + } + ) + { + uniform token info:id = "UsdTransform2d" + float2 inputs:in.connect = ${r(`/uvReader_${S}.outputs:result`)} + float inputs:rotation = ${C} + float2 inputs:scale = (${g.x}, ${g.y}) + float2 inputs:translation = (${T.x}, ${T.y}) + float2 outputs:result + } + + def Shader "Texture_${p.id}_${_}" + { + uniform token info:id = "UsdUVTexture" + asset inputs:file = @${m.fileName}@ + float2 inputs:st.connect = ${r(`/Transform2d_${_}.outputs:result`)} + token inputs:wrapS = "repeat" + token inputs:wrapT = "repeat" + float4 inputs:scale = (${v.r}, ${v.g}, ${v.b}, ${v.a}) + float outputs:r + float outputs:g + float outputs:b + float3 outputs:rgb + float outputs:a + } + `,o=[],l=[],h=(p,m,_,S,g,T=!1,C=!1)=>{let v=e[p];if(v){let E=this.getTextureFileIds(v);this.textureMap.set(v,E.refName);let y=e[`${p}Channel`]||"rgb",P=r(`/${E.name}_${g}.outputs:${y}`);o.push(TV(_,`${S}.connect`,P)),T&&e.alphaTest>0;let A=e[`${p}Tiling`],w=e[`${p}Offset`],I=e[`${p}Rotation`],D=e[`${p}Uv`]===1?"st1":"st",O=C&&m?m:F.WHITE;l.push(a(v,E,g,D,A,w,I,O))}else if(m){let E=_==="float"?`${m}`:`(${m.r}, ${m.g}, ${m.b})`;o.push(TV(_,S,E))}};h("diffuseMap",e.diffuse,"color3f","diffuseColor","diffuse",!1,!0),(e.transparent||e.alphaTest>0)&&h("opacityMap",e.opacity,"float","opacity","opacity",!0),h("normalMap",null,"normal3f","normal","normal"),h("emissiveMap",e.emissive,"color3f","emissiveColor","emissive",!1,!0),h("aoMap",null,"float","occlusion","occlusion");let f=e.useMetalness?e.metalness:0;h("metalnessMap",f,"float","metallic","metallic");let u=e.glossInvert?e.gloss:1-e.gloss;h("glossMap",u,"float","roughness","roughness");let d=` + def Material "${s}" + { + def Shader "PreviewSurface" + { + uniform token info:id = "UsdPreviewSurface" +${o.join(` +`)} + int inputs:useSpecularWorkflow = 0 + token outputs:surface + } + + token outputs:surface.connect = ${r("/PreviewSurface.outputs:surface")} + + def Shader "uvReader_st" + { + uniform token info:id = "UsdPrimvarReader_float2" + token inputs:varname = "st" + float2 inputs:fallback = (0.0, 0.0) + float2 outputs:result + } + + def Shader "uvReader_st1" + { + uniform token info:id = "UsdPrimvarReader_float2" + token inputs:varname = "st1" + float2 inputs:fallback = (0.0, 0.0) + float2 outputs:result + } + + ${l.join(` +`)} + } + `;return this.materials.push(d),r("")}buildMesh(e){let s=[],i=[],r=[],a=[],o=[];e.getVertexStream(ee,s),e.getVertexStream(Ot,r),e.getVertexStream(_t,a),e.getVertexStream(ri,o),e.getIndices(i);let l=i.length||s.length,h=Array(l/3).fill(3).join(", ");if(!i.length)for(let p=0;p{switch(c){case 0:return 5121;case 1:return 5123;case 2:return 5125}return 0},EV=c=>{switch(c){case js:return 5120;case ai:return 5121;case qs:return 5122;case Ri:return 5123;case He:return 5124;case kt:return 5125;case ye:return 5126}return 0},A9=c=>{switch(c){case 1:return"SCALAR";case 2:return"VEC2";case 3:return"VEC3";case 4:return"VEC4"}return 0},C9=c=>{switch(c){case ee:return"POSITION";case Ot:return"NORMAL";case vs:return"TANGENT";case Ct:return"COLOR_0";case $t:return"JOINTS_0";case bs:return"WEIGHTS_0";case _t:return"TEXCOORD_0";case ri:return"TEXCOORD_1";case Ca:return"TEXCOORD_2";case Pa:return"TEXCOORD_3";case wa:return"TEXCOORD_4";case Ia:return"TEXCOORD_5";case Ra:return"TEXCOORD_6";case ba:return"TEXCOORD_7"}return""},AV=function(c){switch(c){case 0:return 9728;case 1:return 9729;case 2:return 9984;case 4:return 9985;case 3:return 9986;case 5:return 9987}return 0},CV=function(c){switch(c){case 1:return 33071;case 2:return 33648;case 0:return 10497}return 0};function P9(c){let e=c.getContext("2d").getImageData(0,0,c.width,c.height).data;for(let s=3;s{e.entities.push(l)});let o=l=>{l.forEach(h=>{let f=h.material;s.indexOf(f)<0&&(e.materials.push(f),PV.forEach(S=>{let g=f[S];g&&a.indexOf(g)<0&&(S!=="normalMap"&&e.compressableTexture.add(g),a.push(g))}));let u=h.node,d=r.find(S=>S.node===u);d||(d={node:u,meshInstances:[]},r.push(d)),d.meshInstances.push(h);let p=h.mesh,m=p.vertexBuffer;i.indexOf(m)<0&&i.unshift(m);let _=p.indexBuffer[0];i.indexOf(_)<0&&i.push(_),p.skin&&e.skins.indexOf(p.skin)<0&&e.skins.push(p.skin)})};return e.entities.forEach(l=>{l.camera&&e.cameras.push(l.camera),l.render&&l.render.enabled&&o(l.render.meshInstances),l.model&&l.model.enabled&&l.model.meshInstances&&o(l.model.meshInstances)}),e}writeBufferViews(t,e){e.bufferViews=[];for(let s of t.buffers)c.writeBufferView(t,e,s)}static writeBufferView(t,e,s){e.buffers=e.buffers??[],e.buffers[0]=e.buffers[0]??{byteLength:0};let i=e.buffers[0];i.byteLength=R.roundUp(i.byteLength,4);let r=i.byteLength,a=(l,h,f,u)=>{let d={buffer:0,byteLength:h,byteOffset:f};return(l===Vb||l===yV)&&(d.target=l),u!==void 0&&(d.byteStride=u),e.bufferViews.push(d)-1},o;if(s instanceof ft){o=s.lock();let l=s.getFormat();if(l.interleaved){let h=a(Vb,o.byteLength,r,l.size);t.bufferViewMap.set(s,[h])}else{let h=[];for(let f of l.elements){let u=a(Vb,f.size*l.vertexCount,r+f.offset,f.size);h.push(u)}t.bufferViewMap.set(s,h)}}else if(s instanceof os){o=s.lock();let l=a(yV,o.byteLength,r);t.bufferViewMap.set(s,[l])}else{o=s;let l=a(void 0,o.byteLength,r);t.bufferViewMap.set(s,[l])}i.byteLength+=o.byteLength}writeCameras(t,e){t.cameras.length>0&&(e.cameras=t.cameras.map(s=>{let i=s.projection,r=s.nearClip,a=s.farClip,o={};if(i===ni)o.type="orthographic",o.orthographic={xmag:1,ymag:1,znear:r,zfar:a};else{let l=s.fov;o.type="perspective",o.perspective={yfov:l*R.DEG_TO_RAD,znear:r,zfar:a}}return o}))}attachTexture(t,e,s,i,r,a){let o=e[r];if(o){let l=t.textures.indexOf(o);l<0,s[i]={index:l};let h=e[`${r}Uv`]??0;h!==0&&(s[i].texCoord=h);let f=e[`${r}Tiling`],u=e[`${r}Offset`],d=e[`${r}Rotation`];(f&&!f.equals(B.ONE)||u&&!u.equals(B.ZERO)||d!==0)&&(s[i].extensions={KHR_texture_transform:{}},a.extensionsUsed=a.extensionsUsed??[],a.extensionsUsed.includes("KHR_texture_transform")||a.extensionsUsed.push("KHR_texture_transform"),a.extensionsRequired=a.extensionsRequired??[],a.extensionsRequired.includes("KHR_texture_transform")||a.extensionsRequired.push("KHR_texture_transform"),f&&!f.equals(B.ONE)&&(s[i].extensions.KHR_texture_transform.scale=[f.x,f.y]),u&&!u.equals(B.ZERO)&&(s[i].extensions.KHR_texture_transform.offset=[u.x,u.y-1+f.y]),d!==0&&(s[i].extensions.KHR_texture_transform.rotation=d*R.DEG_TO_RAD))}}addExtension(t,e,s,i={}){e.extensions=e.extensions||{},e.extensions[s]=i,t.extensionsUsed=t.extensionsUsed??[],t.extensionsUsed.includes(s)||t.extensionsUsed.push(s)}writeStandardMaterial(t,e,s,i){let{diffuse:r,emissive:a,opacity:o,metalness:l,gloss:h,glossInvert:f}=e,u=s.pbrMetallicRoughness,d=e.useLighting?r:a;if(!d.equals(F.WHITE)||o!==1){let{r:_,g:S,b:g}=d.clone().linear();u.baseColorFactor=[_,S,g,o]}e.useMetalness?l!==1&&(u.metallicFactor=l):u.metallicFactor=0;let p=f?h:1-h;if(p!==1&&(u.roughnessFactor=p),this.attachTexture(t,e,u,"baseColorTexture",e.useLighting?"diffuseMap":"emissiveMap",i),this.attachTexture(t,e,u,"metallicRoughnessTexture","metalnessMap",i),e.useLighting&&!a.equals(F.BLACK)){let{r:_,g:S,b:g}=a.clone().linear();s.emissiveFactor=[_,S,g]}if(e.enableGGXSpecular&&(e.anisotropyIntensity!==0||e.anisotropyRotation!==0||e.anisotropyMap)){let _={};e.anisotropyIntensity!==0&&(_.anisotropyStrength=e.anisotropyIntensity),e.anisotropyRotation!==0&&(_.anisotropyRotation=e.anisotropyRotation*R.DEG_TO_RAD),this.attachTexture(t,e,_,"anisotropyTexture","anisotropyMap",i),Object.keys(_).length>0&&this.addExtension(i,s,"KHR_materials_anisotropy",_)}if(e.clearCoat>0){let _={clearcoatFactor:Math.min(e.clearCoat*4,1)};e.clearCoatGloss!==0&&(_.clearcoatRoughnessFactor=e.clearCoatGloss),this.attachTexture(t,e,_,"clearcoatTexture","clearCoatMap",i),this.attachTexture(t,e,_,"clearcoatRoughnessTexture","clearCoatGlossMap",i),e.clearCoatNormalMap&&(this.attachTexture(t,e,_,"clearcoatNormalTexture","clearCoatNormalMap",i),e.clearCoatBumpiness!==1&&(_.clearcoatNormalTexture.scale=e.clearCoatBumpiness)),this.addExtension(i,s,"KHR_materials_clearcoat",_)}e.dispersion!==0&&this.addExtension(i,s,"KHR_materials_dispersion",{dispersion:e.dispersion}),e.useLighting&&e.emissiveIntensity!==1&&this.addExtension(i,s,"KHR_materials_emissive_strength",{emissiveStrength:e.emissiveIntensity});let m=1/1.5;if(e.refractionIndex!==m&&e.refractionIndex>0&&this.addExtension(i,s,"KHR_materials_ior",{ior:1/e.refractionIndex}),e.useIridescence){let _={};e.iridescence!==0&&(_.iridescenceFactor=e.iridescence),e.iridescenceRefractionIndex!==1.3&&(_.iridescenceIor=e.iridescenceRefractionIndex),e.iridescenceThicknessMin!==100&&(_.iridescenceThicknessMinimum=e.iridescenceThicknessMin),e.iridescenceThicknessMax!==400&&(_.iridescenceThicknessMaximum=e.iridescenceThicknessMax),this.attachTexture(t,e,_,"iridescenceTexture","iridescenceMap",i),this.attachTexture(t,e,_,"iridescenceThicknessTexture","iridescenceThicknessMap",i),Object.keys(_).length>0&&this.addExtension(i,s,"KHR_materials_iridescence",_)}if(e.useSheen){let _={};if(!e.sheen.equals(F.BLACK)){let{r:S,g,b:T}=e.sheen.clone().linear();_.sheenColorFactor=[S,g,T]}e.sheenGloss!==0&&(_.sheenRoughnessFactor=e.sheenGloss),this.attachTexture(t,e,_,"sheenColorTexture","sheenMap",i),this.attachTexture(t,e,_,"sheenRoughnessTexture","sheenGlossMap",i),Object.keys(_).length>0&&this.addExtension(i,s,"KHR_materials_sheen",_)}if(e.useMetalnessSpecularColor||!e.useMetalness){let _={};if(!e.specular.equals(F.WHITE)){let{r:S,g,b:T}=e.specular.clone().linear();_.specularColorFactor=[S,g,T]}e.specularityFactor!==1&&(_.specularFactor=e.specularityFactor),this.attachTexture(t,e,_,"specularColorTexture","specularMap",i),this.attachTexture(t,e,_,"specularTexture","specularityFactorMap",i),Object.keys(_).length>0&&this.addExtension(i,s,"KHR_materials_specular",_)}if(e.useDynamicRefraction&&(e.refraction!==0||e.refractionMap)){let _={};e.refraction!==0&&(_.transmissionFactor=e.refraction),this.attachTexture(t,e,_,"transmissionTexture","refractionMap",i),Object.keys(_).length>0&&this.addExtension(i,s,"KHR_materials_transmission",_)}if(e.useLighting||this.addExtension(i,s,"KHR_materials_unlit"),e.useDynamicRefraction&&(e.thickness!==0||e.attenuationDistance!==0||!e.attenuation.equals(F.WHITE)||e.thicknessMap)){let _={};if(e.thickness!==0&&(_.thicknessFactor=e.thickness),e.attenuationDistance!==0&&(_.attenuationDistance=e.attenuationDistance),!e.attenuation.equals(F.WHITE)){let{r:S,g,b:T}=e.attenuation.clone().linear();_.attenuationColor=[S,g,T]}this.attachTexture(t,e,_,"thicknessTexture","thicknessMap",i),Object.keys(_).length>0&&this.addExtension(i,s,"KHR_materials_volume",_)}}writeMaterials(t,e){t.materials.length>0&&(e.materials=t.materials.map(s=>{let{name:i,blendType:r,cull:a,alphaTest:o}=s,l={pbrMetallicRoughness:{}};return i&&i.length>0&&(l.name=i),s instanceof it&&this.writeStandardMaterial(t,s,l,e),r===ls?l.alphaMode="BLEND":r===wt&&o!==0&&(l.alphaMode="MASK",l.alphaCutoff=o),a===0&&(l.doubleSided=!0),this.attachTexture(t,s,l,"normalTexture","normalMap",e),this.attachTexture(t,s,l,"occlusionTexture","aoMap",e),this.attachTexture(t,s,l,"emissiveTexture","emissiveMap",e),l}))}writeNodes(t,e){t.entities.length>0&&(e.nodes=t.entities.map(s=>{let i=s.name,r=s.getLocalPosition(),a=s.getLocalRotation(),o=s.getLocalScale(),l={};i&&i.length>0&&(l.name=i),r.equals(x.ZERO)||(l.translation=[r.x,r.y,r.z]),a.equals($.IDENTITY)||(l.rotation=[a.x,a.y,a.z,a.w]),o.equals(x.ONE)||(l.scale=[o.x,o.y,o.z]),s.camera&&s.camera.enabled&&(l.camera=t.cameras.indexOf(s.camera));let h=t.entityMeshInstances.find(f=>f.node===s);if(h){l.mesh=t.entityMeshInstances.indexOf(h);let f=h.meshInstances[0];f&&f.mesh.skin&&(l.skin=t.skins.indexOf(f.mesh.skin))}return s.children.length>0&&(l.children=[],s.children.forEach(f=>{l.children.push(t.entities.indexOf(f))})),l}))}writeMeshes(t,e,s){t.entityMeshInstances.length>0&&(e.accessors=[],e.meshes=[],t.entityMeshInstances.forEach(i=>{let r={primitives:[]};i.meshInstances.forEach(o=>{let l=c.createPrimitive(t,e,o.mesh,s);l.material=t.materials.indexOf(o.material),r.primitives.push(l)}),e.meshes.push(r)}))}static createPrimitive(t,e,s,i={}){let r={attributes:{}},{vertexBuffer:a}=s,{format:o}=a,{interleaved:l,elements:h}=o,f=a.getNumVertices();h.forEach((d,p)=>{let m=C9(d.name);if(i.stripUnusedAttributes){let C=!0;if(m.startsWith("TEXCOORD_")){let v=parseInt(m.split("_")[1],10);C=t.materials.some(E=>PV.some(y=>E[y]?(E[`${y}Uv`]??0)===v:!1))}if(m==="COLOR_0"&&(C=t.materials.some(v=>v.vertexColors)),m==="TANGENT"&&(C=t.materials.some(v=>v.normalMap)),(m==="JOINTS_0"||m==="WEIGHTS_0")&&(C=t.entityMeshInstances.some(v=>v.meshInstances.some(E=>E.mesh.skin))),!C)return}let _=t.bufferViewMap.get(a);_||(c.writeBufferView(t,e,a),t.buffers.push(a),_=t.bufferViewMap.get(a));let g={bufferView:_[l?0:p],byteOffset:l?d.offset:0,componentType:EV(d.dataType),type:A9(d.numComponents),count:f},T=e.accessors.push(g)-1;if(r.attributes[m]=T,d.name===ee){let C=[];s.getPositions(C);let v=new x,E=new x;ge.computeMinMax(C,v,E),g.min=[v.x,v.y,v.z],g.max=[E.x,E.y,E.z]}});let u=s.indexBuffer[0];if(u){let d=t.bufferViewMap.get(u);d||(c.writeBufferView(t,e,u),t.buffers.push(u),d=t.bufferViewMap.get(u));let m={bufferView:d[0],componentType:E9(u.getFormat()),count:u.getNumIndices(),type:"SCALAR"},_=e.accessors.push(m)-1;r.indices=_}return r}writeSkins(t,e){t.skins.length>0&&(e.skins=t.skins.map(s=>{let i=new Float32Array(s.inverseBindPose.length*16);for(let f=0;f{let u=t.entities.find(d=>d.name===f);return t.entities.indexOf(u)});return{inverseBindMatrices:l,joints:h}}))}convertTextures(t,e){let s={maxTextureSize:e.maxTextureSize},i=[];return t.forEach(r=>{let a=this.textureToCanvas(r,s);a.then(o=>new Promise(l=>l(o))),i.push(a)}),i}writeTextures(t,e,s,i){let r=t.textures,a=[];for(let o=0;o{let p=new FileReader;return p.readAsArrayBuffer(d),new Promise(m=>{p.onloadend=()=>{m(p)}})}).then(d=>{let p=this.getPaddedArrayBuffer(d.result);c.writeBufferView(t,s,p),t.buffers.push(p);let m=t.bufferViewMap.get(p);s.images[o]={mimeType:u,bufferView:m[0]},s.samplers[o]={minFilter:AV(l.minFilter),magFilter:AV(l.magFilter),wrapS:CV(l.addressU),wrapT:CV(l.addressV)},s.textures[o]={sampler:o,source:o}}))}return Promise.all(a)}getBlob(t,e){if(t.toBlob!==void 0)return new Promise(i=>{t.toBlob(i,e)});let s=1;return e==="image/jpeg"&&(s=.92),t.convertToBlob({type:e,quality:s})}getPaddedArrayBuffer(t,e=0){let s=R.roundUp(t.byteLength,4);if(s!==t.byteLength){let i=new Uint8Array(s);if(i.set(new Uint8Array(t)),e!==0)for(let r=t.byteLength;r{let r={asset:{version:"2.0",generator:"PlayCanvas GltfExporter"},scenes:[{nodes:[0]}],images:[],samplers:[],textures:[],scene:0};return this.writeBufferViews(t,r),this.writeCameras(t,r),this.writeMeshes(t,r,e),this.writeMaterials(t,r),this.writeNodes(t,r,e),this.writeSkins(t,r),await this.writeTextures(t,i,r,e),r.images.length||delete r.images,r.samplers.length||delete r.samplers,r.textures.length||delete r.textures,r})}build(t,e={}){let s=this.collectResources(t);return this.buildJson(s,e).then(i=>{let a=new TextEncoder().encode(JSON.stringify(i)),o=12,l=8,h=a.length,f=4-(h&3)&3,u=8,d=i.buffers.reduce((g,T)=>R.roundUp(g+T.byteLength,4),0),p=o+l+h+f;d>0&&(p+=u+d);let m=new ArrayBuffer(p),_=new DataView(m);_.setUint32(0,1179937895,!0),_.setUint32(4,2,!0),_.setUint32(8,p,!0),_.setUint32(12,h+f,!0),_.setUint32(16,1313821514,!0);let S=o+l;new Uint8Array(m,S,h).set(a),S+=h;for(let g=0;g0&&(_.setUint32(S,d,!0),_.setUint32(S+4,5130562,!0),S+=u,s.buffers.forEach(g=>{let T,C=s.bufferViewMap.get(g)[0],v=i.bufferViews[C].byteOffset;if(g instanceof ArrayBuffer)T=new Uint8Array(g);else{let y=g.lock();y instanceof ArrayBuffer?T=new Uint8Array(y):T=new Uint8Array(y.buffer,y.byteOffset,y.byteLength)}new Uint8Array(m,S+v,T.byteLength).set(T)})),Promise.resolve(m)})}};var cn="none",zA="lighting",GA="combine";var wV=` uniform sampler2D sourceTexture; uniform vec2 sourceInvResolution; varying vec2 uv0; @@ -17116,7 +17950,7 @@ void main() #endif gl_FragColor = vec4(value, 1.0); } -`,b_=` +`;var IV=` var sourceTexture: texture_2d; var sourceTextureSampler: sampler; uniform sourceInvResolution: vec2f; @@ -17161,7 +17995,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { output.color = vec4f(vec3f(value), 1.0); return output; } -`;class bg extends dH{setSourceTexture(e){this._sourceTexture=e,this.options.resizeSource=e;}execute(){this.sourceTextureId.setValue(this.sourceTexture),this.premultiplyTexture&&this.premultiplyTextureId.setValue(this.premultiplyTexture),this.sourceInvResolutionValue[0]=1/this.sourceTexture.width,this.sourceInvResolutionValue[1]=1/this.sourceTexture.height,this.sourceInvResolutionId.setValue(this.sourceInvResolutionValue),super.execute();}constructor(e,t,i={}){super(e),this.sourceTexture=t,this.premultiplyTexture=i.premultiplyTexture,n$.get(e,tz).set("downsamplePS",bm),n$.get(e,tV).set("downsamplePS",b_);let s=i.boxFilter??false,r=`${s?"Box":""}-${i.premultiplyTexture?"Premultiply":""}-${i.premultiplySrcChannel??""}-${i.removeInvalid?"RemoveInvalid":""}`,a=new Map;s&&a.set("BOXFILTER",""),i.premultiplyTexture&&a.set("PREMULTIPLY",""),i.removeInvalid&&a.set("REMOVE_INVALID",""),a.set("{PREMULTIPLY_SRC_CHANNEL}",i.premultiplySrcChannel??"x"),this.shader=nJ.createShader(e,{uniqueName:`DownSampleShader:${r}`,attributes:{aPosition:e8},vertexChunk:"quadVS",fragmentChunk:"downsamplePS",fragmentDefines:a}),this.sourceTextureId=e.scope.resolve("sourceTexture"),this.premultiplyTextureId=e.scope.resolve("premultiplyTexture"),this.sourceInvResolutionId=e.scope.resolve("sourceInvResolution"),this.sourceInvResolutionValue=new Float32Array(2);}}var bv=` +`;var hn=class extends Ut{constructor(t,e,s={}){super(t),this.sourceTexture=e,this.premultiplyTexture=s.premultiplyTexture,ne.get(t,fe).set("downsamplePS",wV),ne.get(t,se).set("downsamplePS",IV);let i=s.boxFilter??!1,r=`${i?"Box":""}-${s.premultiplyTexture?"Premultiply":""}-${s.premultiplySrcChannel??""}-${s.removeInvalid?"RemoveInvalid":""}`,a=new Map;i&&a.set("BOXFILTER",""),s.premultiplyTexture&&a.set("PREMULTIPLY",""),s.removeInvalid&&a.set("REMOVE_INVALID",""),a.set("{PREMULTIPLY_SRC_CHANNEL}",s.premultiplySrcChannel??"x"),this.shader=Se.createShader(t,{uniqueName:`DownSampleShader:${r}`,attributes:{aPosition:ee},vertexChunk:"quadVS",fragmentChunk:"downsamplePS",fragmentDefines:a}),this.sourceTextureId=t.scope.resolve("sourceTexture"),this.premultiplyTextureId=t.scope.resolve("premultiplyTexture"),this.sourceInvResolutionId=t.scope.resolve("sourceInvResolution"),this.sourceInvResolutionValue=new Float32Array(2)}setSourceTexture(t){this._sourceTexture=t,this.options.resizeSource=t}execute(){this.sourceTextureId.setValue(this.sourceTexture),this.premultiplyTexture&&this.premultiplyTextureId.setValue(this.premultiplyTexture),this.sourceInvResolutionValue[0]=1/this.sourceTexture.width,this.sourceInvResolutionValue[1]=1/this.sourceTexture.height,this.sourceInvResolutionId.setValue(this.sourceInvResolutionValue),super.execute()}};var RV=` uniform sampler2D sourceTexture; uniform vec2 sourceInvResolution; varying vec2 uv0; @@ -17183,7 +18017,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { value += (a + c + g + i) * 0.0625; gl_FragColor = vec4(value, 1.0); } -`,bS=` +`;var bV=` var sourceTexture: texture_2d; var sourceTextureSampler: sampler; uniform sourceInvResolution: vec2f; @@ -17208,7 +18042,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { output.color = vec4f(vec3f(value), 1.0); return output; } -`;class by extends dH{execute(){this.sourceTextureId.setValue(this.sourceTexture),this.sourceInvResolutionValue[0]=1/this.sourceTexture.width,this.sourceInvResolutionValue[1]=1/this.sourceTexture.height,this.sourceInvResolutionId.setValue(this.sourceInvResolutionValue),super.execute();}constructor(e,t){super(e),this.sourceTexture=t,n$.get(e,tz).set("upsamplePS",bv),n$.get(e,tV).set("upsamplePS",bS),this.shader=nJ.createShader(e,{uniqueName:"UpSampleShader",attributes:{aPosition:e8},vertexChunk:"quadVS",fragmentChunk:"upsamplePS"}),this.sourceTextureId=e.scope.resolve("sourceTexture"),this.sourceInvResolutionId=e.scope.resolve("sourceInvResolution"),this.sourceInvResolutionValue=new Float32Array(2);}}class bx extends an{destroy(){this.destroyRenderPasses(),this.destroyRenderTargets();}destroyRenderTargets(e=0){for(let t=e;t=0;s--){let e=new by(t,i),r=this.renderTargets[s];e.init(r),e.blendState=iy.ADDBLEND,this.beforePasses.push(e),i=r.colorBuffer;}}onDisable(){this.renderTargets[0]?.resize(1,1),this.destroyRenderPasses(),this.destroyRenderTargets(1);}frameUpdate(){super.frameUpdate();let e=this.calcMipLevels(this._sourceTexture.width,this._sourceTexture.height,1),t=ei.clamp(e,1,this.blurLevel);this.renderTargets.length!==t&&(this.destroyRenderPasses(),this.destroyRenderTargets(1),this.createRenderTargets(t),this.createRenderPasses(t));}constructor(e,t,i){super(e),this.blurLevel=16,this.renderTargets=[],this._sourceTexture=t,this.textureFormat=i,this.bloomRenderTarget=this.createRenderTarget(0),this.bloomTexture=this.bloomRenderTarget.colorBuffer;}}let bT={composePS:` +`;var ig=class extends Ut{constructor(t,e){super(t),this.sourceTexture=e,ne.get(t,fe).set("upsamplePS",RV),ne.get(t,se).set("upsamplePS",bV),this.shader=Se.createShader(t,{uniqueName:"UpSampleShader",attributes:{aPosition:ee},vertexChunk:"quadVS",fragmentChunk:"upsamplePS"}),this.sourceTextureId=t.scope.resolve("sourceTexture"),this.sourceInvResolutionId=t.scope.resolve("sourceInvResolution"),this.sourceInvResolutionValue=new Float32Array(2)}execute(){this.sourceTextureId.setValue(this.sourceTexture),this.sourceInvResolutionValue[0]=1/this.sourceTexture.width,this.sourceInvResolutionValue[1]=1/this.sourceTexture.height,this.sourceInvResolutionId.setValue(this.sourceInvResolutionValue),super.execute()}};var rg=class extends Nt{constructor(e,s,i){super(e);n(this,"bloomTexture");n(this,"blurLevel",16);n(this,"bloomRenderTarget");n(this,"textureFormat");n(this,"renderTargets",[]);this._sourceTexture=s,this.textureFormat=i,this.bloomRenderTarget=this.createRenderTarget(0),this.bloomTexture=this.bloomRenderTarget.colorBuffer}destroy(){this.destroyRenderPasses(),this.destroyRenderTargets()}destroyRenderTargets(e=0){for(let s=e;s=0;r--){let a=new ig(s,i),o=this.renderTargets[r];a.init(o),a.blendState=Oe.ADDBLEND,this.beforePasses.push(a),i=o.colorBuffer}}onDisable(){this.renderTargets[0]?.resize(1,1),this.destroyRenderPasses(),this.destroyRenderTargets(1)}frameUpdate(){super.frameUpdate();let e=this.calcMipLevels(this._sourceTexture.width,this._sourceTexture.height,1),s=R.clamp(e,1,this.blurLevel);this.renderTargets.length!==s&&(this.destroyRenderPasses(),this.destroyRenderTargets(1),this.createRenderTargets(s),this.createRenderPasses(s))}};var DV=` #include "tonemappingPS" #include "gammaPS" varying vec2 uv0; @@ -17276,7 +18110,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { result = gammaCorrectOutput(result); gl_FragColor = vec4(result, scene.a); } -`,composeBloomPS:` +`;var LV=` #ifdef BLOOM uniform sampler2D bloomTexture; uniform float bloomIntensity; @@ -17288,7 +18122,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return color + dBloom * bloomIntensity; } #endif -`,composeDofPS:` +`;var MV=` #ifdef DOF uniform sampler2D cocTexture; uniform sampler2D blurTexture; @@ -17326,7 +18160,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return mix(color, blur, dCoc.r + dCoc.g); } #endif -`,composeSsaoPS:` +`;var OV=` #ifdef SSAO #define SSAO_TEXTURE #endif @@ -17348,7 +18182,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { #endif } #endif -`,composeGradingPS:` +`;var FV=` #ifdef GRADING uniform vec3 brightnessContrastSaturation; uniform vec3 tint; @@ -17367,7 +18201,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { brightnessContrastSaturation.y); } #endif -`,composeColorEnhancePS:` +`;var NV=` #ifdef COLOR_ENHANCE uniform vec4 colorEnhanceParams; uniform float colorEnhanceMidtones; @@ -17416,7 +18250,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return max(vec3(0.0), color); } #endif -`,composeVignettePS:` +`;var BV=` #ifdef VIGNETTE uniform vec4 vignetterParams; uniform vec3 vignetteColor; @@ -17437,7 +18271,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return mix(vignetteColor, color, calcVignette(uv)); } #endif -`,composeFringingPS:` +`;var UV=` #ifdef FRINGING uniform float fringingIntensity; vec3 applyFringing(vec3 color, vec2 uv) { @@ -17448,7 +18282,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return color; } #endif -`,composeCasPS:` +`;var kV=` #ifdef CAS uniform float sharpness; #ifdef CAS_HDR @@ -17476,31 +18310,49 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return toHDR(res); } #endif -`,composeColorLutPS:` +`;var zV=` #ifdef COLOR_LUT + const float COLOR_LUT_N = 16.0; + const float COLOR_LUT_W = 256.0; + const float COLOR_LUT_MAX = COLOR_LUT_N - 1.0; + const float COLOR_LUT_HALF_PX_X = 0.5 / COLOR_LUT_W; + const float COLOR_LUT_HALF_PX_Y = 0.5 / COLOR_LUT_N; + const float COLOR_LUT_R_SCALE = COLOR_LUT_MAX / COLOR_LUT_W; + const float COLOR_LUT_G_SCALE = COLOR_LUT_MAX / COLOR_LUT_N; + const float COLOR_LUT_SLICE = 1.0 / COLOR_LUT_N; + uniform vec3 colorLUTParams; uniform sampler2D colorLUT; - uniform vec4 colorLUTParams; + #ifdef COLOR_LUT2 + uniform sampler2D colorLUT2; + #endif + vec3 sampleColorLUT(sampler2D lut, vec2 uv_l, vec2 uv_h, float t) { + vec3 color_l = texture2DLod(lut, uv_l, 0.0).rgb; + vec3 color_h = texture2DLod(lut, uv_h, 0.0).rgb; + return mix(color_l, color_h, t); + } vec3 applyColorLUT(vec3 color) { - vec3 c = clamp(color, 0.0, 1.0); - float width = colorLUTParams.x; - float height = colorLUTParams.y; - float maxColor = colorLUTParams.z; - float cell = c.b * maxColor; + vec3 srgbCoord = pow(max(color, vec3(0.0)) + 0.0000001, vec3(1.0 / 2.2)); + vec3 c = clamp(srgbCoord, 0.0, 1.0); + float cell = c.b * COLOR_LUT_MAX; float cell_l = floor(cell); float cell_h = ceil(cell); - float half_px_x = 0.5 / width; - float half_px_y = 0.5 / height; - float r_offset = half_px_x + c.r / height * (maxColor / height); - float g_offset = half_px_y + c.g * (maxColor / height); - vec2 uv_l = vec2(cell_l / height + r_offset, g_offset); - vec2 uv_h = vec2(cell_h / height + r_offset, g_offset); - vec3 color_l = texture2DLod(colorLUT, uv_l, 0.0).rgb; - vec3 color_h = texture2DLod(colorLUT, uv_h, 0.0).rgb; - vec3 lutColor = mix(color_l, color_h, fract(cell)); - return mix(color, lutColor, colorLUTParams.w); + float t = fract(cell); + float r_offset = COLOR_LUT_HALF_PX_X + c.r * COLOR_LUT_R_SCALE; + float g_offset = COLOR_LUT_HALF_PX_Y + c.g * COLOR_LUT_G_SCALE; + vec2 uv_l = vec2(cell_l * COLOR_LUT_SLICE + r_offset, g_offset); + vec2 uv_h = vec2(cell_h * COLOR_LUT_SLICE + r_offset, g_offset); + vec3 lut1 = sampleColorLUT(colorLUT, uv_l, uv_h, t); + #ifdef COLOR_LUT2 + vec3 lut2 = sampleColorLUT(colorLUT2, uv_l, uv_h, t); + float w1 = colorLUTParams.x * (1.0 - colorLUTParams.z); + float w2 = colorLUTParams.y * colorLUTParams.z; + return color + (lut1 - color) * w1 + (lut2 - color) * w2; + #else + return mix(color, lut1, colorLUTParams.x); + #endif } #endif -`,composeDeclarationsPS:"",composeMainStartPS:"",composeMainEndPS:""},bE={composePS:` +`;var GV={composePS:DV,composeBloomPS:LV,composeDofPS:MV,composeSsaoPS:OV,composeGradingPS:FV,composeColorEnhancePS:NV,composeVignettePS:BV,composeFringingPS:UV,composeCasPS:kV,composeColorLutPS:zV,composeDeclarationsPS:"",composeMainStartPS:"",composeMainEndPS:""};var VV=` #include "tonemappingPS" #include "gammaPS" varying uv0: vec2f; @@ -17572,7 +18424,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { output.color = vec4f(result, scene.a); return output; } -`,composeBloomPS:` +`;var HV=` #ifdef BLOOM var bloomTexture: texture_2d; var bloomTextureSampler: sampler; @@ -17585,7 +18437,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return color + dBloom * uniform.bloomIntensity; } #endif -`,composeDofPS:` +`;var WV=` #ifdef DOF var cocTexture: texture_2d; var cocTextureSampler: sampler; @@ -17625,7 +18477,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return mix(color, blur, dCoc.r + dCoc.g); } #endif -`,composeSsaoPS:` +`;var XV=` #ifdef SSAO #define SSAO_TEXTURE #endif @@ -17648,7 +18500,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { #endif } #endif -`,composeGradingPS:` +`;var YV=` #ifdef GRADING uniform brightnessContrastSaturation: vec3f; uniform tint: vec3f; @@ -17667,7 +18519,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { uniform.brightnessContrastSaturation.y); } #endif -`,composeColorEnhancePS:` +`;var KV=` #ifdef COLOR_ENHANCE uniform colorEnhanceParams: vec4f; uniform colorEnhanceMidtones: f32; @@ -17717,7 +18569,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return max(vec3f(0.0), colorOut); } #endif -`,composeVignettePS:` +`;var jV=` #ifdef VIGNETTE uniform vignetterParams: vec4f; uniform vignetteColor: vec3f; @@ -17738,7 +18590,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return mix(uniform.vignetteColor, color, calcVignette(uv)); } #endif -`,composeFringingPS:` +`;var qV=` #ifdef FRINGING uniform fringingIntensity: f32; fn applyFringing(color: vec3f, uv: vec2f) -> vec3f { @@ -17750,7 +18602,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return colorOut; } #endif -`,composeCasPS:` +`;var $V=` #ifdef CAS uniform sharpness: f32; #ifdef CAS_HDR @@ -17778,32 +18630,51 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { return toHDR(vec3f(res)); } #endif -`,composeColorLutPS:` +`;var ZV=` #ifdef COLOR_LUT + const COLOR_LUT_N: f32 = 16.0; + const COLOR_LUT_W: f32 = 256.0; + const COLOR_LUT_MAX: f32 = COLOR_LUT_N - 1.0; + const COLOR_LUT_HALF_PX_X: f32 = 0.5 / COLOR_LUT_W; + const COLOR_LUT_HALF_PX_Y: f32 = 0.5 / COLOR_LUT_N; + const COLOR_LUT_R_SCALE: f32 = COLOR_LUT_MAX / COLOR_LUT_W; + const COLOR_LUT_G_SCALE: f32 = COLOR_LUT_MAX / COLOR_LUT_N; + const COLOR_LUT_SLICE: f32 = 1.0 / COLOR_LUT_N; + uniform colorLUTParams: vec3f; var colorLUT: texture_2d; var colorLUTSampler: sampler; - uniform colorLUTParams: vec4f; + #ifdef COLOR_LUT2 + var colorLUT2: texture_2d; + var colorLUT2Sampler: sampler; + #endif + fn sampleColorLUT(lut: texture_2d, lutSampler: sampler, uv_l: vec2f, uv_h: vec2f, t: f32) -> vec3f { + let color_l: vec3f = textureSampleLevel(lut, lutSampler, uv_l, 0.0).rgb; + let color_h: vec3f = textureSampleLevel(lut, lutSampler, uv_h, 0.0).rgb; + return mix(color_l, color_h, vec3f(t)); + } fn applyColorLUT(color: vec3f) -> vec3f { - var c: vec3f = clamp(color, vec3f(0.0), vec3f(1.0)); - let width: f32 = uniform.colorLUTParams.x; - let height: f32 = uniform.colorLUTParams.y; - let maxColor: f32 = uniform.colorLUTParams.z; - let cell: f32 = c.b * maxColor; + let srgbCoord: vec3f = pow(max(color, vec3f(0.0)) + vec3f(0.0000001), vec3f(1.0 / 2.2)); + let c: vec3f = clamp(srgbCoord, vec3f(0.0), vec3f(1.0)); + let cell: f32 = c.b * COLOR_LUT_MAX; let cell_l: f32 = floor(cell); let cell_h: f32 = ceil(cell); - let half_px_x: f32 = 0.5 / width; - let half_px_y: f32 = 0.5 / height; - let r_offset: f32 = half_px_x + c.r / height * (maxColor / height); - let g_offset: f32 = half_px_y + c.g * (maxColor / height); - let uv_l: vec2f = vec2f(cell_l / height + r_offset, g_offset); - let uv_h: vec2f = vec2f(cell_h / height + r_offset, g_offset); - let color_l: vec3f = textureSampleLevel(colorLUT, colorLUTSampler, uv_l, 0.0).rgb; - let color_h: vec3f = textureSampleLevel(colorLUT, colorLUTSampler, uv_h, 0.0).rgb; - let lutColor: vec3f = mix(color_l, color_h, fract(cell)); - return mix(color, lutColor, uniform.colorLUTParams.w); + let t: f32 = fract(cell); + let r_offset: f32 = COLOR_LUT_HALF_PX_X + c.r * COLOR_LUT_R_SCALE; + let g_offset: f32 = COLOR_LUT_HALF_PX_Y + c.g * COLOR_LUT_G_SCALE; + let uv_l: vec2f = vec2f(cell_l * COLOR_LUT_SLICE + r_offset, g_offset); + let uv_h: vec2f = vec2f(cell_h * COLOR_LUT_SLICE + r_offset, g_offset); + let lut1: vec3f = sampleColorLUT(colorLUT, colorLUTSampler, uv_l, uv_h, t); + #ifdef COLOR_LUT2 + let lut2: vec3f = sampleColorLUT(colorLUT2, colorLUT2Sampler, uv_l, uv_h, t); + let w1: f32 = uniform.colorLUTParams.x * (1.0 - uniform.colorLUTParams.z); + let w2: f32 = uniform.colorLUTParams.y * uniform.colorLUTParams.z; + return color + (lut1 - color) * w1 + (lut2 - color) * w2; + #else + return mix(color, lut1, vec3f(uniform.colorLUTParams.x)); + #endif } #endif -`,composeDeclarationsPS:"",composeMainStartPS:"",composeMainEndPS:""};class bw extends dH{set debug(e){this._debug!==e&&(this._debug=e,this._shaderDirty=true);}get debug(){return this._debug}set colorLUT(e){this._colorLUT!==e&&(this._colorLUT=e,this._shaderDirty=true);}get colorLUT(){return this._colorLUT}set bloomTexture(e){this._bloomTexture!==e&&(this._bloomTexture=e,this._shaderDirty=true);}get bloomTexture(){return this._bloomTexture}set cocTexture(e){this._cocTexture!==e&&(this._cocTexture=e,this._shaderDirty=true);}get cocTexture(){return this._cocTexture}set ssaoTexture(e){this._ssaoTexture!==e&&(this._ssaoTexture=e,this._shaderDirty=true);}get ssaoTexture(){return this._ssaoTexture}set taaEnabled(e){this._taaEnabled!==e&&(this._taaEnabled=e,this._shaderDirty=true);}get taaEnabled(){return this._taaEnabled}set gradingEnabled(e){this._gradingEnabled!==e&&(this._gradingEnabled=e,this._shaderDirty=true);}get gradingEnabled(){return this._gradingEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._shaderDirty=true);}get vignetteEnabled(){return this._vignetteEnabled}set fringingEnabled(e){this._fringingEnabled!==e&&(this._fringingEnabled=e,this._shaderDirty=true);}get fringingEnabled(){return this._fringingEnabled}set colorEnhanceEnabled(e){this._colorEnhanceEnabled!==e&&(this._colorEnhanceEnabled=e,this._shaderDirty=true);}get colorEnhanceEnabled(){return this._colorEnhanceEnabled}set toneMapping(e){this._toneMapping!==e&&(this._toneMapping=e,this._shaderDirty=true);}get toneMapping(){return this._toneMapping}set sharpness(e){this._sharpness!==e&&(this._sharpness=e,this._shaderDirty=true);}get sharpness(){return this._sharpness}get isSharpnessEnabled(){return this._sharpness>0}set hdrScene(e){this._hdrScene!==e&&(this._hdrScene=e,this._shaderDirty=true);}get hdrScene(){return this._hdrScene}postInit(){this.setClearColor(es.BLACK),this.setClearDepth(1),this.setClearStencil(0);}frameUpdate(){let e=+!(this.renderTarget??this.device.backBuffer).isColorBufferSrgb(0);this._gammaCorrection!==e&&(this._gammaCorrection=e,this._shaderDirty=true);let t=n$.get(this.device,this.device.isWebGPU?tV:tz);for(let[e,i]of this._customComposeChunks.entries()){let s=t.get(e);s!==i&&(this._customComposeChunks.set(e,s),this._shaderDirty=true);}if(this._shaderDirty){this._shaderDirty=false;let e=nd[this._gammaCorrection],t=this._customComposeChunks,i=iL(t.get("composeDeclarationsPS")??""),s=iL(t.get("composeMainStartPS")??""),r=iL(t.get("composeMainEndPS")??""),a=`${this.toneMapping}-${e}-${this.bloomTexture?"bloom":"nobloom"}-${this.cocTexture?"dof":"nodof"}-${this.blurTextureUpscale?"dofupscale":""}-${this.ssaoTexture?"ssao":"nossao"}-${this.gradingEnabled?"grading":"nograding"}-${this.colorEnhanceEnabled?"colorenhance":"nocolorenhance"}-${this.colorLUT?"colorlut":"nocolorlut"}-${this.vignetteEnabled?"vignette":"novignette"}-${this.fringingEnabled?"fringing":"nofringing"}-${this.taaEnabled?"taa":"notaa"}-${this.isSharpnessEnabled?this._hdrScene?"cashdr":"cas":"nocas"}-${this._debug??""}-decl${i}-start${s}-end${r}`;if(this._key!==a){this._key=a;let t=new Map;t.set("TONEMAP",nu[this.toneMapping]),t.set("GAMMA",e),this.bloomTexture&&t.set("BLOOM",true),this.cocTexture&&t.set("DOF",true),this.blurTextureUpscale&&t.set("DOF_UPSCALE",true),this.ssaoTexture&&t.set("SSAO",true),this.gradingEnabled&&t.set("GRADING",true),this.colorEnhanceEnabled&&t.set("COLOR_ENHANCE",true),this.colorLUT&&t.set("COLOR_LUT",true),this.vignetteEnabled&&t.set("VIGNETTE",true),this.fringingEnabled&&t.set("FRINGING",true),this.taaEnabled&&t.set("TAA",true),this.isSharpnessEnabled&&(t.set("CAS",true),this._hdrScene&&t.set("CAS_HDR",true)),this._debug&&t.set("DEBUG_COMPOSE",this._debug),this.shader=nJ.createShader(this.device,{uniqueName:`ComposeShader-${a}`,attributes:{aPosition:e8},vertexChunk:"quadVS",fragmentChunk:"composePS",fragmentDefines:t});}}}execute(){let e=this.sceneTexture;this.sceneTextureId.setValue(e),this.sceneTextureInvResValue[0]=1/e.width,this.sceneTextureInvResValue[1]=1/e.height,this.sceneTextureInvResId.setValue(this.sceneTextureInvResValue),this._bloomTexture&&(this.bloomTextureId.setValue(this._bloomTexture),this.bloomIntensityId.setValue(this.bloomIntensity)),this._cocTexture&&(this.cocTextureId.setValue(this._cocTexture),this.blurTextureId.setValue(this.blurTexture)),this._ssaoTexture&&this.ssaoTextureId.setValue(this._ssaoTexture),this._gradingEnabled&&(this.bcsId.setValue([this.gradingBrightness,this.gradingContrast,this.gradingSaturation]),this.tintId.setValue([this.gradingTint.r,this.gradingTint.g,this.gradingTint.b])),this._colorEnhanceEnabled&&(this.colorEnhanceParamsId.setValue([this.colorEnhanceShadows,this.colorEnhanceHighlights,this.colorEnhanceVibrance,this.colorEnhanceDehaze]),this.colorEnhanceMidtonesId.setValue(this.colorEnhanceMidtones));let t=this._colorLUT;t&&(this.colorLUTParams[0]=t.width,this.colorLUTParams[1]=t.height,this.colorLUTParams[2]=t.height-1,this.colorLUTParams[3]=this.colorLUTIntensity,this.colorLUTParamsId.setValue(this.colorLUTParams),this.colorLUTId.setValue(t)),this._vignetteEnabled&&(this.vignetterParamsId.setValue([this.vignetteInner,this.vignetteOuter,this.vignetteCurvature,this.vignetteIntensity]),this.vignetteColorId.setValue([this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b])),this._fringingEnabled&&this.fringingIntensityId.setValue(this.fringingIntensity/1024),this.isSharpnessEnabled&&this.sharpnessId.setValue(ei.lerp(-0.125,-0.2,this.sharpness)),super.execute();}constructor(e){super(e),this.sceneTexture=null,this.bloomIntensity=.01,this._bloomTexture=null,this._cocTexture=null,this.blurTexture=null,this.blurTextureUpscale=false,this._ssaoTexture=null,this._toneMapping=0,this._gradingEnabled=false,this.gradingSaturation=1,this.gradingContrast=1,this.gradingBrightness=1,this.gradingTint=new es(1,1,1,1),this._shaderDirty=true,this._vignetteEnabled=false,this.vignetteInner=.5,this.vignetteOuter=1,this.vignetteCurvature=.5,this.vignetteIntensity=.3,this.vignetteColor=new es(0,0,0),this._fringingEnabled=false,this.fringingIntensity=10,this._colorEnhanceEnabled=false,this.colorEnhanceShadows=0,this.colorEnhanceHighlights=0,this.colorEnhanceVibrance=0,this.colorEnhanceDehaze=0,this.colorEnhanceMidtones=0,this._taaEnabled=false,this._hdrScene=true,this._sharpness=.5,this._gammaCorrection=1,this._colorLUT=null,this.colorLUTIntensity=1,this._key="",this._debug=null,this._customComposeChunks=new Map([["composeDeclarationsPS",""],["composeMainStartPS",""],["composeMainEndPS",""]]),n$.get(e,tz).add(bT,false),n$.get(e,tV).add(bE,false);let{scope:t}=e;this.sceneTextureId=t.resolve("sceneTexture"),this.bloomTextureId=t.resolve("bloomTexture"),this.cocTextureId=t.resolve("cocTexture"),this.ssaoTextureId=t.resolve("ssaoTexture"),this.blurTextureId=t.resolve("blurTexture"),this.bloomIntensityId=t.resolve("bloomIntensity"),this.bcsId=t.resolve("brightnessContrastSaturation"),this.tintId=t.resolve("tint"),this.vignetterParamsId=t.resolve("vignetterParams"),this.vignetteColorId=t.resolve("vignetteColor"),this.fringingIntensityId=t.resolve("fringingIntensity"),this.sceneTextureInvResId=t.resolve("sceneTextureInvRes"),this.sceneTextureInvResValue=new Float32Array(2),this.sharpnessId=t.resolve("sharpness"),this.colorLUTId=t.resolve("colorLUT"),this.colorLUTParams=new Float32Array(4),this.colorLUTParamsId=t.resolve("colorLUTParams"),this.colorEnhanceParamsId=t.resolve("colorEnhanceParams"),this.colorEnhanceMidtonesId=t.resolve("colorEnhanceMidtones");}}var bb=` +`;var QV={composePS:VV,composeBloomPS:HV,composeDofPS:WV,composeSsaoPS:XV,composeGradingPS:YV,composeColorEnhancePS:KV,composeVignettePS:jV,composeFringingPS:qV,composeCasPS:$V,composeColorLutPS:ZV,composeDeclarationsPS:"",composeMainStartPS:"",composeMainEndPS:""};var ag=class extends Ut{constructor(e){super(e);n(this,"sceneTexture",null);n(this,"bloomIntensity",.01);n(this,"_bloomTexture",null);n(this,"_cocTexture",null);n(this,"blurTexture",null);n(this,"blurTextureUpscale",!1);n(this,"_ssaoTexture",null);n(this,"_toneMapping",Qn);n(this,"_gradingEnabled",!1);n(this,"gradingSaturation",1);n(this,"gradingContrast",1);n(this,"gradingBrightness",1);n(this,"gradingTint",new F(1,1,1,1));n(this,"_shaderDirty",!0);n(this,"_vignetteEnabled",!1);n(this,"vignetteInner",.5);n(this,"vignetteOuter",1);n(this,"vignetteCurvature",.5);n(this,"vignetteIntensity",.3);n(this,"vignetteColor",new F(0,0,0));n(this,"_fringingEnabled",!1);n(this,"fringingIntensity",10);n(this,"_colorEnhanceEnabled",!1);n(this,"colorEnhanceShadows",0);n(this,"colorEnhanceHighlights",0);n(this,"colorEnhanceVibrance",0);n(this,"colorEnhanceDehaze",0);n(this,"colorEnhanceMidtones",0);n(this,"_taaEnabled",!1);n(this,"_hdrScene",!0);n(this,"_sharpness",.5);n(this,"_gammaCorrection",No);n(this,"_colorLUT",null);n(this,"_colorLUT2",null);n(this,"colorLUTIntensity",1);n(this,"colorLUT2Intensity",1);n(this,"colorLUTBlend",0);n(this,"_key","");n(this,"_debug",null);n(this,"_customComposeChunks",new Map([["composeDeclarationsPS",""],["composeMainStartPS",""],["composeMainEndPS",""]]));ne.get(e,fe).add(GV,!1),ne.get(e,se).add(QV,!1);let{scope:s}=e;this.sceneTextureId=s.resolve("sceneTexture"),this.bloomTextureId=s.resolve("bloomTexture"),this.cocTextureId=s.resolve("cocTexture"),this.ssaoTextureId=s.resolve("ssaoTexture"),this.blurTextureId=s.resolve("blurTexture"),this.bloomIntensityId=s.resolve("bloomIntensity"),this.bcsId=s.resolve("brightnessContrastSaturation"),this.tintId=s.resolve("tint"),this.vignetterParamsId=s.resolve("vignetterParams"),this.vignetteColorId=s.resolve("vignetteColor"),this.fringingIntensityId=s.resolve("fringingIntensity"),this.sceneTextureInvResId=s.resolve("sceneTextureInvRes"),this.sceneTextureInvResValue=new Float32Array(2),this.sharpnessId=s.resolve("sharpness"),this.colorLUTId=s.resolve("colorLUT"),this.colorLUT2Id=s.resolve("colorLUT2"),this.colorLUTParams=new Float32Array(3),this.colorLUTParamsId=s.resolve("colorLUTParams"),this.colorEnhanceParamsId=s.resolve("colorEnhanceParams"),this.colorEnhanceMidtonesId=s.resolve("colorEnhanceMidtones")}set debug(e){this._debug!==e&&(this._debug=e,this._shaderDirty=!0)}get debug(){return this._debug}set colorLUT(e){this._colorLUT!==e&&(this._colorLUT=e,this._shaderDirty=!0,this._validateColorLUT(e,"colorLUT"))}get colorLUT(){return this._colorLUT}set colorLUT2(e){this._colorLUT2!==e&&(this._colorLUT2=e,this._shaderDirty=!0,this._validateColorLUT(e,"colorLUT2"))}get colorLUT2(){return this._colorLUT2}_validateColorLUT(e,s){}set bloomTexture(e){this._bloomTexture!==e&&(this._bloomTexture=e,this._shaderDirty=!0)}get bloomTexture(){return this._bloomTexture}set cocTexture(e){this._cocTexture!==e&&(this._cocTexture=e,this._shaderDirty=!0)}get cocTexture(){return this._cocTexture}set ssaoTexture(e){this._ssaoTexture!==e&&(this._ssaoTexture=e,this._shaderDirty=!0)}get ssaoTexture(){return this._ssaoTexture}set taaEnabled(e){this._taaEnabled!==e&&(this._taaEnabled=e,this._shaderDirty=!0)}get taaEnabled(){return this._taaEnabled}set gradingEnabled(e){this._gradingEnabled!==e&&(this._gradingEnabled=e,this._shaderDirty=!0)}get gradingEnabled(){return this._gradingEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._shaderDirty=!0)}get vignetteEnabled(){return this._vignetteEnabled}set fringingEnabled(e){this._fringingEnabled!==e&&(this._fringingEnabled=e,this._shaderDirty=!0)}get fringingEnabled(){return this._fringingEnabled}set colorEnhanceEnabled(e){this._colorEnhanceEnabled!==e&&(this._colorEnhanceEnabled=e,this._shaderDirty=!0)}get colorEnhanceEnabled(){return this._colorEnhanceEnabled}set toneMapping(e){this._toneMapping!==e&&(this._toneMapping=e,this._shaderDirty=!0)}get toneMapping(){return this._toneMapping}set sharpness(e){this._sharpness!==e&&(this._sharpness=e,this._shaderDirty=!0)}get sharpness(){return this._sharpness}get isSharpnessEnabled(){return this._sharpness>0}set hdrScene(e){this._hdrScene!==e&&(this._hdrScene=e,this._shaderDirty=!0)}get hdrScene(){return this._hdrScene}postInit(){this.setClearColor(F.BLACK),this.setClearDepth(1),this.setClearStencil(0)}frameUpdate(){let i=(this.renderTarget??this.device.backBuffer).isColorBufferSrgb(0)?Zi:No;this._gammaCorrection!==i&&(this._gammaCorrection=i,this._shaderDirty=!0);let r=ne.get(this.device,this.device.isWebGPU?se:fe);for(let[a,o]of this._customComposeChunks.entries()){let l=r.get(a);l!==o&&(this._customComposeChunks.set(a,l),this._shaderDirty=!0)}if(this._shaderDirty){this._shaderDirty=!1;let a=qg[this._gammaCorrection],o=this._customComposeChunks,l=xt(o.get("composeDeclarationsPS")??""),h=xt(o.get("composeMainStartPS")??""),f=xt(o.get("composeMainEndPS")??""),u=`${this.toneMapping}-${a}-${this.bloomTexture?"bloom":"nobloom"}-${this.cocTexture?"dof":"nodof"}-${this.blurTextureUpscale?"dofupscale":""}-${this.ssaoTexture?"ssao":"nossao"}-${this.gradingEnabled?"grading":"nograding"}-${this.colorEnhanceEnabled?"colorenhance":"nocolorenhance"}-${this.colorLUT?"colorlut":"nocolorlut"}-${this.colorLUT2?"colorlut2":"nocolorlut2"}-${this.vignetteEnabled?"vignette":"novignette"}-${this.fringingEnabled?"fringing":"nofringing"}-${this.taaEnabled?"taa":"notaa"}-${this.isSharpnessEnabled?this._hdrScene?"cashdr":"cas":"nocas"}-${this._debug??""}-decl${l}-start${h}-end${f}`;if(this._key!==u){this._key=u;let d=new Map;d.set("TONEMAP",bf[this.toneMapping]),d.set("GAMMA",a),this.bloomTexture&&d.set("BLOOM",!0),this.cocTexture&&d.set("DOF",!0),this.blurTextureUpscale&&d.set("DOF_UPSCALE",!0),this.ssaoTexture&&d.set("SSAO",!0),this.gradingEnabled&&d.set("GRADING",!0),this.colorEnhanceEnabled&&d.set("COLOR_ENHANCE",!0),this.colorLUT&&d.set("COLOR_LUT",!0),this.colorLUT&&this.colorLUT2&&d.set("COLOR_LUT2",!0),this.vignetteEnabled&&d.set("VIGNETTE",!0),this.fringingEnabled&&d.set("FRINGING",!0),this.taaEnabled&&d.set("TAA",!0),this.isSharpnessEnabled&&(d.set("CAS",!0),this._hdrScene&&d.set("CAS_HDR",!0)),this._debug&&d.set("DEBUG_COMPOSE",this._debug),this.shader=Se.createShader(this.device,{uniqueName:`ComposeShader-${u}`,attributes:{aPosition:ee},vertexChunk:"quadVS",fragmentChunk:"composePS",fragmentDefines:d})}}}execute(){let e=this.sceneTexture;this.sceneTextureId.setValue(e),this.sceneTextureInvResValue[0]=1/e.width,this.sceneTextureInvResValue[1]=1/e.height,this.sceneTextureInvResId.setValue(this.sceneTextureInvResValue),this._bloomTexture&&(this.bloomTextureId.setValue(this._bloomTexture),this.bloomIntensityId.setValue(this.bloomIntensity)),this._cocTexture&&(this.cocTextureId.setValue(this._cocTexture),this.blurTextureId.setValue(this.blurTexture)),this._ssaoTexture&&this.ssaoTextureId.setValue(this._ssaoTexture),this._gradingEnabled&&(this.bcsId.setValue([this.gradingBrightness,this.gradingContrast,this.gradingSaturation]),this.tintId.setValue([this.gradingTint.r,this.gradingTint.g,this.gradingTint.b])),this._colorEnhanceEnabled&&(this.colorEnhanceParamsId.setValue([this.colorEnhanceShadows,this.colorEnhanceHighlights,this.colorEnhanceVibrance,this.colorEnhanceDehaze]),this.colorEnhanceMidtonesId.setValue(this.colorEnhanceMidtones));let s=this._colorLUT;s&&(this.colorLUTParams[0]=this.colorLUTIntensity,this.colorLUTParams[1]=this.colorLUT2Intensity,this.colorLUTParams[2]=this.colorLUTBlend,this.colorLUTParamsId.setValue(this.colorLUTParams),this.colorLUTId.setValue(s),this._colorLUT2&&this.colorLUT2Id.setValue(this._colorLUT2)),this._vignetteEnabled&&(this.vignetterParamsId.setValue([this.vignetteInner,this.vignetteOuter,this.vignetteCurvature,this.vignetteIntensity]),this.vignetteColorId.setValue([this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b])),this._fringingEnabled&&this.fringingIntensityId.setValue(this.fringingIntensity/1024),this.isSharpnessEnabled&&this.sharpnessId.setValue(R.lerp(-.125,-.2,this.sharpness)),super.execute()}};var JV=` vec4 SampleTextureCatmullRom(TEXTURE_ACCEPT(tex), vec2 uv, vec2 texSize) { vec2 samplePos = uv * texSize; vec2 texPos1 = floor(samplePos - 0.5) + 0.5; @@ -17829,7 +18700,7 @@ vec4 SampleTextureCatmullRom(TEXTURE_ACCEPT(tex), vec2 uv, vec2 texSize) { result += texture2DLod(tex, vec2(texPos3.x, texPos3.y), 0.0) * w3.x * w3.y; return result; } -`,bC=` +`;var eH=` fn SampleTextureCatmullRom(tex: texture_2d, texSampler: sampler, uv: vec2f, texSize: vec2f) -> vec4f { let samplePos: vec2f = uv * texSize; let texPos1: vec2f = floor(samplePos - 0.5) + 0.5; @@ -17855,7 +18726,7 @@ fn SampleTextureCatmullRom(tex: texture_2d, texSampler: sampler, uv: vec2f, result = result + textureSampleLevel(tex, texSampler, vec2f(texPos3.x, texPos3.y), 0.0) * w3.x * w3.y; return result; } -`,bA=` +`;var tH=` #include "sampleCatmullRomPS" #include "screenDepthPS" uniform sampler2D sourceTexture; @@ -17874,18 +18745,18 @@ fn SampleTextureCatmullRom(tex: texture_2d, texSampler: sampler, uv: vec2f, vec4 screenPrevious = matrix_viewProjectionPrevious * worldPosition; return (screenPrevious.xy / screenPrevious.w) * 0.5 + 0.5; } - vec4 colorClamp(vec2 uv, vec4 historyColor) { - vec3 minColor = vec3(9999.0); - vec3 maxColor = vec3(-9999.0); + vec3 colorClampPremul(vec2 uv, vec3 historyPremul) { + vec3 minPremul = vec3(9999.0); + vec3 maxPremul = vec3(-9999.0); for(float x = -1.0; x <= 1.0; ++x) { for(float y = -1.0; y <= 1.0; ++y) { - vec3 color = texture2D(sourceTexture, uv + vec2(x, y) / textureSize).rgb; - minColor = min(minColor, color); - maxColor = max(maxColor, color); + vec4 s = texture2D(sourceTexture, uv + vec2(x, y) / textureSize); + vec3 premul = s.rgb * s.a; + minPremul = min(minPremul, premul); + maxPremul = max(maxPremul, premul); } } - vec3 clamped = clamp(historyColor.rgb, minColor, maxColor); - return vec4(clamped, historyColor.a); + return clamp(historyPremul, minPremul, maxPremul); } void main() { @@ -17894,16 +18765,22 @@ fn SampleTextureCatmullRom(tex: texture_2d, texSampler: sampler, uv: vec2f, float depth = delinearizeDepth(linearDepth); vec2 historyUv = reproject(uv0, depth); #ifdef QUALITY_HIGH - vec4 historyColor = SampleTextureCatmullRom(TEXTURE_PASS(historyTexture), historyUv, textureSize); + vec4 historySample = SampleTextureCatmullRom(TEXTURE_PASS(historyTexture), historyUv, textureSize); #else - vec4 historyColor = texture2D(historyTexture, historyUv); + vec4 historySample = texture2D(historyTexture, historyUv); #endif - vec4 historyColorClamped = colorClamp(uv0, historyColor); + vec3 historyPremul = historySample.rgb * historySample.a; + vec3 srcPremul = srcColor.rgb * srcColor.a; + vec3 historyPremulClamped = colorClampPremul(uv0, historyPremul); float mixFactor = (historyUv.x < 0.0 || historyUv.x > 1.0 || historyUv.y < 0.0 || historyUv.y > 1.0) ? 1.0 : 0.05; - gl_FragColor = mix(historyColorClamped, srcColor, mixFactor); + vec3 mixedPremul = mix(historyPremulClamped, srcPremul, mixFactor); + float a = srcColor.a; + const float UNPREMUL_EPS = 1.0 / 255.0; + vec3 rgbStraight = (a > UNPREMUL_EPS) ? (mixedPremul / a) : srcColor.rgb; + gl_FragColor = vec4(rgbStraight, a); } -`,bP=` +`;var sH=` #include "sampleCatmullRomPS" #include "screenDepthPS" var sourceTexture: texture_2d; @@ -17926,18 +18803,18 @@ fn SampleTextureCatmullRom(tex: texture_2d, texSampler: sampler, uv: vec2f, result.y = 1.0 - result.y; return result; } - fn colorClamp(uv: vec2f, historyColor: vec4f) -> vec4f { - var minColor = vec3f(9999.0); - var maxColor = vec3f(-9999.0); + fn colorClampPremul(uv: vec2f, historyPremul: vec3f) -> vec3f { + var minPremul = vec3f(9999.0); + var maxPremul = vec3f(-9999.0); for (var ix: i32 = -1; ix <= 1; ix = ix + 1) { for (var iy: i32 = -1; iy <= 1; iy = iy + 1) { - let color_sample = textureSample(sourceTexture, sourceTextureSampler, uv + vec2f(f32(ix), f32(iy)) / uniform.textureSize).rgb; - minColor = min(minColor, color_sample); - maxColor = max(maxColor, color_sample); + let s = textureSample(sourceTexture, sourceTextureSampler, uv + vec2f(f32(ix), f32(iy)) / uniform.textureSize); + let premul = s.rgb * s.a; + minPremul = min(minPremul, premul); + maxPremul = max(maxPremul, premul); } } - let clamped = clamp(historyColor.rgb, minColor, maxColor); - return vec4f(clamped, historyColor.a); + return clamp(historyPremul, minPremul, maxPremul); } @fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput { @@ -17947,17 +18824,23 @@ fn SampleTextureCatmullRom(tex: texture_2d, texSampler: sampler, uv: vec2f, let depth = delinearizeDepth(linearDepth); let historyUv = reproject(uv0, depth); #ifdef QUALITY_HIGH - var historyColor: vec4f = SampleTextureCatmullRom(historyTexture, historyTextureSampler, historyUv, uniform.textureSize); + var historySample: vec4f = SampleTextureCatmullRom(historyTexture, historyTextureSampler, historyUv, uniform.textureSize); #else - var historyColor: vec4f = textureSample(historyTexture, historyTextureSampler, historyUv); + var historySample: vec4f = textureSample(historyTexture, historyTextureSampler, historyUv); #endif - let historyColorClamped = colorClamp(uv0, historyColor); + let historyPremul = historySample.rgb * historySample.a; + let srcPremul = srcColor.rgb * srcColor.a; + let historyPremulClamped = colorClampPremul(uv0, historyPremul); let mixFactor_condition = historyUv.x < 0.0 || historyUv.x > 1.0 || historyUv.y < 0.0 || historyUv.y > 1.0; let mixFactor = select(0.05, 1.0, mixFactor_condition); - output.color = mix(historyColorClamped, srcColor, mixFactor); + let mixedPremul = mix(historyPremulClamped, srcPremul, mixFactor); + let a = srcColor.a; + let UNPREMUL_EPS = 1.0 / 255.0; + let rgbStraight = select(srcColor.rgb, mixedPremul / a, a > UNPREMUL_EPS); + output.color = vec4f(rgbStraight, a); return output; } -`;class bI extends dH{destroy(){this.renderTarget&&(this.renderTarget.destroyTextureBuffers(),this.renderTarget.destroy(),this.renderTarget=null);}setup(){for(let e=0;e<2;++e)this.historyTextures[e]=new ic(this.device,{name:`TAA-History-${e}`,width:4,height:4,format:this.sourceTexture.format,mipmaps:false,minFilter:1,magFilter:1,addressU:1,addressV:1}),this.historyRenderTargets[e]=new iG({colorBuffer:this.historyTextures[e],depth:false});this.historyTexture=this.historyTextures[0],this.init(this.historyRenderTargets[0],{resizeSource:this.sourceTexture});}before(){this.sourceTextureId.setValue(this.sourceTexture),this.historyTextureId.setValue(this.historyTextures[1-this.historyIndex]),this.textureSize[0]=this.sourceTexture.width,this.textureSize[1]=this.sourceTexture.height,this.textureSizeId.setValue(this.textureSize);let e=this.cameraComponent.camera;this.viewProjPrevId.setValue(e._viewProjPrevious.data),this.viewProjInvId.setValue(e._viewProjInverse.data),this.jittersId.setValue(e._jitters),this.cameraParamsId.setValue(e.fillShaderParams(this.cameraParams));}update(){return this.historyIndex=1-this.historyIndex,this.historyTexture=this.historyTextures[this.historyIndex],this.renderTarget=this.historyRenderTargets[this.historyIndex],this.historyTexture}constructor(e,t,i){super(e),this.historyIndex=0,this.historyTexture=null,this.historyTextures=[],this.historyRenderTargets=[],this.sourceTexture=t,this.cameraComponent=i,n$.get(e,tz).set("sampleCatmullRomPS",bb),n$.get(e,tV).set("sampleCatmullRomPS",bC),n$.get(e,tz).set("taaResolvePS",bA),n$.get(e,tV).set("taaResolvePS",bP);let s=new Map;s.set("QUALITY_HIGH",true),nJ.addScreenDepthChunkDefines(e,i.shaderParams,s),this.shader=nJ.createShader(e,{uniqueName:"TaaResolveShader",attributes:{aPosition:e8},vertexChunk:"quadVS",fragmentChunk:"taaResolvePS",fragmentDefines:s});let{scope:r}=e;this.sourceTextureId=r.resolve("sourceTexture"),this.textureSizeId=r.resolve("textureSize"),this.textureSize=new Float32Array(2),this.historyTextureId=r.resolve("historyTexture"),this.viewProjPrevId=r.resolve("matrix_viewProjectionPrevious"),this.viewProjInvId=r.resolve("matrix_viewProjectionInverse"),this.jittersId=r.resolve("jitters"),this.cameraParams=new Float32Array(4),this.cameraParamsId=r.resolve("camera_params"),this.setup();}}var bD=` +`;var og=class extends Ut{constructor(e,s,i){super(e);n(this,"historyIndex",0);n(this,"historyTexture",null);n(this,"historyTextures",[]);n(this,"historyRenderTargets",[]);this.sourceTexture=s,this.cameraComponent=i,ne.get(e,fe).set("sampleCatmullRomPS",JV),ne.get(e,se).set("sampleCatmullRomPS",eH),ne.get(e,fe).set("taaResolvePS",tH),ne.get(e,se).set("taaResolvePS",sH);let r=new Map;r.set("QUALITY_HIGH",!0),Se.addScreenDepthChunkDefines(e,i.shaderParams,r),this.shader=Se.createShader(e,{uniqueName:"TaaResolveShader",attributes:{aPosition:ee},vertexChunk:"quadVS",fragmentChunk:"taaResolvePS",fragmentDefines:r});let{scope:a}=e;this.sourceTextureId=a.resolve("sourceTexture"),this.textureSizeId=a.resolve("textureSize"),this.textureSize=new Float32Array(2),this.historyTextureId=a.resolve("historyTexture"),this.viewProjPrevId=a.resolve("matrix_viewProjectionPrevious"),this.viewProjInvId=a.resolve("matrix_viewProjectionInverse"),this.jittersId=a.resolve("jitters"),this.cameraParams=new Float32Array(4),this.cameraParamsId=a.resolve("camera_params"),this.setup()}destroy(){this.renderTarget&&(this.renderTarget.destroyTextureBuffers(),this.renderTarget.destroy(),this.renderTarget=null)}setup(){for(let e=0;e<2;++e)this.historyTextures[e]=new Z(this.device,{name:`TAA-History-${e}`,width:4,height:4,format:this.sourceTexture.format,mipmaps:!1,minFilter:1,magFilter:1,addressU:1,addressV:1}),this.historyRenderTargets[e]=new me({colorBuffer:this.historyTextures[e],depth:!1});this.historyTexture=this.historyTextures[0],this.init(this.historyRenderTargets[0],{resizeSource:this.sourceTexture})}before(){this.sourceTextureId.setValue(this.sourceTexture),this.historyTextureId.setValue(this.historyTextures[1-this.historyIndex]),this.textureSize[0]=this.sourceTexture.width,this.textureSize[1]=this.sourceTexture.height,this.textureSizeId.setValue(this.textureSize);let e=this.cameraComponent.camera;this.viewProjPrevId.setValue(e._viewProjPrevious.data),this.viewProjInvId.setValue(e._viewProjInverse.data),this.jittersId.setValue(e._jitters),this.cameraParamsId.setValue(e.fillShaderParams(this.cameraParams))}update(){return this.historyIndex=1-this.historyIndex,this.historyTexture=this.historyTextures[this.historyIndex],this.renderTarget=this.historyRenderTargets[this.historyIndex],this.historyTexture}};var iH=` #include "screenDepthPS" varying vec2 uv0; uniform vec3 params; @@ -17978,7 +18861,7 @@ fn SampleTextureCatmullRom(tex: texture_2d, texSampler: sampler, uv: vec2f, #endif gl_FragColor = vec4(cocFar, cocNear, 0.0, 0.0); } -`,bR=` +`;var rH=` #include "screenDepthPS" varying uv0: vec2f; uniform params: vec3f; @@ -18000,7 +18883,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { output.color = vec4f(cocFar, cocNear, 0.0, 0.0); return output; } -`;class bL extends dH{execute(){let{paramsValue:e,focusRange:t}=this;e[0]=this.focusDistance+.001,e[1]=t,e[2]=1/t,this.paramsId.setValue(e);let i=this.cameraComponent.camera;this.cameraParamsId.setValue(i.fillShaderParams(this.cameraParams)),super.execute();}constructor(e,t,i){super(e),this.cameraComponent=t,n$.get(e,tz).set("cocPS",bD),n$.get(e,tV).set("cocPS",bR);let s=new Map;i&&s.set("NEAR_BLUR",""),nJ.addScreenDepthChunkDefines(e,t.shaderParams,s),this.shader=nJ.createShader(e,{uniqueName:`CocShader-${i}`,attributes:{aPosition:e8},vertexChunk:"quadVS",fragmentChunk:"cocPS",fragmentDefines:s}),this.paramsId=e.scope.resolve("params"),this.paramsValue=new Float32Array(3),this.cameraParams=new Float32Array(4),this.cameraParamsId=e.scope.resolve("camera_params");}}var bM=` +`;var VA=class extends Ut{constructor(e,s,i){super(e);n(this,"focusDistance");n(this,"focusRange");this.cameraComponent=s,ne.get(e,fe).set("cocPS",iH),ne.get(e,se).set("cocPS",rH);let r=new Map;i&&r.set("NEAR_BLUR",""),Se.addScreenDepthChunkDefines(e,s.shaderParams,r),this.shader=Se.createShader(e,{uniqueName:`CocShader-${i}`,attributes:{aPosition:ee},vertexChunk:"quadVS",fragmentChunk:"cocPS",fragmentDefines:r}),this.paramsId=e.scope.resolve("params"),this.paramsValue=new Float32Array(3),this.cameraParams=new Float32Array(4),this.cameraParamsId=e.scope.resolve("camera_params")}execute(){let{paramsValue:e,focusRange:s}=this;e[0]=this.focusDistance+.001,e[1]=s,e[2]=1/s,this.paramsId.setValue(e);let i=this.cameraComponent.camera;this.cameraParamsId.setValue(i.fillShaderParams(this.cameraParams)),super.execute()}};var aH=` #if defined(NEAR_BLUR) uniform sampler2D nearTexture; #endif @@ -18047,7 +18930,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { } pcFragColor0 = vec4(sum, 1.0); } -`,bO=` +`;var oH=` #if defined(NEAR_BLUR) var nearTexture: texture_2d; var nearTextureSampler: sampler; @@ -18099,7 +18982,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { output.color = vec4f(sum, 1.0); return output; } -`;class bF extends dH{set blurRings(e){this._blurRings!==e&&(this._blurRings=e,this.shader=null);}get blurRings(){return this._blurRings}set blurRingPoints(e){this._blurRingPoints!==e&&(this._blurRingPoints=e,this.shader=null);}get blurRingPoints(){return this._blurRingPoints}createShader(){this.kernel=new Float32Array(ec.concentric(this.blurRings,this.blurRingPoints));let e=this.kernel.length>>1,t=null!==this.nearTexture,i=new Map;i.set("{KERNEL_COUNT}",e),i.set("{INV_KERNEL_COUNT}",1/e),t&&i.set("NEAR_BLUR",""),this.shader=nJ.createShader(this.device,{uniqueName:`DofBlurShader-${e}-${t?"nearBlur":"noNearBlur"}`,attributes:{aPosition:e8},vertexChunk:"quadVS",fragmentChunk:"dofBlurPS",fragmentDefines:i});}execute(){this.shader||this.createShader(),this.nearTextureId.setValue(this.nearTexture),this.farTextureId.setValue(this.farTexture),this.cocTextureId.setValue(this.cocTexture),this.kernelId.setValue(this.kernel),this.kernelCountId.setValue(this.kernel.length>>1),this.blurRadiusNearId.setValue(this.blurRadiusNear),this.blurRadiusFarId.setValue(this.blurRadiusFar),super.execute();}constructor(e,t,i,s){super(e),this.blurRadiusNear=1,this.blurRadiusFar=1,this._blurRings=3,this._blurRingPoints=3,this.nearTexture=t,this.farTexture=i,this.cocTexture=s,n$.get(e,tz).set("dofBlurPS",bM),n$.get(e,tV).set("dofBlurPS",bO);let{scope:r}=e;this.kernelId=r.resolve("kernel[0]"),this.kernelCountId=r.resolve("kernelCount"),this.blurRadiusNearId=r.resolve("blurRadiusNear"),this.blurRadiusFarId=r.resolve("blurRadiusFar"),this.nearTextureId=r.resolve("nearTexture"),this.farTextureId=r.resolve("farTexture"),this.cocTextureId=r.resolve("cocTexture");}}class bN extends an{destroy(){this.destroyRenderPasses(),this.cocPass=null,this.farPass=null,this.blurPass=null,this.destroyRT(this.cocRT),this.destroyRT(this.farRt),this.destroyRT(this.blurRt),this.cocRT=null,this.farRt=null,this.blurRt=null;}destroyRenderPasses(){for(let e=0;e{e.defaultUniformBuffer.destroy(),e.destroy();}),this.viewBindGroups.length=0;}setupRenderTarget(e){let{device:t}=this;this.linearDepthFormat=t.textureFloatRenderable?15:7,this.linearDepthTexture=ic.createDataTexture2D(t,"SceneLinearDepthTexture",1,1,this.linearDepthFormat);let i=new iG({name:"PrepassRT",colorBuffer:this.linearDepthTexture,depth:true,samples:1});this.camera.shaderParams.sceneDepthMapLinear=true,this.init(i,e);}after(){this.device.scope.resolve("uSceneDepthMap").setValue(this.linearDepthTexture);}execute(){let{renderer:e,scene:t,renderTarget:i}=this,s=this.camera.camera,r=t.layers.layerList,a=t.layers.subLayerEnabled,n=t.layers.subLayerList;for(let t=0;t>1,s=this.nearTexture!==null,i=new Map;i.set("{KERNEL_COUNT}",e),i.set("{INV_KERNEL_COUNT}",1/e),s&&i.set("NEAR_BLUR",""),this.shader=Se.createShader(this.device,{uniqueName:`DofBlurShader-${e}-${s?"nearBlur":"noNearBlur"}`,attributes:{aPosition:ee},vertexChunk:"quadVS",fragmentChunk:"dofBlurPS",fragmentDefines:i})}execute(){this.shader||this.createShader(),this.nearTextureId.setValue(this.nearTexture),this.farTextureId.setValue(this.farTexture),this.cocTextureId.setValue(this.cocTexture),this.kernelId.setValue(this.kernel),this.kernelCountId.setValue(this.kernel.length>>1),this.blurRadiusNearId.setValue(this.blurRadiusNear),this.blurRadiusFarId.setValue(this.blurRadiusFar),super.execute()}};var ng=class extends Nt{constructor(e,s,i,r,a,o){super(e);n(this,"focusDistance",100);n(this,"focusRange",50);n(this,"blurRadius",1);n(this,"blurRings",3);n(this,"blurRingPoints",3);n(this,"highQuality",!0);n(this,"cocTexture",null);n(this,"blurTexture",null);n(this,"cocPass",null);n(this,"farPass",null);n(this,"blurPass",null);this.highQuality=a,this.cocPass=this.setupCocPass(e,s,i,o),this.beforePasses.push(this.cocPass);let l=a?i:r;this.farPass=this.setupFarPass(e,l,.5),this.beforePasses.push(this.farPass),this.blurPass=this.setupBlurPass(e,r,o,a?2:.5),this.beforePasses.push(this.blurPass)}destroy(){this.destroyRenderPasses(),this.cocPass=null,this.farPass=null,this.blurPass=null,this.destroyRT(this.cocRT),this.destroyRT(this.farRt),this.destroyRT(this.blurRt),this.cocRT=null,this.farRt=null,this.blurRt=null}destroyRenderPasses(){for(let e=0;e{e.defaultUniformBuffer.destroy(),e.destroy()}),this.viewBindGroups.length=0}setupRenderTarget(e){let{device:s}=this;this.linearDepthFormat=s.textureFloatRenderable?Mt:ce,this.linearDepthTexture=Z.createDataTexture2D(s,"SceneLinearDepthTexture",1,1,this.linearDepthFormat);let i=new me({name:"PrepassRT",colorBuffer:this.linearDepthTexture,depth:!0,samples:1});this.camera.shaderParams.sceneDepthMapLinear=!0,this.init(i,e)}after(){this.device.scope.resolve(w9).setValue(this.linearDepthTexture)}execute(){let{renderer:e,scene:s,renderTarget:i}=this,r=this.camera.camera,a=s.layers.layerList,o=s.layers.subLayerEnabled,l=s.layers.subLayerList;for(let h=0;h FragmentOutput { mediump float ao = sum / totalWeight; gl_FragColor.r = ao; } -`,bz=` +`;var lH=` #include "screenDepthPS" varying uv0: vec2f; var sourceTexture: texture_2d; @@ -18181,7 +19064,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { output.color = vec4f(ao, ao, ao, 1.0); return output; } -`;class bV extends dH{execute(){this.filterSizeId.setValue(4),this.sourceTextureId.setValue(this.sourceTexture);let{width:e,height:t}=this.sourceTexture;this.sourceInvResolutionValue[0]=1/e,this.sourceInvResolutionValue[1]=1/t,this.sourceInvResolutionId.setValue(this.sourceInvResolutionValue),super.execute();}constructor(e,t,i,s){super(e),this.sourceTexture=t,n$.get(e,tz).set("depthAwareBlurPS",bU),n$.get(e,tV).set("depthAwareBlurPS",bz);let r=new Map;s&&r.set("HORIZONTAL",""),nJ.addScreenDepthChunkDefines(e,i.shaderParams,r),this.shader=nJ.createShader(e,{uniqueName:`DepthAware${s?"Horizontal":"Vertical"}BlurShader`,attributes:{aPosition:e8},vertexChunk:"quadVS",fragmentChunk:"depthAwareBlurPS",fragmentDefines:r});let a=this.device.scope;this.sourceTextureId=a.resolve("sourceTexture"),this.sourceInvResolutionId=a.resolve("sourceInvResolution"),this.sourceInvResolutionValue=new Float32Array(2),this.filterSizeId=a.resolve("filterSize");}}var bG=` +`;var Hu=class extends Ut{constructor(t,e,s,i){super(t),this.sourceTexture=e,ne.get(t,fe).set("depthAwareBlurPS",nH),ne.get(t,se).set("depthAwareBlurPS",lH);let r=new Map;i&&r.set("HORIZONTAL",""),Se.addScreenDepthChunkDefines(t,s.shaderParams,r),this.shader=Se.createShader(t,{uniqueName:`DepthAware${i?"Horizontal":"Vertical"}BlurShader`,attributes:{aPosition:ee},vertexChunk:"quadVS",fragmentChunk:"depthAwareBlurPS",fragmentDefines:r});let a=this.device.scope;this.sourceTextureId=a.resolve("sourceTexture"),this.sourceInvResolutionId=a.resolve("sourceInvResolution"),this.sourceInvResolutionValue=new Float32Array(2),this.filterSizeId=a.resolve("filterSize")}execute(){this.filterSizeId.setValue(4),this.sourceTextureId.setValue(this.sourceTexture);let{width:t,height:e}=this.sourceTexture;this.sourceInvResolutionValue[0]=1/t,this.sourceInvResolutionValue[1]=1/e,this.sourceInvResolutionId.setValue(this.sourceInvResolutionValue),super.execute()}};var cH=` #include "screenDepthPS" varying vec2 uv0; @@ -18293,7 +19176,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { ao = pow(ao, uPower); gl_FragColor = vec4(ao, ao, ao, 1.0); } -`,bH=` +`;var hH=` #include "screenDepthPS" varying uv0: vec2f; uniform uInvResolution: vec2f; @@ -18406,7 +19289,7 @@ fn fragmentMain(input: FragmentInput) -> FragmentOutput { output.color = vec4f(ao, ao, ao, 1.0); return output; } -`;class bW extends dH{destroy(){if(this.renderTarget?.destroyTextureBuffers(),this.renderTarget?.destroy(),this.renderTarget=null,this.afterPasses.length>0){let e=this.afterPasses[0].renderTarget;e?.destroyTextureBuffers(),e?.destroy();}this.afterPasses.forEach(e=>e.destroy()),this.afterPasses.length=0,super.destroy();}set scale(e){this._scale=e,this.scaleX=e,this.scaleY=e;}get scale(){return this._scale}createRenderTarget(e){return new iG({depth:false,colorBuffer:ic.createDataTexture2D(this.device,e,1,1,52)})}execute(){let{device:e,sourceTexture:t,sampleCount:i,minAngle:s,scale:r}=this,{width:a,height:n}=this.renderTarget.colorBuffer,o=e.scope;o.resolve("uAspect").setValue(a/n),o.resolve("uInvResolution").setValue([1/a,1/n]),o.resolve("uSampleCount").setValue([i,1/i]);let l=Math.sin(s*ei.DEG_TO_RAD);o.resolve("uMinHorizonAngleSineSquared").setValue(l*l);let h=1/(i-.5)*62.82,c=this.radius/r,d=.1*c,u=2*d*6.282*this.intensity/i,f=.5*t.height;o.resolve("uSpiralTurns").setValue(10),o.resolve("uAngleIncCosSin").setValue([Math.cos(h),Math.sin(h)]),o.resolve("uMaxLevel").setValue(0),o.resolve("uInvRadiusSquared").setValue(1/(c*c)),o.resolve("uBias").setValue(.001),o.resolve("uPeak2").setValue(d*d),o.resolve("uIntensity").setValue(u),o.resolve("uPower").setValue(this.power),o.resolve("uProjectionScaleRadius").setValue(f*c),o.resolve("uRandomize").setValue(this.randomize?this._blueNoise.value():0),super.execute();}after(){this.ssaoTextureId.setValue(this.ssaoTexture);let e=this.sourceTexture;this.ssaoTextureSizeInvId.setValue([1/e.width,1/e.height]);}constructor(e,t,i,s){super(e),this.radius=5,this.intensity=1,this.power=1,this.sampleCount=10,this.minAngle=5,this.randomize=false,this._scale=1,this._blueNoise=new ld(19),this.sourceTexture=t,this.cameraComponent=i,n$.get(e,tz).set("ssaoPS",bG),n$.get(e,tV).set("ssaoPS",bH);let r=new Map;nJ.addScreenDepthChunkDefines(e,i.shaderParams,r),this.shader=nJ.createShader(e,{uniqueName:"SsaoShader",attributes:{aPosition:e8},vertexChunk:"quadVS",fragmentChunk:"ssaoPS",fragmentDefines:r});let a=this.createRenderTarget("SsaoFinalTexture");this.ssaoTexture=a.colorBuffer,this.init(a,{resizeSource:this.sourceTexture});let n=new es(0,0,0,0);if(this.setClearColor(n),s){let t=this.createRenderTarget("SsaoTempTexture"),s=new bV(e,a.colorBuffer,i,true);s.init(t,{resizeSource:a.colorBuffer}),s.setClearColor(n);let r=new bV(e,t.colorBuffer,i,false);r.init(a,{resizeSource:a.colorBuffer}),r.setClearColor(n),this.afterPasses.push(s),this.afterPasses.push(r);}this.ssaoTextureId=e.scope.resolve("ssaoTexture"),this.ssaoTextureSizeInvId=e.scope.resolve("ssaoTextureSizeInv");}}class bX{constructor(){this.stencil=false,this.samples=1,this.sceneColorMap=false,this.lastGrabLayerId=2,this.lastGrabLayerIsTransparent=false,this.lastSceneLayerId=3,this.lastSceneLayerIsTransparent=true,this.taaEnabled=false,this.bloomEnabled=false,this.ssaoType=bu,this.ssaoBlurEnabled=true,this.prepassEnabled=false,this.dofEnabled=false,this.dofNearBlur=false,this.dofHighQuality=true;}}let bY=new bX;class bq extends an{destroy(){this.reset();}reset(){this.sceneTexture=null,this.sceneTextureHalf=null,this.rt&&(this.rt.destroyTextureBuffers(),this.rt.destroy(),this.rt=null),this.rtHalf&&(this.rtHalf.destroyTextureBuffers(),this.rtHalf.destroy(),this.rtHalf=null),this.beforePasses.forEach(e=>e.destroy()),this.beforePasses.length=0,this.prePass=null,this.scenePass=null,this.scenePassTransparent=null,this.colorGrabPass=null,this.composePass=null,this.bloomPass=null,this.ssaoPass=null,this.taaPass=null,this.afterPass=null,this.scenePassHalf=null,this.dofPass=null;}sanitizeOptions(e){return ((e=Object.assign({},bY,e)).taaEnabled||e.ssaoType!==bu||e.dofEnabled)&&(e.prepassEnabled=true),e}set renderTargetScale(e){this._renderTargetScale=e,this.scenePass&&(this.scenePass.scaleX=e,this.scenePass.scaleY=e);}get renderTargetScale(){return this._renderTargetScale}needsReset(e){let t,i,s=this.options;return e.ssaoType!==s.ssaoType||e.ssaoBlurEnabled!==s.ssaoBlurEnabled||e.taaEnabled!==s.taaEnabled||e.samples!==s.samples||e.stencil!==s.stencil||e.bloomEnabled!==s.bloomEnabled||e.prepassEnabled!==s.prepassEnabled||e.sceneColorMap!==s.sceneColorMap||e.dofEnabled!==s.dofEnabled||e.dofNearBlur!==s.dofNearBlur||e.dofHighQuality!==s.dofHighQuality||(t=e.formats)!==(i=s.formats)&&(!(Array.isArray(t)&&Array.isArray(i))||t.length!==i.length||!t.every((e,t)=>e===i[t]))}update(e){e=this.sanitizeOptions(e),(this.needsReset(e)||this.layersDirty)&&(this.layersDirty=false,this.reset()),this.options=e,this.sceneTexture||this.setupRenderPasses(this.options);}createRenderTarget(e,t,i,s,r){return new iG({colorBuffer:new ic(this.device,{name:e,width:4,height:4,format:this.hdrFormat,mipmaps:false,minFilter:1,magFilter:1,addressU:1,addressV:1}),depth:t,stencil:i,samples:s,flipY:r})}setupRenderPasses(e){let{device:t}=this,i=this.cameraComponent,s=i.renderTarget;this.hdrFormat=t.getRenderableHdrFormat(e.formats,true,e.samples)||7,this._bloomEnabled=e.bloomEnabled&&7!==this.hdrFormat,this._sceneHalfEnabled=this._bloomEnabled||e.dofEnabled,i.shaderParams.ssaoEnabled=e.ssaoType===bf;let r=!!s?.flipY;this.rt=this.createRenderTarget("SceneColor",true,e.stencil,e.samples,r),this.sceneTexture=this.rt.colorBuffer,this._sceneHalfEnabled&&(this.rtHalf=this.createRenderTarget("SceneColorHalf",false,false,1,r),this.sceneTextureHalf=this.rtHalf.colorBuffer),this.sceneOptions={resizeSource:s,scaleX:this.renderTargetScale,scaleY:this.renderTargetScale},this.createPasses(e);let a=this.collectPasses();this.beforePasses=a.filter(e=>null!=e),this.updateCameraUseFlags();}updateCameraUseFlags(){let e=new Map,t=new Map;for(let i=0;i{e.firstCameraUse=true;}),t.forEach(e=>{e.lastCameraUse=true;});}collectPasses(){return [this.prePass,this.ssaoPass,this.scenePass,this.colorGrabPass,this.scenePassTransparent,this.taaPass,this.scenePassHalf,this.bloomPass,this.dofPass,this.composePass,this.afterPass]}createPasses(e){this.setupScenePrepass(e),this.setupSsaoPass(e);let t=this.setupScenePass(e),i=this.setupTaaPass(e);this.setupSceneHalfPass(e,i),this.setupBloomPass(e,this.sceneTextureHalf),this.setupDofPass(e,this.sceneTexture,this.sceneTextureHalf),this.setupComposePass(e),this.setupAfterPass(e,t);}setupScenePrepass(e){if(e.prepassEnabled){let{app:e,device:t,cameraComponent:i}=this,{scene:s,renderer:r}=e;this.prePass=new bk(t,s,r,i,this.sceneOptions);}}setupScenePassSettings(e){e.gammaCorrection=0,e.toneMapping=6;}setupScenePass(e){let{app:t,device:i,cameraComponent:s}=this,{scene:r,renderer:a}=t,n=r.layers;this.scenePass=new hh(i,n,r,a),this.setupScenePassSettings(this.scenePass),this.scenePass.init(this.rt,this.sceneOptions);let o=e.sceneColorMap?e.lastGrabLayerId:e.lastSceneLayerId,l=e.sceneColorMap?e.lastGrabLayerIsTransparent:e.lastSceneLayerIsTransparent,h={lastAddedIndex:0,clearRenderTarget:true};return h.lastAddedIndex=this.scenePass.addLayers(n,s,h.lastAddedIndex,h.clearRenderTarget,o,l),h.clearRenderTarget=false,e.sceneColorMap&&(this.colorGrabPass=new oA(i),this.colorGrabPass.source=this.rt,this.scenePassTransparent=new hh(i,n,r,a),this.setupScenePassSettings(this.scenePassTransparent),this.scenePassTransparent.init(this.rt),h.lastAddedIndex=this.scenePassTransparent.addLayers(n,s,h.lastAddedIndex,h.clearRenderTarget,e.lastSceneLayerId,e.lastSceneLayerIsTransparent),this.scenePassTransparent.rendersAnything||(this.scenePassTransparent.destroy(),this.scenePassTransparent=null),this.scenePassTransparent&&e.prepassEnabled&&(this.scenePassTransparent.depthStencilOps.storeDepth=true)),h}setupSsaoPass(e){let{ssaoBlurEnabled:t,ssaoType:i}=e,{device:s,cameraComponent:r}=this;i!==bu&&(this.ssaoPass=new bW(s,this.sceneTexture,r,t));}setupSceneHalfPass(e,t){this._sceneHalfEnabled&&(this.scenePassHalf=new bg(this.device,this.sceneTexture,{boxFilter:true,removeInvalid:true}),this.scenePassHalf.name="RenderPassSceneHalf",this.scenePassHalf.init(this.rtHalf,{resizeSource:t,scaleX:.5,scaleY:.5}),this.scenePassHalf.setClearColor(es.BLACK));}setupBloomPass(e,t){this._bloomEnabled&&(this.bloomPass=new bx(this.device,t,this.hdrFormat));}setupDofPass(e,t,i){e.dofEnabled&&(this.dofPass=new bN(this.device,this.cameraComponent,t,i,e.dofHighQuality,e.dofNearBlur));}setupTaaPass(e){let t=this.sceneTexture;return e.taaEnabled&&(this.taaPass=new bI(this.device,this.sceneTexture,this.cameraComponent),t=this.taaPass.historyTexture),t}setupComposePass(e){this.composePass=new bw(this.device),this.composePass.bloomTexture=this.bloomPass?.bloomTexture,this.composePass.hdrScene=7!==this.hdrFormat,this.composePass.taaEnabled=e.taaEnabled,this.composePass.cocTexture=this.dofPass?.cocTexture,this.composePass.blurTexture=this.dofPass?.blurTexture,this.composePass.blurTextureUpscale=!this.dofPass?.highQuality;let t=this.cameraComponent.renderTarget;this.composePass.init(t),this.composePass.ssaoTexture=e.ssaoType===bp?this.ssaoPass.ssaoTexture:null;}setupAfterPass(e,t){let{app:i,cameraComponent:s}=this,{scene:r,renderer:a}=i,n=r.layers,o=s.renderTarget;this.afterPass=new hh(this.device,n,r,a),this.afterPass.init(o),this.afterPass.addLayers(n,s,t.lastAddedIndex,t.clearRenderTarget);}frameUpdate(){this.layersDirty&&this.cameraFrame.update(),super.frameUpdate();let e=this.taaPass?.update()??this.rt.colorBuffer;this.composePass.sceneTexture=e,this.scenePassHalf?.setSourceTexture(e);}constructor(e,t,i,s={}){super(e.graphicsDevice),this._renderTargetScale=1,this.layersDirty=false,this.rt=null,this.app=e,this.cameraComponent=i,this.cameraFrame=t,this.options=this.sanitizeOptions(s),this.setupRenderPasses(this.options);}}let bj=new ed,bK=new ex;class b${copy(e){return this.set(e.position,e.angles,e.distance)}clone(){return new b$(this.position.clone(),this.angles.clone(),this.distance)}equalsApprox(e,t=1e-6){return this.position.equalsApprox(e.position,t)&&this.angles.equalsApprox(e.angles,t)&&Math.abs(this.distance-e.distance){let e=new Map;return {down:t=>{e.set(t.pointerId,[t.screenX,t.screenY]);},move:t=>{if(!e.has(t.pointerId))return [0,0];let i=e.get(t.pointerId),s=t.screenX-i[0],r=t.screenY-i[1];return i[0]=t.screenX,i[1]=t.screenY,[s,r]},up:t=>{e.delete(t.pointerId);}}},b3=new ef;class b4{get value(){return this._value}down(e,t){return this._position.set(e,t),this._value.set(0,0),[e,t,e,t]}move(e,t){b3.set(e-this._position.x,t-this._position.y),b3.length()>this._range&&b3.normalize().mulScalar(this._range),this._value.set(ei.clamp(b3.x/this._range,-1,1),ei.clamp(b3.y/this._range,-1,1));let{x:i,y:s}=this._position;return [i,s,i+b3.x,s+b3.y]}up(){return this._position.set(0,0),this._value.set(0,0),[-1,-1,-1,-1]}constructor({range:e}={}){this._range=70,this._position=new ef,this._value=new ef,this._range=e??this._range;}}let b5=(e,t)=>0===e.indexOf(t),b6=(e,t)=>-1!==e.indexOf(t,e.length-t.length),b8=new ef,b9={passive:false},b7={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,0:26,1:27,2:28,3:29,4:30,5:31,6:32,7:33,8:34,9:35,UP:36,DOWN:37,LEFT:38,RIGHT:39,SPACE:40,SHIFT:41,CTRL:42},Ce=Object.keys(b7).length,Ct=Array(Ce).fill(0);class Ci extends bJ{_onWheel(e){e.preventDefault(),this.deltas.wheel.append([e.deltaY]);}_onPointerDown(e){this._movementState.down(e),"mouse"!==e.pointerType||(this._pointerLock?document.pointerLockElement!==this._element&&this._element?.requestPointerLock():this._element?.setPointerCapture(e.pointerId),this._clearButtons(),this._button[e.button]=1,this.deltas.button.append(this._button),-1===this._pointerId&&(this._pointerId=e.pointerId));}_onPointerMove(e){let[t,i]=this._pointerLock&&document.pointerLockElement===this._element?[e.movementX,e.movementY]:this._movementState.move(e);if("mouse"===e.pointerType&&e.target===this._element){if(this._pointerLock){if(document.pointerLockElement!==this._element)return}else if(this._pointerId!==e.pointerId)return;this.deltas.mouse.append([t,i]);}}_onPointerUp(e){this._movementState.up(e),"mouse"!==e.pointerType||(this._pointerLock||this._element?.releasePointerCapture(e.pointerId),this._clearButtons(),this.deltas.button.append(this._button),this._pointerId===e.pointerId&&(this._pointerId=-1));}_onContextMenu(e){e.preventDefault();}_onKeyDown(e){this._pointerLock&&document.pointerLockElement!==this._element||(e.stopPropagation(),this._setKey(e.code,1));}_onKeyUp(e){e.stopPropagation(),this._setKey(e.code,0);}_clearButtons(){for(let e=0;e1-Math.pow(e,1e3*t),Co=new ed,Cl=new ed,Ch=new ed,Cc=new ed,Cd=new ed,Cu=new ex,Cf=new ed,Cp=new ed,Cm=new ed,C_=new ex,Cg=new ed,Cv=new ed,CS=new ex,Cy=new ed,Cx=new ed,CT=new ed,CE=new ex,Cw=new ey,Cb=new ey,CC=new eM;class CA extends X{static createLayer(e,t="Gizmo",i=e.scene.layers.layerList.length){let s=new hy({name:t,clearDepthBuffer:true,opaqueSortMode:0,transparentSortMode:0});return e.scene.layers.insert(s,i),s}set enabled(e){let t=this.root.getLocalPosition().distance(this.camera.entity.getPosition()),i=!!e&&this.nodes.length>0&&t>1e-4;i!==this.root.enabled&&(this.root.enabled=i,this._renderUpdate=true);}get enabled(){return this.root.enabled}get mouseButtons(){return this._mouseButtons}set layer(e){this._layer!==e&&(this._camera.layers=this._camera.layers.filter(e=>e!==this._layer.id),this._layer=e,this._camera.layers=this._camera.layers.concat(this._layer.id),this.enabled=true);}get layer(){return this._layer}set camera(e){this._camera!==e&&(this._camera.layers=this._camera.layers.filter(e=>e!==this._layer.id),this._camera=e,this._camera.layers=this._camera.layers.concat(this._layer.id),this.enabled=true);}get camera(){return this._camera}set coordSpace(e){this._coordSpace=e??this._coordSpace,this._updateRotation();}get coordSpace(){return this._coordSpace}set size(e){this._size=e,this._updateScale();}get size(){return this._size}get facingDir(){if(0===this._camera.projection){let e=this.root.getLocalPosition(),t=this._camera.entity.getPosition();return CT.sub2(t,e).normalize()}return CT.copy(this._camera.entity.forward).mulScalar(-1)}get cameraDir(){let e=this._camera.entity.getPosition(),t=this.root.getLocalPosition();return CT.sub2(e,t).normalize()}_onPointerDown(e){if(!this.enabled||document.pointerLockElement||!this.mouseButtons[e.button])return;let t=this._getSelection(e.offsetX,e.offsetY);t[0]&&(this.preventDefault&&e.preventDefault(),e.stopPropagation());let{canvas:i}=this._device;i.setPointerCapture(e.pointerId),this.fire(CA.EVENT_POINTERDOWN,e.offsetX,e.offsetY,t[0]);}_onPointerMove(e){if(!this.enabled||document.pointerLockElement)return;let t=this._getSelection(e.offsetX,e.offsetY);t[0]&&(this.preventDefault&&e.preventDefault(),e.stopPropagation()),this.fire(CA.EVENT_POINTERMOVE,e.offsetX,e.offsetY,t[0]);}_onPointerUp(e){if(!this.enabled||document.pointerLockElement||!this.mouseButtons[e.button])return;let t=this._getSelection(e.offsetX,e.offsetY);t[0]&&(this.preventDefault&&e.preventDefault(),e.stopPropagation());let{canvas:i}=this._device;i.releasePointerCapture(e.pointerId),this.fire(CA.EVENT_POINTERUP,e.offsetX,e.offsetY,t[0]);}_updatePosition(){if(Cx.set(0,0,0),"local"===this._coordSpace)Cx.copy(this.nodes[this.nodes.length-1].getPosition());else {for(let e=0;eMath.abs(this._scale-this.root.getLocalScale().x)||(this.root.setLocalScale(this._scale,this._scale,this._scale),this.fire(CA.EVENT_SCALEUPDATE,this._scale),this._renderUpdate=true);}_getSelection(e,t){let i=this._camera.screenToWorld(e,t,0),s=this._camera.screenToWorld(e,t,this._camera.farClip-this._camera.nearClip),r=Cy.copy(s).sub(i).normalize(),a=[];for(let e=0;e0!==e.priority&&0!==t.priority?t.priority-e.priority:e.dist-t.dist),a[0].meshInstances):[]}attach(e=[]){if(Array.isArray(e)){if(0===e.length)return;this.nodes=e;}else this.nodes=[e];this._updatePosition(),this._updateRotation(),this._updateScale(),this.fire(CA.EVENT_NODESATTACH),this.enabled=true;}detach(){this.enabled=false,this.fire(CA.EVENT_NODESDETACH),this.nodes=[];}prerender(){}update(){this._renderUpdate&&(this._renderUpdate=false,this.fire(CA.EVENT_RENDERUPDATE)),this.enabled&&(this._updatePosition(),this._updateRotation(),this._updateScale());}destroy(){this.detach(),this._device.canvas.removeEventListener("pointerdown",this._onPointerDown),this._device.canvas.removeEventListener("pointermove",this._onPointerMove),this._device.canvas.removeEventListener("pointerup",this._onPointerUp),this._handles.forEach(e=>e.off()),this.root.destroy();}constructor(e,t,i="gizmo"){super(),this._size=1,this._scale=1,this._coordSpace="world",this._handles=[],this._mouseButtons=[true,true,true],this._renderUpdate=false,this.nodes=[],this.intersectShapes=[],this.preventDefault=true,this._layer=t,this._camera=e,this._camera.layers=this._camera.layers.concat(this._layer.id),this._app=this._camera.system.app,this._device=this._app.graphicsDevice,this.root=new f9(i),this._app.root.addChild(this.root),this.root.enabled=false,this._updateScale(),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._device.canvas.addEventListener("pointerdown",this._onPointerDown),this._device.canvas.addEventListener("pointermove",this._onPointerMove),this._device.canvas.addEventListener("pointerup",this._onPointerUp),this._handles.push(this._app.on("prerender",()=>this.prerender())),this._handles.push(this._app.on("update",()=>this.update())),this._handles.push(this._app.on("destroy",()=>this.destroy()));}}CA.EVENT_POINTERDOWN="pointer:down",CA.EVENT_POINTERMOVE="pointer:move",CA.EVENT_POINTERUP="pointer:up",CA.EVENT_POSITIONUPDATE="position:update",CA.EVENT_ROTATIONUPDATE="rotation:update",CA.EVENT_SCALEUPDATE="scale:update",CA.EVENT_NODESATTACH="nodes:attach",CA.EVENT_NODESDETACH="nodes:detach",CA.EVENT_RENDERUPDATE="render:update";let CP=Object.freeze(new es(1,.3,.3)),CI=Object.freeze(new es(.3,1,.3)),CD=Object.freeze(new es(.3,.3,1));Object.freeze(new es(1,1,.5));let CR=Object.freeze(new es(.5,.5,.5,.5)),CL=(e,t)=>new es(e.r,e.g,e.b,t),CM=new ed,CO=new ed,CF=new ed,CN=new eM,CB=new eR,Ck=new es,CU=["x","y","z"];class Cz extends CA{get theme(){return this._theme}set xAxisColor(e){this.setTheme({shapeBase:{x:e},shapeHover:{x:CL(e,this.colorAlpha)},guideBase:{x:e},guideOcclusion:1});}get xAxisColor(){return this._theme.shapeBase.x}set yAxisColor(e){this.setTheme({shapeBase:{y:e},shapeHover:{y:CL(e,this.colorAlpha)},guideBase:{y:e},guideOcclusion:1});}get yAxisColor(){return this._theme.shapeBase.y}set zAxisColor(e){this.setTheme({shapeBase:{z:e},shapeHover:{z:CL(e,this.colorAlpha)},guideBase:{z:e},guideOcclusion:1});}get zAxisColor(){return this._theme.shapeBase.z}set colorAlpha(e){this.setTheme({shapeHover:{x:CL(this._theme.shapeHover.x,e),y:CL(this._theme.shapeHover.y,e),z:CL(this._theme.shapeHover.z,e),xyz:CL(this._theme.shapeHover.xyz,e),f:CL(this._theme.shapeHover.f,e)}});}get colorAlpha(){return (this._theme.shapeHover.x.a+this._theme.shapeHover.y.a+this._theme.shapeHover.z.a+this._theme.shapeHover.xyz.a+this._theme.shapeHover.f.a)/5}get _dragging(){return !this._hoverAxis&&!!this._selectedAxis}_getAxis(e){return e?e.node.name.split(":")[1]:""}_getIsPlane(e){return !!e&&-1!==e.node.name.indexOf("plane")}_hover(e){if(this._dragging)return;let t=new Set(this._hovering),i=false,s=e=>{t.has(e)?t.delete(e):(this._hovering.add(e),this._shapes[e]?.hover(true),i=true);};if(this._hoverAxis=this._getAxis(e),this._hoverIsPlane=this._getIsPlane(e),this._hoverAxis)if("xyz"===this._hoverAxis)s("x"),s("y"),s("z"),s("xyz");else if(this._hoverIsPlane)switch(this._hoverAxis){case "x":s("y"),s("z"),s("yz");break;case "y":s("x"),s("z"),s("xz");break;case "z":s("x"),s("y"),s("xy");}else s(this._hoverAxis);for(let e of t)this._hovering.delete(e),this._shapes[e]?.hover(false),i=true;i&&(this._renderUpdate=true);}_createRay(e){if(0===this._camera.projection)return CN.origin.copy(this._camera.entity.getPosition()),CN.direction.sub2(e,CN.origin).normalize(),CN;let t=this._camera.farClip-this._camera.nearClip;return CN.origin.sub2(e,CM.copy(this._camera.entity.forward).mulScalar(t)),CN.direction.copy(this._camera.entity.forward),CN}_createPlane(e,t,i){let s=CM.copy(this.facingDir),r=CB.normal.set(0,0,0);return t?r.copy(this._camera.entity.forward).mulScalar(-1):(r[e]=1,this._rootStartRot.transformVector(r,r),i&&(CO.cross(r,s).normalize(),r.cross(CO,r).normalize())),CB.setFromPointNormal(this._rootStartPos,r)}_dirFromAxis(e,t){return "f"===e?t.copy(this._camera.entity.forward).mulScalar(-1):(t.set(0,0,0),t[e]=1),t}_projectToAxis(e,t){CM.set(0,0,0),CM[t]=1,e.copy(CM.mulScalar(CM.dot(e)));let i=e[t];e.set(0,0,0),e[t]=i;}_screenToPoint(e,t,i=false,s=false){let r=this._camera.screenToWorld(e,t,1),a=this._selectedAxis,n=this._createRay(r);return !this._createPlane(a,i,s).intersectsRay(n,CF),CF}_drawGuideLines(e,t,i,s){for(let r of CU){if("xyz"===i){this._drawSpanLine(e,t,r);continue}s?r!==i&&this._drawSpanLine(e,t,r):r===i&&this._drawSpanLine(e,t,r);}}_drawSpanLine(e,t,i){let s=this._dirFromAxis(i,CM),r=this._theme.guideBase[i],a=CM.copy(s).mulScalar(this._camera.farClip-this._camera.nearClip),n=CO.copy(a).mulScalar(-1);if(t.transformVector(a,a).add(e),t.transformVector(n,n).add(e),this._theme.guideOcclusion<1){let e=Ck.copy(r);e.a*=1-this._theme.guideOcclusion,this._app.drawLine(a,n,e,false,this._layer);}0!==r.a&&this._app.drawLine(a,n,r,true);}_createTransform(){for(let e in this._shapes){let t=this._shapes[e];this.root.addChild(t.entity),this.intersectShapes.push(t);for(let e=0;e{let s=this._shapeMap.get(i);if(s?.disabled||this._dragging||!i)return;this._hoverAxis="",this._hoverIsPlane=false,this._selectedAxis=this._getAxis(i),this._selectedIsPlane=this._getIsPlane(i),this._rootStartPos.copy(this.root.getLocalPosition()),this._rootStartRot.copy(this.root.getRotation());let r=this._screenToPoint(e,t);this._selectionStartPoint.copy(r),this.fire(Cz.EVENT_TRANSFORMSTART,r,e,t);}),this.on(CA.EVENT_POINTERMOVE,(e,t,i)=>{let s=this._shapeMap.get(i);if(s?.disabled||(this._hover(i),!this._dragging))return;let r=this._screenToPoint(e,t);this.fire(Cz.EVENT_TRANSFORMMOVE,r,e,t);}),this.on(CA.EVENT_POINTERUP,(e,t,i)=>{this._hover(i),this._dragging&&(i&&(this._hoverAxis=this._selectedAxis,this._hoverIsPlane=this._selectedIsPlane),this._selectedAxis="",this._selectedIsPlane=false,this.fire(Cz.EVENT_TRANSFORMEND));}),this.on(CA.EVENT_NODESDETACH,()=>{this._hoverAxis="",this._hoverIsPlane=false,this._hover(),this.fire(CA.EVENT_POINTERUP);});}}Cz.EVENT_TRANSFORMSTART="transform:start",Cz.EVENT_TRANSFORMMOVE="transform:move",Cz.EVENT_TRANSFORMEND="transform:end";let CV=new ed,CG=new ed,CH=new ed;class CW{get transform(){return this._transform}get priority(){return this._priority}setTransform(e=new ed,t=new ex,i=new ed){this.transform.setTRS(e,t,i);}fromGeometry(e){if(!e||!(e instanceof c4))throw Error("No geometry provided.");let t=e.positions??[],i=e.indices??[];this.tris=[];for(let e=0;e0){let e=this.afterPasses[0].renderTarget;e?.destroyTextureBuffers(),e?.destroy()}this.afterPasses.forEach(e=>e.destroy()),this.afterPasses.length=0,super.destroy()}set scale(e){this._scale=e,this.scaleX=e,this.scaleY=e}get scale(){return this._scale}createRenderTarget(e){return new me({depth:!1,colorBuffer:Z.createDataTexture2D(this.device,e,1,1,Wr)})}execute(){let{device:e,sourceTexture:s,sampleCount:i,minAngle:r,scale:a}=this,{width:o,height:l}=this.renderTarget.colorBuffer,h=e.scope;h.resolve("uAspect").setValue(o/l),h.resolve("uInvResolution").setValue([1/o,1/l]),h.resolve("uSampleCount").setValue([i,1/i]);let f=Math.sin(r*R.DEG_TO_RAD);h.resolve("uMinHorizonAngleSineSquared").setValue(f*f);let u=10,d=1/(i-.5)*u*2*3.141,p=this.radius/a,m=.001,_=.1*p,S=2*(_*2*3.141)*this.intensity/i,g=.5*s.height;h.resolve("uSpiralTurns").setValue(u),h.resolve("uAngleIncCosSin").setValue([Math.cos(d),Math.sin(d)]),h.resolve("uMaxLevel").setValue(0),h.resolve("uInvRadiusSquared").setValue(1/(p*p)),h.resolve("uBias").setValue(m),h.resolve("uPeak2").setValue(_*_),h.resolve("uIntensity").setValue(S),h.resolve("uPower").setValue(this.power),h.resolve("uProjectionScaleRadius").setValue(g*p),h.resolve("uRandomize").setValue(this.randomize?this._blueNoise.value():0),super.execute()}after(){this.ssaoTextureId.setValue(this.ssaoTexture);let e=this.sourceTexture;this.ssaoTextureSizeInvId.setValue([1/e.width,1/e.height])}};var Wu=class{constructor(){n(this,"formats");n(this,"stencil",!1);n(this,"samples",1);n(this,"sceneColorMap",!1);n(this,"lastGrabLayerId",$n);n(this,"lastGrabLayerIsTransparent",!1);n(this,"lastSceneLayerId",Zn);n(this,"lastSceneLayerIsTransparent",!0);n(this,"taaEnabled",!1);n(this,"bloomEnabled",!1);n(this,"ssaoType",cn);n(this,"ssaoBlurEnabled",!0);n(this,"prepassEnabled",!1);n(this,"dofEnabled",!1);n(this,"dofNearBlur",!1);n(this,"dofHighQuality",!0)}},I9=new Wu,hg=class extends Nt{constructor(e,s,i,r={}){super(e.graphicsDevice);n(this,"app");n(this,"prePass");n(this,"scenePass");n(this,"composePass");n(this,"bloomPass");n(this,"ssaoPass");n(this,"taaPass");n(this,"scenePassHalf");n(this,"dofPass");n(this,"_renderTargetScale",1);n(this,"layersDirty",!1);n(this,"cameraFrame");n(this,"rt",null);this.app=e,this.cameraComponent=i,this.cameraFrame=s,this.options=this.sanitizeOptions(r),this.setupRenderPasses(this.options)}destroy(){this.reset()}reset(){this.sceneTexture=null,this.sceneTextureHalf=null,this.rt&&(this.rt.destroyTextureBuffers(),this.rt.destroy(),this.rt=null),this.rtHalf&&(this.rtHalf.destroyTextureBuffers(),this.rtHalf.destroy(),this.rtHalf=null),this.beforePasses.forEach(e=>e.destroy()),this.beforePasses.length=0,this.prePass=null,this.scenePass=null,this.scenePassTransparent=null,this.colorGrabPass=null,this.composePass=null,this.bloomPass=null,this.ssaoPass=null,this.taaPass=null,this.afterPass=null,this.scenePassHalf=null,this.dofPass=null}sanitizeOptions(e){return e=Object.assign({},I9,e),(e.taaEnabled||e.ssaoType!==cn||e.dofEnabled)&&(e.prepassEnabled=!0),e}set renderTargetScale(e){this._renderTargetScale=e,this.scenePass&&(this.scenePass.scaleX=e,this.scenePass.scaleY=e)}get renderTargetScale(){return this._renderTargetScale}needsReset(e){let s=this.options,i=(r,a)=>r!==a&&(!(Array.isArray(r)&&Array.isArray(a))||r.length!==a.length||!r.every((o,l)=>o===a[l]));return e.ssaoType!==s.ssaoType||e.ssaoBlurEnabled!==s.ssaoBlurEnabled||e.taaEnabled!==s.taaEnabled||e.samples!==s.samples||e.stencil!==s.stencil||e.bloomEnabled!==s.bloomEnabled||e.prepassEnabled!==s.prepassEnabled||e.sceneColorMap!==s.sceneColorMap||e.dofEnabled!==s.dofEnabled||e.dofNearBlur!==s.dofNearBlur||e.dofHighQuality!==s.dofHighQuality||i(e.formats,s.formats)}update(e){e=this.sanitizeOptions(e),(this.needsReset(e)||this.layersDirty)&&(this.layersDirty=!1,this.reset()),this.options=e,this.sceneTexture||this.setupRenderPasses(this.options)}createRenderTarget(e,s,i,r,a){let o=new Z(this.device,{name:e,width:4,height:4,format:this.hdrFormat,mipmaps:!1,minFilter:1,magFilter:1,addressU:1,addressV:1});return new me({colorBuffer:o,depth:s,stencil:i,samples:r,flipY:a})}setupRenderPasses(e){let{device:s}=this,i=this.cameraComponent,r=i.renderTarget;this.hdrFormat=s.getRenderableHdrFormat(e.formats,!0,e.samples)||ce,this._bloomEnabled=e.bloomEnabled&&this.hdrFormat!==ce,this._sceneHalfEnabled=this._bloomEnabled||e.dofEnabled,i.shaderParams.ssaoEnabled=e.ssaoType===zA;let a=!!r?.flipY;this.rt=this.createRenderTarget("SceneColor",!0,e.stencil,e.samples,a),this.sceneTexture=this.rt.colorBuffer,this._sceneHalfEnabled&&(this.rtHalf=this.createRenderTarget("SceneColorHalf",!1,!1,1,a),this.sceneTextureHalf=this.rtHalf.colorBuffer),this.sceneOptions={resizeSource:r,scaleX:this.renderTargetScale,scaleY:this.renderTargetScale},this.createPasses(e);let o=this.collectPasses();this.beforePasses=o.filter(l=>l!=null),this.updateCameraUseFlags()}updateCameraUseFlags(){let e=new Map,s=new Map;for(let i=0;i{i.firstCameraUse=!0}),s.forEach(i=>{i.lastCameraUse=!0})}collectPasses(){return[this.prePass,this.ssaoPass,this.scenePass,this.colorGrabPass,this.scenePassTransparent,this.taaPass,this.scenePassHalf,this.bloomPass,this.dofPass,this.composePass,this.afterPass]}createPasses(e){this.setupScenePrepass(e),this.setupSsaoPass(e);let s=this.setupScenePass(e),i=this.setupTaaPass(e);this.setupSceneHalfPass(e,i),this.setupBloomPass(e,this.sceneTextureHalf),this.setupDofPass(e,this.sceneTexture,this.sceneTextureHalf),this.setupComposePass(e),this.setupAfterPass(e,s)}setupScenePrepass(e){if(e.prepassEnabled){let{app:s,device:i,cameraComponent:r}=this,{scene:a,renderer:o}=s;this.prePass=new lg(i,a,o,r,this.sceneOptions)}}setupScenePassSettings(e){e.gammaCorrection=Zi,e.toneMapping=Rf}setupScenePass(e){let{app:s,device:i,cameraComponent:r}=this,{scene:a,renderer:o}=s,l=a.layers;this.scenePass=new Ya(i,l,a,o),this.setupScenePassSettings(this.scenePass),this.scenePass.init(this.rt,this.sceneOptions);let h=e.sceneColorMap?e.lastGrabLayerId:e.lastSceneLayerId,f=e.sceneColorMap?e.lastGrabLayerIsTransparent:e.lastSceneLayerIsTransparent,u={lastAddedIndex:0,clearRenderTarget:!0};return u.lastAddedIndex=this.scenePass.addLayers(l,r,u.lastAddedIndex,u.clearRenderTarget,h,f),u.clearRenderTarget=!1,e.sceneColorMap&&(this.colorGrabPass=new wc(i),this.colorGrabPass.source=this.rt,this.scenePassTransparent=new Ya(i,l,a,o),this.setupScenePassSettings(this.scenePassTransparent),this.scenePassTransparent.init(this.rt),u.lastAddedIndex=this.scenePassTransparent.addLayers(l,r,u.lastAddedIndex,u.clearRenderTarget,e.lastSceneLayerId,e.lastSceneLayerIsTransparent),this.scenePassTransparent.rendersAnything||(this.scenePassTransparent.destroy(),this.scenePassTransparent=null),this.scenePassTransparent&&e.prepassEnabled&&(this.scenePassTransparent.depthStencilOps.storeDepth=!0)),u}setupSsaoPass(e){let{ssaoBlurEnabled:s,ssaoType:i}=e,{device:r,cameraComponent:a}=this;i!==cn&&(this.ssaoPass=new cg(r,this.sceneTexture,a,s))}setupSceneHalfPass(e,s){this._sceneHalfEnabled&&(this.scenePassHalf=new hn(this.device,this.sceneTexture,{boxFilter:!0,removeInvalid:!0}),this.scenePassHalf.name="RenderPassSceneHalf",this.scenePassHalf.init(this.rtHalf,{resizeSource:s,scaleX:.5,scaleY:.5}),this.scenePassHalf.setClearColor(F.BLACK))}setupBloomPass(e,s){this._bloomEnabled&&(this.bloomPass=new rg(this.device,s,this.hdrFormat))}setupDofPass(e,s,i){e.dofEnabled&&(this.dofPass=new ng(this.device,this.cameraComponent,s,i,e.dofHighQuality,e.dofNearBlur))}setupTaaPass(e){let s=this.sceneTexture;return e.taaEnabled&&(this.taaPass=new og(this.device,this.sceneTexture,this.cameraComponent),s=this.taaPass.historyTexture),s}setupComposePass(e){this.composePass=new ag(this.device),this.composePass.bloomTexture=this.bloomPass?.bloomTexture,this.composePass.hdrScene=this.hdrFormat!==ce,this.composePass.taaEnabled=e.taaEnabled,this.composePass.cocTexture=this.dofPass?.cocTexture,this.composePass.blurTexture=this.dofPass?.blurTexture,this.composePass.blurTextureUpscale=!this.dofPass?.highQuality;let i=this.cameraComponent.renderTarget;this.composePass.init(i),this.composePass.ssaoTexture=e.ssaoType===GA?this.ssaoPass.ssaoTexture:null}setupAfterPass(e,s){let{app:i,cameraComponent:r}=this,{scene:a,renderer:o}=i,l=a.layers,h=r.renderTarget;this.afterPass=new Ya(this.device,l,a,o),this.afterPass.init(h),this.afterPass.addLayers(l,r,s.lastAddedIndex,s.clearRenderTarget)}frameUpdate(){this.layersDirty&&this.cameraFrame.update(),super.frameUpdate();let e=this.taaPass?.update()??this.rt.colorBuffer;this.composePass.sceneTexture=e,this.scenePassHalf?.setSourceTexture(e)}};var WA=class{constructor(t,e){n(this,"_enabled",!0);n(this,"rendering",{renderFormats:[Gi,Me,ke],stencil:!1,renderTargetScale:1,samples:1,sceneColorMap:!1,sceneDepthMap:!1,toneMapping:0,sharpness:0});n(this,"ssao",{type:cn,blurEnabled:!0,randomize:!1,intensity:.5,radius:30,samples:12,power:6,minAngle:10,scale:1});n(this,"bloom",{intensity:0,blurLevel:16});n(this,"grading",{enabled:!1,brightness:1,contrast:1,saturation:1,tint:new F(1,1,1,1)});n(this,"colorLUT",{texture:null,intensity:1,texture2:null,intensity2:1,blend:0});n(this,"vignette",{intensity:0,inner:.5,outer:1,curvature:.5,color:new F(0,0,0)});n(this,"taa",{enabled:!1,jitter:1});n(this,"fringing",{intensity:0});n(this,"colorEnhance",{enabled:!1,shadows:0,highlights:0,vibrance:0,midtones:0,dehaze:0});n(this,"dof",{enabled:!1,nearBlur:!1,focusDistance:100,focusRange:10,blurRadius:3,blurRings:4,blurRingPoints:5,highQuality:!0});n(this,"debug",null);n(this,"options",new Wu);n(this,"renderPassCamera",null);this.app=t,this.cameraComponent=e,this.updateOptions(),this.enable(),this.cameraLayersChanged=e.on("set:layers",()=>{this.renderPassCamera&&(this.renderPassCamera.layersDirty=!0)})}destroy(){this.disable(),this.cameraLayersChanged.off()}enable(){this.renderPassCamera=this.createRenderPass(),this.cameraComponent.framePasses=[this.renderPassCamera]}disable(){let t=this.cameraComponent;t.framePasses?.forEach(e=>{e.destroy()}),t.framePasses=[],t.rendering=null,t.jitter=0,t.shaderParams.ssaoEnabled=!1,this.renderPassCamera=null}createRenderPass(){return new hg(this.app,this,this.cameraComponent,this.options)}set enabled(t){this._enabled!==t&&(t?this.enable():this.disable(),this._enabled=t)}get enabled(){return this._enabled}updateOptions(){let{options:t,rendering:e,bloom:s,taa:i,ssao:r}=this;t.stencil=e.stencil,t.samples=e.samples,t.sceneColorMap=e.sceneColorMap,t.prepassEnabled=e.sceneDepthMap,t.bloomEnabled=s.intensity>0,t.taaEnabled=i.enabled,t.ssaoType=r.type,t.ssaoBlurEnabled=r.blurEnabled,t.formats=e.renderFormats.slice(),t.dofEnabled=this.dof.enabled,t.dofNearBlur=this.dof.nearBlur,t.dofHighQuality=this.dof.highQuality}update(){if(!this._enabled)return;let t=this.cameraComponent,{options:e,renderPassCamera:s,rendering:i,bloom:r,grading:a,colorEnhance:o,vignette:l,fringing:h,taa:f,ssao:u}=this;this.updateOptions(),s.update(e);let{composePass:d,bloomPass:p,ssaoPass:m,dofPass:_}=s;s.renderTargetScale=R.clamp(i.renderTargetScale,.1,1),d.toneMapping=i.toneMapping,d.sharpness=i.sharpness,e.bloomEnabled&&p&&(d.bloomIntensity=r.intensity,p.blurLevel=r.blurLevel),e.dofEnabled&&(_.focusDistance=this.dof.focusDistance,_.focusRange=this.dof.focusRange,_.blurRadius=this.dof.blurRadius,_.blurRings=this.dof.blurRings,_.blurRingPoints=this.dof.blurRingPoints),e.ssaoType!==cn&&(m.intensity=u.intensity,m.power=u.power,m.radius=u.radius,m.sampleCount=u.samples,m.minAngle=u.minAngle,m.scale=u.scale,m.randomize=u.randomize),d.gradingEnabled=a.enabled,a.enabled&&(d.gradingSaturation=a.saturation,d.gradingBrightness=a.brightness,d.gradingContrast=a.contrast,d.gradingTint=a.tint),d.colorLUT=this.colorLUT.texture,d.colorLUTIntensity=this.colorLUT.intensity,d.colorLUT2=this.colorLUT.texture2,d.colorLUT2Intensity=this.colorLUT.intensity2,d.colorLUTBlend=this.colorLUT.blend,d.vignetteEnabled=l.intensity>0,d.vignetteEnabled&&(d.vignetteInner=l.inner,d.vignetteOuter=l.outer,d.vignetteCurvature=l.curvature,d.vignetteIntensity=l.intensity,d.vignetteColor.copy(l.color)),d.fringingEnabled=h.intensity>0,d.fringingEnabled&&(d.fringingIntensity=h.intensity),d.colorEnhanceEnabled=o.enabled,o.enabled&&(d.colorEnhanceShadows=o.shadows,d.colorEnhanceHighlights=o.highlights,d.colorEnhanceVibrance=o.vibrance,d.colorEnhanceMidtones=o.midtones,d.colorEnhanceDehaze=o.dehaze),t.jitter=f.enabled?f.jitter:0,d.debug=this.debug,d.debug==="ssao"&&e.ssaoType===cn&&(d.debug=null),d.debug==="vignette"&&!d.vignetteEnabled&&(d.debug=null)}};var R9=new x,b9=new $,ei=class c{constructor(t=x.ZERO,e=x.ZERO,s=0){n(this,"position",new x);n(this,"angles",new x);n(this,"distance",0);n(this,"pitchRange",new B(-1/0,1/0));n(this,"yawRange",new B(-1/0,1/0));n(this,"xRange",new B(-1/0,1/0));n(this,"yRange",new B(-1/0,1/0));n(this,"zRange",new B(-1/0,1/0));this.set(t,e,s)}copy(t){return this.set(t.position,t.angles,t.distance)}clone(){return new c(this.position.clone(),this.angles.clone(),this.distance)}equalsApprox(t,e=1e-6){return this.position.equalsApprox(t.position,e)&&this.angles.equalsApprox(t.angles,e)&&Math.abs(this.distance-t.distance){let c=new Map;return{down:t=>{c.set(t.pointerId,[t.screenX,t.screenY])},move:t=>{if(!c.has(t.pointerId))return[0,0];let e=c.get(t.pointerId),s=t.screenX-e[0],i=t.screenY-e[1];return e[0]=t.screenX,e[1]=t.screenY,[s,i]},up:t=>{c.delete(t.pointerId)}}};var Xu=new B,Yu=class{constructor({range:t}={}){n(this,"_range",70);n(this,"_position",new B);n(this,"_value",new B);this._range=t??this._range}get value(){return this._value}down(t,e){return this._position.set(t,e),this._value.set(0,0),[t,e,t,e]}move(t,e){Xu.set(t-this._position.x,e-this._position.y),Xu.length()>this._range&&Xu.normalize().mulScalar(this._range),this._value.set(R.clamp(Xu.x/this._range,-1,1),R.clamp(Xu.y/this._range,-1,1));let{x:s,y:i}=this._position;return[s,i,s+Xu.x,i+Xu.y]}up(){return this._position.set(0,0),this._value.set(0,0),[-1,-1,-1,-1]}};var XA=class extends cr{constructor(){super({input:[0,0],doubleTap:[0]});n(this,"_movementState",Mh());n(this,"_layout","joystick");n(this,"_pointerData",new Map);n(this,"_lastPointer",{x:0,y:0,time:0});n(this,"_joystick");this._joystick=new Yu,this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this)}set layout(e){this._layout!==e&&(this._layout=e,this.read(),this._pointerData.clear())}get layout(){return this._layout}get joystick(){return this._joystick}_onPointerDown(e){let{pointerType:s,pointerId:i,clientX:r,clientY:a}=e;if(this._movementState.down(e),s!=="touch")return;this._element?.setPointerCapture(i),this._pointerData.set(i,{x:r,y:a});let o=Date.now();(this._lastPointer.x-r)**2+(this._lastPointer.y-a)**2<100&&o-this._lastPointer.time<250&&this.deltas.doubleTap.append([1]),this._lastPointer.x=r,this._lastPointer.y=a,this._lastPointer.time=o,this._layout==="joystick"&&this.fire("joystick:position",this._joystick.down(r,a))}_onPointerMove(e){let{pointerType:s,pointerId:i,target:r,clientX:a,clientY:o}=e,[l,h]=this._movementState.move(e);if(s!=="touch"||r!==this._element)return;let f=this._pointerData.get(i);f&&(f.x=a,f.y=o,this._layout==="joystick"?this.fire("joystick:position",this._joystick.move(a,o)):this.deltas.input.append([l,h]))}_onPointerUp(e){let{pointerType:s,pointerId:i}=e;this._movementState.up(e),!(s!=="touch"||(this._element?.releasePointerCapture(i),!this._pointerData.get(i)))&&(this._pointerData.delete(i),this._layout==="joystick"&&this.fire("joystick:position",this._joystick.up()))}attach(e){super.attach(e),this._element=e,this._element.addEventListener("pointerdown",this._onPointerDown),this._element.addEventListener("pointermove",this._onPointerMove),this._element.addEventListener("pointerup",this._onPointerUp),this._element.addEventListener("pointercancel",this._onPointerUp)}detach(){this._element&&(this._element.removeEventListener("pointerdown",this._onPointerDown),this._element.removeEventListener("pointermove",this._onPointerMove),this._element.removeEventListener("pointerup",this._onPointerUp),this._element.removeEventListener("pointercancel",this._onPointerUp),this._pointerData.clear(),super.detach())}read(){return this.deltas.input.append([this._joystick.value.x,this._joystick.value.y]),super.read()}destroy(){this._joystick.up(),super.destroy()}};var Wb=(c,t)=>c.indexOf(t)===0,Xb=(c,t)=>c.indexOf(t,c.length-t.length)!==-1,YA=class extends cr{constructor(e){super({leftInput:[0,0],rightInput:[0,0],doubleTap:[0]});n(this,"_movementState",Mh());n(this,"_layout","joystick-touch");n(this,"_pointerData",new Map);n(this,"_lastPointer",{x:0,y:0,time:0});n(this,"_leftJoystick");n(this,"_rightJoystick");e&&(this.layout=e),this._leftJoystick=new Yu,this._rightJoystick=new Yu,this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this)}set layout(e){this._layout!==e&&(this._layout=e,this.read(),this._pointerData.clear())}get layout(){return this._layout}get leftJoystick(){return this._leftJoystick}get rightJoystick(){return this._rightJoystick}_onPointerDown(e){let{pointerType:s,pointerId:i,clientX:r,clientY:a}=e;if(this._movementState.down(e),s!=="touch")return;this._element?.setPointerCapture(i);let o=r1&&(this._getMidPoint(this._pointerPos),this._pinchDist=this._getPinchDist()))}_onPointerMove(e){let{pointerType:s,target:i,pointerId:r}=e,[a,o]=this._movementState.move(e);if(s==="touch"&&i===this._element&&this._pointerEvents.size!==0)if(this._pointerEvents.set(r,e),this._pointerEvents.size>1){let l=this._getMidPoint(M9);this.deltas.touch.append([l.x-this._pointerPos.x,l.y-this._pointerPos.y]),this._pointerPos.copy(l);let h=this._getPinchDist();this._pinchDist>0&&this.deltas.pinch.append([this._pinchDist-h]),this._pinchDist=h}else this.deltas.touch.append([a,o])}_onPointerUp(e){let{pointerType:s,pointerId:i}=e;this._movementState.up(e),s==="touch"&&(this._element?.releasePointerCapture(i),this._pointerEvents.delete(i),this.deltas.count.append([-1]),this._pointerEvents.size<2&&(this._pinchDist=-1),this._pointerPos.set(0,0))}_onContextMenu(e){e.preventDefault()}_getMidPoint(e){if(this._pointerEvents.size<2)return e.set(0,0);let[s,i]=this._pointerEvents.values(),r=s.clientX-i.clientX,a=s.clientY-i.clientY;return e.set(i.clientX+r*.5,i.clientY+a*.5)}_getPinchDist(){if(this._pointerEvents.size<2)return 0;let[e,s]=this._pointerEvents.values(),i=e.clientX-s.clientX,r=e.clientY-s.clientY;return Math.sqrt(i*i+r*r)}attach(e){super.attach(e),this._element=e,this._element.addEventListener("pointerdown",this._onPointerDown),this._element.addEventListener("pointermove",this._onPointerMove),this._element.addEventListener("pointerup",this._onPointerUp),this._element.addEventListener("pointercancel",this._onPointerUp),this._element.addEventListener("contextmenu",this._onContextMenu)}detach(){this._element&&(this._element.removeEventListener("pointerdown",this._onPointerDown),this._element.removeEventListener("pointermove",this._onPointerMove),this._element.removeEventListener("pointerup",this._onPointerUp),this._element.removeEventListener("pointercancel",this._onPointerUp),this._element.removeEventListener("contextmenu",this._onContextMenu),this._pointerEvents.clear(),super.detach())}};var fH={passive:!1},uH={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,0:26,1:27,2:28,3:29,4:30,5:31,6:32,7:33,8:34,9:35,UP:36,DOWN:37,LEFT:38,RIGHT:39,SPACE:40,SHIFT:41,CTRL:42},jA=Object.keys(uH).length,Yb=Array(jA).fill(0),$A=class $A extends cr{constructor({pointerLock:e=!1}={}){super({key:Array(jA).fill(0),button:[0,0,0],mouse:[0,0],wheel:[0]});n(this,"_movementState",Mh());n(this,"_pointerId",-1);n(this,"_pointerLock");n(this,"_keyMap",new Map);n(this,"_keyPrev",Array(jA).fill(0));n(this,"_keyNow",Array(jA).fill(0));n(this,"_button",Array(3).fill(0));this._pointerLock=e??!1;let{keyCode:s}=$A;for(let i=0;i<26;i++){let r=`Key${String.fromCharCode(65+i)}`;this._keyMap.set(r,s.A+i)}for(let i=0;i<10;i++){let r=`Digit${i}`;this._keyMap.set(r,s[0]+i)}this._keyMap.set("ArrowUp",s.UP),this._keyMap.set("ArrowDown",s.DOWN),this._keyMap.set("ArrowLeft",s.LEFT),this._keyMap.set("ArrowRight",s.RIGHT),this._keyMap.set("Space",s.SPACE),this._keyMap.set("ShiftLeft",s.SHIFT),this._keyMap.set("ShiftRight",s.SHIFT),this._keyMap.set("ControlLeft",s.CTRL),this._keyMap.set("ControlRight",s.CTRL),this._onWheel=this._onWheel.bind(this),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onKeyUp=this._onKeyUp.bind(this)}_onWheel(e){e.preventDefault(),this.deltas.wheel.append([e.deltaY])}_onPointerDown(e){this._movementState.down(e),e.pointerType==="mouse"&&(this._pointerLock?document.pointerLockElement!==this._element&&this._element?.requestPointerLock():this._element?.setPointerCapture(e.pointerId),this._clearButtons(),this._button[e.button]=1,this.deltas.button.append(this._button),this._pointerId===-1&&(this._pointerId=e.pointerId))}_onPointerMove(e){let[s,i]=this._pointerLock&&document.pointerLockElement===this._element?[e.movementX,e.movementY]:this._movementState.move(e);if(e.pointerType==="mouse"&&e.target===this._element){if(this._pointerLock){if(document.pointerLockElement!==this._element)return}else if(this._pointerId!==e.pointerId)return;this.deltas.mouse.append([s,i])}}_onPointerUp(e){this._movementState.up(e),e.pointerType==="mouse"&&(this._pointerLock||this._element?.releasePointerCapture(e.pointerId),this._clearButtons(),this.deltas.button.append(this._button),this._pointerId===e.pointerId&&(this._pointerId=-1))}_onContextMenu(e){e.preventDefault()}_onKeyDown(e){this._pointerLock&&document.pointerLockElement!==this._element||(e.stopPropagation(),this._setKey(e.code,1))}_onKeyUp(e){e.stopPropagation(),this._setKey(e.code,0)}_clearButtons(){for(let e=0;e1-Math.pow(c,t*1e3);var yx=new x,O9=new x,pH=new x,mH=new x,_H=new x,ZA=new $,QA=class extends fn{constructor(){super(...arguments);n(this,"_targetPose",new ei);n(this,"rotateDamping",.98);n(this,"moveDamping",.98)}set pitchRange(e){this._targetPose.pitchRange.copy(e),this._pose.copy(this._targetPose.rotate(x.ZERO))}get pitchRange(){return this._targetPose.pitchRange}set yawRange(e){this._targetPose.yawRange.copy(e),this._pose.copy(this._targetPose.rotate(x.ZERO))}get yawRange(){return this._targetPose.yawRange}attach(e,s=!0){this._targetPose.copy(e),s||this._pose.copy(this._targetPose)}detach(){this._targetPose.copy(this._pose)}update(e,s){let{move:i,rotate:r}=e.read();return this._targetPose.rotate(O9.set(-r[1],-r[0],0)),ZA.setFromEulerAngles(this._pose.angles),ZA.transformVector(x.FORWARD,pH),ZA.transformVector(x.RIGHT,mH),ZA.transformVector(x.UP,_H),yx.set(0,0,0),yx.add(pH.mulScalar(i[2])),yx.add(mH.mulScalar(i[0])),yx.add(_H.mulScalar(i[1])),this._targetPose.move(yx),this._pose.lerp(this._pose,this._targetPose,co(this.moveDamping,s),co(this.rotateDamping,s))}destroy(){this.detach()}};var F9=new x,Ku=new x,N9=new x,gH=new $,JA=class extends fn{constructor(){super(...arguments);n(this,"_targetRootPose",new ei);n(this,"_rootPose",new ei);n(this,"_targetChildPose",new ei);n(this,"_childPose",new ei);n(this,"rotateDamping",.98);n(this,"moveDamping",.98);n(this,"zoomDamping",.98)}set pitchRange(e){this._targetRootPose.pitchRange.copy(e),this._rootPose.copy(this._targetRootPose.rotate(x.ZERO))}get pitchRange(){return this._targetRootPose.pitchRange}set yawRange(e){this._targetRootPose.yawRange.copy(e),this._rootPose.copy(this._targetRootPose.rotate(x.ZERO))}get yawRange(){return this._targetRootPose.yawRange}set zoomRange(e){this._targetChildPose.zRange.copy(e),this._childPose.copy(this._targetChildPose.move(x.ZERO))}get zoomRange(){return this._targetRootPose.zRange}attach(e,s=!0){this._targetRootPose.set(e.getFocus(F9),e.angles,0),this._targetChildPose.position.set(0,0,e.distance),s||(this._rootPose.copy(this._targetRootPose),this._childPose.copy(this._targetChildPose))}detach(){this._targetRootPose.copy(this._rootPose),this._targetChildPose.copy(this._childPose)}update(e,s){let{move:i,rotate:r}=e.read();Ku.set(i[0],i[1],0),gH.setFromEulerAngles(this._rootPose.angles).transformVector(Ku,Ku),this._targetRootPose.move(Ku);let{z:a}=this._targetChildPose.position;return this._targetChildPose.move(Ku.set(0,0,a*(1+i[2])-a)),this._targetRootPose.rotate(N9.set(-r[1],-r[0],0)),this._rootPose.lerp(this._rootPose,this._targetRootPose,co(this.moveDamping,s),co(this.rotateDamping,s),1),this._childPose.lerp(this._childPose,this._targetChildPose,co(this.zoomDamping,s),1,1),gH.setFromEulerAngles(this._rootPose.angles).transformVector(this._childPose.position,Ku).add(this._rootPose.position),this._pose.set(Ku,this._rootPose.angles,this._childPose.position.z)}destroy(){this.detach()}};var SH=.001,B9=new x,xH=new x,U9=new $,eC=class extends fn{constructor(){super(...arguments);n(this,"_targetRootPose",new ei);n(this,"_rootPose",new ei);n(this,"_targetChildPose",new ei);n(this,"_childPose",new ei);n(this,"focusDamping",.98)}attach(e,s=!0){this._targetRootPose.set(e.getFocus(B9),e.angles,0),this._targetChildPose.position.set(0,0,e.distance),s||(this._rootPose.copy(this._targetRootPose),this._childPose.copy(this._targetChildPose))}detach(){this._targetRootPose.copy(this._rootPose),this._targetChildPose.copy(this._childPose)}complete(){return this._targetRootPose.equalsApprox(this._rootPose,SH)&&this._targetChildPose.equalsApprox(this._childPose,SH)}update(e,s){return e.read(),this._rootPose.lerp(this._rootPose,this._targetRootPose,co(this.focusDamping,s),co(this.focusDamping,s),1),this._childPose.lerp(this._childPose,this._targetChildPose,co(this.focusDamping,s),1,1),U9.setFromEulerAngles(this._rootPose.angles).transformVector(this._childPose.position,xH).add(this._rootPose.position),this._pose.set(xH,this._rootPose.angles,this._childPose.position.length())}destroy(){this.detach()}};var vH="local",TH="world",yH="x",EH="y",AH="z",CH="yz",PH="xz",wH="xy",IH="xyz",RH="face";var tC=new x,ju=new x,jb=new x,Ex=new $,k9=new W,z9=new W,sC=new ws,G9=1e-4,V9=.3,H9=.32,qb=1e-6,W9=1e-4,As=class As extends J{constructor(e,s,i="gizmo"){super();n(this,"_size",1);n(this,"_scale",1);n(this,"_coordSpace","world");n(this,"_app");n(this,"_device");n(this,"_handles",[]);n(this,"_mouseButtons",[!0,!0,!0]);n(this,"_camera");n(this,"_layer");n(this,"_renderUpdate",!1);n(this,"nodes",[]);n(this,"root");n(this,"intersectShapes",[]);n(this,"preventDefault",!0);this._layer=s,this._camera=e,this._camera.layers=this._camera.layers.concat(this._layer.id),this._app=this._camera.system.app,this._device=this._app.graphicsDevice,this.root=new Ne(i),this._app.root.addChild(this.root),this.root.enabled=!1,this._updateScale(),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._device.canvas.addEventListener("pointerdown",this._onPointerDown),this._device.canvas.addEventListener("pointermove",this._onPointerMove),this._device.canvas.addEventListener("pointerup",this._onPointerUp),this._handles.push(this._app.on("prerender",()=>this.prerender())),this._handles.push(this._app.on("update",()=>this.update())),this._handles.push(this._app.on("destroy",()=>this.destroy()))}static createLayer(e,s="Gizmo",i=e.scene.layers.layerList.length){let r=new Dt({name:s,clearDepthBuffer:!0,opaqueSortMode:Ho,transparentSortMode:Ho});return e.scene.layers.insert(r,i),r}set enabled(e){let s=this.root.getLocalPosition().distance(this.camera.entity.getPosition()),i=e?this.nodes.length>0&&s>W9:!1;i!==this.root.enabled&&(this.root.enabled=i,this._renderUpdate=!0)}get enabled(){return this.root.enabled}get mouseButtons(){return this._mouseButtons}set layer(e){this._layer!==e&&(this._camera.layers=this._camera.layers.filter(s=>s!==this._layer.id),this._layer=e,this._camera.layers=this._camera.layers.concat(this._layer.id),this.enabled=!0)}get layer(){return this._layer}set camera(e){this._camera!==e&&(this._camera.layers=this._camera.layers.filter(s=>s!==this._layer.id),this._camera=e,this._camera.layers=this._camera.layers.concat(this._layer.id),this.enabled=!0)}get camera(){return this._camera}set coordSpace(e){this._coordSpace=e??this._coordSpace,this._updateRotation()}get coordSpace(){return this._coordSpace}set size(e){this._size=e,this._updateScale()}get size(){return this._size}get facingDir(){if(this._camera.projection===ts){let e=this.root.getLocalPosition(),s=this._camera.entity.getPosition();return jb.sub2(s,e).normalize()}return jb.copy(this._camera.entity.forward).mulScalar(-1)}get cameraDir(){let e=this._camera.entity.getPosition(),s=this.root.getLocalPosition();return jb.sub2(e,s).normalize()}_onPointerDown(e){if(!this.enabled||document.pointerLockElement||!this.mouseButtons[e.button])return;let s=this._getSelection(e.offsetX,e.offsetY);s[0]&&(this.preventDefault&&e.preventDefault(),e.stopPropagation());let{canvas:i}=this._device;i.setPointerCapture(e.pointerId),this.fire(As.EVENT_POINTERDOWN,e.offsetX,e.offsetY,s[0])}_onPointerMove(e){if(!this.enabled||document.pointerLockElement)return;let s=this._getSelection(e.offsetX,e.offsetY);s[0]&&(this.preventDefault&&e.preventDefault(),e.stopPropagation()),this.fire(As.EVENT_POINTERMOVE,e.offsetX,e.offsetY,s[0])}_onPointerUp(e){if(!this.enabled||document.pointerLockElement||!this.mouseButtons[e.button])return;let s=this._getSelection(e.offsetX,e.offsetY);s[0]&&(this.preventDefault&&e.preventDefault(),e.stopPropagation());let{canvas:i}=this._device;i.releasePointerCapture(e.pointerId),this.fire(As.EVENT_POINTERUP,e.offsetX,e.offsetY,s[0])}_updatePosition(){if(ju.set(0,0,0),this._coordSpace==="local")ju.copy(this.nodes[this.nodes.length-1].getPosition());else{for(let e=0;el.priority!==0&&h.priority!==0?h.priority-l.priority:l.dist-h.dist),o[0].meshInstances):[]}attach(e=[]){if(Array.isArray(e)){if(e.length===0)return;this.nodes=e}else this.nodes=[e];this._updatePosition(),this._updateRotation(),this._updateScale(),this.fire(As.EVENT_NODESATTACH),this.enabled=!0}detach(){this.enabled=!1,this.fire(As.EVENT_NODESDETACH),this.nodes=[]}prerender(){}update(){this._renderUpdate&&(this._renderUpdate=!1,this.fire(As.EVENT_RENDERUPDATE)),this.enabled&&(this._updatePosition(),this._updateRotation(),this._updateScale())}destroy(){this.detach(),this._device.canvas.removeEventListener("pointerdown",this._onPointerDown),this._device.canvas.removeEventListener("pointermove",this._onPointerMove),this._device.canvas.removeEventListener("pointerup",this._onPointerUp),this._handles.forEach(e=>e.off()),this.root.destroy()}};n(As,"EVENT_POINTERDOWN","pointer:down"),n(As,"EVENT_POINTERMOVE","pointer:move"),n(As,"EVENT_POINTERUP","pointer:up"),n(As,"EVENT_POSITIONUPDATE","position:update"),n(As,"EVENT_ROTATIONUPDATE","rotation:update"),n(As,"EVENT_SCALEUPDATE","scale:update"),n(As,"EVENT_NODESATTACH","nodes:attach"),n(As,"EVENT_NODESDETACH","nodes:detach"),n(As,"EVENT_RENDERUPDATE","render:update");var ho=As;var fg=Object.freeze(new F(1,.3,.3)),ug=Object.freeze(new F(.3,1,.3)),dg=Object.freeze(new F(.3,.3,1)),Zpt=Object.freeze(new F(1,1,.5)),iC=Object.freeze(new F(.5,.5,.5,.5)),Bl=(c,t)=>new F(c.r,c.g,c.b,t);var Oh=new x,$b=new x,Zb=new x,qu=new ws,bH=new go,X9=new F,Y9=["x","y","z"],Fh=class Fh extends ho{constructor(e,s,i="gizmo:transform"){super(e,s,i);n(this,"_theme",{shapeBase:{x:fg.clone(),y:ug.clone(),z:dg.clone(),xyz:new F(.8,.8,.8,1),f:new F(.8,.8,.8,1)},shapeHover:{x:new F().lerp(fg,F.WHITE,.75),y:new F().lerp(ug,F.WHITE,.75),z:new F().lerp(dg,F.WHITE,.75),xyz:F.WHITE.clone(),f:F.WHITE.clone()},guideBase:{x:fg.clone(),y:ug.clone(),z:dg.clone()},guideOcclusion:.8,disabled:iC.clone()});n(this,"_rootStartPos",new x);n(this,"_rootStartRot",new $);n(this,"_shapes",{});n(this,"_shapeMap",new Map);n(this,"_hovering",new Set);n(this,"_hoverAxis","");n(this,"_hoverIsPlane",!1);n(this,"_selectedAxis","");n(this,"_selectedIsPlane",!1);n(this,"_selectionStartPoint",new x);n(this,"snap",!1);n(this,"snapIncrement",1);n(this,"dragMode","selected");this.on(ho.EVENT_POINTERDOWN,(r,a,o)=>{if(this._shapeMap.get(o)?.disabled||this._dragging||!o)return;this._hoverAxis="",this._hoverIsPlane=!1,this._selectedAxis=this._getAxis(o),this._selectedIsPlane=this._getIsPlane(o),this._rootStartPos.copy(this.root.getLocalPosition()),this._rootStartRot.copy(this.root.getRotation());let h=this._screenToPoint(r,a);this._selectionStartPoint.copy(h),this.fire(Fh.EVENT_TRANSFORMSTART,h,r,a)}),this.on(ho.EVENT_POINTERMOVE,(r,a,o)=>{if(this._shapeMap.get(o)?.disabled||(this._hover(o),!this._dragging))return;let h=this._screenToPoint(r,a);this.fire(Fh.EVENT_TRANSFORMMOVE,h,r,a)}),this.on(ho.EVENT_POINTERUP,(r,a,o)=>{this._hover(o),this._dragging&&(o&&(this._hoverAxis=this._selectedAxis,this._hoverIsPlane=this._selectedIsPlane),this._selectedAxis="",this._selectedIsPlane=!1,this.fire(Fh.EVENT_TRANSFORMEND))}),this.on(ho.EVENT_NODESDETACH,()=>{this._hoverAxis="",this._hoverIsPlane=!1,this._hover(),this.fire(ho.EVENT_POINTERUP)})}get theme(){return this._theme}set xAxisColor(e){this.setTheme({shapeBase:{x:e},shapeHover:{x:Bl(e,this.colorAlpha)},guideBase:{x:e},guideOcclusion:1})}get xAxisColor(){return this._theme.shapeBase.x}set yAxisColor(e){this.setTheme({shapeBase:{y:e},shapeHover:{y:Bl(e,this.colorAlpha)},guideBase:{y:e},guideOcclusion:1})}get yAxisColor(){return this._theme.shapeBase.y}set zAxisColor(e){this.setTheme({shapeBase:{z:e},shapeHover:{z:Bl(e,this.colorAlpha)},guideBase:{z:e},guideOcclusion:1})}get zAxisColor(){return this._theme.shapeBase.z}set colorAlpha(e){this.setTheme({shapeHover:{x:Bl(this._theme.shapeHover.x,e),y:Bl(this._theme.shapeHover.y,e),z:Bl(this._theme.shapeHover.z,e),xyz:Bl(this._theme.shapeHover.xyz,e),f:Bl(this._theme.shapeHover.f,e)}})}get colorAlpha(){return(this._theme.shapeHover.x.a+this._theme.shapeHover.y.a+this._theme.shapeHover.z.a+this._theme.shapeHover.xyz.a+this._theme.shapeHover.f.a)/5}get _dragging(){return!this._hoverAxis&&!!this._selectedAxis}_getAxis(e){return e?e.node.name.split(":")[1]:""}_getIsPlane(e){return e?e.node.name.indexOf("plane")!==-1:!1}_hover(e){if(this._dragging)return;let s=new Set(this._hovering),i=!1,r=a=>{s.has(a)?s.delete(a):(this._hovering.add(a),this._shapes[a]?.hover(!0),i=!0)};if(this._hoverAxis=this._getAxis(e),this._hoverIsPlane=this._getIsPlane(e),this._hoverAxis)if(this._hoverAxis==="xyz")r("x"),r("y"),r("z"),r("xyz");else if(this._hoverIsPlane)switch(this._hoverAxis){case"x":r("y"),r("z"),r("yz");break;case"y":r("x"),r("z"),r("xz");break;case"z":r("x"),r("y"),r("xy");break}else r(this._hoverAxis);for(let a of s)this._hovering.delete(a),this._shapes[a]?.hover(!1),i=!0;i&&(this._renderUpdate=!0)}_createRay(e){if(this._camera.projection===ts)return qu.origin.copy(this._camera.entity.getPosition()),qu.direction.sub2(e,qu.origin).normalize(),qu;let s=this._camera.farClip-this._camera.nearClip;return qu.origin.sub2(e,Oh.copy(this._camera.entity.forward).mulScalar(s)),qu.direction.copy(this._camera.entity.forward),qu}_createPlane(e,s,i){let r=Oh.copy(this.facingDir),a=bH.normal.set(0,0,0);return s?a.copy(this._camera.entity.forward).mulScalar(-1):(a[e]=1,this._rootStartRot.transformVector(a,a),i&&($b.cross(a,r).normalize(),a.cross($b,a).normalize())),bH.setFromPointNormal(this._rootStartPos,a)}_dirFromAxis(e,s){return e==="f"?s.copy(this._camera.entity.forward).mulScalar(-1):(s.set(0,0,0),s[e]=1),s}_projectToAxis(e,s){Oh.set(0,0,0),Oh[s]=1,e.copy(Oh.mulScalar(Oh.dot(e)));let i=e[s];e.set(0,0,0),e[s]=i}_screenToPoint(e,s,i=!1,r=!1){let a=this._camera.screenToWorld(e,s,1),o=this._selectedAxis,l=this._createRay(a);return this._createPlane(o,i,r).intersectsRay(l,Zb),Zb}_drawGuideLines(e,s,i,r){for(let a of Y9){if(i==="xyz"){this._drawSpanLine(e,s,a);continue}r?a!==i&&this._drawSpanLine(e,s,a):a===i&&this._drawSpanLine(e,s,a)}}_drawSpanLine(e,s,i){let r=this._dirFromAxis(i,Oh),a=this._theme.guideBase[i],o=Oh.copy(r).mulScalar(this._camera.farClip-this._camera.nearClip),l=$b.copy(o).mulScalar(-1);if(s.transformVector(o,o).add(e),s.transformVector(l,l).add(e),this._theme.guideOcclusion<1){let h=X9.copy(a);h.a*=1-this._theme.guideOcclusion,this._app.drawLine(o,l,h,!1,this._layer)}a.a!==0&&this._app.drawLine(o,l,a,!0)}_createTransform(){for(let e in this._shapes){let s=this._shapes[e];this.root.addChild(s.entity),this.intersectShapes.push(s);for(let i=0;i FragmentOutput { #endif return output; } - `},CY=new c4;CY.positions=[],CY.normals=[];class Cq{set disabled(e){this._disabled=e??false,this.hover(false);}get disabled(){return this._disabled}set visible(e){if(e!==this._visible){for(let t=0;t0?"1":"0"),this._material.setParameter("uDepth",this._depth),this._material.setParameter("uColor",i.toArray()),this._material.cull=this._cull,this._material.blendType=2,this._material.update();let s=[];for(let e=0;ethis._flipped.distance(e)||(this._flipped.copy(e),this._update());}get flipped(){return this._flipped}_update(){let e=this._size/2+this._gap;this._position.set(this._flipped.x?-e:e,this._flipped.y?-e:e,this._flipped.z?-e:e),this._position[this.axis]=0,this.entity.setLocalPosition(this._position),this.entity.setLocalEulerAngles(this._rotation),this.entity.setLocalScale(this._size,this._size,this._size);}constructor(e,t={}){super(e,"plane",t),this._cull=0,this._size=.16,this._gap=0,this._flipped=new ed,this._size=t.size??this._size,this._gap=t.gap??this._gap,this.triData=[new CW(new uw)],this._createRenderComponent(this.entity,[on.fromGeometry(this.device,new uw)]),this._update();}}let CK=new ed,C$=new ed,CZ=new ex;class CQ extends Cq{set gap(e){this._gap=e??this._gap,this._update();}get gap(){return this._gap}set lineThickness(e){this._lineThickness=e??this._lineThickness,this._update();}get lineThickness(){return this._lineThickness}set lineLength(e){this._lineLength=e??this._lineLength,this._update();}get lineLength(){return this._lineLength}set arrowThickness(e){this._arrowThickness=e??this._arrowThickness,this._update();}get arrowThickness(){return this._arrowThickness}set arrowLength(e){this._arrowLength=e??this._arrowLength,this._update();}get arrowLength(){return this._arrowLength}set tolerance(e){this._tolerance=e,this._update();}get tolerance(){return this._tolerance}_update(){CK.set(0,this._gap+.5*this._arrowLength+this._lineLength,0),CZ.set(0,0,0,1),C$.set(this._arrowThickness,this._arrowLength,this._arrowThickness),this.triData[0].setTransform(CK,CZ,C$),CK.set(0,this._gap+.5*this._lineLength,0),CZ.set(0,0,0,1),C$.set(this._lineThickness+this._tolerance,this._lineLength,this._lineThickness+this._tolerance),this.triData[1].setTransform(CK,CZ,C$),this._head.setLocalPosition(0,this._gap+.5*this._arrowLength+this._lineLength,0),this._head.setLocalScale(this._arrowThickness,this._arrowLength,this._arrowThickness),this._line.setLocalPosition(0,this._gap+.5*this._lineLength,0),this._line.setLocalScale(this._lineThickness,this._lineLength,this._lineThickness);}constructor(e,t={}){super(e,"arrow",t),this._gap=0,this._lineThickness=.02,this._lineLength=.5,this._arrowThickness=.12,this._arrowLength=.18,this._tolerance=.1,this._gap=t.gap??this._gap,this._lineThickness=t.lineThickness??this._lineThickness,this._lineLength=t.lineLength??this._lineLength,this._arrowThickness=t.arrowThickness??this._arrowThickness,this._arrowLength=t.arrowLength??this._arrowLength,this._tolerance=t.tolerance??this._tolerance,this.triData=[new CW(new uT),new CW(new uE,1)],this._head=new f9(`head:${this.axis}`),this.entity.addChild(this._head),this._createRenderComponent(this._head,[on.fromGeometry(this.device,new uT)]),this._line=new f9(`line:${this.axis}`),this.entity.addChild(this._line),this._createRenderComponent(this._line,[on.fromGeometry(this.device,new uE)]),this._update();}}class CJ extends Cq{set radius(e){this._radius=e??this._radius,this._update();}get radius(){return this._radius}_update(){let e=2*this._radius;this.entity.setLocalScale(e,e,e);}constructor(e,t={}){super(e,"sphereCenter",t),this._radius=.03,this._radius=t.radius??this._radius,this.triData=[new CW(new c6,2)],this._createRenderComponent(this.entity,[on.fromGeometry(this.device,new c6({latitudeBands:32,longitudeBands:32}))]),this._update();}}let C0=new ed,C1=new ed,C2=new ed,C3=new ed,C4=new ex,C5=["x","y","z"];class C6 extends Cq{_createTorusGeometry(e){return new ub({tubeRadius:this._tubeRadius+this._tolerance,ringRadius:this._ringRadius,sectorAngle:e,segments:20})}_createTorusMesh(e){let t=new ub({tubeRadius:this._tubeRadius,ringRadius:this._ringRadius,sectorAngle:e,segments:80});return on.fromGeometry(this.device,t)}set tubeRadius(e){this._tubeRadius=e??this._tubeRadius,this._update();}get tubeRadius(){return this._tubeRadius}set ringRadius(e){this._ringRadius=e??this._ringRadius,this._update();}get ringRadius(){return this._ringRadius}set tolerance(e){this._tolerance=e??this._tolerance,this._update();}get tolerance(){return this._tolerance}_update(){this._triDataCache[0].fromGeometry(this._createTorusGeometry(this._sectorAngle)),this._triDataCache[1].fromGeometry(this._createTorusGeometry(360)),this.meshInstances[0].mesh=this._createTorusMesh(this._sectorAngle),this.meshInstances[1].mesh=this._createTorusMesh(360);}show(e){switch(e){case "sector":this.triData[0]=this._triDataCache[0],this.meshInstances[0].visible=true,this.meshInstances[1].visible=false;break;case "ring":this.triData[0]=this._triDataCache[1],this.meshInstances[0].visible=false,this.meshInstances[1].visible=true;break;case "none":this.meshInstances[0].visible=false,this.meshInstances[1].visible=false;}}constructor(e,t={}){super(e,"disk",t),this._tubeRadius=.01,this._ringRadius=.5,this._sectorAngle=360,this._tolerance=.05,this._tubeRadius=t.tubeRadius??this._tubeRadius,this._ringRadius=t.ringRadius??this._ringRadius,this._sectorAngle=t.sectorAngle??this._sectorAngle,this._triDataCache=[new CW(this._createTorusGeometry(this._sectorAngle)),new CW(this._createTorusGeometry(360))],this.triData=[this._triDataCache[0]],this._createRenderComponent(this.entity,[this._createTorusMesh(this._sectorAngle),this._createTorusMesh(360)]),this.show("sector"),this._update();}}let C8=new ed;class C9{set thickness(e){this._thickness=e??this._thickness;}get thickness(){return this._thickness}draw(e,t,i,s){this._material.setParameter("uColor",s.toArray());let r=C8.sub2(t,e).normalize(),a=Math.atan2(-r.y,Math.sqrt(r.x*r.x+r.z*r.z))*ei.RAD_TO_DEG,n=Math.atan2(-r.x,-r.z)*ei.RAD_TO_DEG;this.entity.setLocalEulerAngles(-a+90,n,0);let o=e.distance(t)*i;this.entity.setLocalPosition(r.mulScalar(.5*o).add(e)),this.entity.setLocalScale(this._thickness*i,o,this._thickness*i);}destroy(){this._material.destroy(),this.entity.destroy();}constructor(e,t,i={}){this._thickness=.02,this._material=new cT(CX),this.entity=new f9("mesh-line"),this._thickness=i.thickness??this._thickness,this._material.blendState=iy.ALPHABLEND,this._material.setDefine("DEPTH_WRITE","1"),this._material.setParameter("uDepth",0),this._material.update();let s=new oS(on.fromGeometry(e.graphicsDevice,new uE),this._material);this.entity.addComponent("render",{meshInstances:[s],layers:[t.id]});}}let C7=new ed,Ae=new ed,At=new ed,Ai=new ed,As=new ex,Ar=new ex,Aa=new es,An=["x","y","z"];class Ao extends Cq{set size(e){this._size=e??this._size,this._update();}get size(){return this._size}_update(){this.entity.setLocalScale(this._size,this._size,this._size);}constructor(e,t={}){super(e,"boxCenter",t),this._size=.06,this._size=t.size??this._size,this.triData=[new CW(new c5,2)],this._createRenderComponent(this.entity,[on.fromGeometry(this.device,new c5)]),this._update();}}let Al=new ed,Ah=new ed,Ac=new ex;class Ad extends Cq{set gap(e){this._gap=e??this._gap,this._update();}get gap(){return this._gap}set lineThickness(e){this._lineThickness=e??this._lineThickness,this._update();}get lineThickness(){return this._lineThickness}set lineLength(e){this._lineLength=e??this._lineLength,this._update();}get lineLength(){return this._lineLength}set boxSize(e){this._boxSize=e??this._boxSize,this._update();}get boxSize(){return this._boxSize}set tolerance(e){this._tolerance=e,this._update();}get tolerance(){return this._tolerance}set flipped(e){this._flipped!==e&&(this._flipped=e,this._rotation.equals(ed.ZERO)?Al.set(0,0,180*!!this._flipped):Al.copy(this._rotation).mulScalar(this._flipped?-1:1),this._line.enabled=!this._flipped,this.entity.setLocalEulerAngles(Al));}get flipped(){return this._flipped}_update(){Al.set(0,this._gap+.5*this._boxSize+this._lineLength,0),Ac.set(0,0,0,1),Ah.set(this._boxSize,this._boxSize,this._boxSize),this.triData[0].setTransform(Al,Ac,Ah),Al.set(0,this._gap+.5*this._lineLength,0),Ac.set(0,0,0,1),Ah.set(this._lineThickness+this._tolerance,this._lineLength,this._lineThickness+this._tolerance),this.triData[1].setTransform(Al,Ac,Ah),this._box.setLocalPosition(0,this._gap+.5*this._boxSize+this._lineLength,0),this._box.setLocalScale(this._boxSize,this._boxSize,this._boxSize),this._line.setLocalPosition(0,this._gap+.5*this._lineLength,0),this._line.setLocalScale(this._lineThickness,this._lineLength,this._lineThickness);}constructor(e,t={}){super(e,"boxLine",t),this._gap=0,this._lineThickness=.02,this._lineLength=.5,this._boxSize=.12,this._tolerance=.1,this._flipped=false,this._gap=t.gap??this._gap,this._lineThickness=t.lineThickness??this._lineThickness,this._lineLength=t.lineLength??this._lineLength,this._boxSize=t.boxSize??this._boxSize,this._tolerance=t.tolerance??this._tolerance,this.triData=[new CW(new c5),new CW(new uE,1)],this._box=new f9(`box:${this.axis}`),this.entity.addChild(this._box),this._createRenderComponent(this._box,[on.fromGeometry(this.device,new c5)]),this._line=new f9(`line:${this.axis}`),this.entity.addChild(this._line),this._createRenderComponent(this._line,[on.fromGeometry(this.device,new uE)]),this._update();}}let Au=new ed,Af=new ed,Ap=new ed,Am=new ed,A_=new ex,Ag=new ed,Av=new ed,AS=new ed,Ay=new ey;class Ax extends X{set anchor(e){this._anchor.copy(e),this.dom.style.top=this._anchor.x?"0px":"auto",this.dom.style.right=this._anchor.y?"0px":"auto",this.dom.style.bottom=this._anchor.z?"0px":"auto",this.dom.style.left=this._anchor.w?"0px":"auto";}get anchor(){return this._anchor}set colorX(e){this._colorX.copy(e),this._shapes.px.children[0].setAttribute("fill",this._colorX.toString(false)),this._shapes.px.children[0].setAttribute("stroke",this._colorX.toString(false)),this._shapes.nx.children[0].setAttribute("stroke",this._colorX.toString(false)),this._shapes.xaxis.setAttribute("stroke",this._colorX.toString(false));}get colorX(){return this._colorX}set colorY(e){this._colorY.copy(e),this._shapes.py.children[0].setAttribute("fill",this._colorY.toString(false)),this._shapes.py.children[0].setAttribute("stroke",this._colorY.toString(false)),this._shapes.ny.children[0].setAttribute("stroke",this._colorY.toString(false)),this._shapes.yaxis.setAttribute("stroke",this._colorY.toString(false));}get colorY(){return this._colorY}set colorZ(e){this._colorZ.copy(e),this._shapes.pz.children[0].setAttribute("fill",this._colorZ.toString(false)),this._shapes.pz.children[0].setAttribute("stroke",this._colorZ.toString(false)),this._shapes.nz.children[0].setAttribute("stroke",this._colorZ.toString(false)),this._shapes.zaxis.setAttribute("stroke",this._colorZ.toString(false));}get colorZ(){return this._colorZ}set colorNeg(e){this._colorNeg.copy(e),this._shapes.px.children[0].setAttribute("fill",this._colorNeg.toString(false)),this._shapes.py.children[0].setAttribute("fill",this._colorNeg.toString(false)),this._shapes.pz.children[0].setAttribute("fill",this._colorNeg.toString(false));}get colorNeg(){return this._colorNeg}set radius(e){this._radius=e,this._shapes.px.children[0].setAttribute("r",`${e}`),this._shapes.py.children[0].setAttribute("r",`${e}`),this._shapes.pz.children[0].setAttribute("r",`${e}`),this._shapes.nx.children[0].setAttribute("r",`${e}`),this._shapes.ny.children[0].setAttribute("r",`${e}`),this._shapes.nz.children[0].setAttribute("r",`${e}`),this._resize();}get radius(){return this._radius}set textSize(e){this._textSize=e,this._shapes.px.children[1].setAttribute("font-size",`${e}`),this._shapes.py.children[1].setAttribute("font-size",`${e}`),this._shapes.pz.children[1].setAttribute("font-size",`${e}`);}get textSize(){return this._textSize}set lineThickness(e){this._lineThickness=e,this._shapes.xaxis.setAttribute("stroke-width",`${e}`),this._shapes.yaxis.setAttribute("stroke-width",`${e}`),this._shapes.zaxis.setAttribute("stroke-width",`${e}`),this._shapes.px.children[0].setAttribute("stroke-width",`${e}`),this._shapes.py.children[0].setAttribute("stroke-width",`${e}`),this._shapes.pz.children[0].setAttribute("stroke-width",`${e}`),this._shapes.nx.children[0].setAttribute("stroke-width",`${e}`),this._shapes.ny.children[0].setAttribute("stroke-width",`${e}`),this._shapes.nz.children[0].setAttribute("stroke-width",`${e}`),this._resize();}get lineThickness(){return this._lineThickness}set lineLength(e){this._lineLength=e,this._resize();}get lineLength(){return this._lineLength}_resize(){this._size=2*(this.lineLength+this.radius+this.lineThickness),this.dom.style.width=`${this._size}px`,this.dom.style.height=`${this._size}px`,this._svg.setAttribute("width",`${this._size}`),this._svg.setAttribute("height",`${this._size}`),this._group.setAttribute("transform",`translate(${.5*this._size}, ${.5*this._size})`);}_transform(e,t,i){e.setAttribute("transform",`translate(${t*this._lineLength}, ${i*this._lineLength})`);}_x2y2(e,t,i){e.setAttribute("x2",`${t*this._lineLength}`),e.setAttribute("y2",`${i*this._lineLength}`);}_line(e){let t=document.createElementNS(this._svg.namespaceURI,"line");return t.setAttribute("stroke",e),t.setAttribute("stroke-width",`${this._lineThickness}`),this._group.appendChild(t),t}_circle(e,t=false,i){let s=document.createElementNS(this._svg.namespaceURI,"g"),r=document.createElementNS(this._svg.namespaceURI,"circle");if(r.setAttribute("fill",t?e:this._colorNeg.toString(false)),r.setAttribute("stroke",e),r.setAttribute("stroke-width",`${this._lineThickness}`),r.setAttribute("r",`${this._radius}`),r.setAttribute("cx","0"),r.setAttribute("cy","0"),r.setAttribute("pointer-events","all"),s.appendChild(r),i){let e=document.createElementNS(this._svg.namespaceURI,"text");e.setAttribute("font-size",`${this._textSize}`),e.setAttribute("font-family","Arial"),e.setAttribute("font-weight","bold"),e.setAttribute("text-anchor","middle"),e.setAttribute("alignment-baseline","central"),e.textContent=i,s.appendChild(e);}return s.setAttribute("cursor","pointer"),this._group.appendChild(s),s}update(e){if(!this._size)return;Ay.invert(e),Ay.getX(Ag),Ay.getY(Av),Ay.getZ(AS),this._transform(this._shapes.px,Ag.x,-Ag.y),this._transform(this._shapes.nx,-Ag.x,Ag.y),this._transform(this._shapes.py,Av.x,-Av.y),this._transform(this._shapes.ny,-Av.x,Av.y),this._transform(this._shapes.pz,AS.x,-AS.y),this._transform(this._shapes.nz,-AS.x,AS.y),this._x2y2(this._shapes.xaxis,Ag.x,-Ag.y),this._x2y2(this._shapes.yaxis,Av.x,-Av.y),this._x2y2(this._shapes.zaxis,AS.x,-AS.y);let t=[{n:["xaxis","px"],value:Ag.z},{n:["yaxis","py"],value:Av.z},{n:["zaxis","pz"],value:AS.z},{n:["nx"],value:-Ag.z},{n:["ny"],value:-Av.z},{n:["nz"],value:-AS.z}].sort((e,t)=>e.value-t.value),i=document.createDocumentFragment();t.forEach(e=>{e.n.forEach(e=>{i.appendChild(this._shapes[e]);});}),this._group.appendChild(i);}destroy(){this.dom.remove(),this.off();}constructor(e){super(),this._size=0,this._anchor=new ep(1,1,1,1),this._colorX=CP.clone(),this._colorY=CI.clone(),this._colorZ=CD.clone(),this._colorNeg=new es(.3,.3,.3),this._radius=10,this._textSize=10,this._lineThickness=2,this._lineLength=40,this.dom=document.createElement("div"),this.dom.id="view-cube-container",this.dom.style.cssText="position: absolute;margin: auto;pointer-events: none",document.body.appendChild(this.dom),this.anchor=e??this._anchor,this._svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this._svg.id="view-cube-svg",this._group=document.createElementNS(this._svg.namespaceURI,"g"),this._svg.appendChild(this._group),this._resize();let t=this._colorX.toString(false),i=this._colorY.toString(false),s=this._colorZ.toString(false);this._shapes={nx:this._circle(t),ny:this._circle(i),nz:this._circle(s),px:this._circle(t,true,"X"),py:this._circle(i,true,"Y"),pz:this._circle(s,true,"Z"),xaxis:this._line(t),yaxis:this._line(i),zaxis:this._line(s)},this._shapes.px.children[0].addEventListener("pointerdown",()=>{this.fire(Ax.EVENT_CAMERAALIGN,ed.RIGHT);}),this._shapes.py.children[0].addEventListener("pointerdown",()=>{this.fire(Ax.EVENT_CAMERAALIGN,ed.UP);}),this._shapes.pz.children[0].addEventListener("pointerdown",()=>{this.fire(Ax.EVENT_CAMERAALIGN,ed.BACK);}),this._shapes.nx.children[0].addEventListener("pointerdown",()=>{this.fire(Ax.EVENT_CAMERAALIGN,ed.LEFT);}),this._shapes.ny.children[0].addEventListener("pointerdown",()=>{this.fire(Ax.EVENT_CAMERAALIGN,ed.DOWN);}),this._shapes.nz.children[0].addEventListener("pointerdown",()=>{this.fire(Ax.EVENT_CAMERAALIGN,ed.FORWARD);}),this.dom.appendChild(this._svg);}}Ax.EVENT_CAMERAALIGN="camera:align",e.ABSOLUTE_URL=fz,e.ACTION_GAMEPAD=aC,e.ACTION_KEYBOARD=ab,e.ACTION_MOUSE=aw,e.ADDRESS_CLAMP_TO_EDGE=1,e.ADDRESS_MIRRORED_REPEAT=2,e.ADDRESS_REPEAT=0,e.AMBIENTSRC_AMBIENTSH=ny,e.AMBIENTSRC_CONSTANT=nT,e.AMBIENTSRC_ENVALATLAS=nx,e.ANIM_BLEND_1D="1D",e.ANIM_BLEND_2D_CARTESIAN=pG,e.ANIM_BLEND_2D_DIRECTIONAL=pV,e.ANIM_BLEND_DIRECT=pH,e.ANIM_CONTROL_STATES=pX,e.ANIM_EQUAL_TO=pF,e.ANIM_GREATER_THAN=pR,e.ANIM_GREATER_THAN_EQUAL_TO=pM,e.ANIM_INTERRUPTION_NEXT=pP,e.ANIM_INTERRUPTION_NEXT_PREV=pD,e.ANIM_INTERRUPTION_NONE=pC,e.ANIM_INTERRUPTION_PREV=pA,e.ANIM_INTERRUPTION_PREV_NEXT=pI,e.ANIM_LAYER_ADDITIVE=pq,e.ANIM_LAYER_OVERWRITE=pY,e.ANIM_LESS_THAN=pL,e.ANIM_LESS_THAN_EQUAL_TO=pO,e.ANIM_NOT_EQUAL_TO=pN,e.ANIM_PARAMETER_BOOLEAN=pU,e.ANIM_PARAMETER_FLOAT=pk,e.ANIM_PARAMETER_INTEGER=pB,e.ANIM_PARAMETER_TRIGGER=pz,e.ANIM_STATE_ANY="ANY",e.ANIM_STATE_END="END",e.ANIM_STATE_START=pW,e.ASPECT_AUTO=0,e.ASPECT_MANUAL=1,e.ASSET_ANIMATION="animation",e.ASSET_AUDIO="audio",e.ASSET_CONTAINER="container",e.ASSET_CSS="css",e.ASSET_CUBEMAP="cubemap",e.ASSET_HTML="html",e.ASSET_IMAGE="image",e.ASSET_JSON="json",e.ASSET_MATERIAL="material",e.ASSET_MODEL="model",e.ASSET_SCRIPT="script",e.ASSET_SHADER="shader",e.ASSET_TEXT="text",e.ASSET_TEXTURE="texture",e.ASSET_TEXTUREATLAS="textureatlas",e.AXIS_KEY="key",e.AXIS_MOUSE_X="mousex",e.AXIS_MOUSE_Y="mousey",e.AXIS_PAD_L_X="padlx",e.AXIS_PAD_L_Y="padly",e.AXIS_PAD_R_X="padrx",e.AXIS_PAD_R_Y="padry",e.AnimBinder=pJ,e.AnimClip=pb,e.AnimClipHandler=xe,e.AnimComponent=mf,e.AnimComponentLayer=md,e.AnimComponentSystem=m_,e.AnimController=mr,e.AnimCurve=yT,e.AnimData=yE,e.AnimEvaluator=p$,e.AnimEvents=pZ,e.AnimSnapshot=pw,e.AnimStateGraph=mu,e.AnimStateGraphHandler=xt,e.AnimTarget=p0,e.AnimTrack=pQ,e.Animation=dL,e.AnimationComponent=p2,e.AnimationComponentSystem=p5,e.AnimationHandler=y7,e.AnimationKey=dD,e.AnimationNode=dR,e.AppBase=pa,e.AppOptions=po,e.Application=class extends pa{createDevice(e,t){return t.graphicsDeviceOptions||(t.graphicsDeviceOptions={}),k.browser&&navigator.xr&&(t.graphicsDeviceOptions.xrCompatible=true),t.graphicsDeviceOptions.alpha=t.graphicsDeviceOptions.alpha||false,new r5(e,t.graphicsDeviceOptions)}addComponentSystems(e){e.componentSystems=[gF,m8,_G,p5,m_,ga,gE,vE,vA,vH,vi,my,gm,gG,_M,mk,g2,g6,vf,_9,_Y,vg,y_];}addResourceHandles(e){e.resourceHandlers=[yx,y7,xe,xt,xZ,xY,TI,Ti,xG,xr,x5,xQ,xc,xV,xh,x6,xz,xd,xp,xa,Tn,x7,Tt,xl,xF];}constructor(e,t={}){super(e);let i=new po;i.graphicsDevice=t.graphicsDevice??this.createDevice(e,t),this.addComponentSystems(i),this.addResourceHandles(i),i.elementInput=t.elementInput,i.keyboard=t.keyboard,i.mouse=t.mouse,i.touch=t.touch,i.gamepads=t.gamepads,i.scriptPrefix=t.scriptPrefix,i.assetPrefix=t.assetPrefix,i.scriptsOrder=t.scriptsOrder,i.soundManager=new a8,i.lightmapper=py,i.batchManager=ob,i.xr=Ed,this.init(i);}},e.Asset=fX,e.AssetListLoader=class extends X{destroy(){this._registry.off("load",this._onLoad),this._registry.off("error",this._onError),this._waitingAssets.forEach(e=>{this._registry.off(`add:${e}`,this._onAddAsset);}),this.off("progress"),this.off("load");}_assetHasDependencies(e){return "model"===e.type&&e.file?.url&&e.file.url&&e.file.url.match(/.json$/g)}load(e,t){if(this._loading)return;this._loading=true,this._callback=e,this._scope=t,this._registry.on("load",this._onLoad,this),this._registry.on("error",this._onError,this);let i=false;this._assets.forEach(e=>{e.loaded||(i=true,this._assetHasDependencies(e)&&this._registry.loadFromUrl(e.file.url,e.type,(t,i)=>{t?this._onError(t,e):this._onLoad(e);}),this._loadingAssets.add(e),this._registry.add(e));}),this._loadingAssets.forEach(e=>{this._assetHasDependencies(e)||this._registry.load(e);}),i||0!==this._waitingAssets.size||this._loadingComplete();}ready(e,t=this){this._loaded?e.call(t,Array.from(this._assets)):this.once("load",i=>{e.call(t,i);});}_loadingComplete(){this._loaded||(this._loaded=true,this._registry.off("load",this._onLoad,this),this._registry.off("error",this._onError,this),this._failed.length?(this._callback&&this._callback.call(this._scope,"Failed to load some assets",this._failed),this.fire("error",this._failed)):(this._callback&&this._callback.call(this._scope),this.fire("load",Array.from(this._assets))));}_onLoad(e){this._loadingAssets.has(e)&&(this.fire("progress",e),this._loadingAssets.delete(e)),0===this._loadingAssets.size&&setTimeout(()=>{this._loadingComplete();},0);}_onError(e,t){this._loadingAssets.has(t)&&(this._failed.push(t),this._loadingAssets.delete(t)),0===this._loadingAssets.size&&setTimeout(()=>{this._loadingComplete();},0);}_onAddAsset(e){this._waitingAssets.delete(e),this._assets.add(e),e.loaded||(this._loadingAssets.add(e),this._registry.load(e));}_waitForAsset(e){this._waitingAssets.add(e),this._registry.once(`add:${e}`,this._onAddAsset,this);}constructor(e,t){super(),this._assets=new Set,this._loadingAssets=new Set,this._waitingAssets=new Set,this._loading=false,this._loaded=false,this._failed=[],this._registry=t,e.forEach(e=>{if(e instanceof fX)e.registry||(e.registry=t),this._assets.add(e);else {let i=t.get(e);i?this._assets.add(i):this._waitForAsset(e);}});}},e.AssetReference=gv,e.AssetRegistry=fq,e.AudioHandler=xr,e.AudioListenerComponent=mg,e.AudioListenerComponentSystem=my,e.BAKE_COLOR=0,e.BAKE_COLORDIR=1,e.BINDGROUP_MESH=1,e.BINDGROUP_MESH_UB=2,e.BINDGROUP_VIEW=0,e.BLENDEQUATION_ADD=0,e.BLENDEQUATION_MAX=4,e.BLENDEQUATION_MIN=3,e.BLENDEQUATION_REVERSE_SUBTRACT=2,e.BLENDEQUATION_SUBTRACT=1,e.BLENDMODE_CONSTANT=11,e.BLENDMODE_CONSTANT_ALPHA=11,e.BLENDMODE_CONSTANT_COLOR=11,e.BLENDMODE_DST_ALPHA=9,e.BLENDMODE_DST_COLOR=4,e.BLENDMODE_ONE=1,e.BLENDMODE_ONE_MINUS_CONSTANT=12,e.BLENDMODE_ONE_MINUS_CONSTANT_ALPHA=12,e.BLENDMODE_ONE_MINUS_CONSTANT_COLOR=12,e.BLENDMODE_ONE_MINUS_DST_ALPHA=10,e.BLENDMODE_ONE_MINUS_DST_COLOR=5,e.BLENDMODE_ONE_MINUS_SRC_ALPHA=8,e.BLENDMODE_ONE_MINUS_SRC_COLOR=3,e.BLENDMODE_SRC_ALPHA=6,e.BLENDMODE_SRC_ALPHA_SATURATE=7,e.BLENDMODE_SRC_COLOR=2,e.BLENDMODE_ZERO=0,e.BLEND_ADDITIVE=1,e.BLEND_ADDITIVEALPHA=6,e.BLEND_MAX=10,e.BLEND_MIN=9,e.BLEND_MULTIPLICATIVE=5,e.BLEND_MULTIPLICATIVE2X=7,e.BLEND_NONE=3,e.BLEND_NORMAL=2,e.BLEND_PREMULTIPLIED=4,e.BLEND_SCREEN=8,e.BLEND_SUBTRACTIVE=0,e.BLUR_BOX=0,e.BLUR_GAUSSIAN=1,e.BODYFLAG_KINEMATIC_OBJECT=2,e.BODYFLAG_NORESPONSE_OBJECT=4,e.BODYFLAG_STATIC_OBJECT=1,e.BODYGROUP_DEFAULT=1,e.BODYGROUP_DYNAMIC=1,e.BODYGROUP_ENGINE_1=8,e.BODYGROUP_ENGINE_2=32,e.BODYGROUP_ENGINE_3=64,e.BODYGROUP_KINEMATIC=4,e.BODYGROUP_NONE=0,e.BODYGROUP_STATIC=2,e.BODYGROUP_TRIGGER=16,e.BODYGROUP_USER_1=128,e.BODYGROUP_USER_2=256,e.BODYGROUP_USER_3=512,e.BODYGROUP_USER_4=1024,e.BODYGROUP_USER_5=2048,e.BODYGROUP_USER_6=4096,e.BODYGROUP_USER_7=8192,e.BODYGROUP_USER_8=16384,e.BODYMASK_ALL=65535,e.BODYMASK_NONE=0,e.BODYMASK_NOT_STATIC=65533,e.BODYMASK_NOT_STATIC_KINEMATIC=65529,e.BODYMASK_STATIC=2,e.BODYSTATE_ACTIVE_TAG=1,e.BODYSTATE_DISABLE_DEACTIVATION=4,e.BODYSTATE_DISABLE_SIMULATION=5,e.BODYSTATE_ISLAND_SLEEPING=2,e.BODYSTATE_WANTS_DEACTIVATION=3,e.BODYTYPE_DYNAMIC=mW,e.BODYTYPE_KINEMATIC=mX,e.BODYTYPE_STATIC=mH,e.BUFFERUSAGE_COPY_DST=8,e.BUFFERUSAGE_COPY_SRC=4,e.BUFFERUSAGE_INDEX=16,e.BUFFERUSAGE_INDIRECT=256,e.BUFFERUSAGE_READ=1,e.BUFFERUSAGE_STORAGE=128,e.BUFFERUSAGE_UNIFORM=64,e.BUFFERUSAGE_VERTEX=32,e.BUFFERUSAGE_WRITE=2,e.BUFFER_DYNAMIC=1,e.BUFFER_GPUDYNAMIC=3,e.BUFFER_STATIC=0,e.BUFFER_STREAM=2,e.BUTTON_TRANSITION_MODE_SPRITE_CHANGE=1,e.BUTTON_TRANSITION_MODE_TINT=0,e.Batch=n9,e.BatchGroup=n7,e.BatchManager=ob,e.BinaryHandler=xa,e.BindGroupFormat=ii,e.BindStorageBufferFormat=t7,e.BindStorageTextureFormat=it,e.BindTextureFormat=ie,e.BindUniformBufferFormat=t9,e.BlendState=iy,e.BoundingBox=eA,e.BoundingSphere=eD,e.BoxGeometry=c5,e.Bundle=f$,e.BundleHandler=fJ,e.BundleRegistry=fj,e.ButtonComponent=mO,e.ButtonComponentSystem=mk,e.CHUNKAPI_1_51="1.51",e.CHUNKAPI_1_55="1.55",e.CHUNKAPI_1_56="1.56",e.CHUNKAPI_1_57="1.57",e.CHUNKAPI_1_58="1.58",e.CHUNKAPI_1_60="1.60",e.CHUNKAPI_1_62="1.62",e.CHUNKAPI_1_65="1.65",e.CHUNKAPI_1_70="1.70",e.CHUNKAPI_2_1="2.1",e.CHUNKAPI_2_3="2.3",e.CHUNKAPI_2_5="2.5",e.CHUNKAPI_2_6="2.6",e.CHUNKAPI_2_7="2.7",e.CHUNKAPI_2_8="2.8",e.CLEARFLAG_COLOR=1,e.CLEARFLAG_DEPTH=2,e.CLEARFLAG_STENCIL=4,e.CUBEFACE_NEGX=1,e.CUBEFACE_NEGY=3,e.CUBEFACE_NEGZ=5,e.CUBEFACE_POSX=0,e.CUBEFACE_POSY=2,e.CUBEFACE_POSZ=4,e.CUBEPROJ_BOX=1,e.CUBEPROJ_NONE=0,e.CULLFACE_BACK=1,e.CULLFACE_FRONT=2,e.CULLFACE_FRONTANDBACK=3,e.CULLFACE_NONE=0,e.CURVE_LINEAR=0,e.CURVE_SMOOTHSTEP=1,e.CURVE_SPLINE=4,e.CURVE_STEP=5,e.Camera=oN,e.CameraComponent=vy,e.CameraComponentSystem=vE,e.CameraFrame=class{destroy(){this.disable(),this.cameraLayersChanged.off();}enable(){this.renderPassCamera=this.createRenderPass(),this.cameraComponent.framePasses=[this.renderPassCamera];}disable(){let e=this.cameraComponent;e.framePasses?.forEach(e=>{e.destroy();}),e.framePasses=[],e.rendering=null,e.jitter=0,e.shaderParams.ssaoEnabled=false,this.renderPassCamera=null;}createRenderPass(){return new bq(this.app,this,this.cameraComponent,this.options)}set enabled(e){this._enabled!==e&&(e?this.enable():this.disable(),this._enabled=e);}get enabled(){return this._enabled}updateOptions(){let{options:e,rendering:t,bloom:i,taa:s,ssao:r}=this;e.stencil=t.stencil,e.samples=t.samples,e.sceneColorMap=t.sceneColorMap,e.prepassEnabled=t.sceneDepthMap,e.bloomEnabled=i.intensity>0,e.taaEnabled=s.enabled,e.ssaoType=r.type,e.ssaoBlurEnabled=r.blurEnabled,e.formats=t.renderFormats.slice(),e.dofEnabled=this.dof.enabled,e.dofNearBlur=this.dof.nearBlur,e.dofHighQuality=this.dof.highQuality;}update(){if(!this._enabled)return;let e=this.cameraComponent,{options:t,renderPassCamera:i,rendering:s,bloom:r,grading:a,colorEnhance:n,vignette:o,fringing:l,taa:h,ssao:c}=this;this.updateOptions(),i.update(t);let{composePass:d,bloomPass:u,ssaoPass:f,dofPass:p}=i;i.renderTargetScale=ei.clamp(s.renderTargetScale,.1,1),d.toneMapping=s.toneMapping,d.sharpness=s.sharpness,t.bloomEnabled&&u&&(d.bloomIntensity=r.intensity,u.blurLevel=r.blurLevel),t.dofEnabled&&(p.focusDistance=this.dof.focusDistance,p.focusRange=this.dof.focusRange,p.blurRadius=this.dof.blurRadius,p.blurRings=this.dof.blurRings,p.blurRingPoints=this.dof.blurRingPoints),t.ssaoType!==bu&&(f.intensity=c.intensity,f.power=c.power,f.radius=c.radius,f.sampleCount=c.samples,f.minAngle=c.minAngle,f.scale=c.scale,f.randomize=c.randomize),d.gradingEnabled=a.enabled,a.enabled&&(d.gradingSaturation=a.saturation,d.gradingBrightness=a.brightness,d.gradingContrast=a.contrast,d.gradingTint=a.tint),d.colorLUT=this.colorLUT.texture,d.colorLUTIntensity=this.colorLUT.intensity,d.vignetteEnabled=o.intensity>0,d.vignetteEnabled&&(d.vignetteInner=o.inner,d.vignetteOuter=o.outer,d.vignetteCurvature=o.curvature,d.vignetteIntensity=o.intensity,d.vignetteColor.copy(o.color)),d.fringingEnabled=l.intensity>0,d.fringingEnabled&&(d.fringingIntensity=l.intensity),d.colorEnhanceEnabled=n.enabled,n.enabled&&(d.colorEnhanceShadows=n.shadows,d.colorEnhanceHighlights=n.highlights,d.colorEnhanceVibrance=n.vibrance,d.colorEnhanceMidtones=n.midtones,d.colorEnhanceDehaze=n.dehaze),e.jitter=h.enabled?h.jitter:0,d.debug=this.debug,"ssao"===d.debug&&t.ssaoType===bu&&(d.debug=null),"vignette"!==d.debug||d.vignetteEnabled||(d.debug=null);}constructor(e,t){this._enabled=true,this.rendering={renderFormats:[18,12,14],stencil:false,renderTargetScale:1,samples:1,sceneColorMap:false,sceneDepthMap:false,toneMapping:0,sharpness:0},this.ssao={type:bu,blurEnabled:true,randomize:false,intensity:.5,radius:30,samples:12,power:6,minAngle:10,scale:1},this.bloom={intensity:0,blurLevel:16},this.grading={enabled:false,brightness:1,contrast:1,saturation:1,tint:new es(1,1,1,1)},this.colorLUT={texture:null,intensity:1},this.vignette={intensity:0,inner:.5,outer:1,curvature:.5,color:new es(0,0,0)},this.taa={enabled:false,jitter:1},this.fringing={intensity:0},this.colorEnhance={enabled:false,shadows:0,highlights:0,vibrance:0,midtones:0,dehaze:0},this.dof={enabled:false,nearBlur:false,focusDistance:100,focusRange:10,blurRadius:3,blurRings:4,blurRingPoints:5,highQuality:true},this.debug=null,this.options=new bX,this.renderPassCamera=null,this.app=e,this.cameraComponent=t,this.updateOptions(),this.enable(),this.cameraLayersChanged=t.on("set:layers",()=>{this.renderPassCamera&&(this.renderPassCamera.layersDirty=true);});}},e.CameraFrameOptions=bX,e.CanvasFont=class extends X{createTextures(e){let t=this._normalizeCharsSet(e);if(t.length!==this.chars.length)return void this._renderAtlas(t);for(let e=0;e0&&this._renderAtlas(this.chars.concat(i));}destroy(){this.atlases.forEach(e=>e.destroy()),this.chars=null,this.color=null,this.data=null,this.fontName=null,this.fontSize=null,this.glyphSize=null,this.intensity=null,this.atlases=null,this.type=null,this.fontWeight=null;}_colorToRgbString(e,t){let i=Math.round(255*e.r),s=Math.round(255*e.g),r=Math.round(255*e.b);return t?`rgba(${i}, ${s}, ${r}, ${e.a})`:`rgb(${i}, ${s}, ${r})`}renderCharacter(e,t,i,s,r){e.fillStyle=r,e.fillText(t,i,s);}_getAtlas(e){return e>=this.atlases.length&&(this.atlases[e]=new Eu(this.app.graphicsDevice,this.width,this.height,`font-atlas-${this.fontName}-${e}`)),this.atlases[e]}_renderAtlas(e){this.chars=e;let t=this.width,i=this.height,s=this._colorToRgbString(this.color,false),r=this.color.a;this.color.a=1/255;let a=this._colorToRgbString(this.color,true);this.color.a=r;let n=0,o=this._getAtlas(n++);o.clear(a),this.data=this._createJson(this.chars,this.fontName,t,i);let l=H.getSymbols(this.chars.join("")),h=0,c=0,d={};for(let e=0;ev&&(v=this.fontSize*this.fontSize/S,o.ctx.font=`${this.fontWeight} ${v.toString()}px ${this.fontName}`,S=this.fontSize),this.renderCharacter(o.ctx,r,_+p,g+m,s);let y=this.padding+(this.glyphSize-S)/2,x=-this.padding+d[r].descent-c,T=S;this._addChar(this.data,r,h,_,g,u,f,y,x,T,n-1,t,i),(_+=u)+u>t&&(_=0,(g+=f)+f>i&&((o=this._getAtlas(n++)).clear(a),g=0));}this.atlases.splice(n).forEach(e=>e.destroy()),this.atlases.forEach(e=>e.texture.upload()),this.fire("render");}_createJson(e,t,i,s){return {version:3,intensity:this.intensity,info:{face:t,width:i,height:s,maps:[{width:i,height:s}]},chars:{}}}_addChar(e,t,i,s,r,a,n,o,l,h,c,d,u){e.info.maps.lengthe.texture)}constructor(e,t={}){super(),this.type="bitmap",this.app=e,this.intensity=0,this.fontWeight=t.fontWeight||"normal",this.fontSize=parseInt(t.fontSize,10),this.glyphSize=this.fontSize,this.fontName=t.fontName||"Arial",this.color=t.color||new es(1,1,1),this.padding=t.padding||0,this.width=Math.min(4096,t.width||512),this.height=Math.min(4096,t.height||512),this.atlases=[],this.chars="",this.data={};}},e.CapsuleGeometry=ux,e.ChunkUtils=c1,e.CollisionComponent=mV,e.CollisionComponentSystem=m8,e.Color=es,e.Component=px,e.ComponentSystem=pT,e.ComponentSystemRegistry=fK,e.Compute=ar,e.ComputeRadixSort=dz,e.ConeGeometry=uT,e.ContactPoint=gL,e.ContactResult=gM,e.ContainerHandler=xl,e.ContainerResource=class{instantiateModelEntity(e){return null}instantiateRenderEntity(e){return null}getMaterialVariants(){return null}applyMaterialVariant(e,t){}applyMaterialVariantInstances(e,t){}},e.Controller=class{attach(e){this._element=e,this._keyboard&&this._keyboard.attach(e),this._mouse&&this._mouse.attach(e);}detach(){this._keyboard&&this._keyboard.detach(),this._mouse&&this._mouse.detach(),this._element=null;}disableContextMenu(){this._mouse||this._enableMouse(),this._mouse.disableContextMenu();}enableContextMenu(){this._mouse||this._enableMouse(),this._mouse.enableContextMenu();}update(e){for(let e in this._keyboard&&this._keyboard.update(),this._mouse&&this._mouse.update(),this._gamepads&&this._gamepads.update(),this._axesValues={},this._axes)this._axesValues[e]=[];}appendAction(e,t){this._actions[e]=this._actions[e]||[],this._actions[e].push(t);}registerKeys(e,t){if(this._keyboard||this._enableKeyboard(),this._actions[e])throw Error(`Action: ${e} already registered`);if(void 0===t)throw Error("Invalid button");t.length||(t=[t]),this.appendAction(e,{type:ab,keys:t});}registerMouse(e,t){if(this._mouse||this._enableMouse(),void 0===t)throw Error("Invalid button");this.appendAction(e,{type:aw,button:t});}registerPadButton(e,t,i){if(void 0===i)throw Error("Invalid button");this.appendAction(e,{type:aC,button:i,pad:t});}registerAxis(e){let t=e.name;this._axes[t]||(this._axes[t]=[]);let i=this._axes[t].push(t);(e=e||{}).pad=e.pad||0;let s=function(s,r,a,n){switch(r){case "mousex":s._mouse.on("mousemove",e=>{s._axesValues[t][i]=e.dx/10;});break;case "mousey":s._mouse.on("mousemove",e=>{s._axesValues[t][i]=e.dy/10;});break;case "key":s._axes[t].push(()=>s._keyboard.isPressed(n)?a:0);break;case "padrx":s._axes[t].push(()=>s._gamepads.getAxis(e.pad,2));break;case "padry":s._axes[t].push(()=>s._gamepads.getAxis(e.pad,3));break;case "padlx":s._axes[t].push(()=>s._gamepads.getAxis(e.pad,0));break;case "padly":s._axes[t].push(()=>s._gamepads.getAxis(e.pad,1));break;default:throw Error("Unknown axis")}};s(this,e.positive,1,e.positiveKey),(e.negativeKey||e.negative!==e.positive)&&s(this,e.negative,-1,e.negativeKey);}isPressed(e){if(!this._actions[e])return false;let t=this._actions[e].length;for(let i=0;iMath.abs(t)&&(t=i);}else this._axesValues[e]&&Math.abs(this._axesValues[e][s])>Math.abs(t)&&(t=this._axesValues[e][s]);}return t}_enableMouse(){if(this._mouse=new aF,!this._element)throw Error("Controller must be attached to an Element");this._mouse.attach(this._element);}_enableKeyboard(){if(this._keyboard=new aL,!this._element)throw Error("Controller must be attached to an Element");this._keyboard.attach(this._element);}constructor(e,t={}){this._element=null,this._actions={},this._axes={},this._axesValues={},this._keyboard=t.keyboard||null,this._mouse=t.mouse||null,this._gamepads=t.gamepads||null,e&&this.attach(e);}},e.CssHandler=xh,e.CubemapHandler=xc,e.Curve=ea,e.CurveSet=en,e.CylinderGeometry=uE,e.DETAILMODE_ADD="add",e.DETAILMODE_MAX="max",e.DETAILMODE_MIN="min",e.DETAILMODE_MUL="mul",e.DETAILMODE_OVERLAY="overlay",e.DETAILMODE_SCREEN="screen",e.DEVICETYPE_NULL=tK,e.DEVICETYPE_WEBGL2=tY,e.DEVICETYPE_WEBGPU=tq,e.DEVICETYPE_WEBGPU_BARE=tj,e.DISPLAYFORMAT_HDR="hdr",e.DISPLAYFORMAT_LDR="ldr",e.DISPLAYFORMAT_LDR_SRGB=t$,e.DISTANCE_EXPONENTIAL=a3,e.DISTANCE_INVERSE=a2,e.DISTANCE_LINEAR=a1,e.DITHER_BAYER8=nP,e.DITHER_BLUENOISE=nI,e.DITHER_IGNNOISE=nD,e.DITHER_NONE=nA,e.DefaultAnimBinder=p1,e.DepthState=iT,e.DomeGeometry=c8,e.DrawCommands=aa,e.DualGestureSource=class extends bJ{set layout(e){this._layout!==e&&(this._layout=e,this.read(),this._pointerData.clear());}get layout(){return this._layout}get leftJoystick(){return this._leftJoystick}get rightJoystick(){return this._rightJoystick}_onPointerDown(e){let{pointerType:t,pointerId:i,clientX:s,clientY:r}=e;if(this._movementState.down(e),"touch"!==t)return;this._element?.setPointerCapture(i);let a=s<.5*window.innerWidth;this._pointerData.set(i,{x:s,y:r,left:a});let n=Date.now();(this._lastPointer.x-s)**2+(this._lastPointer.y-r)**2<100&&n-this._lastPointer.time<250&&this.deltas.doubleTap.append([1]),this._lastPointer.x=s,this._lastPointer.y=r,this._lastPointer.time=n,a&&b5(this._layout,"joystick")&&this.fire("joystick:position:left",this._leftJoystick.down(s,r)),!a&&b6(this._layout,"joystick")&&this.fire("joystick:position:right",this._rightJoystick.down(s,r));}_onPointerMove(e){let{pointerType:t,pointerId:i,target:s,clientX:r,clientY:a}=e,[n,o]=this._movementState.move(e);if("touch"!==t||s!==this._element)return;let l=this._pointerData.get(i);if(!l)return;let{left:h}=l;l.x=r,l.y=a,h?b5(this._layout,"joystick")?this.fire("joystick:position:left",this._leftJoystick.move(r,a)):this.deltas.leftInput.append([n,o]):b6(this._layout,"joystick")?this.fire("joystick:position:right",this._rightJoystick.move(r,a)):this.deltas.rightInput.append([n,o]);}_onPointerUp(e){let{pointerType:t,pointerId:i}=e;if(this._movementState.up(e),"touch"!==t)return;this._element?.releasePointerCapture(i);let s=this._pointerData.get(i);if(!s)return;let{left:r}=s;this._pointerData.delete(i),r&&b5(this._layout,"joystick")&&this.fire("joystick:position:left",this._leftJoystick.up()),!r&&b6(this._layout,"joystick")&&this.fire("joystick:position:right",this._rightJoystick.up());}attach(e){super.attach(e),this._element=e,this._element.addEventListener("pointerdown",this._onPointerDown),this._element.addEventListener("pointermove",this._onPointerMove),this._element.addEventListener("pointerup",this._onPointerUp),this._element.addEventListener("pointercancel",this._onPointerUp);}detach(){this._element&&(this._element.removeEventListener("pointerdown",this._onPointerDown),this._element.removeEventListener("pointermove",this._onPointerMove),this._element.removeEventListener("pointerup",this._onPointerUp),this._element.removeEventListener("pointercancel",this._onPointerUp),this._pointerData.clear(),super.detach());}read(){return this.deltas.leftInput.append([this._leftJoystick.value.x,this._leftJoystick.value.y]),this.deltas.rightInput.append([this._rightJoystick.value.x,this._rightJoystick.value.y]),super.read()}destroy(){this._leftJoystick.up(),this._rightJoystick.up(),super.destroy();}constructor(e){super({leftInput:[0,0],rightInput:[0,0],doubleTap:[0]}),this._movementState=b2(),this._layout="joystick-touch",this._pointerData=new Map,this._lastPointer={x:0,y:0,time:0},e&&(this.layout=e),this._leftJoystick=new b4,this._rightJoystick=new b4,this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this);}},e.ELEMENTTYPE_GROUP=mx,e.ELEMENTTYPE_IMAGE=mT,e.ELEMENTTYPE_TEXT=mE,e.EMITTERSHAPE_BOX=0,e.EMITTERSHAPE_SPHERE=1,e.EVENT_CULL_END=nk,e.EVENT_GAMEPADCONNECTED="gamepadconnected",e.EVENT_GAMEPADDISCONNECTED="gamepaddisconnected",e.EVENT_KEYDOWN="keydown",e.EVENT_KEYUP="keyup",e.EVENT_MOUSEDOWN="mousedown",e.EVENT_MOUSEMOVE="mousemove",e.EVENT_MOUSEUP="mouseup",e.EVENT_MOUSEWHEEL="mousewheel",e.EVENT_POSTCULL=nB,e.EVENT_POSTRENDER=nM,e.EVENT_POSTRENDER_LAYER=nF,e.EVENT_PRECULL=nN,e.EVENT_PRERENDER=nL,e.EVENT_PRERENDER_LAYER=nO,e.EVENT_SELECT="select",e.EVENT_SELECTEND="selectend",e.EVENT_SELECTSTART="selectstart",e.EVENT_TOUCHCANCEL="touchcancel",e.EVENT_TOUCHEND="touchend",e.EVENT_TOUCHMOVE="touchmove",e.EVENT_TOUCHSTART="touchstart",e.ElementComponent=_D,e.ElementComponentSystem=_M,e.ElementDragHelper=gZ,e.ElementInput=EQ,e.ElementInputEvent=Ej,e.ElementMouseEvent=EK,e.ElementSelectEvent=EZ,e.ElementTouchEvent=E$,e.Entity=f9,e.EnvLighting=dT,e.EventHandle=W,e.EventHandler=X,e.FILLMODE_FILL_WINDOW=fE,e.FILLMODE_KEEP_ASPECT=fw,e.FILLMODE_NONE="NONE",e.FILTER_LINEAR=1,e.FILTER_LINEAR_MIPMAP_LINEAR=5,e.FILTER_LINEAR_MIPMAP_NEAREST=4,e.FILTER_NEAREST=0,e.FILTER_NEAREST_MIPMAP_LINEAR=3,e.FILTER_NEAREST_MIPMAP_NEAREST=2,e.FITMODE_CONTAIN=mb,e.FITMODE_COVER=mC,e.FITMODE_STRETCH=mw,e.FITTING_BOTH=3,e.FITTING_NONE=0,e.FITTING_SHRINK=2,e.FITTING_STRETCH=1,e.FOG_EXP="exp",e.FOG_EXP2="exp2",e.FOG_LINEAR=nr,e.FOG_NONE=ns,e.FONT_BITMAP=_r,e.FONT_MSDF=_s,e.FRESNEL_NONE=0,e.FRESNEL_SCHLICK=2,e.FRONTFACE_CCW=0,e.FRONTFACE_CW=1,e.FUNC_ALWAYS=7,e.FUNC_EQUAL=2,e.FUNC_GREATER=4,e.FUNC_GREATEREQUAL=6,e.FUNC_LESS=1,e.FUNC_LESSEQUAL=3,e.FUNC_NEVER=0,e.FUNC_NOTEQUAL=5,e.FloatPacking=eh,e.FlyController=class extends b1{set pitchRange(e){this._targetPose.pitchRange.copy(e),this._pose.copy(this._targetPose.rotate(ed.ZERO));}get pitchRange(){return this._targetPose.pitchRange}set yawRange(e){this._targetPose.yawRange.copy(e),this._pose.copy(this._targetPose.rotate(ed.ZERO));}get yawRange(){return this._targetPose.yawRange}attach(e,t=true){this._targetPose.copy(e),t||this._pose.copy(this._targetPose);}detach(){this._targetPose.copy(this._pose);}update(e,t){let{move:i,rotate:s}=e.read();return this._targetPose.rotate(Cl.set(-s[1],-s[0],0)),Cu.setFromEulerAngles(this._pose.angles),Cu.transformVector(ed.FORWARD,Ch),Cu.transformVector(ed.RIGHT,Cc),Cu.transformVector(ed.UP,Cd),Co.set(0,0,0),Co.add(Ch.mulScalar(i[2])),Co.add(Cc.mulScalar(i[0])),Co.add(Cd.mulScalar(i[1])),this._targetPose.move(Co),this._pose.lerp(this._pose,this._targetPose,Cn(this.moveDamping,t),Cn(this.rotateDamping,t))}destroy(){this.detach();}constructor(...e){super(...e),this._targetPose=new b$,this.rotateDamping=.98,this.moveDamping=.98;}},e.FocusController=class extends b1{attach(e,t=true){this._targetRootPose.set(e.getFocus(Cg),e.angles,0),this._targetChildPose.position.set(0,0,e.distance),t||(this._rootPose.copy(this._targetRootPose),this._childPose.copy(this._targetChildPose));}detach(){this._targetRootPose.copy(this._rootPose),this._targetChildPose.copy(this._childPose);}complete(){return this._targetRootPose.equalsApprox(this._rootPose,.001)&&this._targetChildPose.equalsApprox(this._childPose,.001)}update(e,t){return e.read(),this._rootPose.lerp(this._rootPose,this._targetRootPose,Cn(this.focusDamping,t),Cn(this.focusDamping,t),1),this._childPose.lerp(this._childPose,this._targetChildPose,Cn(this.focusDamping,t),1,1),CS.setFromEulerAngles(this._rootPose.angles).transformVector(this._childPose.position,Cv).add(this._rootPose.position),this._pose.set(Cv,this._rootPose.angles,this._childPose.position.length())}destroy(){this.detach();}constructor(...e){super(...e),this._targetRootPose=new b$,this._rootPose=new b$,this._targetChildPose=new b$,this._childPose=new b$,this.focusDamping=.98;}},e.FogParams=dE,e.FolderHandler=xd,e.Font=xu,e.FontHandler=xp,e.ForwardRenderer=hp,e.FramePass=an,e.FramePassBloom=bx,e.FramePassCameraFrame=bq,e.FramePassColorGrab=oA,e.FramePassDof=bN,e.FramePassRadixSort=class extends an{destroy(){this._destroyPasses(),this._destroyInternalTextures(),super.destroy();}get sortedIndices(){return this._currentIndices}setup(e,t,i=16){this._keysTexture=e,this._elementCount=t;let s=Math.ceil(i/4);s!==this._numPasses&&(this._destroyPasses(),this._numPasses=s);let r=this._calculateInternalSize(t);r!==this._internalSize&&(this._destroyPasses(),this._resizeInternalTextures(r),this._internalSize=r),0===this._countPasses.length&&this._createPasses();}_calculateInternalSize(e){return Math.pow(2,Math.ceil(Math.log2(Math.ceil(Math.sqrt(e)))))}_resizeInternalTextures(e){this._destroyInternalTextures(),this._keys0=this._createTexture("RadixSortKeys0",e,37),this._keys1=this._createTexture("RadixSortKeys1",e,37),this._indices0=this._createTexture("RadixSortIndices0",e,37),this._indices1=this._createTexture("RadixSortIndices1",e,37);let t=4*e/4;this._prefixSums=this._createTexture("RadixSortPrefixSums",t,15,true),this._sortRT0=new iG({name:"RadixSortRT0",colorBuffers:[this._keys0,this._indices0],depth:false}),this._sortRT1=new iG({name:"RadixSortRT1",colorBuffers:[this._keys1,this._indices1],depth:false}),this._prefixSumsRT=new iG({name:"RadixSortPrefixSumsRT",colorBuffer:this._prefixSums,depth:false});}_createTexture(e,t,i,s=false){return new ic(this.device,{name:e,width:t,height:t,format:i,mipmaps:s,minFilter:2*!!s,magFilter:0,addressU:1,addressV:1})}_destroyInternalTextures(){this._sortRT0?.destroy(),this._sortRT1?.destroy(),this._prefixSumsRT?.destroy(),this._keys0?.destroy(),this._keys1?.destroy(),this._indices0?.destroy(),this._indices1?.destroy(),this._prefixSums?.destroy(),this._sortRT0=null,this._sortRT1=null,this._prefixSumsRT=null,this._keys0=null,this._keys1=null,this._indices0=null,this._indices1=null,this._prefixSums=null;}_createPasses(){let e=this.device,t=this._numPasses,i=this._sortRT1;for(let s=0;ss,calcAabb:e=>e.copy(r)}),this._maxSplats=0,this._numSplats=0,this._format=i,this._maxSplats=t,this._numSplats=t,this.streams.init(this._format,t);}},e.GSplatData=u2,e.GSplatFormat=cG,e.GSplatHandler=xF,e.GSplatInstance=fv,e.GSplatProcessor=class{destroy(){this._renderTarget?.destroy(),this._renderTarget=null,this._quadRender?.destroy(),this._quadRender=null,this._renderPass?.destroy(),this._renderPass=null,this._parameters.clear();}_resolveTexture(e,t,i){if(e.component){let s=i.format.getStream(t);if(s?.storage===1){let i=e.component.getInstanceTexture(t);if(i)return i}}return i.getTexture(t)}_createRenderTarget(){let e=[];for(let t of this._dstStreamDescriptors){let i=this._resolveTexture(this._destination,t.name,this._dstResource);i&&e.push(i);}e.length>0&&(this._renderTarget=new iG({name:"GSplatProcessor-MRT",colorBuffers:e,depth:false,flipY:true}));}_createShader(e){let{processGLSL:t="",processWGSL:i=""}=e,s=this._device,r=this._srcResource.format,a=this._dstResource.format,n="",o="";if(this._useAllInputStreams){let e=[...r.streams,...r.extraStreams],t=this._srcResource===this._dstResource,i=e.filter(e=>!t||!this._dstStreamNames.has(e.name)).map(e=>e.name);n=r.getInputDeclarations(i),o=r.getReadCode();}else n=r.getInputDeclarations(this._source.streams);let l=a.getOutputDeclarations(this._dstStreamDescriptors),h=this._dstStreamDescriptors.map(e=>e1(e.format).returnType),c=new Map;c.set("SH_BANDS","0");let d=s.isWebGPU,u=new Map;u.set("gsplatProcessInputVS",n),u.set("gsplatProcessOutputVS",l),u.set("gsplatProcessReadVS",o),u.set("gsplatProcessChunk",d?i:t);let f=iL([d?i:t,this._useAllInputStreams?"1":"0"].join("|")),p=this._dstStreamDescriptors.map(e=>e.name).join(","),m=nJ.createShader(s,{uniqueName:`GSplatProcessor:${r.hash};${f};out=${p}`,attributes:{vertex_position:e8},vertexDefines:c,fragmentDefines:c,vertexChunk:"fullscreenQuadVS",fragmentGLSL:fS,fragmentWGSL:fy,fragmentIncludes:u,fragmentOutputTypes:h});this._quadRender=new n4(m);}setParameter(e,t){let i=this._device.scope.resolve(e);this._parameters.set(e,{scopeId:i,data:t});}getParameter(e){return this._parameters.get(e)?.data}deleteParameter(e){this._parameters.delete(e);}process(){if(!this._renderPass)return;let e=this._device;for(let{name:t,texture:i}of this._srcTextures)e.scope.resolve(t).setValue(i);for(let[t,i]of(e.scope.resolve("splatTextureSize").setValue(this._srcResource.textureDimensions.x),e.scope.resolve("dstTextureSize").setValue(this._dstResource.textureDimensions.x),e.scope.resolve("srcNumSplats").setValue(this._srcResource.numSplats),e.scope.resolve("dstNumSplats").setValue(this._dstResource.numSplats),this._srcResource.parameters))e.scope.resolve(t).setValue(i);for(let[,e]of this._parameters)e.scopeId.setValue(e.data);this._renderPass.blendState=this.blendState,this._renderPass.render();}constructor(e,t,i,s){for(let s of(this._srcTextures=[],this._renderTarget=null,this._quadRender=null,this._renderPass=null,this._parameters=new Map,this.blendState=iy.NOBLEND,this._device=e,this._source=t,this._destination=i,this._srcResource=t.resource??t.component?.resource,this._dstResource=i.resource??i.component?.resource,this._dstStreamDescriptors=[],this._dstStreamNames=new Set,i.streams)){let e=this._dstResource.format.getStream(s);e&&(this._dstStreamDescriptors.push(e),this._dstStreamNames.add(e.name));}this._useAllInputStreams=!t.streams?.length;let r=this._srcResource.format;for(let e of this._useAllInputStreams?[...r.streams,...r.extraStreams]:t.streams.map(e=>({name:e}))){let i=this._resolveTexture(t,e.name,this._srcResource);this._srcTextures.push({name:e.name,texture:i});}this._createRenderTarget(),this._createShader(s),this._renderPass=new dH(e),this._renderPass.quadRender=this._quadRender,this._renderPass.init(this._renderTarget),this._renderPass.colorOps.clear=false,this._renderPass.depthStencilOps.clearDepth=false;}},e.GSplatResource=fx,e.GSplatResourceBase=uj,e.GSplatSogData=fp,e.GSplatSogResource=fT,e.GamePads=aj,e.GamepadSource=Ca,e.Geometry=c4,e.Gizmo=CA,e.GltfExporter=bd,e.GraphNode=oJ,e.GraphicsDevice=iz,e.HierarchyHandler=xz,e.HtmlHandler=xV,e.Http=aJ,e.I18n=f2,e.INDEXFORMAT_UINT16=1,e.INDEXFORMAT_UINT32=2,e.INDEXFORMAT_UINT8=0,e.INTERPOLATION_CUBIC=2,e.INTERPOLATION_LINEAR=1,e.INTERPOLATION_STEP=0,e.ImageElement=_t,e.IndexBuffer=iw,e.IndexedList=Y,e.InputConsumer=b0,e.InputController=b1,e.InputDelta=bZ,e.InputFrame=bQ,e.InputSource=bJ,e.JointComponent=_k,e.JointComponentSystem=_G,e.JsonHandler=xG,e.JsonStandardMaterialParser=xW,e.KEY_0=48,e.KEY_1=49,e.KEY_2=50,e.KEY_3=51,e.KEY_4=52,e.KEY_5=53,e.KEY_6=54,e.KEY_7=55,e.KEY_8=56,e.KEY_9=57,e.KEY_A=65,e.KEY_ADD=107,e.KEY_ALT=18,e.KEY_B=66,e.KEY_BACKSPACE=8,e.KEY_BACK_SLASH=220,e.KEY_C=67,e.KEY_CAPS_LOCK=20,e.KEY_CLOSE_BRACKET=221,e.KEY_COMMA=188,e.KEY_CONTEXT_MENU=93,e.KEY_CONTROL=17,e.KEY_D=68,e.KEY_DECIMAL=110,e.KEY_DELETE=46,e.KEY_DIVIDE=111,e.KEY_DOWN=40,e.KEY_E=69,e.KEY_END=35,e.KEY_ENTER=13,e.KEY_EQUAL=61,e.KEY_ESCAPE=27,e.KEY_F=70,e.KEY_F1=112,e.KEY_F10=121,e.KEY_F11=122,e.KEY_F12=123,e.KEY_F2=113,e.KEY_F3=114,e.KEY_F4=115,e.KEY_F5=116,e.KEY_F6=117,e.KEY_F7=118,e.KEY_F8=119,e.KEY_F9=120,e.KEY_G=71,e.KEY_H=72,e.KEY_HOME=36,e.KEY_I=73,e.KEY_INSERT=45,e.KEY_J=74,e.KEY_K=75,e.KEY_L=76,e.KEY_LEFT=37,e.KEY_M=77,e.KEY_META=224,e.KEY_MULTIPLY=106,e.KEY_N=78,e.KEY_NUMPAD_0=96,e.KEY_NUMPAD_1=97,e.KEY_NUMPAD_2=98,e.KEY_NUMPAD_3=99,e.KEY_NUMPAD_4=100,e.KEY_NUMPAD_5=101,e.KEY_NUMPAD_6=102,e.KEY_NUMPAD_7=103,e.KEY_NUMPAD_8=104,e.KEY_NUMPAD_9=105,e.KEY_O=79,e.KEY_OPEN_BRACKET=219,e.KEY_P=80,e.KEY_PAGE_DOWN=34,e.KEY_PAGE_UP=33,e.KEY_PAUSE=19,e.KEY_PERIOD=190,e.KEY_PRINT_SCREEN=44,e.KEY_Q=81,e.KEY_R=82,e.KEY_RETURN=13,e.KEY_RIGHT=39,e.KEY_S=83,e.KEY_SEMICOLON=59,e.KEY_SEPARATOR=108,e.KEY_SHIFT=16,e.KEY_SLASH=191,e.KEY_SPACE=32,e.KEY_SUBTRACT=109,e.KEY_T=84,e.KEY_TAB=9,e.KEY_U=85,e.KEY_UP=38,e.KEY_V=86,e.KEY_W=87,e.KEY_WINDOWS=91,e.KEY_X=88,e.KEY_Y=89,e.KEY_Z=90,e.Kernel=ec,e.Key=dD,e.Keyboard=aL,e.KeyboardEvent=aA,e.KeyboardMouseSource=Ci,e.LAYERID_DEPTH=1,e.LAYERID_IMMEDIATE=3,e.LAYERID_SKYBOX=2,e.LAYERID_UI=4,e.LAYERID_WORLD=0,e.LAYER_GIZMO=1,e.LAYER_HUD=0,e.LAYER_WORLD=15,e.LIGHTFALLOFF_INVERSESQUARED=1,e.LIGHTFALLOFF_LINEAR=0,e.LIGHTSHAPE_DISK=2,e.LIGHTSHAPE_PUNCTUAL=0,e.LIGHTSHAPE_RECT=1,e.LIGHTSHAPE_SPHERE=3,e.LIGHTTYPE_COUNT=3,e.LIGHTTYPE_DIRECTIONAL=0,e.LIGHTTYPE_OMNI=1,e.LIGHTTYPE_POINT=1,e.LIGHTTYPE_SPOT=2,e.LIGHT_COLOR_DIVIDER=100,e.Layer=hy,e.LayerComposition=hT,e.LayoutCalculator=_2,e.LayoutChildComponent=_H,e.LayoutChildComponentSystem=_Y,e.LayoutGroupComponent=_5,e.LayoutGroupComponentSystem=_9,e.Light=hL,e.LightComponent=vC,e.LightComponentSystem=vA,e.LightingParams=hM,e.Lightmapper=py,e.LitMaterial=class extends lw{getShaderVariant(e){d5.usedUvs=this.usedUvs.slice(),d5.shaderChunkGLSL=this.shaderChunkGLSL,d5.shaderChunkWGSL=this.shaderChunkWGSL,d5.defines=nJ.getCoreDefines(this,e),dJ.update(d5.litOptions,this,e.scene,e.cameraShaderParams,e.objDefs,e.pass,e.sortedLights);let t=new nV(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),i=nH(e.device);return i.register("lit",d4),i.getProgram("lit",d5,t,this.userId)}constructor(...e){super(...e),this.usedUvs=[true],this.shaderChunkGLSL=null,this.shaderChunkWGSL=null,this.useLighting=true,this.useFog=true,this.useTonemap=true,this.useSkybox=true,this.ambientSH=null,this.pixelSnap=false,this.nineSlicedMode=null,this.twoSidedLighting=false,this.occludeDirect=false,this.occludeSpecular=1,this.occludeSpecularIntensity=1,this.opacityFadesSpecular=true,this.opacityDither=nA,this.opacityShadowDither=nA,this.shadowCatcher=false,this.ggxSpecular=false,this.fresnelModel=2,this.dynamicRefraction=false,this.hasAo=false,this.hasSpecular=false,this.hasSpecularityFactor=false,this.hasLighting=false,this.hasHeights=false,this.hasNormals=false,this.hasSheen=false,this.hasRefraction=false,this.hasIrridescence=false,this.hasMetalness=false,this.hasClearCoat=false,this.hasClearCoatNormals=false;}},e.LitOptions=dQ,e.LitShaderOptions=dQ,e.LocalizedAsset=_i,e.MASK_AFFECT_DYNAMIC=1,e.MASK_AFFECT_LIGHTMAPPED=2,e.MASK_BAKE=4,e.MOTION_FREE=_O,e.MOTION_LIMITED=_F,e.MOTION_LOCKED=_N,e.MOUSEBUTTON_LEFT=0,e.MOUSEBUTTON_MIDDLE=1,e.MOUSEBUTTON_NONE=-1,e.MOUSEBUTTON_RIGHT=2,e.Mat3=eu,e.Mat4=ey,e.Material=lw,e.MaterialHandler=xY,e.Mesh=on,e.MeshInstance=oS,e.MiniStats=w_,e.Model=hF,e.ModelComponent=gi,e.ModelComponentSystem=ga,e.ModelHandler=xZ,e.Morph=hN,e.MorphInstance=hO,e.MorphTarget=hB,e.Mouse=aF,e.MouseEvent=aO,e.MultiTouchSource=class extends bJ{_onPointerDown(e){let{pointerId:t,pointerType:i}=e;this._movementState.down(e),"touch"===i&&(this._element?.setPointerCapture(t),this._pointerEvents.set(t,e),this.deltas.count.append([1]),this._pointerEvents.size>1&&(this._getMidPoint(this._pointerPos),this._pinchDist=this._getPinchDist()));}_onPointerMove(e){let{pointerType:t,target:i,pointerId:s}=e,[r,a]=this._movementState.move(e);if("touch"===t&&i===this._element&&0!==this._pointerEvents.size)if(this._pointerEvents.set(s,e),this._pointerEvents.size>1){let e=this._getMidPoint(b8);this.deltas.touch.append([e.x-this._pointerPos.x,e.y-this._pointerPos.y]),this._pointerPos.copy(e);let t=this._getPinchDist();this._pinchDist>0&&this.deltas.pinch.append([this._pinchDist-t]),this._pinchDist=t;}else this.deltas.touch.append([r,a]);}_onPointerUp(e){let{pointerType:t,pointerId:i}=e;this._movementState.up(e),"touch"===t&&(this._element?.releasePointerCapture(i),this._pointerEvents.delete(i),this.deltas.count.append([-1]),this._pointerEvents.size<2&&(this._pinchDist=-1),this._pointerPos.set(0,0));}_onContextMenu(e){e.preventDefault();}_getMidPoint(e){if(this._pointerEvents.size<2)return e.set(0,0);let[t,i]=this._pointerEvents.values(),s=t.clientX-i.clientX,r=t.clientY-i.clientY;return e.set(i.clientX+.5*s,i.clientY+.5*r)}_getPinchDist(){if(this._pointerEvents.size<2)return 0;let[e,t]=this._pointerEvents.values(),i=e.clientX-t.clientX,s=e.clientY-t.clientY;return Math.sqrt(i*i+s*s)}attach(e){super.attach(e),this._element=e,this._element.addEventListener("pointerdown",this._onPointerDown),this._element.addEventListener("pointermove",this._onPointerMove),this._element.addEventListener("pointerup",this._onPointerUp),this._element.addEventListener("pointercancel",this._onPointerUp),this._element.addEventListener("contextmenu",this._onContextMenu);}detach(){this._element&&(this._element.removeEventListener("pointerdown",this._onPointerDown),this._element.removeEventListener("pointermove",this._onPointerMove),this._element.removeEventListener("pointerup",this._onPointerUp),this._element.removeEventListener("pointercancel",this._onPointerUp),this._element.removeEventListener("contextmenu",this._onContextMenu),this._pointerEvents.clear(),super.detach());}constructor(){super({touch:[0,0],count:[0],pinch:[0]}),this._movementState=b2(),this._pointerEvents=new Map,this._pointerPos=new ef,this._pinchDist=-1,this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onContextMenu=this._onContextMenu.bind(this);}},e.Node=dR,e.NullGraphicsDevice=ai,e.ORIENTATION_HORIZONTAL=0,e.ORIENTATION_VERTICAL=1,e.OrbitController=class extends b1{set pitchRange(e){this._targetRootPose.pitchRange.copy(e),this._rootPose.copy(this._targetRootPose.rotate(ed.ZERO));}get pitchRange(){return this._targetRootPose.pitchRange}set yawRange(e){this._targetRootPose.yawRange.copy(e),this._rootPose.copy(this._targetRootPose.rotate(ed.ZERO));}get yawRange(){return this._targetRootPose.yawRange}set zoomRange(e){this._targetChildPose.zRange.copy(e),this._childPose.copy(this._targetChildPose.move(ed.ZERO));}get zoomRange(){return this._targetRootPose.zRange}attach(e,t=true){this._targetRootPose.set(e.getFocus(Cf),e.angles,0),this._targetChildPose.position.set(0,0,e.distance),t||(this._rootPose.copy(this._targetRootPose),this._childPose.copy(this._targetChildPose));}detach(){this._targetRootPose.copy(this._rootPose),this._targetChildPose.copy(this._childPose);}update(e,t){let{move:i,rotate:s}=e.read();Cp.set(i[0],i[1],0),C_.setFromEulerAngles(this._rootPose.angles).transformVector(Cp,Cp),this._targetRootPose.move(Cp);let{z:r}=this._targetChildPose.position;return this._targetChildPose.move(Cp.set(0,0,r*(1+i[2])-r)),this._targetRootPose.rotate(Cm.set(-s[1],-s[0],0)),this._rootPose.lerp(this._rootPose,this._targetRootPose,Cn(this.moveDamping,t),Cn(this.rotateDamping,t),1),this._childPose.lerp(this._childPose,this._targetChildPose,Cn(this.zoomDamping,t),1,1),C_.setFromEulerAngles(this._rootPose.angles).transformVector(this._childPose.position,Cp).add(this._rootPose.position),this._pose.set(Cp,this._rootPose.angles,this._childPose.position.z)}destroy(){this.detach();}constructor(...e){super(...e),this._targetRootPose=new b$,this._rootPose=new b$,this._targetChildPose=new b$,this._childPose=new b$,this.rotateDamping=.98,this.moveDamping=.98,this.zoomDamping=.98;}},e.OrientedBox=class{set worldTransform(e){this._worldTransform.copy(e),this._modelTransform.copy(e).invert();}get worldTransform(){return this._worldTransform}intersectsRay(e,t){if(this._modelTransform.transformPoint(e.origin,eO.origin),this._modelTransform.transformVector(e.direction,eO.direction),t){let e=this._aabb._intersectsRay(eO,t);return eB.copy(this._modelTransform).invert().transformPoint(t,t),e}return this._aabb._fastIntersectsRay(eO)}containsPoint(e){return this._modelTransform.transformPoint(e,eF),this._aabb.containsPoint(eF)}intersectsBoundingSphere(e){return this._modelTransform.transformPoint(e.center,eN.center),eN.radius=e.radius,!!this._aabb.intersectsBoundingSphere(eN)}constructor(e=new ey,t){this.halfExtents=new ed(.5,.5,.5),t&&this.halfExtents.copy(t),this._modelTransform=e.clone().invert(),this._worldTransform=e.clone(),this._aabb=new eA(new ed,this.halfExtents);}},e.OutlineRenderer=class{destroy(){this.whiteTex.destroy(),this.whiteTex=null,this.outlineCameraEntity.destroy(),this.outlineCameraEntity=null,this.rt.destroyTextureBuffers(),this.rt.destroy(),this.rt=null,this.tempRt.destroyTextureBuffers(),this.tempRt.destroy(),this.tempRt=null,this.app.scene.off("postrender",this.postRender),this.quadRenderer?.destroy(),this.quadRenderer=null;}getMeshInstances(e,t){let i=[];return e&&((t?e.findComponents("render"):e.render?[e.render]:[]).forEach(e=>{e.meshInstances&&i.push(...e.meshInstances);}),(t?e.findComponents("model"):e.model?[e.model]:[]).forEach(e=>{e.meshInstances&&i.push(...e.meshInstances);})),i}addEntity(e,t,i=true){let s=this.getMeshInstances(e,i);s.forEach(e=>{if(e.material instanceof ud){let i=this.outlineShaderPass;e.material.onUpdateShader=e=>{if(e.pass===i){let t=new d6;return t.defines=e.defines,t.opacityMap=e.opacityMap,t.opacityMapUv=e.opacityMapUv,t.opacityMapChannel=e.opacityMapChannel,t.opacityMapTransform=e.opacityMapTransform,t.opacityVertexColor=e.opacityVertexColor,t.opacityVertexColorChannel=e.opacityVertexColorChannel,t.litOptions.vertexColors=e.litOptions.vertexColors,t.litOptions.alphaTest=e.litOptions.alphaTest,t.litOptions.skin=e.litOptions.skin,t.litOptions.batch=e.litOptions.batch,t.litOptions.useInstancing=e.litOptions.useInstancing,t.litOptions.useMorphPosition=e.litOptions.useMorphPosition,t.litOptions.useMorphNormal=e.litOptions.useMorphNormal,t.litOptions.useMorphTextureBasedInt=e.litOptions.useMorphTextureBasedInt,t.litOptions.opacityFadesSpecular=e.litOptions.opacityFadesSpecular,t}return e},wy.linear(t);let s=new Float32Array([wy.r,wy.g,wy.b]);e.setParameter("material_emissive",s,1<{e.material instanceof ud&&(e.material.onUpdateShader=null,e.deleteParameter("material_emissive"));});}removeAllEntities(){this.renderingLayer.clearMeshInstances();}blendOutlines(){let e=this.app.graphicsDevice;e.scope.resolve("source").setValue(this.rt.colorBuffer),e.setDrawStates(this.blendState),this.quadRenderer.render();}onPostRender(){let e=this.app.graphicsDevice,t=e.scope.resolve("uOffset"),i=e.scope.resolve("source"),s=e.scope.resolve("uSrcMultiplier"),{rt:r,tempRt:a,shaderExtend:n}=this,{width:o,height:l}=r;wS[0]=1/o/2,wS[1]=0,t.setValue(wS),i.setValue(r.colorBuffer),s.setValue(0),n8(e,a,n),wS[0]=0,wS[1]=1/l/2,t.setValue(wS),i.setValue(a.colorBuffer),s.setValue(1),n8(e,r,n);}createRenderTarget(e,t,i,s){return new iG({colorBuffer:new ic(this.app.graphicsDevice,{name:e,width:t,height:i,format:20,mipmaps:false,addressU:1,addressV:1,minFilter:5,magFilter:1}),depth:s,flipY:this.app.graphicsDevice.isWebGPU})}updateRenderTarget(e){let t=e.renderTarget?.width??this.app.graphicsDevice.width,i=e.renderTarget?.height??this.app.graphicsDevice.height,s=this.outlineCameraEntity.camera;s.renderTarget&&s.renderTarget.width===t&&s.renderTarget.height===i||(this.rt.resize(t,i),this.tempRt.resize(t,i));}frameUpdate(e,t,i){let s=e.camera;this.updateRenderTarget(s);let r=this.app.scene.on("prerender:layer",(e,a,n)=>{s===e&&n===i&&a===t&&(this.blendOutlines(),r.off());});this.outlineCameraEntity.setLocalPosition(e.getPosition()),this.outlineCameraEntity.setLocalRotation(e.getRotation());let a=this.outlineCameraEntity.camera;a.projection=s.projection,a.horizontalFov=s.horizontalFov,a.fov=s.fov,a.orthoHeight=s.orthoHeight,a.nearClip=s.nearClip,a.farClip=s.farClip;}constructor(e,t,i=-1){this.app=e,this.renderingLayer=t??e.scene.layers.getLayerByName("Immediate"),this.rt=this.createRenderTarget("OutlineTexture",1,1,true),this.outlineCameraEntity=new f9("OutlineCamera"),this.outlineCameraEntity.addComponent("camera",{layers:[this.renderingLayer.id],priority:i,clearColor:new es(0,0,0,0),renderTarget:this.rt}),this.outlineShaderPass=this.outlineCameraEntity.camera.setShaderPass("OutlineShaderPass"),this.postRender=e=>{this.outlineCameraEntity.camera===e&&this.onPostRender();},e.scene.on("postrender",this.postRender),this.app.root.addChild(this.outlineCameraEntity),this.tempRt=this.createRenderTarget("OutlineTempTexture",1,1,false),this.blendState=new iy(true,0,6,8);let s=this.app.graphicsDevice;this.shaderExtend=nJ.createShader(s,{uniqueName:"OutlineExtendShader",attributes:{vertex_position:e8},vertexChunk:"fullscreenQuadVS",fragmentGLSL:wg,fragmentWGSL:wv}),this.shaderBlend=nJ.createShader(s,{uniqueName:"OutlineBlendShader",attributes:{vertex_position:e8},vertexChunk:"fullscreenQuadVS",fragmentChunk:"outputTex2DPS"}),this.quadRenderer=new n4(this.shaderBlend),this.whiteTex=new ic(s,{name:"OutlineWhiteTexture",width:1,height:1,format:20,mipmaps:false}),this.whiteTex.lock().set(new Uint8Array([255,255,255,255])),this.whiteTex.unlock();}},e.PAD_1=0,e.PAD_2=1,e.PAD_3=2,e.PAD_4=3,e.PAD_DOWN=13,e.PAD_FACE_1=0,e.PAD_FACE_2=1,e.PAD_FACE_3=2,e.PAD_FACE_4=3,e.PAD_LEFT=14,e.PAD_L_SHOULDER_1=4,e.PAD_L_SHOULDER_2=6,e.PAD_L_STICK_BUTTON=10,e.PAD_L_STICK_X=0,e.PAD_L_STICK_Y=1,e.PAD_RIGHT=15,e.PAD_R_SHOULDER_1=5,e.PAD_R_SHOULDER_2=7,e.PAD_R_STICK_BUTTON=11,e.PAD_R_STICK_X=2,e.PAD_R_STICK_Y=3,e.PAD_SELECT=8,e.PAD_START=9,e.PAD_UP=12,e.PAD_VENDOR=16,e.PARTICLEMODE_CPU=1,e.PARTICLEMODE_GPU=0,e.PARTICLEORIENTATION_EMITTER=2,e.PARTICLEORIENTATION_SCREEN=0,e.PARTICLEORIENTATION_WORLD=1,e.PARTICLESORT_DISTANCE=1,e.PARTICLESORT_NEWER_FIRST=2,e.PARTICLESORT_NONE=0,e.PARTICLESORT_OLDER_FIRST=3,e.PIXELFORMAT_111110F=18,e.PIXELFORMAT_A8=0,e.PIXELFORMAT_ASTC_4x4=28,e.PIXELFORMAT_ASTC_4x4_SRGB=63,e.PIXELFORMAT_ATC_RGB=29,e.PIXELFORMAT_ATC_RGBA=30,e.PIXELFORMAT_BC6F=65,e.PIXELFORMAT_BC6UF=66,e.PIXELFORMAT_BC7=67,e.PIXELFORMAT_BC7_SRGBA=68,e.PIXELFORMAT_BGRA8=31,e.PIXELFORMAT_DEPTH=16,e.PIXELFORMAT_DEPTH16=69,e.PIXELFORMAT_DEPTHSTENCIL=17,e.PIXELFORMAT_DXT1=8,e.PIXELFORMAT_DXT1_SRGB=54,e.PIXELFORMAT_DXT3=9,e.PIXELFORMAT_DXT3_SRGBA=55,e.PIXELFORMAT_DXT5=10,e.PIXELFORMAT_DXT5_SRGBA=56,e.PIXELFORMAT_ETC1=21,e.PIXELFORMAT_ETC2_RGB=22,e.PIXELFORMAT_ETC2_RGBA=23,e.PIXELFORMAT_ETC2_SRGB=61,e.PIXELFORMAT_ETC2_SRGBA=62,e.PIXELFORMAT_L8=1,e.PIXELFORMAT_L8_A8=2,e.PIXELFORMAT_LA8=2,e.PIXELFORMAT_PVRTC_2BPP_RGBA_1=25,e.PIXELFORMAT_PVRTC_2BPP_RGB_1=24,e.PIXELFORMAT_PVRTC_4BPP_RGBA_1=27,e.PIXELFORMAT_PVRTC_4BPP_RGB_1=26,e.PIXELFORMAT_R16F=50,e.PIXELFORMAT_R16I=34,e.PIXELFORMAT_R16U=35,e.PIXELFORMAT_R32F=15,e.PIXELFORMAT_R32I=36,e.PIXELFORMAT_R32U=37,e.PIXELFORMAT_R4_G4_B4_A4=5,e.PIXELFORMAT_R5_G5_B5_A1=4,e.PIXELFORMAT_R5_G6_B5=3,e.PIXELFORMAT_R8=52,e.PIXELFORMAT_R8I=32,e.PIXELFORMAT_R8U=33,e.PIXELFORMAT_R8_G8_B8=6,e.PIXELFORMAT_R8_G8_B8_A8=7,e.PIXELFORMAT_RG16F=51,e.PIXELFORMAT_RG16I=40,e.PIXELFORMAT_RG16U=41,e.PIXELFORMAT_RG32F=70,e.PIXELFORMAT_RG32I=42,e.PIXELFORMAT_RG32U=43,e.PIXELFORMAT_RG8=53,e.PIXELFORMAT_RG8I=38,e.PIXELFORMAT_RG8S=72,e.PIXELFORMAT_RG8U=39,e.PIXELFORMAT_RGB10A2=74,e.PIXELFORMAT_RGB10A2U=75,e.PIXELFORMAT_RGB16F=11,e.PIXELFORMAT_RGB32F=13,e.PIXELFORMAT_RGB565=3,e.PIXELFORMAT_RGB8=6,e.PIXELFORMAT_RGB9E5=71,e.PIXELFORMAT_RGBA16F=12,e.PIXELFORMAT_RGBA16I=46,e.PIXELFORMAT_RGBA16U=47,e.PIXELFORMAT_RGBA32F=14,e.PIXELFORMAT_RGBA32I=48,e.PIXELFORMAT_RGBA32U=49,e.PIXELFORMAT_RGBA4=5,e.PIXELFORMAT_RGBA5551=4,e.PIXELFORMAT_RGBA8=7,e.PIXELFORMAT_RGBA8I=44,e.PIXELFORMAT_RGBA8S=73,e.PIXELFORMAT_RGBA8U=45,e.PIXELFORMAT_SBGRA8=64,e.PIXELFORMAT_SRGB=19,e.PIXELFORMAT_SRGB8=19,e.PIXELFORMAT_SRGBA=20,e.PIXELFORMAT_SRGBA8=20,e.PRIMITIVE_LINELOOP=2,e.PRIMITIVE_LINES=1,e.PRIMITIVE_LINESTRIP=3,e.PRIMITIVE_POINTS=0,e.PRIMITIVE_TRIANGLES=4,e.PRIMITIVE_TRIFAN=6,e.PRIMITIVE_TRISTRIP=5,e.PROJECTION_ORTHOGRAPHIC=1,e.PROJECTION_PERSPECTIVE=0,e.ParticleEmitter=cy,e.ParticleSystemComponent=gc,e.ParticleSystemComponentSystem=gm,e.Picker=class{destroy(){this.releaseRenderTarget(),this.renderPass?.destroy();}getSelection(e,t,i=1,s=1){let r=this.device;if(r.isWebGPU)return [];t=this.renderTarget.height-(t+s);let a=this.sanitizeRect(e,t,i,s);r.setRenderTarget(this.renderTarget),r.updateBegin();let n=new Uint8Array(4*a.z*a.w);return r.readPixels(a.x,a.y,a.z,a.w,n),r.updateEnd(),this.decodePixels(n,this.mapping)}getSelectionAsync(e,t,i=1,s=1){return this.renderTarget&&this.renderTarget.colorBuffer?this._readTexture(this.renderTarget.colorBuffer,e,t,i,s,this.renderTarget).then(e=>this.decodePixels(e,this.mapping)):Promise.resolve([])}_readTexture(e,t,i,s,r,a){this.device?.isWebGL2&&(i=a.height-(i+r));let n=this.sanitizeRect(t,i,s,r);return e.read(n.x,n.y,n.z,n.w,{immediate:true,renderTarget:a})}async getWorldPointAsync(e,t){let i=this.renderPass.camera;if(!i)return null;let s=new ey().mul2(i.camera.projectionMatrix,i.camera.viewMatrix).invert(),r=i.nearClip,a=i.farClip,n=1===i.projection,o=await this.getPointDepthAsync(e,t);if(null===o)return null;let l=new ep(e/this.width*2-1,(1-t/this.height)*2-1,2*(n?o:a*o/(o*(a-r)+r))-1,1);return s.transformVec4(l,l),l.mulScalar(1/l.w),new ed(l.x,l.y,l.z)}async getPointDepthAsync(e,t){if(!this.depthBuffer)return null;let i=await this._readTexture(this.depthBuffer,e,t,1,1,this.renderTargetDepth),s=(i[0]<<24|i[1]<<16|i[2]<<8|i[3])>>>0;return 0xffffffff===s?null:(Ey[0]=s,ES[0])}sanitizeRect(e,t,i,s){let r=this.renderTarget.width,a=this.renderTarget.height;return e=ei.clamp(Math.floor(e),0,r-1),t=ei.clamp(Math.floor(t),0,a-1),i=Math.min(i=Math.floor(Math.max(i,1)),r-e),s=Math.min(s=Math.floor(Math.max(s,1)),a-t),Ev.set(e,t,i,s)}decodePixels(e,t){let i=[];if(this.deviceValid){let s=e.length;for(let i=0;i>>0;0xffffffff!==n&&Eg.add(t.get(n));}Eg.forEach(e=>{e&&i.push(e);}),Eg.clear();}return i}createTexture(e){return ic.createDataTexture2D(this.device,e,this.width,this.height,7)}allocateRenderTarget(){this.colorBuffer=this.createTexture("pick");let e=[this.colorBuffer];this.depth&&(this.depthBuffer=this.createTexture("pick-depth"),e.push(this.depthBuffer),this.renderTargetDepth=new iG({colorBuffer:this.depthBuffer,depth:false})),this.renderTarget=new iG({colorBuffers:e,depth:true});}releaseRenderTarget(){this.renderTarget?.destroyTextureBuffers(),this.renderTarget?.destroy(),this.renderTarget=null,this.renderTargetDepth?.destroy(),this.renderTargetDepth=null,this.colorBuffer=null,this.depthBuffer=null;}prepare(e,t,i){i instanceof hy&&(i=[i]),this.renderTarget?.resize(this.width,this.height),this.renderTargetDepth?.resize(this.width,this.height),this.mapping.clear();let s=this.renderPass;s.init(this.renderTarget),s.setClearColor(es.WHITE),s.depthStencilOps.clearDepth=true,s.update(e,t,i,this.mapping,this.depth),s.render();}resize(e,t){this.width=Math.floor(e),this.height=Math.floor(t);}constructor(e,t,i,s=false){this.renderTarget=null,this.colorBuffer=null,this.depthBuffer=null,this.renderTargetDepth=null,this.mapping=new Map,this.deviceValid=true,this.device=e.graphicsDevice,this.renderPass=new E_(this.device,e.renderer),this.depth=s,this.width=0,this.height=0,this.resize(t,i),this.allocateRenderTarget(),this.device.on("destroy",()=>{this.deviceValid=false;});}},e.Plane=eR,e.PlaneGeometry=uw,e.Pose=b$,e.PostEffect=dG,e.PostEffectQueue=vS,e.ProgramLibrary=uC,e.QuadRender=n4,e.Quat=ex,e.REFLECTIONSRC_CUBEMAP=ng,e.REFLECTIONSRC_ENVATLAS=nm,e.REFLECTIONSRC_ENVATLASHQ=n_,e.REFLECTIONSRC_NONE=np,e.REFLECTIONSRC_SPHEREMAP=nv,e.RENDERSTYLE_POINTS=2,e.RENDERSTYLE_SOLID=0,e.RENDERSTYLE_WIREFRAME=1,e.RESOLUTION_AUTO=fb,e.RESOLUTION_FIXED=fC,e.RIGIDBODY_ACTIVE_TAG=1,e.RIGIDBODY_CF_KINEMATIC_OBJECT=2,e.RIGIDBODY_CF_NORESPONSE_OBJECT=4,e.RIGIDBODY_CF_STATIC_OBJECT=1,e.RIGIDBODY_DISABLE_DEACTIVATION=4,e.RIGIDBODY_DISABLE_SIMULATION=5,e.RIGIDBODY_ISLAND_SLEEPING=2,e.RIGIDBODY_TYPE_DYNAMIC=mW,e.RIGIDBODY_TYPE_KINEMATIC=mX,e.RIGIDBODY_TYPE_STATIC=mH,e.RIGIDBODY_WANTS_DEACTIVATION=3,e.Ray=eM,e.RaycastResult=gD,e.ReadStream=K,e.RenderComponent=gS,e.RenderComponentSystem=gE,e.RenderHandler=yx,e.RenderPass=ah,e.RenderPassCompose=bw,e.RenderPassDepthAwareBlur=bV,e.RenderPassDownsample=bg,e.RenderPassForward=hh,e.RenderPassPicker=E_,e.RenderPassPrepass=bk,e.RenderPassShaderQuad=dH,e.RenderPassSsao=bW,e.RenderPassTAA=bI,e.RenderPassUpsample=by,e.RenderTarget=iG,e.ResourceHandler=fQ,e.ResourceLoader=f0,e.RigidBodyComponent=gP,e.RigidBodyComponentSystem=gF,e.RotateGizmo=class extends Cz{set xyzTubeRadius(e){this._setDiskProp("tubeRadius",e);}get xyzTubeRadius(){return this._shapes.x.tubeRadius}set xyzRingRadius(e){this._setDiskProp("ringRadius",e);}get xyzRingRadius(){return this._shapes.x.ringRadius}set faceTubeRadius(e){this._shapes.f.tubeRadius=e;}get faceTubeRadius(){return this._shapes.f.tubeRadius}set faceRingRadius(e){this._shapes.f.ringRadius=e;}get faceRingRadius(){return this._shapes.f.ringRadius}set centerRadius(e){this._shapes.xyz.radius=e;}get centerRadius(){return this._shapes.xyz.radius}set ringTolerance(e){this._setDiskProp("tolerance",e),this._shapes.f.tolerance=e;}get ringTolerance(){return this._shapes.x.tolerance}set angleGuideThickness(e){this._guideAngleLines[0].thickness=e,this._guideAngleLines[1].thickness=e;}get angleGuideThickness(){return this._guideAngleLines[0].thickness}set orbitRotation(e){this.rotationMode=e?"orbit":"absolute";}get orbitRotation(){return "orbit"===this.rotationMode}_setDiskProp(e,t){this._shapes.x[e]=t,this._shapes.y[e]=t,this._shapes.z[e]=t;}_storeGuidePoints(){let e=this.root.getLocalPosition(),t="f"===this._selectedAxis?this.faceRingRadius:this.xyzRingRadius;this._guideAngleStart.copy(this._selectionStartPoint).sub(e).normalize(),this._guideAngleStart.mulScalar(t),this._guideAngleEnd.copy(this._guideAngleStart);}_updateGuidePoints(e){let t=this._selectedAxis;"f"===t?Ae.copy(this.facingDir):(Ae.set(0,0,0),Ae[t]=1,this._rootStartRot.transformVector(Ae,Ae)),As.setFromAxisAngle(Ae,e),As.transformVector(this._guideAngleStart,this._guideAngleEnd),this._renderUpdate=true;}_angleGuide(e){let t=this._selectedAxis;if(e&&"show"!==this.dragMode&&"xyz"!==t){let e=this.root.getLocalPosition(),i=this._theme.shapeHover[t],s=Aa.copy(i);s.a*=.3,this._guideAngleLines[0].draw(e,Ae.copy(this._guideAngleStart).add(e),this._scale,s),this._guideAngleLines[1].draw(e,Ae.copy(this._guideAngleEnd).add(e),this._scale,i),this._guideAngleLines[0].entity.enabled=true,this._guideAngleLines[1].entity.enabled=true;}else this._guideAngleLines[0].entity.enabled=false,this._guideAngleLines[1].entity.enabled=false;}_shapesLookAtCamera(){let e,t;if(0===this._camera.projection){let e=this._camera.entity.getPosition().sub(this.root.getPosition()).normalize(),t=Math.atan2(-e.y,Math.sqrt(e.x*e.x+e.z*e.z))*ei.RAD_TO_DEG,i=Math.atan2(-e.x,-e.z)*ei.RAD_TO_DEG;this._shapes.f.entity.setEulerAngles(-t+90,i,0);}else As.copy(this._camera.entity.getRotation()).getEulerAngles(Ae),this._shapes.f.entity.setEulerAngles(Ae),this._shapes.f.entity.rotateLocal(-90,0,0);let i=Ae.copy(this.facingDir);As.copy(this.root.getRotation()).invert().transformVector(i,i),e=Math.atan2(i.z,i.y)*ei.RAD_TO_DEG,this._shapes.x.entity.setLocalEulerAngles(0,e-90,-90),e=Math.atan2(i.x,i.z)*ei.RAD_TO_DEG,this._shapes.y.entity.setLocalEulerAngles(0,e,0),e=Math.atan2(i.y,i.x)*ei.RAD_TO_DEG,this._shapes.z.entity.setLocalEulerAngles(90,0,e+90),this._dragging||(t=1-Math.abs(i.dot(this.root.right))>1e-4,this._shapes.x.show(t?"sector":"ring"),t=1-Math.abs(i.dot(this.root.up))>1e-4,this._shapes.y.show(t?"sector":"ring"),t=1-Math.abs(i.dot(this.root.forward))>1e-4,this._shapes.z.show(t?"sector":"ring")),i.equalsApprox(this._facingDir,1e-6)||(this._facingDir.copy(i),this._renderUpdate=true);}_drag(e){for(let t in this._shapes){let i=this._shapes[t];if(i instanceof C6)switch(this.dragMode){case "show":break;case "hide":i.show(e?t===this._selectedAxis?"ring":"none":"sector");continue;case "selected":i.show(e&&t===this._selectedAxis?"ring":"sector");}}this._renderUpdate=true;}_storeNodeRotations(){let e=this.root.getLocalPosition();for(let t=0;t.9999)Ae.set(this._screenStartPos.y>=At.y?1:-1,this._screenStartPos.x>=At.x?-1:1,0).normalize();else {let e=Ae.cross(a.normal,o).normalize();this._camera.worldToScreen(e.add(s),Ai),Ae.sub2(Ai,At).normalize();}At.set(t,i,0),n=Ae.dot(At);break;case "orbit":switch(Ae.sub2(e,s),r){case "x":As.copy(this._rootStartRot).invert().transformVector(Ae,Ae),n=Math.atan2(Ae.z,Ae.y)*ei.RAD_TO_DEG;break;case "y":As.copy(this._rootStartRot).invert().transformVector(Ae,Ae),n=Math.atan2(Ae.x,Ae.z)*ei.RAD_TO_DEG;break;case "z":As.copy(this._rootStartRot).invert().transformVector(Ae,Ae),n=Math.atan2(Ae.y,Ae.x)*ei.RAD_TO_DEG;break;case "f":As.copy(this._camera.entity.getRotation()).invert().transformVector(Ae,Ae),n=Math.sign(l)*Math.atan2(Ae.y,Ae.x)*ei.RAD_TO_DEG;}0>Ae.sub2(e,this._camera.entity.getPosition()).normalize().dot(this._camera.entity.forward)&&(n+=180);}return n}_drawGuideLines(e,t,i,s){for(let r of An)"xyz"!==i&&(s?r!==i&&this._drawSpanLine(e,t,r):r===i&&this._drawSpanLine(e,t,r));}prerender(){super.prerender(),this.enabled&&this._shapesLookAtCamera();}destroy(){this._guideAngleLines.forEach(e=>e.destroy()),super.destroy();}constructor(e,t){super(e,t,"gizmo:rotate"),this._shapes={z:new C6(this._device,{axis:"z",layers:[this._layer.id],rotation:new ed(90,0,90),defaultColor:this._theme.shapeBase.z,hoverColor:this._theme.shapeHover.z,disabledColor:this._theme.disabled,sectorAngle:180}),x:new C6(this._device,{axis:"x",layers:[this._layer.id],rotation:new ed(0,0,-90),defaultColor:this._theme.shapeBase.x,hoverColor:this._theme.shapeHover.x,disabledColor:this._theme.disabled,sectorAngle:180}),y:new C6(this._device,{axis:"y",layers:[this._layer.id],rotation:new ed(0,0,0),defaultColor:this._theme.shapeBase.y,hoverColor:this._theme.shapeHover.y,disabledColor:this._theme.disabled,sectorAngle:180}),f:new C6(this._device,{axis:"f",layers:[this._layer.id],defaultColor:this._theme.shapeBase.f,hoverColor:this._theme.shapeHover.f,disabledColor:this._theme.disabled,ringRadius:.55}),xyz:new CJ(this._device,{axis:"xyz",layers:[this._layer.id],defaultColor:this._theme.shapeBase.xyz,hoverColor:this._theme.shapeHover.xyz,disabledColor:this._theme.disabled,radius:.5})},this._selectionStartAngle=0,this._nodeLocalRotations=new Map,this._nodeRotations=new Map,this._nodeOffsets=new Map,this._screenPos=new ef,this._screenStartPos=new ef,this._guideAngleStart=new ed,this._guideAngleEnd=new ed,this._facingDir=new ed,this.snapIncrement=5,this.rotationMode="absolute",this.setTheme({shapeBase:{xyz:new es(0,0,0,0)},shapeHover:{xyz:new es(1,1,1,.2)}}),this._createTransform(),this._guideAngleLines=[new C9(this._app,this._layer),new C9(this._app,this._layer)],this._guideAngleLines.forEach(e=>{this._app.root.addChild(e.entity),e.entity.enabled=false;}),this.on(Cz.EVENT_TRANSFORMSTART,(e,t,i)=>{this._screenPos.set(t,i),this._screenStartPos.set(t,i),this._selectionStartAngle=this._calculateArcAngle(e,t,i),this._storeNodeRotations(),this._storeGuidePoints(),this._drag(true),this._angleGuide(true);}),this.on(Cz.EVENT_TRANSFORMMOVE,(e,t,i)=>{let s=this._selectedAxis;if(s)if(this._screenPos.set(t,i),"xyz"===s){let t=Ae.copy(this.facingDir),i=At.copy(e).sub(this._selectionStartPoint),r=Ae.cross(t,i).normalize(),a=this._screenPos.distance(this._screenStartPos);this._setNodeRotations(s,r,a);}else {let r=this._calculateArcAngle(e,t,i)-this._selectionStartAngle;this.snap&&(r=Math.round(r/this.snapIncrement)*this.snapIncrement);let a=this._dirFromAxis(s,Ae);this._setNodeRotations(s,a,r),this._updateGuidePoints(r),this._angleGuide(true);}}),this.on(Cz.EVENT_TRANSFORMEND,()=>{this._drag(false),this._angleGuide(false);}),this.on(Cz.EVENT_NODESDETACH,()=>{this._nodeLocalRotations.clear(),this._nodeRotations.clear(),this._nodeOffsets.clear();});}},e.SAMPLETYPE_DEPTH=2,e.SAMPLETYPE_FLOAT=0,e.SAMPLETYPE_INT=3,e.SAMPLETYPE_UINT=4,e.SAMPLETYPE_UNFILTERABLE_FLOAT=1,e.SCALEMODE_BLEND=gB,e.SCALEMODE_NONE=gN,e.SCROLLBAR_VISIBILITY_SHOW_ALWAYS=0,e.SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED=1,e.SCROLL_MODE_BOUNCE=1,e.SCROLL_MODE_CLAMP=0,e.SCROLL_MODE_INFINITE=2,e.SEMANTIC_ATTR0=tu,e.SEMANTIC_ATTR1=tf,e.SEMANTIC_ATTR10=tT,e.SEMANTIC_ATTR11=tE,e.SEMANTIC_ATTR12=tw,e.SEMANTIC_ATTR13=tb,e.SEMANTIC_ATTR14=tC,e.SEMANTIC_ATTR15=tA,e.SEMANTIC_ATTR2=tp,e.SEMANTIC_ATTR3=tm,e.SEMANTIC_ATTR4=t_,e.SEMANTIC_ATTR5=tg,e.SEMANTIC_ATTR6=tv,e.SEMANTIC_ATTR7=tS,e.SEMANTIC_ATTR8=ty,e.SEMANTIC_ATTR9=tx,e.SEMANTIC_BLENDINDICES=tt,e.SEMANTIC_BLENDWEIGHT=te,e.SEMANTIC_COLOR=ti,e.SEMANTIC_NORMAL=e9,e.SEMANTIC_POSITION=e8,e.SEMANTIC_TANGENT=e7,e.SEMANTIC_TEXCOORD=ts,e.SEMANTIC_TEXCOORD0=tr,e.SEMANTIC_TEXCOORD1=ta,e.SEMANTIC_TEXCOORD2=tn,e.SEMANTIC_TEXCOORD3=to,e.SEMANTIC_TEXCOORD4=tl,e.SEMANTIC_TEXCOORD5=th,e.SEMANTIC_TEXCOORD6=tc,e.SEMANTIC_TEXCOORD7=td,e.SHADERDEF_BATCH=16384,e.SHADERDEF_DIRLM=128,e.SHADERDEF_INSTANCING=32,e.SHADERDEF_LM=64,e.SHADERDEF_LMAMBIENT=4096,e.SHADERDEF_MORPH_NORMAL=2048,e.SHADERDEF_MORPH_POSITION=1024,e.SHADERDEF_MORPH_TEXTURE_BASED_INT=8192,e.SHADERDEF_NOSHADOW=1,e.SHADERDEF_SCREENSPACE=256,e.SHADERDEF_SKIN=2,e.SHADERDEF_TANGENTS=512,e.SHADERDEF_UV0=4,e.SHADERDEF_UV1=8,e.SHADERDEF_VCOLOR=16,e.SHADERLANGUAGE_GLSL=tz,e.SHADERLANGUAGE_WGSL=tV,e.SHADERPASS_ALBEDO="debug_albedo",e.SHADERPASS_AO="debug_ao",e.SHADERPASS_EMISSION="debug_emission",e.SHADERPASS_FORWARD="forward",e.SHADERPASS_GLOSS="debug_gloss",e.SHADERPASS_LIGHTING="debug_lighting",e.SHADERPASS_METALNESS="debug_metalness",e.SHADERPASS_OPACITY="debug_opacity",e.SHADERPASS_SPECULARITY="debug_specularity",e.SHADERPASS_UV0="debug_uv0",e.SHADERPASS_WORLDNORMAL="debug_world_normal",e.SHADERSTAGE_COMPUTE=4,e.SHADERSTAGE_FRAGMENT=2,e.SHADERSTAGE_VERTEX=1,e.SHADERTAG_MATERIAL=1,e.SHADER_DEPTH_PICK=4,e.SHADER_FORWARD=0,e.SHADER_PICK=3,e.SHADER_PREPASS=1,e.SHADER_SHADOW=2,e.SHADOWCAMERA_NAME=nU,e.SHADOWUPDATE_NONE=0,e.SHADOWUPDATE_REALTIME=2,e.SHADOWUPDATE_THISFRAME=1,e.SHADOW_CASCADE_0=1,e.SHADOW_CASCADE_1=2,e.SHADOW_CASCADE_2=4,e.SHADOW_CASCADE_3=8,e.SHADOW_CASCADE_ALL=255,e.SHADOW_PCF1=5,e.SHADOW_PCF1_16F=7,e.SHADOW_PCF1_32F=5,e.SHADOW_PCF3=0,e.SHADOW_PCF3_16F=8,e.SHADOW_PCF3_32F=0,e.SHADOW_PCF5=4,e.SHADOW_PCF5_16F=9,e.SHADOW_PCF5_32F=4,e.SHADOW_PCSS_32F=6,e.SHADOW_VSM16=2,e.SHADOW_VSM32=3,e.SHADOW_VSM_16F=2,e.SHADOW_VSM_32F=3,e.SKYTYPE_BOX="box",e.SKYTYPE_DOME=nC,e.SKYTYPE_INFINITE=nb,e.SORTMODE_BACK2FRONT=3,e.SORTMODE_CUSTOM=5,e.SORTMODE_FRONT2BACK=4,e.SORTMODE_MANUAL=1,e.SORTMODE_MATERIALMESH=2,e.SORTMODE_NONE=0,e.SPECOCC_AO=1,e.SPECOCC_GLOSSDEPENDENT=2,e.SPECOCC_NONE=0,e.SPRITETYPE_ANIMATED=vr,e.SPRITETYPE_SIMPLE=vs,e.SPRITE_RENDERMODE_SIMPLE=0,e.SPRITE_RENDERMODE_SLICED=1,e.SPRITE_RENDERMODE_TILED=2,e.SSAOTYPE_COMBINE=bp,e.SSAOTYPE_LIGHTING=bf,e.SSAOTYPE_NONE=bu,e.STENCILOP_DECREMENT=5,e.STENCILOP_DECREMENTWRAP=6,e.STENCILOP_INCREMENT=3,e.STENCILOP_INCREMENTWRAP=4,e.STENCILOP_INVERT=7,e.STENCILOP_KEEP=0,e.STENCILOP_REPLACE=2,e.STENCILOP_ZERO=1,e.ScaleGizmo=class extends Cz{set coordSpace(e){}get coordSpace(){return this._coordSpace}set uniform(e){this._uniform=e??this._uniform;}get uniform(){return this._uniform}set axisGap(e){this._setArrowProp("gap",e);}get axisGap(){return this._shapes.x.gap}set axisLineThickness(e){this._setArrowProp("lineThickness",e);}get axisLineThickness(){return this._shapes.x.lineThickness}set axisLineLength(e){this._setArrowProp("lineLength",e);}get axisLineLength(){return this._shapes.x.lineLength}set axisLineTolerance(e){this._setArrowProp("tolerance",e);}get axisLineTolerance(){return this._shapes.x.tolerance}set axisBoxSize(e){this._setArrowProp("boxSize",e);}get axisBoxSize(){return this._shapes.x.boxSize}set axisPlaneSize(e){this._setPlaneProp("size",e);}get axisPlaneSize(){return this._shapes.yz.size}set axisPlaneGap(e){this._setPlaneProp("gap",e);}get axisPlaneGap(){return this._shapes.yz.gap}set axisCenterSize(e){this._shapes.xyz.size=e;}get axisCenterSize(){return this._shapes.xyz.size}set flipShapes(e){this.flipPlanes=e;}get flipShapes(){return this.flipPlanes}_setArrowProp(e,t){this._shapes.x[e]=t,this._shapes.y[e]=t,this._shapes.z[e]=t;}_setPlaneProp(e,t){this._shapes.yz[e]=t,this._shapes.xz[e]=t,this._shapes.xy[e]=t;}_shapesLookAtCamera(){let e,t,i=this.cameraDir,s=false;e=1-Math.abs(i.dot(this.root.right))>.01,this._shapes.x.entity.enabled!==e&&(this._shapes.x.entity.enabled=e,s=true),e=1-Math.abs(i.dot(this.root.up))>.01,this._shapes.y.entity.enabled!==e&&(this._shapes.y.entity.enabled=e,s=true),e=1-Math.abs(i.dot(this.root.forward))>.01,this._shapes.z.entity.enabled!==e&&(this._shapes.z.entity.enabled=e,s=true),Au.cross(i,this.root.right),e=1-Au.length()>.01,this._shapes.yz.entity.enabled!==e&&(this._shapes.yz.entity.enabled=e,s=true),t=this.flipPlanes?Af.set(0,+(0>Au.dot(this.root.forward)),+(0>Au.dot(this.root.up))):ed.ZERO,this._shapes.yz.flipped.equals(t)||(this._shapes.yz.flipped=t,s=true),Au.cross(i,this.root.forward),e=1-Au.length()>.01,this._shapes.xy.entity.enabled!==e&&(this._shapes.xy.entity.enabled=e,s=true),t=this.flipPlanes?Af.set(+(0>Au.dot(this.root.up)),+(Au.dot(this.root.right)>0),0):ed.ZERO,this._shapes.xy.flipped.equals(t)||(this._shapes.xy.flipped=t,s=true),Au.cross(i,this.root.up),e=1-Au.length()>.01,this._shapes.xz.entity.enabled!==e&&(this._shapes.xz.entity.enabled=e,s=true),t=this.flipPlanes?Af.set(+(Au.dot(this.root.forward)>0),0,+(Au.dot(this.root.right)>0)):ed.ZERO,this._shapes.xz.flipped.equals(t)||(this._shapes.xz.flipped=t,s=true),s&&(this._renderUpdate=true);}_drag(e){for(let t in this._shapes){let i=this._shapes[t];switch(this.dragMode){case "show":continue;case "hide":i.visible=!e;continue;case "selected":if("xyz"===this._selectedAxis){i.visible=!e||1===t.length;continue}if(this._selectedIsPlane){i.visible=!e||1===t.length&&!t.includes(this._selectedAxis);continue}i.visible=!e||t===this._selectedAxis;continue}}this._renderUpdate=true;}_storeNodeScales(){for(let e=0;e{this._storeNodeScales(),this._drag(true);}),this.on(Cz.EVENT_TRANSFORMMOVE,e=>{let t=Am.copy(e).sub(this._selectionStartPoint);this.snap&&(t.mulScalar(1/this.snapIncrement),t.round(),t.mulScalar(this.snapIncrement)),t.mulScalar(1/this._scale),this._setNodeScales(t.add(ed.ONE));}),this.on(Cz.EVENT_TRANSFORMEND,()=>{this._drag(false);}),this.on(Cz.EVENT_NODESDETACH,()=>{this._nodeScales.clear();});}},e.Scene=dw,e.SceneHandler=xQ,e.SceneRegistry=pe,e.SceneRegistryItem=f7,e.SceneSettingsHandler=class extends fQ{load(e,t){xU.load(e,this.maxRetries,t);}open(e,t){return t.settings}constructor(e){super(e,"scenesettings");}},e.ScopeId=iP,e.ScopeSpace=iI,e.ScreenComponent=gU,e.ScreenComponentSystem=gG,e.Script=vN,e.ScriptAttributes=vM,e.ScriptComponent=vz,e.ScriptComponentSystem=vH,e.ScriptHandler=x5,e.ScriptRegistry=f3,e.ScriptType=vU,e.ScrollViewComponent=gJ,e.ScrollViewComponentSystem=g2,e.ScrollbarComponent=g3,e.ScrollbarComponentSystem=g6,e.Shader=r_,e.ShaderChunks=n$,e.ShaderHandler=x6,e.ShaderMaterial=cT,e.ShaderPass=nq,e.ShaderUtils=nJ,e.SingleContactResult=gR,e.SingleGestureSource=class extends bJ{set layout(e){this._layout!==e&&(this._layout=e,this.read(),this._pointerData.clear());}get layout(){return this._layout}get joystick(){return this._joystick}_onPointerDown(e){let{pointerType:t,pointerId:i,clientX:s,clientY:r}=e;if(this._movementState.down(e),"touch"!==t)return;this._element?.setPointerCapture(i),this._pointerData.set(i,{x:s,y:r});let a=Date.now();(this._lastPointer.x-s)**2+(this._lastPointer.y-r)**2<100&&a-this._lastPointer.time<250&&this.deltas.doubleTap.append([1]),this._lastPointer.x=s,this._lastPointer.y=r,this._lastPointer.time=a,"joystick"===this._layout&&this.fire("joystick:position",this._joystick.down(s,r));}_onPointerMove(e){let{pointerType:t,pointerId:i,target:s,clientX:r,clientY:a}=e,[n,o]=this._movementState.move(e);if("touch"!==t||s!==this._element)return;let l=this._pointerData.get(i);l&&(l.x=r,l.y=a,"joystick"===this._layout?this.fire("joystick:position",this._joystick.move(r,a)):this.deltas.input.append([n,o]));}_onPointerUp(e){let{pointerType:t,pointerId:i}=e;this._movementState.up(e),"touch"!==t||(this._element?.releasePointerCapture(i),this._pointerData.get(i)&&(this._pointerData.delete(i),"joystick"===this._layout&&this.fire("joystick:position",this._joystick.up())));}attach(e){super.attach(e),this._element=e,this._element.addEventListener("pointerdown",this._onPointerDown),this._element.addEventListener("pointermove",this._onPointerMove),this._element.addEventListener("pointerup",this._onPointerUp),this._element.addEventListener("pointercancel",this._onPointerUp);}detach(){this._element&&(this._element.removeEventListener("pointerdown",this._onPointerDown),this._element.removeEventListener("pointermove",this._onPointerMove),this._element.removeEventListener("pointerup",this._onPointerUp),this._element.removeEventListener("pointercancel",this._onPointerUp),this._pointerData.clear(),super.detach());}read(){return this.deltas.input.append([this._joystick.value.x,this._joystick.value.y]),super.read()}destroy(){this._joystick.up(),super.destroy();}constructor(){super({input:[0,0],doubleTap:[0]}),this._movementState=b2(),this._layout="joystick",this._pointerData=new Map,this._lastPointer={x:0,y:0,time:0},this._joystick=new b4,this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this);}},e.Skeleton=dO,e.Skin=db,e.SkinBatchInstance=oi,e.SkinInstance=ot,e.Sky=de,e.SortedLoopArray=$,e.Sound=a9,e.SoundComponent=g7,e.SoundComponentSystem=vi,e.SoundInstance=ne,e.SoundInstance3d=nt,e.SoundManager=a8,e.SoundSlot=g9,e.SphereGeometry=c6,e.Sprite=dP,e.SpriteAnimationClip=va,e.SpriteComponent=vc,e.SpriteComponentSystem=vf,e.SpriteHandler=x7,e.StandardMaterial=ud,e.StandardMaterialOptions=d6,e.StencilParameters=iU,e.StorageBuffer=rO,e.TEXHINT_ASSET=2,e.TEXHINT_LIGHTMAP=3,e.TEXHINT_NONE=0,e.TEXHINT_SHADOWMAP=1,e.TEXPROPERTY_ADDRESS_U=4,e.TEXPROPERTY_ADDRESS_V=8,e.TEXPROPERTY_ADDRESS_W=16,e.TEXPROPERTY_ALL=255,e.TEXPROPERTY_ANISOTROPY=128,e.TEXPROPERTY_COMPARE_FUNC=64,e.TEXPROPERTY_COMPARE_ON_READ=32,e.TEXPROPERTY_MAG_FILTER=2,e.TEXPROPERTY_MIN_FILTER=1,e.TEXTUREDIMENSION_1D="1d",e.TEXTUREDIMENSION_2D="2d",e.TEXTUREDIMENSION_2D_ARRAY=tM,e.TEXTUREDIMENSION_3D="3d",e.TEXTUREDIMENSION_CUBE=tO,e.TEXTUREDIMENSION_CUBE_ARRAY=tF,e.TEXTURELOCK_NONE=0,e.TEXTURELOCK_READ=1,e.TEXTURELOCK_WRITE=2,e.TEXTUREPROJECTION_CUBE=tB,e.TEXTUREPROJECTION_EQUIRECT=tk,e.TEXTUREPROJECTION_NONE=tN,e.TEXTUREPROJECTION_OCTAHEDRAL=tU,e.TEXTURETYPE_DEFAULT=tP,e.TEXTURETYPE_RGBE=tD,e.TEXTURETYPE_RGBM=tI,e.TEXTURETYPE_RGBP=tR,e.TEXTURETYPE_SWIZZLEGGGR=tL,e.TONEMAP_ACES=3,e.TONEMAP_ACES2=4,e.TONEMAP_FILMIC=1,e.TONEMAP_HEJL=2,e.TONEMAP_LINEAR=0,e.TONEMAP_NEUTRAL=5,e.TONEMAP_NONE=6,e.TRACEID_ASSETS="Assets",e.TRACEID_BINDGROUPFORMAT_ALLOC="BindGroupFormatAlloc",e.TRACEID_BINDGROUP_ALLOC="BindGroupAlloc",e.TRACEID_COMPUTEPIPELINE_ALLOC="ComputePipelineAlloc",e.TRACEID_ELEMENT="Element",e.TRACEID_GPU_TIMINGS=E,e.TRACEID_OCTREE_RESOURCES="OctreeResources",e.TRACEID_PIPELINELAYOUT_ALLOC="PipelineLayoutAlloc",e.TRACEID_RENDERPIPELINE_ALLOC="RenderPipelineAlloc",e.TRACEID_RENDER_ACTION="RenderAction",e.TRACEID_RENDER_FRAME="RenderFrame",e.TRACEID_RENDER_FRAME_TIME="RenderFrameTime",e.TRACEID_RENDER_PASS="RenderPass",e.TRACEID_RENDER_PASS_DETAIL="RenderPassDetail",e.TRACEID_RENDER_QUEUE="RenderQueue",e.TRACEID_RENDER_TARGET_ALLOC="RenderTargetAlloc",e.TRACEID_SHADER_ALLOC="ShaderAlloc",e.TRACEID_SHADER_COMPILE="ShaderCompile",e.TRACEID_TEXTURES="Textures",e.TRACEID_TEXTURE_ALLOC="TextureAlloc",e.TRACEID_VRAM_IB="VRAM.Ib",e.TRACEID_VRAM_SB="VRAM.Sb",e.TRACEID_VRAM_TEXTURE="VRAM.Texture",e.TRACEID_VRAM_VB="VRAM.Vb",e.TYPE_FLOAT16=7,e.TYPE_FLOAT32=6,e.TYPE_INT16=2,e.TYPE_INT32=4,e.TYPE_INT8=0,e.TYPE_UINT16=3,e.TYPE_UINT32=5,e.TYPE_UINT8=1,e.Tags=Z,e.Template=Te,e.TemplateHandler=Tt,e.TextElement=_x,e.TextHandler=Ti,e.Texture=ic,e.TextureAtlas=dI,e.TextureAtlasHandler=Tn,e.TextureHandler=TI,e.TextureUtils=ir,e.TextureView=il,e.TorusGeometry=ub,e.Touch=a$,e.TouchDevice=aQ,e.TouchEvent=aZ,e.Tracing=et,e.TransformFeedback=class{static createShader(e,t,i,s){return new r_(e,rp.createDefinition(e,{name:i,vertexCode:t,feedbackVaryings:s,useTransformFeedback:true,fragmentCode:"void main(void) {gl_FragColor = vec4(0.0);}"}))}destroy(){this._destroyOutputBuffer&&this._outputBuffer.destroy();}process(e,t=true){let i=this.device,s=i.getRenderTarget();if(i.setRenderTarget(null),i.updateBegin(),i.setVertexBuffer(this._inputBuffer),i.setRaster(false),i.setTransformFeedbackBuffer(this._outputBuffer),i.setShader(e),i.draw({type:0,base:0,baseVertex:0,count:this._inputBuffer.numVertices,indexed:false}),i.setTransformFeedbackBuffer(null),i.setRaster(true),i.updateEnd(),i.setRenderTarget(s),t){let e=this._inputBuffer.impl.bufferId;this._inputBuffer.impl.bufferId=this._outputBuffer.impl.bufferId,this._outputBuffer.impl.bufferId=e,e=this._inputBuffer.impl.vao,this._inputBuffer.impl.vao=this._outputBuffer.impl.vao,this._outputBuffer.impl.vao=e;}}get inputBuffer(){return this._inputBuffer}get outputBuffer(){return this._outputBuffer}constructor(e,t,i=3){ void 0===t||t instanceof iR||(i=t,t=void 0),this.device=e.device;let s=this.device.gl,r=t??e;3===i&&r.usage!==i&&(s.bindBuffer(s.ARRAY_BUFFER,r.impl.bufferId),s.bufferData(s.ARRAY_BUFFER,r.storage,s.DYNAMIC_COPY)),this._inputBuffer=e,this._destroyOutputBuffer=!t,this._outputBuffer=t??new iR(e.device,e.format,e.numVertices,{usage:i,data:e.storage});}},e.TransformGizmo=Cz,e.TranslateGizmo=class extends Cz{set axisGap(e){this._setArrowProp("gap",e);}get axisGap(){return this._shapes.x.gap}set axisLineThickness(e){this._setArrowProp("lineThickness",e);}get axisLineThickness(){return this._shapes.x.lineThickness}set axisLineLength(e){this._setArrowProp("lineLength",e);}get axisLineLength(){return this._shapes.x.lineLength}set axisLineTolerance(e){this._setArrowProp("tolerance",e);}get axisLineTolerance(){return this._shapes.x.tolerance}set axisArrowThickness(e){this._setArrowProp("arrowThickness",e);}get axisArrowThickness(){return this._shapes.x.arrowThickness}set axisArrowLength(e){this._setArrowProp("arrowLength",e);}get axisArrowLength(){return this._shapes.x.arrowLength}set axisPlaneSize(e){this._setPlaneProp("size",e);}get axisPlaneSize(){return this._shapes.yz.size}set axisPlaneGap(e){this._setPlaneProp("gap",e);}get axisPlaneGap(){return this._shapes.yz.gap}set axisCenterSize(e){this._shapes.xyz.radius=e;}get axisCenterSize(){return this._shapes.xyz.radius}set flipShapes(e){this.flipPlanes=e;}get flipShapes(){return this.flipPlanes}_setArrowProp(e,t){this._shapes.x[e]=t,this._shapes.y[e]=t,this._shapes.z[e]=t;}_setPlaneProp(e,t){this._shapes.yz[e]=t,this._shapes.xz[e]=t,this._shapes.xy[e]=t;}_shapesLookAtCamera(){let e,t,i=this.cameraDir,s=false;e=1-Math.abs(i.dot(this.root.right))>.01,this._shapes.x.entity.enabled!==e&&(this._shapes.x.entity.enabled=e,s=true),e=1-Math.abs(i.dot(this.root.up))>.01,this._shapes.y.entity.enabled!==e&&(this._shapes.y.entity.enabled=e,s=true),e=1-Math.abs(i.dot(this.root.forward))>.01,this._shapes.z.entity.enabled!==e&&(this._shapes.z.entity.enabled=e,s=true),C0.cross(i,this.root.right),e=1-C0.length()>.01,this._shapes.yz.entity.enabled!==e&&(this._shapes.yz.entity.enabled=e,s=true),t=this.flipPlanes?C1.set(0,+(0>C0.dot(this.root.forward)),+(0>C0.dot(this.root.up))):ed.ZERO,this._shapes.yz.flipped.equals(t)||(this._shapes.yz.flipped=t,s=true),C0.cross(i,this.root.forward),e=1-C0.length()>.01,this._shapes.xy.entity.enabled!==e&&(this._shapes.xy.entity.enabled=e,s=true),t=this.flipPlanes?C1.set(+(0>C0.dot(this.root.up)),+(C0.dot(this.root.right)>0),0):ed.ZERO,this._shapes.xy.flipped.equals(t)||(this._shapes.xy.flipped=t,s=true),C0.cross(i,this.root.up),e=1-C0.length()>.01,this._shapes.xz.entity.enabled!==e&&(this._shapes.xz.entity.enabled=e,s=true),t=this.flipPlanes?C1.set(+(C0.dot(this.root.forward)>0),0,+(C0.dot(this.root.right)>0)):ed.ZERO,this._shapes.xz.flipped.equals(t)||(this._shapes.xz.flipped=t,s=true),s&&(this._renderUpdate=true);}_drag(e){for(let t in this._shapes){let i=this._shapes[t];switch(this.dragMode){case "show":continue;case "hide":i.visible=!e;continue;case "selected":if("xyz"===this._selectedAxis){i.visible=!e||1===t.length;continue}if(this._selectedIsPlane){i.visible=!e||1===t.length&&!t.includes(this._selectedAxis);continue}i.visible=!e||t===this._selectedAxis;}}this._renderUpdate=true;}_storeNodePositions(){for(let e=0;e{this._storeNodePositions(),this._drag(true);}),this.on(Cz.EVENT_TRANSFORMMOVE,e=>{let t=C3.copy(e).sub(this._selectionStartPoint);this.snap&&(t.mulScalar(1/this.snapIncrement),t.round(),t.mulScalar(this.snapIncrement)),this._setNodePositions(t);}),this.on(Cz.EVENT_TRANSFORMEND,()=>{this._drag(false);}),this.on(Cz.EVENT_NODESDETACH,()=>{this._nodeLocalPositions.clear(),this._nodePositions.clear();});}},e.Tri=eH,e.UNIFORMTYPE_BOOL=0,e.UNIFORMTYPE_BOOLARRAY=32,e.UNIFORMTYPE_BVEC2=9,e.UNIFORMTYPE_BVEC2ARRAY=35,e.UNIFORMTYPE_BVEC3=10,e.UNIFORMTYPE_BVEC3ARRAY=38,e.UNIFORMTYPE_BVEC4=11,e.UNIFORMTYPE_BVEC4ARRAY=41,e.UNIFORMTYPE_FLOAT=2,e.UNIFORMTYPE_FLOATARRAY=17,e.UNIFORMTYPE_INT=1,e.UNIFORMTYPE_INTARRAY=30,e.UNIFORMTYPE_ITEXTURE2D=42,e.UNIFORMTYPE_ITEXTURE2D_ARRAY=48,e.UNIFORMTYPE_ITEXTURE3D=46,e.UNIFORMTYPE_ITEXTURECUBE=44,e.UNIFORMTYPE_IVEC2=6,e.UNIFORMTYPE_IVEC2ARRAY=33,e.UNIFORMTYPE_IVEC3=7,e.UNIFORMTYPE_IVEC3ARRAY=36,e.UNIFORMTYPE_IVEC4=8,e.UNIFORMTYPE_IVEC4ARRAY=39,e.UNIFORMTYPE_MAT2=12,e.UNIFORMTYPE_MAT3=13,e.UNIFORMTYPE_MAT4=14,e.UNIFORMTYPE_MAT4ARRAY=24,e.UNIFORMTYPE_TEXTURE2D=15,e.UNIFORMTYPE_TEXTURE2D_ARRAY=25,e.UNIFORMTYPE_TEXTURE2D_SHADOW=18,e.UNIFORMTYPE_TEXTURE3D=20,e.UNIFORMTYPE_TEXTURECUBE=16,e.UNIFORMTYPE_TEXTURECUBE_SHADOW=19,e.UNIFORMTYPE_UINT=26,e.UNIFORMTYPE_UINTARRAY=31,e.UNIFORMTYPE_UTEXTURE2D=43,e.UNIFORMTYPE_UTEXTURE2D_ARRAY=49,e.UNIFORMTYPE_UTEXTURE3D=47,e.UNIFORMTYPE_UTEXTURECUBE=45,e.UNIFORMTYPE_UVEC2=27,e.UNIFORMTYPE_UVEC2ARRAY=34,e.UNIFORMTYPE_UVEC3=28,e.UNIFORMTYPE_UVEC3ARRAY=37,e.UNIFORMTYPE_UVEC4=29,e.UNIFORMTYPE_UVEC4ARRAY=40,e.UNIFORMTYPE_VEC2=3,e.UNIFORMTYPE_VEC2ARRAY=21,e.UNIFORMTYPE_VEC3=4,e.UNIFORMTYPE_VEC3ARRAY=22,e.UNIFORMTYPE_VEC4=5,e.UNIFORMTYPE_VEC4ARRAY=23,e.UNIFORM_BUFFER_DEFAULT_SLOT_NAME=tQ,e.UNUSED_UNIFORM_NAME=tJ,e.URI=ee,e.UniformBufferFormat=sg,e.UniformFormat=s_,e.UsdzExporter=class extends wx{init(){this.meshMap=new Map,this.textureMap=new Map,this.materialMap=new Map,this.materials=[],this.files={},this.nodeNames=new Set;}done(){this.meshMap=null,this.textureMap=null,this.materialMap=null,this.materials=null,this.files=null,this.nodeNames=null;}build(e,t={}){let i;this.init(),this.addFile(null,br);let s=[];e&&e.findComponents("render").forEach(e=>{s.push(...e.meshInstances);});let r="";s.forEach(e=>{r+=this.buildMeshInstance(e);}),r+=(i=this.materials,` -def "Materials" -{ - ${i.join("\n")} + `};var OH=new Jt;OH.positions=[];OH.normals=[];var hr=class{constructor(t,e,s){n(this,"_position",new x);n(this,"_rotation",new x);n(this,"_scale",new x(1,1,1));n(this,"_layers",[]);n(this,"_material",new ct(rC));n(this,"_disabled",!1);n(this,"_visible",!0);n(this,"_defaultColor",F.WHITE);n(this,"_hoverColor",F.BLACK);n(this,"_disabledColor",iC);n(this,"_cull",1);n(this,"_depth",-1);n(this,"device");n(this,"axis");n(this,"entity");n(this,"triData",[]);n(this,"meshInstances",[]);this.device=t,this.axis=s.axis??"x",s.position instanceof x&&this._position.copy(s.position),s.rotation instanceof x&&this._rotation.copy(s.rotation),s.scale instanceof x&&this._scale.copy(s.scale),this._disabled=s.disabled??this._disabled,this._visible=s.visible??this._visible,this._layers=s.layers??this._layers,s.defaultColor instanceof F&&(this._defaultColor=s.defaultColor),s.hoverColor instanceof F&&(this._hoverColor=s.hoverColor),s.disabledColor instanceof F&&(this._disabledColor=s.disabledColor),this._cull=s.cull??this._cull,this._depth=s.depth??this._depth,this.entity=new Ne(`${e}:${this.axis}`),this.entity.setLocalPosition(this._position),this.entity.setLocalEulerAngles(this._rotation),this.entity.setLocalScale(this._scale)}set disabled(t){this._disabled=t??!1,this.hover(!1)}get disabled(){return this._disabled}set visible(t){if(t!==this._visible){for(let e=0;e0?"1":"0"),this._material.setParameter("uDepth",this._depth),this._material.setParameter("uColor",s.toArray()),this._material.cull=this._cull,this._material.blendType=ls,this._material.update();let i=[];for(let r=0;r{this._storeNodePositions(),this._drag(!0)}),this.on(is.EVENT_TRANSFORMMOVE,i=>{let r=j9.copy(i).sub(this._selectionStartPoint);this.snap&&(r.mulScalar(1/this.snapIncrement),r.round(),r.mulScalar(this.snapIncrement)),this._setNodePositions(r)}),this.on(is.EVENT_TRANSFORMEND,()=>{this._drag(!1)}),this.on(is.EVENT_NODESDETACH,()=>{this._nodeLocalPositions.clear(),this._nodePositions.clear()})}set axisGap(e){this._setArrowProp("gap",e)}get axisGap(){return this._shapes.x.gap}set axisLineThickness(e){this._setArrowProp("lineThickness",e)}get axisLineThickness(){return this._shapes.x.lineThickness}set axisLineLength(e){this._setArrowProp("lineLength",e)}get axisLineLength(){return this._shapes.x.lineLength}set axisLineTolerance(e){this._setArrowProp("tolerance",e)}get axisLineTolerance(){return this._shapes.x.tolerance}set axisArrowThickness(e){this._setArrowProp("arrowThickness",e)}get axisArrowThickness(){return this._shapes.x.arrowThickness}set axisArrowLength(e){this._setArrowProp("arrowLength",e)}get axisArrowLength(){return this._shapes.x.arrowLength}set axisPlaneSize(e){this._setPlaneProp("size",e)}get axisPlaneSize(){return this._shapes.yz.size}set axisPlaneGap(e){this._setPlaneProp("gap",e)}get axisPlaneGap(){return this._shapes.yz.gap}set axisCenterSize(e){this._shapes.xyz.radius=e}get axisCenterSize(){return this._shapes.xyz.radius}set flipShapes(e){this.flipPlanes=e}get flipShapes(){return this.flipPlanes}_setArrowProp(e,s){this._shapes.x[e]=s,this._shapes.y[e]=s,this._shapes.z[e]=s}_setPlaneProp(e,s){this._shapes.yz[e]=s,this._shapes.xz[e]=s,this._shapes.xy[e]=s}_shapesLookAtCamera(){let e=this.cameraDir,s=!1,i,r;i=e.dot(this.root.right),r=1-Math.abs(i)>gg,this._shapes.x.entity.enabled!==r&&(this._shapes.x.entity.enabled=r,s=!0),i=e.dot(this.root.up),r=1-Math.abs(i)>gg,this._shapes.y.entity.enabled!==r&&(this._shapes.y.entity.enabled=r,s=!0),i=e.dot(this.root.forward),r=1-Math.abs(i)>gg,this._shapes.z.entity.enabled!==r&&(this._shapes.z.entity.enabled=r,s=!0);let a;ti.cross(e,this.root.right),r=1-ti.length()>gg,this._shapes.yz.entity.enabled!==r&&(this._shapes.yz.entity.enabled=r,s=!0),a=this.flipPlanes?fo.set(0,+(ti.dot(this.root.forward)<0),+(ti.dot(this.root.up)<0)):x.ZERO,this._shapes.yz.flipped.equals(a)||(this._shapes.yz.flipped=a,s=!0),ti.cross(e,this.root.forward),r=1-ti.length()>gg,this._shapes.xy.entity.enabled!==r&&(this._shapes.xy.entity.enabled=r,s=!0),a=this.flipPlanes?fo.set(+(ti.dot(this.root.up)<0),+(ti.dot(this.root.right)>0),0):x.ZERO,this._shapes.xy.flipped.equals(a)||(this._shapes.xy.flipped=a,s=!0),ti.cross(e,this.root.up),r=1-ti.length()>gg,this._shapes.xz.entity.enabled!==r&&(this._shapes.xz.entity.enabled=r,s=!0),a=this.flipPlanes?fo.set(+(ti.dot(this.root.forward)>0),0,+(ti.dot(this.root.right)>0)):x.ZERO,this._shapes.xz.flipped.equals(a)||(this._shapes.xz.flipped=a,s=!0),s&&(this._renderUpdate=!0)}_drag(e){for(let s in this._shapes){let i=this._shapes[s];switch(this.dragMode){case"show":continue;case"hide":{i.visible=!e;continue}case"selected":{if(this._selectedAxis==="xyz"){i.visible=e?s.length===1:!0;continue}if(this._selectedIsPlane){i.visible=e?s.length===1&&!s.includes(this._selectedAxis):!0;continue}i.visible=e?s===this._selectedAxis:!0}}}this._renderUpdate=!0}_storeNodePositions(){for(let e=0;e{this._app.root.addChild(i.entity),i.entity.enabled=!1}),this.on(is.EVENT_TRANSFORMSTART,(i,r,a)=>{this._screenPos.set(r,a),this._screenStartPos.set(r,a),this._selectionStartAngle=this._calculateArcAngle(i,r,a),this._storeNodeRotations(),this._storeGuidePoints(),this._drag(!0),this._angleGuide(!0)}),this.on(is.EVENT_TRANSFORMMOVE,(i,r,a)=>{let o=this._selectedAxis;if(o)if(this._screenPos.set(r,a),o==="xyz"){let l=Ke.copy(this.facingDir),h=$u.copy(i).sub(this._selectionStartPoint),f=Ke.cross(l,h).normalize(),u=this._screenPos.distance(this._screenStartPos);this._setNodeRotations(o,f,u)}else{let l=this._calculateArcAngle(i,r,a)-this._selectionStartAngle;this.snap&&(l=Math.round(l/this.snapIncrement)*this.snapIncrement);let h=this._dirFromAxis(o,Ke);this._setNodeRotations(o,h,l),this._updateGuidePoints(l),this._angleGuide(!0)}}),this.on(is.EVENT_TRANSFORMEND,()=>{this._drag(!1),this._angleGuide(!1)}),this.on(is.EVENT_NODESDETACH,()=>{this._nodeLocalRotations.clear(),this._nodeRotations.clear(),this._nodeOffsets.clear()})}set xyzTubeRadius(e){this._setDiskProp("tubeRadius",e)}get xyzTubeRadius(){return this._shapes.x.tubeRadius}set xyzRingRadius(e){this._setDiskProp("ringRadius",e)}get xyzRingRadius(){return this._shapes.x.ringRadius}set faceTubeRadius(e){this._shapes.f.tubeRadius=e}get faceTubeRadius(){return this._shapes.f.tubeRadius}set faceRingRadius(e){this._shapes.f.ringRadius=e}get faceRingRadius(){return this._shapes.f.ringRadius}set centerRadius(e){this._shapes.xyz.radius=e}get centerRadius(){return this._shapes.xyz.radius}set ringTolerance(e){this._setDiskProp("tolerance",e),this._shapes.f.tolerance=e}get ringTolerance(){return this._shapes.x.tolerance}set angleGuideThickness(e){this._guideAngleLines[0].thickness=e,this._guideAngleLines[1].thickness=e}get angleGuideThickness(){return this._guideAngleLines[0].thickness}set orbitRotation(e){this.rotationMode=e?"orbit":"absolute"}get orbitRotation(){return this.rotationMode==="orbit"}_setDiskProp(e,s){this._shapes.x[e]=s,this._shapes.y[e]=s,this._shapes.z[e]=s}_storeGuidePoints(){let e=this.root.getLocalPosition(),r=this._selectedAxis==="f"?this.faceRingRadius:this.xyzRingRadius;this._guideAngleStart.copy(this._selectionStartPoint).sub(e).normalize(),this._guideAngleStart.mulScalar(r),this._guideAngleEnd.copy(this._guideAngleStart)}_updateGuidePoints(e){let s=this._selectedAxis;s==="f"?Ke.copy(this.facingDir):(Ke.set(0,0,0),Ke[s]=1,this._rootStartRot.transformVector(Ke,Ke)),Sa.setFromAxisAngle(Ke,e),Sa.transformVector(this._guideAngleStart,this._guideAngleEnd),this._renderUpdate=!0}_angleGuide(e){let s=this._selectedAxis;if(e&&this.dragMode!=="show"&&s!=="xyz"){let i=this.root.getLocalPosition(),r=this._theme.shapeHover[s],a=J9.copy(r);a.a*=.3,this._guideAngleLines[0].draw(i,Ke.copy(this._guideAngleStart).add(i),this._scale,a),this._guideAngleLines[1].draw(i,Ke.copy(this._guideAngleEnd).add(i),this._scale,r),this._guideAngleLines[0].entity.enabled=!0,this._guideAngleLines[1].entity.enabled=!0}else this._guideAngleLines[0].entity.enabled=!1,this._guideAngleLines[1].entity.enabled=!1}_shapesLookAtCamera(){if(this._camera.projection===ts){let a=this._camera.entity.getPosition().sub(this.root.getPosition()).normalize(),o=Math.atan2(-a.y,Math.sqrt(a.x*a.x+a.z*a.z))*R.RAD_TO_DEG,l=Math.atan2(-a.x,-a.z)*R.RAD_TO_DEG;this._shapes.f.entity.setEulerAngles(-o+90,l,0)}else Sa.copy(this._camera.entity.getRotation()).getEulerAngles(Ke),this._shapes.f.entity.setEulerAngles(Ke),this._shapes.f.entity.rotateLocal(-90,0,0);let e,s,i,r=Ke.copy(this.facingDir);Sa.copy(this.root.getRotation()).invert().transformVector(r,r),e=Math.atan2(r.z,r.y)*R.RAD_TO_DEG,this._shapes.x.entity.setLocalEulerAngles(0,e-90,-90),e=Math.atan2(r.x,r.z)*R.RAD_TO_DEG,this._shapes.y.entity.setLocalEulerAngles(0,e,0),e=Math.atan2(r.y,r.x)*R.RAD_TO_DEG,this._shapes.z.entity.setLocalEulerAngles(90,0,e+90),this._dragging||(s=r.dot(this.root.right),i=1-Math.abs(s)>fC,this._shapes.x.show(i?"sector":"ring"),s=r.dot(this.root.up),i=1-Math.abs(s)>fC,this._shapes.y.show(i?"sector":"ring"),s=r.dot(this.root.forward),i=1-Math.abs(s)>fC,this._shapes.z.show(i?"sector":"ring")),r.equalsApprox(this._facingDir,e7)||(this._facingDir.copy(r),this._renderUpdate=!0)}_drag(e){for(let s in this._shapes){let i=this._shapes[s];if(i instanceof Nh)switch(this.dragMode){case"show":break;case"hide":{i.show(e?s===this._selectedAxis?"ring":"none":"sector");continue}case"selected":{i.show(e&&s===this._selectedAxis?"ring":"sector");break}}}this._renderUpdate=!0}_storeNodeRotations(){let e=this.root.getLocalPosition();for(let s=0;s1-fC)Ke.set(this._screenStartPos.y>=$u.y?1:-1,this._screenStartPos.x>=$u.x?-1:1,0).normalize();else{let u=Ke.cross(o.normal,h).normalize();this._camera.worldToScreen(u.add(r),NH),Ke.sub2(NH,$u).normalize()}$u.set(s,i,0),l=Ke.dot($u);break}case"orbit":{switch(Ke.sub2(e,r),a){case"x":{Sa.copy(this._rootStartRot).invert().transformVector(Ke,Ke),l=Math.atan2(Ke.z,Ke.y)*R.RAD_TO_DEG;break}case"y":{Sa.copy(this._rootStartRot).invert().transformVector(Ke,Ke),l=Math.atan2(Ke.x,Ke.z)*R.RAD_TO_DEG;break}case"z":{Sa.copy(this._rootStartRot).invert().transformVector(Ke,Ke),l=Math.atan2(Ke.y,Ke.x)*R.RAD_TO_DEG;break}case"f":{Sa.copy(this._camera.entity.getRotation()).invert().transformVector(Ke,Ke),l=Math.sign(f)*Math.atan2(Ke.y,Ke.x)*R.RAD_TO_DEG;break}}Ke.sub2(e,this._camera.entity.getPosition()).normalize().dot(this._camera.entity.forward)<0&&(l+=180);break}}return l}_drawGuideLines(e,s,i,r){for(let a of t7)i!=="xyz"&&(r?a!==i&&this._drawSpanLine(e,s,a):a===i&&this._drawSpanLine(e,s,a))}prerender(){super.prerender(),this.enabled&&this._shapesLookAtCamera()}destroy(){this._guideAngleLines.forEach(e=>e.destroy()),super.destroy()}};var dC=class extends hr{constructor(e,s={}){super(e,"boxCenter",s);n(this,"_size",.06);this._size=s.size??this._size,this.triData=[new ui(new ci,2)],this._createRenderComponent(this.entity,[_e.fromGeometry(this.device,new ci)]),this._update()}set size(e){this._size=e??this._size,this._update()}get size(){return this._size}_update(){this.entity.setLocalScale(this._size,this._size,this._size)}};var Zu=new x,pC=new x,mC=new $,Sg=class extends hr{constructor(e,s={}){super(e,"boxLine",s);n(this,"_gap",0);n(this,"_lineThickness",.02);n(this,"_lineLength",.5);n(this,"_boxSize",.12);n(this,"_tolerance",.1);n(this,"_box");n(this,"_line");n(this,"_flipped",!1);this._gap=s.gap??this._gap,this._lineThickness=s.lineThickness??this._lineThickness,this._lineLength=s.lineLength??this._lineLength,this._boxSize=s.boxSize??this._boxSize,this._tolerance=s.tolerance??this._tolerance,this.triData=[new ui(new ci),new ui(new Ci,1)],this._box=new Ne(`box:${this.axis}`),this.entity.addChild(this._box),this._createRenderComponent(this._box,[_e.fromGeometry(this.device,new ci)]),this._line=new Ne(`line:${this.axis}`),this.entity.addChild(this._line),this._createRenderComponent(this._line,[_e.fromGeometry(this.device,new Ci)]),this._update()}set gap(e){this._gap=e??this._gap,this._update()}get gap(){return this._gap}set lineThickness(e){this._lineThickness=e??this._lineThickness,this._update()}get lineThickness(){return this._lineThickness}set lineLength(e){this._lineLength=e??this._lineLength,this._update()}get lineLength(){return this._lineLength}set boxSize(e){this._boxSize=e??this._boxSize,this._update()}get boxSize(){return this._boxSize}set tolerance(e){this._tolerance=e,this._update()}get tolerance(){return this._tolerance}set flipped(e){this._flipped!==e&&(this._flipped=e,this._rotation.equals(x.ZERO)?Zu.set(0,0,this._flipped?180:0):Zu.copy(this._rotation).mulScalar(this._flipped?-1:1),this._line.enabled=!this._flipped,this.entity.setLocalEulerAngles(Zu))}get flipped(){return this._flipped}_update(){Zu.set(0,this._gap+this._boxSize*.5+this._lineLength,0),mC.set(0,0,0,1),pC.set(this._boxSize,this._boxSize,this._boxSize),this.triData[0].setTransform(Zu,mC,pC),Zu.set(0,this._gap+this._lineLength*.5,0),mC.set(0,0,0,1),pC.set(this._lineThickness+this._tolerance,this._lineLength,this._lineThickness+this._tolerance),this.triData[1].setTransform(Zu,mC,pC),this._box.setLocalPosition(0,this._gap+this._boxSize*.5+this._lineLength,0),this._box.setLocalScale(this._boxSize,this._boxSize,this._boxSize),this._line.setLocalPosition(0,this._gap+this._lineLength*.5,0),this._line.setLocalScale(this._lineThickness,this._lineLength,this._lineThickness)}};var si=new x,_C=new x,xa=new x,s7=new x,i7=new $,xg=.01,gC=class extends is{constructor(e,s){super(e,s,"gizmo:scale");n(this,"_shapes",{xyz:new dC(this._device,{axis:"xyz",layers:[this._layer.id],defaultColor:this._theme.shapeBase.xyz,hoverColor:this._theme.shapeHover.xyz,disabledColor:this._theme.disabled}),yz:new un(this._device,{axis:"x",layers:[this._layer.id],rotation:new x(0,0,-90),defaultColor:this._theme.shapeBase.x,hoverColor:this._theme.shapeHover.x,disabledColor:this._theme.disabled,depth:1}),xz:new un(this._device,{axis:"y",layers:[this._layer.id],rotation:new x(0,0,0),defaultColor:this._theme.shapeBase.y,hoverColor:this._theme.shapeHover.y,disabledColor:this._theme.disabled,depth:1}),xy:new un(this._device,{axis:"z",layers:[this._layer.id],rotation:new x(90,0,0),defaultColor:this._theme.shapeBase.z,hoverColor:this._theme.shapeHover.z,disabledColor:this._theme.disabled,depth:1}),x:new Sg(this._device,{axis:"x",layers:[this._layer.id],rotation:new x(0,0,-90),defaultColor:this._theme.shapeBase.x,hoverColor:this._theme.shapeHover.x,disabledColor:this._theme.disabled}),y:new Sg(this._device,{axis:"y",layers:[this._layer.id],rotation:new x(0,0,0),defaultColor:this._theme.shapeBase.y,hoverColor:this._theme.shapeHover.y,disabledColor:this._theme.disabled}),z:new Sg(this._device,{axis:"z",layers:[this._layer.id],rotation:new x(90,0,0),defaultColor:this._theme.shapeBase.z,hoverColor:this._theme.shapeHover.z,disabledColor:this._theme.disabled})});n(this,"_coordSpace","local");n(this,"_nodeScales",new Map);n(this,"_uniform",!1);n(this,"snapIncrement",1);n(this,"flipPlanes",!0);n(this,"lowerBoundScale",new x(-1/0,-1/0,-1/0));this._createTransform(),this.on(is.EVENT_TRANSFORMSTART,()=>{this._storeNodeScales(),this._drag(!0)}),this.on(is.EVENT_TRANSFORMMOVE,i=>{let r=s7.copy(i).sub(this._selectionStartPoint);this.snap&&(r.mulScalar(1/this.snapIncrement),r.round(),r.mulScalar(this.snapIncrement)),r.mulScalar(1/this._scale),this._setNodeScales(r.add(x.ONE))}),this.on(is.EVENT_TRANSFORMEND,()=>{this._drag(!1)}),this.on(is.EVENT_NODESDETACH,()=>{this._nodeScales.clear()})}set coordSpace(e){}get coordSpace(){return this._coordSpace}set uniform(e){this._uniform=e??this._uniform}get uniform(){return this._uniform}set axisGap(e){this._setArrowProp("gap",e)}get axisGap(){return this._shapes.x.gap}set axisLineThickness(e){this._setArrowProp("lineThickness",e)}get axisLineThickness(){return this._shapes.x.lineThickness}set axisLineLength(e){this._setArrowProp("lineLength",e)}get axisLineLength(){return this._shapes.x.lineLength}set axisLineTolerance(e){this._setArrowProp("tolerance",e)}get axisLineTolerance(){return this._shapes.x.tolerance}set axisBoxSize(e){this._setArrowProp("boxSize",e)}get axisBoxSize(){return this._shapes.x.boxSize}set axisPlaneSize(e){this._setPlaneProp("size",e)}get axisPlaneSize(){return this._shapes.yz.size}set axisPlaneGap(e){this._setPlaneProp("gap",e)}get axisPlaneGap(){return this._shapes.yz.gap}set axisCenterSize(e){this._shapes.xyz.size=e}get axisCenterSize(){return this._shapes.xyz.size}set flipShapes(e){this.flipPlanes=e}get flipShapes(){return this.flipPlanes}_setArrowProp(e,s){this._shapes.x[e]=s,this._shapes.y[e]=s,this._shapes.z[e]=s}_setPlaneProp(e,s){this._shapes.yz[e]=s,this._shapes.xz[e]=s,this._shapes.xy[e]=s}_shapesLookAtCamera(){let e=this.cameraDir,s=!1,i,r;i=e.dot(this.root.right),r=1-Math.abs(i)>xg,this._shapes.x.entity.enabled!==r&&(this._shapes.x.entity.enabled=r,s=!0),i=e.dot(this.root.up),r=1-Math.abs(i)>xg,this._shapes.y.entity.enabled!==r&&(this._shapes.y.entity.enabled=r,s=!0),i=e.dot(this.root.forward),r=1-Math.abs(i)>xg,this._shapes.z.entity.enabled!==r&&(this._shapes.z.entity.enabled=r,s=!0);let a;si.cross(e,this.root.right),r=1-si.length()>xg,this._shapes.yz.entity.enabled!==r&&(this._shapes.yz.entity.enabled=r,s=!0),a=this.flipPlanes?_C.set(0,+(si.dot(this.root.forward)<0),+(si.dot(this.root.up)<0)):x.ZERO,this._shapes.yz.flipped.equals(a)||(this._shapes.yz.flipped=a,s=!0),si.cross(e,this.root.forward),r=1-si.length()>xg,this._shapes.xy.entity.enabled!==r&&(this._shapes.xy.entity.enabled=r,s=!0),a=this.flipPlanes?_C.set(+(si.dot(this.root.up)<0),+(si.dot(this.root.right)>0),0):x.ZERO,this._shapes.xy.flipped.equals(a)||(this._shapes.xy.flipped=a,s=!0),si.cross(e,this.root.up),r=1-si.length()>xg,this._shapes.xz.entity.enabled!==r&&(this._shapes.xz.entity.enabled=r,s=!0),a=this.flipPlanes?_C.set(+(si.dot(this.root.forward)>0),0,+(si.dot(this.root.right)>0)):x.ZERO,this._shapes.xz.flipped.equals(a)||(this._shapes.xz.flipped=a,s=!0),s&&(this._renderUpdate=!0)}_drag(e){for(let s in this._shapes){let i=this._shapes[s];switch(this.dragMode){case"show":continue;case"hide":{i.visible=!e;continue}case"selected":{if(this._selectedAxis==="xyz"){i.visible=e?s.length===1:!0;continue}if(this._selectedIsPlane){i.visible=e?s.length===1&&!s.includes(this._selectedAxis):!0;continue}i.visible=e?s===this._selectedAxis:!0;continue}}}this._renderUpdate=!0}_storeNodeScales(){for(let e=0;e{this.fire(Gl.EVENT_CAMERAALIGN,x.RIGHT)}),this._shapes.py.children[0].addEventListener("pointerdown",()=>{this.fire(Gl.EVENT_CAMERAALIGN,x.UP)}),this._shapes.pz.children[0].addEventListener("pointerdown",()=>{this.fire(Gl.EVENT_CAMERAALIGN,x.BACK)}),this._shapes.nx.children[0].addEventListener("pointerdown",()=>{this.fire(Gl.EVENT_CAMERAALIGN,x.LEFT)}),this._shapes.ny.children[0].addEventListener("pointerdown",()=>{this.fire(Gl.EVENT_CAMERAALIGN,x.DOWN)}),this._shapes.nz.children[0].addEventListener("pointerdown",()=>{this.fire(Gl.EVENT_CAMERAALIGN,x.FORWARD)}),this.dom.appendChild(this._svg)}set anchor(e){this._anchor.copy(e),this.dom.style.top=this._anchor.x?"0px":"auto",this.dom.style.right=this._anchor.y?"0px":"auto",this.dom.style.bottom=this._anchor.z?"0px":"auto",this.dom.style.left=this._anchor.w?"0px":"auto"}get anchor(){return this._anchor}set colorX(e){this._colorX.copy(e),this._shapes.px.children[0].setAttribute("fill",this._colorX.toString(!1)),this._shapes.px.children[0].setAttribute("stroke",this._colorX.toString(!1)),this._shapes.nx.children[0].setAttribute("stroke",this._colorX.toString(!1)),this._shapes.xaxis.setAttribute("stroke",this._colorX.toString(!1))}get colorX(){return this._colorX}set colorY(e){this._colorY.copy(e),this._shapes.py.children[0].setAttribute("fill",this._colorY.toString(!1)),this._shapes.py.children[0].setAttribute("stroke",this._colorY.toString(!1)),this._shapes.ny.children[0].setAttribute("stroke",this._colorY.toString(!1)),this._shapes.yaxis.setAttribute("stroke",this._colorY.toString(!1))}get colorY(){return this._colorY}set colorZ(e){this._colorZ.copy(e),this._shapes.pz.children[0].setAttribute("fill",this._colorZ.toString(!1)),this._shapes.pz.children[0].setAttribute("stroke",this._colorZ.toString(!1)),this._shapes.nz.children[0].setAttribute("stroke",this._colorZ.toString(!1)),this._shapes.zaxis.setAttribute("stroke",this._colorZ.toString(!1))}get colorZ(){return this._colorZ}set colorNeg(e){this._colorNeg.copy(e),this._shapes.px.children[0].setAttribute("fill",this._colorNeg.toString(!1)),this._shapes.py.children[0].setAttribute("fill",this._colorNeg.toString(!1)),this._shapes.pz.children[0].setAttribute("fill",this._colorNeg.toString(!1))}get colorNeg(){return this._colorNeg}set radius(e){this._radius=e,this._shapes.px.children[0].setAttribute("r",`${e}`),this._shapes.py.children[0].setAttribute("r",`${e}`),this._shapes.pz.children[0].setAttribute("r",`${e}`),this._shapes.nx.children[0].setAttribute("r",`${e}`),this._shapes.ny.children[0].setAttribute("r",`${e}`),this._shapes.nz.children[0].setAttribute("r",`${e}`),this._resize()}get radius(){return this._radius}set textSize(e){this._textSize=e,this._shapes.px.children[1].setAttribute("font-size",`${e}`),this._shapes.py.children[1].setAttribute("font-size",`${e}`),this._shapes.pz.children[1].setAttribute("font-size",`${e}`)}get textSize(){return this._textSize}set lineThickness(e){this._lineThickness=e,this._shapes.xaxis.setAttribute("stroke-width",`${e}`),this._shapes.yaxis.setAttribute("stroke-width",`${e}`),this._shapes.zaxis.setAttribute("stroke-width",`${e}`),this._shapes.px.children[0].setAttribute("stroke-width",`${e}`),this._shapes.py.children[0].setAttribute("stroke-width",`${e}`),this._shapes.pz.children[0].setAttribute("stroke-width",`${e}`),this._shapes.nx.children[0].setAttribute("stroke-width",`${e}`),this._shapes.ny.children[0].setAttribute("stroke-width",`${e}`),this._shapes.nz.children[0].setAttribute("stroke-width",`${e}`),this._resize()}get lineThickness(){return this._lineThickness}set lineLength(e){this._lineLength=e,this._resize()}get lineLength(){return this._lineLength}_resize(){this._size=2*(this.lineLength+this.radius+this.lineThickness),this.dom.style.width=`${this._size}px`,this.dom.style.height=`${this._size}px`,this._svg.setAttribute("width",`${this._size}`),this._svg.setAttribute("height",`${this._size}`),this._group.setAttribute("transform",`translate(${this._size*.5}, ${this._size*.5})`)}_transform(e,s,i){e.setAttribute("transform",`translate(${s*this._lineLength}, ${i*this._lineLength})`)}_x2y2(e,s,i){e.setAttribute("x2",`${s*this._lineLength}`),e.setAttribute("y2",`${i*this._lineLength}`)}_line(e){let s=document.createElementNS(this._svg.namespaceURI,"line");return s.setAttribute("stroke",e),s.setAttribute("stroke-width",`${this._lineThickness}`),this._group.appendChild(s),s}_circle(e,s=!1,i){let r=document.createElementNS(this._svg.namespaceURI,"g"),a=document.createElementNS(this._svg.namespaceURI,"circle");if(a.setAttribute("fill",s?e:this._colorNeg.toString(!1)),a.setAttribute("stroke",e),a.setAttribute("stroke-width",`${this._lineThickness}`),a.setAttribute("r",`${this._radius}`),a.setAttribute("cx","0"),a.setAttribute("cy","0"),a.setAttribute("pointer-events","all"),r.appendChild(a),i){let o=document.createElementNS(this._svg.namespaceURI,"text");o.setAttribute("font-size",`${this._textSize}`),o.setAttribute("font-family","Arial"),o.setAttribute("font-weight","bold"),o.setAttribute("text-anchor","middle"),o.setAttribute("alignment-baseline","central"),o.textContent=i,r.appendChild(o)}return r.setAttribute("cursor","pointer"),this._group.appendChild(r),r}update(e){if(!this._size)return;SC.invert(e),SC.getX(Ul),SC.getY(kl),SC.getZ(zl),this._transform(this._shapes.px,Ul.x,-Ul.y),this._transform(this._shapes.nx,-Ul.x,Ul.y),this._transform(this._shapes.py,kl.x,-kl.y),this._transform(this._shapes.ny,-kl.x,kl.y),this._transform(this._shapes.pz,zl.x,-zl.y),this._transform(this._shapes.nz,-zl.x,zl.y),this._x2y2(this._shapes.xaxis,Ul.x,-Ul.y),this._x2y2(this._shapes.yaxis,kl.x,-kl.y),this._x2y2(this._shapes.zaxis,zl.x,-zl.y);let s=[{n:["xaxis","px"],value:Ul.z},{n:["yaxis","py"],value:kl.z},{n:["zaxis","pz"],value:zl.z},{n:["nx"],value:-Ul.z},{n:["ny"],value:-kl.z},{n:["nz"],value:-zl.z}].sort((r,a)=>r.value-a.value),i=document.createDocumentFragment();s.forEach(r=>{r.n.forEach(a=>{i.appendChild(this._shapes[a])})}),this._group.appendChild(i)}destroy(){this.dom.remove(),this.off()}};n(Gl,"EVENT_CAMERAALIGN","camera:align");var xC=Gl;return WH(r7);})(); +for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(pc))) { + Object.defineProperty(exports, key, descriptor.get ? { + get: descriptor.get, + set: (value) => Object.defineProperty(exports, key, { value, writable: true, enumerable: descriptor.enumerable, configurable: true }), + enumerable: descriptor.enumerable, + configurable: true + } : descriptor); } -`),this.addFile(null,br,"",r);let a={maxTextureSize:t.maxTextureSize},n=Array.from(this.textureMap.keys()),o=[];for(let e=0;ee?new Promise(t=>e.toBlob(t,"image/png",1)).then(e=>e.arrayBuffer()):new Promise(e=>e(null)));o.push(i);}return Promise.all(o).then(e=>{e.forEach((e,t)=>{let i=n[t],s=this.getTextureFileIds(i);this.files[s.fileName]=new Uint8Array(e);}),this.alignFiles();let t=function(e,t){t||(t={});var i={},s=[];w8(e,"",i,t);var r=0,a=0;for(var n in i){var o=i[n],l=o[0],h=o[1],c=8*(0!=h.level),d=be(n),u=d.length,f=h.comment,p=f&&be(f),m=p&&p.length,_=bt(h.extra);u>65535&&wW(11);var g=c?w4(l,h||{},0,0):l,v=g.length,S=w3();S.p(l),s.push(w5(h,{size:l.length,crc:S.d(),c:g,f:d,m:p,u:u!=n.length||p&&f.length!=m,o:r,compression:c})),r+=30+u+_+v,a+=76+2*(u+_)+(m||0)+v;}for(var y=new wT(a+22),x=r,T=a-r,E=0;E`;return {name:t,fileName:r,refName:a}}getTextureFileIds(e){return this.getFileIds("texture",`Texture_${e.id}`,"Texture","png")}addFile(e,t,i="",s=""){let r=null;s&&(r=be(s=`${ba} -${s}`));let a=this.getFileIds(e,t,i);return this.files[a.fileName]=r,a.refName}getMaterialRef(e){let t=this.materialMap.get(e);return t||(t=this.buildMaterial(e),this.materialMap.set(e,t)),t}getMeshRef(e){let t=this.meshMap.get(e);return t||(t=this.buildMesh(e),this.meshMap.set(e,t)),t}buildArray2(e){let t=[],i=e.length;for(let s=0;s`<${i}${e}>`,r=[],a=[],n=(t,i,n,o,l,h=false,c=false)=>{let d=e[t];if(d){let u=this.getTextureFileIds(d);this.textureMap.set(d,u.refName);let f=e[`${t}Channel`]||"rgb",p=s(`/${u.name}_${l}.outputs:${f}`);r.push(bn(n,`${o}.connect`,p)),h&&e.alphaTest;let m=e[`${t}Tiling`],_=e[`${t}Offset`],g=e[`${t}Rotation`],v=1===e[`${t}Uv`]?"st1":"st",S=c&&i?i:es.WHITE;a.push(` - def Shader "Transform2d_${l}" ( - sdrMetadata = { - string role = "math" - } - ) - { - uniform token info:id = "UsdTransform2d" - float2 inputs:in.connect = ${s(`/uvReader_${v}.outputs:result`)} - float inputs:rotation = ${g} - float2 inputs:scale = (${m.x}, ${m.y}) - float2 inputs:translation = (${_.x}, ${_.y}) - float2 outputs:result - } - - def Shader "Texture_${d.id}_${l}" - { - uniform token info:id = "UsdUVTexture" - asset inputs:file = @${u.fileName}@ - float2 inputs:st.connect = ${s(`/Transform2d_${l}.outputs:result`)} - token inputs:wrapS = "repeat" - token inputs:wrapT = "repeat" - float4 inputs:scale = (${S.r}, ${S.g}, ${S.b}, ${S.a}) - float outputs:r - float outputs:g - float outputs:b - float3 outputs:rgb - float outputs:a - } - `);}else if(i){let e="float"===n?`${i}`:`(${i.r}, ${i.g}, ${i.b})`;r.push(bn(n,o,e));}};n("diffuseMap",e.diffuse,"color3f","diffuseColor","diffuse",false,true),(e.transparent||e.alphaTest>0)&&n("opacityMap",e.opacity,"float","opacity","opacity",true),n("normalMap",null,"normal3f","normal","normal"),n("emissiveMap",e.emissive,"color3f","emissiveColor","emissive",false,true),n("aoMap",null,"float","occlusion","occlusion"),n("metalnessMap",e.useMetalness?e.metalness:0,"float","metallic","metallic"),n("glossMap",e.glossInvert?e.gloss:1-e.gloss,"float","roughness","roughness");let o=` - def Material "${t}" - { - def Shader "PreviewSurface" - { - uniform token info:id = "UsdPreviewSurface" -${r.join("\n")} - int inputs:useSpecularWorkflow = 0 - token outputs:surface - } - - token outputs:surface.connect = ${s("/PreviewSurface.outputs:surface")} - - def Shader "uvReader_st" - { - uniform token info:id = "UsdPrimvarReader_float2" - token inputs:varname = "st" - float2 inputs:fallback = (0.0, 0.0) - float2 outputs:result - } - - def Shader "uvReader_st1" - { - uniform token info:id = "UsdPrimvarReader_float2" - token inputs:varname = "st1" - float2 inputs:fallback = (0.0, 0.0) - float2 outputs:result - } - - ${a.join("\n")} - } - `;return this.materials.push(o),s("")}buildMesh(e){let t,i,s,r,a=[],n=[],o=[],l=[],h=[];e.getVertexStream(e8,a),e.getVertexStream(e9,o),e.getVertexStream(tr,l),e.getVertexStream(ta,h),e.getIndices(n);let c=n.length||a.length,d=Array(c/3).fill(3).join(", ");if(!n.length)for(let e=0;enew rU(e,{...t,featureLevel:i}).initWebGpu(t.glslangUrl,t.twgslUrl));}a===tY&&s.push(()=>new r5(e,t)),a===tK&&s.push(()=>new ai(e,t));}return new Promise((e,t)=>{let i=0,r=()=>{i>=s.length?t(Error("Failed to create a graphics device")):Promise.resolve(s[i++]()).then(t=>{t?e(t):r();}).catch(e=>{r();});};r();})},e.createMesh=function(e,t,i={}){let s=new c4;return s.positions=t,s.normals=i.normals,s.tangents=i.tangents,s.colors=i.colors,s.uvs=i.uvs,s.uvs1=i.uvs1,s.blendIndices=i.blendIndices,s.blendWeights=i.blendWeights,s.indices=i.indices,on.fromGeometry(e,s,i)},e.createPlane=function(e,t){return on.fromGeometry(e,new uw(t))},e.createScript=x1,e.createShader=function(e,t,i,s=false,r={}){},e.createShaderFromCode=function(e,t,i,s,r,a=false,n={}){"boolean"==typeof a?n.useTransformFeedback=a:"object"==typeof a&&(n={...n,...a});let o=nH(e),l=o.getCachedShader(s);return l||(l=new r_(e,rp.createDefinition(e,{...n,name:s,vertexCode:t,fragmentCode:i,attributes:r})),o.setCachedShader(s,l)),l},e.createSphere=function(e,t){return on.fromGeometry(e,new c6(t))},e.createTorus=function(e,t){return on.fromGeometry(e,new ub(t))},e.createURI=function(e){let t="";if((e.authority||e.scheme)&&(e.host||e.hostpath))throw Error("Can't have 'scheme' or 'authority' and 'host' or 'hostpath' option");if(e.host&&e.hostpath)throw Error("Can't have 'host' and 'hostpath' option");if(e.path&&e.hostpath)throw Error("Can't have 'path' and 'hostpath' option");return e.scheme&&(t+=`${e.scheme}:`),e.authority&&(t+=`//${e.authority}`),e.host&&(t+=e.host),e.path&&(t+=e.path),e.hostpath&&(t+=e.hostpath),e.query&&(t+=`?${e.query}`),e.fragment&&(t+=`#${e.fragment}`),t},e.cubemaProjectionNames=nc,e.ditherNames=nR,e.dracoDecode=yA,e.dracoInitialize=e=>{e?.lazyInit?_=e:yC(e);},e.drawFullscreenQuad=function(e,t,i,s,r){let a;if(r){let i=t?t.width:e.width,s=t?t.height:e.height;a=EJ.set(r.x*i,r.y*s,r.z*i,r.w*s);}n8(e,t,s,a);},e.drawQuadWithShader=n8,e.extend=C,e.fresnelNames=na,e.gammaNames=nd,e.getGlslShaderType=e1,e.getPixelFormatArrayType=e6,e.getReservedScriptNames=function(){return x0},e.getTouchTargetCoords=aK,e.getWgslShaderType=e2,e.guid=A,e.http=a0,e.indexFormatByteSize=eW,e.isCompressedPixelFormat=eY,e.isIntegerPixelFormat=ej,e.isSrgbPixelFormat=eq,e.lightFalloffNames=nl,e.lightShapeNames=no,e.lightTypeNames=nn,e.math=ei,e.now=Q,e.path=P,e.pixelFormatGammaToLinear=e4,e.pixelFormatInfo=eX,e.pixelFormatLinearToGamma=e3,e.platform=k,e.primitiveGlslToWgslTypeMap=t4,e.reflectionSrcNames=nS,e.registerScript=x3,e.reprojectTexture=dy,e.requiresManualGamma=e5,e.revision=b,e.script=fP,e.semanticToLocation=t5,e.shaderChunks=E2,e.shadowTypeInfo=nh,e.specularOcclusionNames=nf,e.spriteRenderModeNames=nw,e.string=H,e.tonemapNames=nu,e.typedArrayIndexFormats=t2,e.typedArrayIndexFormatsByteSize=t3,e.typedArrayToType={Int8Array:0,Uint8Array:1,Int16Array:2,Uint16Array:3,Int32Array:4,Uint32Array:5,Float32Array:6},e.typedArrayTypes=t0,e.typedArrayTypesByteSize=t1,e.uniformTypeToName=tG,e.uniformTypeToNameMapWGSL=tW,e.uniformTypeToNameWGSL=tH,e.uniformTypeToStorage=tX,e.version=w,e.vertexTypesNames=["INT8","UINT8","INT16","UINT16","INT32","UINT32","FLOAT32","FLOAT16"];},"object"==typeof exports&&"u">typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="u">typeof globalThis?globalThis:e||self).pc={}); +})); diff --git a/web/viewer_gaussian.html b/web/viewer_gaussian.html index c2cbe11..3471ea8 100644 --- a/web/viewer_gaussian.html +++ b/web/viewer_gaussian.html @@ -209,6 +209,7 @@ +